diff --git a/.agents/skills/formchem-harness/EVALS.json b/.agents/skills/formchem-harness/EVALS.json
index b9836b2d..079543e0 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, version 0.4.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.4.0 has drawings but no direct agent drawing tools (0.8.0); agents work through run_command and Form extensions, and several evals check that the agent stays inside that.",
+ "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.6.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.6.0 has drawings, four reaction tools and four read-only analysis tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction and analysis tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 17 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O.",
"evals": [
{
"id": 1,
@@ -138,10 +138,79 @@
"Calls extensions_list and uses an extension command only if one states that it reads the drawing or checks structures",
"Reports valence errors only from that extension's answer; with no suitable extension, says the agent cannot read the rows and points the person at the Check Structure dialog instead of computing valence itself"
]
+ },
+ {
+ "id": 13,
+ "name": "map-and-export-the-drawn-reaction",
+ "prompt": "Map the atoms of the esterification I drew in FormChem and give me the reaction SMILES.",
+ "files": [],
+ "expected_behavior": [
+ "Calls get_context, then perceive_reactions, and keeps the reaction and step ids it returns",
+ "Calls map_reaction with those ids (mode left at discard) and reports the mapped count and the bonds broken and formed from its answer",
+ "Calls export_reaction with format smiles and quotes the text exactly, passing on any conditions_dropped warning",
+ "Ends with a ready handoff naming the drawing and that Undo removes the mapping"
+ ]
+ },
+ {
+ "id": 14,
+ "name": "yield-without-amounts",
+ "prompt": "What is the theoretical yield of my FormChem reaction?",
+ "files": [],
+ "expected_behavior": [
+ "Calls perceive_reactions, then reaction_stoichiometry for the step",
+ "Quotes the theoretical yield with its unit only when the answer gives one, never computing it from its own molecular weights",
+ "When no amounts are typed, posts a question handoff asking the person to type a mass, volume, equivalents or scale in the Stoichiometry panel, and says no tool can type them"
+ ]
+ },
+ {
+ "id": 15,
+ "name": "druglike-properties-with-methods",
+ "prompt": "Is the structure in my FormChem drawing drug-like? Give me cLogP and TPSA.",
+ "files": [],
+ "expected_behavior": [
+ "Calls get_context, then the properties tool (not compute-properties through run_command)",
+ "Quotes cLogP 3.07 and TPSA 37.3 with their units and the methods the tool names (Crippen.MolLogP, rdMolDescriptors.CalcTPSA), and the Lipinski and Veber verdicts as the tool gives them",
+ "Does not compute any value with its own chemistry and present it as FormChem's",
+ "Posts no approval-gated call for this read-only question"
+ ]
+ },
+ {
+ "id": 16,
+ "name": "racemic-and-group",
+ "prompt": "In FormChem, mark the stereocentre of my ibuprofen as racemic and tell me what the CXSMILES becomes.",
+ "files": [],
+ "expected_behavior": [
+ "Calls stereo first to find the centre and its current label S",
+ "Says the command acts on the canvas selection and either asks the person to select the centre or explains what select-all would include, then runs set-stereo-group-and once",
+ "Calls stereo again and quotes the new CXSMILES with its &1 group exactly as returned",
+ "Ends with a ready handoff saying the change is one undo step"
+ ]
+ },
+ {
+ "id": 17,
+ "name": "find-carboxylic-acids",
+ "prompt": "Which structures in my FormChem drawing have a carboxylic acid?",
+ "files": [],
+ "expected_behavior": [
+ "Calls substructure with a SMARTS such as C(=O)[OH] (or [CX3](=O)[OX2H1])",
+ "Reports the hit count and the fragment ids from the answer, naming the structures by what get_context or the tools say",
+ "Does not run search-substructure through run_command to get the answer, since its result is a selection the agent cannot read"
+ ]
}
],
"trigger_evals": [
{"query": "what can FormChem do at the moment", "should_trigger": true},
+ {"query": "what is the cLogP and TPSA of the molecule in my FormChem drawing?", "should_trigger": true},
+ {"query": "is the stereocentre in my formchem drawing R or S?", "should_trigger": true},
+ {"query": "run a structure check on my FormChem drawing and list the warnings", "should_trigger": true},
+ {"query": "find every carboxylic acid in my formchem drawing with SMARTS", "should_trigger": true},
+ {"query": "make water an agent instead of a product in my FormChem reaction", "should_trigger": true},
+ {"query": "add enhanced stereo group support to formchem's backend/app/services/chem/stereo.py", "should_trigger": false},
+ {"query": "compute the Lipinski properties of this SMILES with an RDKit script", "should_trigger": false},
+ {"query": "map the atoms of the reaction in my formchem drawing", "should_trigger": true},
+ {"query": "export the drawn reaction in FormChem as an RXN file", "should_trigger": true},
+ {"query": "what is the limiting reagent in my formchem scheme?", "should_trigger": true},
+ {"query": "insert a cyclohexane chair template in FormChem", "should_trigger": true},
{"query": "open preferences in formchem", "should_trigger": true},
{"query": "is the formchem engine running? I get connection refused", "should_trigger": true},
{"query": "run the hello command of my formchem extension", "should_trigger": true},
@@ -167,6 +236,8 @@
{"query": "run the show-grid command in formvis", "should_trigger": false},
{"query": "install the molecule tools extension from FormPortal", "should_trigger": false},
{"query": "convert this SDF file to SMILES with RDKit in a Python script", "should_trigger": false},
- {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false}
+ {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false},
+ {"query": "fix the perception distances in formchem's services/chem/reactions.py", "should_trigger": false},
+ {"query": "balance this equation for me: Fe + O2 -> Fe2O3", "should_trigger": false}
]
}
diff --git a/.agents/skills/formchem-harness/SKILL.md b/.agents/skills/formchem-harness/SKILL.md
index e8eb6343..5c7d6f83 100644
--- a/.agents/skills/formchem-harness/SKILL.md
+++ b/.agents/skills/formchem-harness/SKILL.md
@@ -1,25 +1,25 @@
---
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 or insert a structure from SMILES, clean up a drawing, undo, select all, zoom, run a FormChem menu command or extension, read or change the open fchem drawing through an extension, check a structure for valence errors, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff) are available. Covers connecting on 127.0.0.1:8220 when the tools do not show up, the approval question, the commands catalogue, the extension drawing contract and handoff. There are no direct drawing tools before 0.8.0, so it also covers saying so plainly. Not for changing FormChem's source code (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for 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: insert a structure from SMILES or a template, undo, run a menu command or extension, read the open fchem drawing, perceive or map a reaction, export reaction SMILES or RXN, read stoichiometry, set reaction roles, get cLogP, TPSA or Lipinski, check a structure, read R/S labels and stereo groups, find a substructure by SMARTS, add hydrogens, contract an abbreviation, define an R-group, or asks what FormChem can do, and FormChem is named or its tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry, properties, check_structure, stereo, substructure) are available. Covers 127.0.0.1:8220, approval, handoff and what waits for 0.8.0. 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.4.0"
+ version: "0.6.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.
-## What exists today (0.4.0)
+## What exists today (0.6.0)
-FormChem 0.4.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws with tools and hover keys. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help.
+FormChem 0.6.0 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 where the person draws structures with tools and hover keys. 0.5.0 added reactions and annotations (arrows, brackets, shapes, tables, TLC plates, captions, reaction perception, atom mapping, balance, the Stoichiometry panel, 206 templates, Find and rulers). 0.6.0 adds stereo, queries and analysis: CIP labels and enhanced stereo groups, Assign Wedges, abbreviations, explicit hydrogens, atom lists and query bonds, R-groups and Markush enumeration, substructure search and SMARTS, calculated properties with their methods, the isotope pattern, the Check Structure panel and Set Reaction Roles. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help.
-The MCP server still has six tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server.
+The MCP server has fourteen tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server.
-**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected), undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, clean up, lay out, check structure and zoom (`window-commands`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`).
+**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out and zoom (`window-commands`), plus the chemistry commands (wedges, stereo groups, hydrogens, abbreviations, query features, R-groups). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry and balance, and set roles with `set-reaction-roles {role, objects}` (`reactions`). Through the analysis tools: properties with their methods, the structure check, CIP labels and stereo groups, and substructure hits by id (`structure-analysis`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`).
-**What it cannot do yet.** There are no direct drawing tools: no drawing atoms and bonds by call, no reading SMILES or InChIKey back through MCP (the formula in `get_context` is all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work.
+**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading the whole structure or its InChIKey back through MCP (the formula in `get_context`, the SMILES and CXSMILES in `stereo` and the other tools' answers are all), no rendering, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work.
## Doctrine (applies to every route)
@@ -39,6 +39,8 @@ formchem-harness/
sub-skills/
session-and-connection/ connecting, get_context, the approval question, errors
window-commands/ drawing work through run_command; references/command-catalogue.md
+ reactions/ the four reaction tools, the Reaction menu commands and Set Reaction Roles
+ structure-analysis/ the four analysis tools and the stereo, hydrogen, abbreviation and query commands
extension-drawings/ reading and changing the drawing through a Form extension
handoff/ handoff states, notes, clearing, what the person sees
visual-qa/ checking what the person sees without a render tool
@@ -52,12 +54,14 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere
| --- | --- |
| No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` |
| "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` |
-| Draw or insert a structure from SMILES, open a drawing or structure file, undo, save, select all, clean up, zoom | `window-commands` |
-| Read atoms, bonds, SMILES, InChIKey or valence errors from the open drawing, change it by id, check a structure | `extension-drawings` (and `window-commands` when no extension fits) |
+| Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` |
+| The reaction in the drawing: its steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` |
+| Properties (cLogP, TPSA, Lipinski), a structure check, R or S, stereo groups, a substructure or SMARTS match, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` |
+| Read atoms, bonds, InChIKey or valence errors from the open drawing, change it by id | `extension-drawings` (and `window-commands` when no extension fits) |
| Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` |
| Tell the person you are done, ask them something, clear your note | `handoff` |
| Check what the person sees, did the command work, which commands are on | `visual-qa` |
-| Draw atom by atom, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists |
+| Draw atom by atom, place an arrow or shape, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists |
| Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` |
## When something fails
@@ -74,11 +78,15 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere
| "takes no parameters" | The command does not accept arguments in this build | Run it without `params`; if it prompts, ask the person to fill the prompt |
| "Could not read the SMILES" | `insert-smiles {smiles}` got a string the engine cannot parse; nothing was inserted | Check the SMILES, fix it once, or ask the person |
| "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path |
+| "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it |
+| An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns |
+| "Give smarts, or query_object" or "is not a fragment of this drawing" | `substructure` has no pattern, or the query fragment id is wrong | Pass a SMARTS or a fragment id from the tools' answers |
+| A fragment slot holding `error` in an analysis answer | The engine could not read that fragment; the others are fine | Report it for that fragment and go on with the rest |
## Done means
- `get_context` was called first and its answer shaped the plan.
-- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, and requests beyond the commands were answered with "the drawing tools arrive in 0.8.0".
+- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, reaction numbers were quoted from the reaction tools, and requests beyond them were answered with "the drawing tools arrive in 0.8.0".
- Every command run returned without `isError`, or its error was reported to the person.
- 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 d73cfc33..cfef0fe0 100644
--- a/.agents/skills/formchem-harness/references/tools.md
+++ b/.agents/skills/formchem-harness/references/tools.md
@@ -1,9 +1,28 @@
# FormChem MCP tools
-Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 6 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`; edit the server, never this file. 14 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.
+## Contents
+
+- Tool kinds (the table below)
+- get_context
+- list_commands
+- run_command
+- extensions_list
+- extension_command
+- handoff
+- perceive_reactions
+- map_reaction
+- export_reaction
+- reaction_stoichiometry
+- properties
+- check_structure
+- stereo
+- substructure
+- Resource
+
| Tool | Kind |
| --- | --- |
| `get_context` | read-only |
@@ -12,10 +31,18 @@ Read-only tools never ask the person. An approval-gated tool asks the person in
| `extensions_list` | read-only |
| `extension_command` | approval-gated |
| `handoff` | approval-gated when it changes something |
+| `perceive_reactions` | approval-gated |
+| `map_reaction` | approval-gated |
+| `export_reaction` | read-only |
+| `reaction_stoichiometry` | read-only |
+| `properties` | read-only |
+| `check_structure` | read-only |
+| `stereo` | read-only |
+| `substructure` | read-only |
## get_context
-FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; dedicated drawing tools arrive in 0.8.0.
+FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in 0.8.0.
Arguments: none.
@@ -65,6 +92,88 @@ Tells the person where your work stands: working (still on it), ready (done, for
| `state` | working or ready or question or clear | no | |
| `note` | string | no | One short line for the person |
+## perceive_reactions
+
+Works out the reaction steps of a drawing from where its structures sit around the reaction arrows (before the tail: reactants, after the head: products, beside the arrow: agents and conditions text; plus signs join) and writes them to the drawing as one undo step. Steps someone set by hand are kept. Returns every reaction with its step ids.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Drawing id from get_context; may be left out when one drawing is open |
+| `page` | string | no | Page id; all pages when left out |
+
+## map_reaction
+
+Maps the atoms of one reaction step (reactant atom to product atom numbers) and marks the bonds broken, formed or changed in order, as one undo step. mode discard (default) maps from scratch, keep keeps the numbers already drawn, alter may change them, clear removes the mapping.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | |
+| `reaction` | string | no | Reaction id from perceive_reactions; the first reaction when left out |
+| `step` | string | no | Step id; the first step when left out |
+| `mode` | discard or keep or alter or clear | no | |
+
+## export_reaction
+
+One reaction step as reaction SMILES (format smiles) or an RXN file (rxn for V2000, rxnv3000), with its map numbers. Does not change the drawing.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | |
+| `reaction` | string | no | |
+| `step` | string | no | |
+| `format` | smiles or rxn or rxnv3000 | no | |
+
+## reaction_stoichiometry
+
+The stoichiometry of one reaction step worked out from the amounts the person typed in its grid and the molecular weights: moles, equivalents, masses, volumes, the limiting reagent, theoretical yields and the percent yield, plus the balance check. Does not change the drawing.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | |
+| `reaction` | string | no | |
+| `step` | string | no | |
+
+## properties
+
+Drug-like properties of the structures in an open drawing, per fragment: formula, MW, exact mass, cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis; every value names the RDKit method behind it.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `object` | string | no | One fragment id; absent: every fragment |
+
+## check_structure
+
+Checks the structures of an open drawing: valence errors, unusual charges, wedge problems, overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing and R-group gaps; each issue has a code, a severity (error, warning, info) and the atom and bond ids it concerns.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `object` | string | no | One fragment id; absent: every fragment |
+| `query` | boolean | no | True when the drawing is a search query, so query features are not reported |
+
+## stereo
+
+Stereochemistry of an open drawing per fragment: each stereocentre, stereogenic double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), whether it is defined, undefined or unknown, its enhanced stereo group (abs, and1, or1) and the CXSMILES that carries the groups.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `object` | string | no | One fragment id; absent: every fragment |
+
+## substructure
+
+Searches the fragments of an open drawing for a substructure given as SMARTS or as a query fragment drawn in the same drawing; returns every hit with its fragment id and the matched atom and bond ids.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `smarts` | string | no | SMARTS pattern, such as C(=O)[OH] |
+| `query_object` | string | no | A fragment of the drawing to use as the query instead of smarts |
+| `objects` | array of string | no | Fragment ids to search; absent: all |
+| `chirality` | boolean | no | |
+| `max_hits` | integer | no | Most hits to return (default 1000) |
+
## 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/extension-drawings/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md
index 86da271d..98f99df2 100644
--- a/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md
+++ b/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md
@@ -17,7 +17,7 @@ Use an extension as the agent's hands on the drawing until FormChem has its own
## What an extension sees
- `document.read {what: "all"}`: a head (`id`, `title`, `rev`, `dirty`, `path`, `page`, `writable`, `mode`, `format`, `format_version`), the whole `document`, and `derived` when the engine's cache matches `rev`. `what` may also be `page`, `selection` or `json`.
-- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). This is the honest way to check a structure before `check-structure` arrives in 0.6.0.
+- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). From 0.6.0 the `check_structure` tool returns the full structure check by code and id (`structure-analysis`); the derived cache stays the way to read InChIKey and valence errors inside an extension.
- With no drawing open: `writable: false`, `page: null`. Check both before offering a change.
## What an extension can change
diff --git a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md
index 3707b779..0775514f 100644
--- a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md
+++ b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md
@@ -31,9 +31,9 @@ A handoff with a state changes what the person sees, so the first one from an ou
- A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?"
- No emoji, no markdown, no links the person cannot click.
-## In 0.4.0
+## In 0.6.0
-A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead").
+A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed", "Assigned wedges in Ibuprofen; the centre reads S". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead").
## Procedure
diff --git a/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md
new file mode 100644
index 00000000..90c83d04
--- /dev/null
+++ b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md
@@ -0,0 +1,59 @@
+---
+name: reactions
+description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem."
+---
+
+# Reactions
+
+## Purpose
+
+Answer reaction questions from what FormChem computes, not from the agent's own chemistry, and make reaction changes as undo steps the person sees. Hands back reaction and step ids, the engine's answers quoted as numbers, and a handoff naming what changed.
+
+## Preconditions
+
+`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. An agent cannot draw arrows or place structures by position before 0.8.0; `insert-smiles` and `insert-template` put things in the middle of the view, so a scheme is the person's to arrange.
+
+## Tools and commands
+
+| Goal | Call | Changes the drawing |
+| --- | --- | --- |
+| Find the steps and their roles | `perceive_reactions {doc?, page?}`: lists every reaction and step id, reactants, products, agents and conditions; steps set by hand say "(set by hand)" and are kept | yes, one undo step; "No change" when nothing moved |
+| Map atoms | `map_reaction {doc?, reaction?, step?, mode?}`: `discard` (default) maps from scratch, `keep` keeps drawn numbers, `alter` may change them, `clear` removes them; the answer gives map numbers and bonds broken and formed | yes, one undo step |
+| The reaction as text | `export_reaction {doc?, reaction?, step?, format?}`: `smiles`, `rxn` (V2000) or `rxnv3000`, with map numbers | no |
+| Amounts and yields | `reaction_stoichiometry {doc?, reaction?, step?}`: rows with mmol, equiv, mass, volume, the limiting reagent, the theoretical and percent yield, and the balance check | no |
+| Balance coefficients | `run_command {id: "balance-reaction"}` on the selected or first step; `check-reaction` opens the balance dialog for the person | yes, one undo step |
+| Insert a template | `run_command {id: "insert-template", params: {id: "[template id]"}}`; the ids come from the engine's `GET /api/templates` | yes, one undo step |
+| Paste a reaction | `paste-reaction` reads the person's clipboard; an agent cannot fill the clipboard, so it is the person's | yes |
+| The grid on the page | `stoichiometry-grid` inserts or refreshes the grid for the selected or first step; `show-stoichiometry` opens the panel for the person | yes for the grid |
+
+`doc` may be left out when one drawing is open; `reaction` and `step` default to the first. The two changing tools ask the person the first time like any change.
+
+## Procedure
+
+1. **Context.** `get_context`; name the drawing by title.
+2. **Steps first.** `perceive_reactions` before any step-level tool. Keep the reaction and step ids it returns; never guess ids. "No reaction arrow has structures before or after it" means the scheme is not drawn as FormChem reads it (structures within 2.5 bond lengths of the arrow's line, reagents within 1.5 of the arrow): say so and ask the person to move them.
+3. **One step at a time.** Pass the ids to `map_reaction`, `export_reaction` or `reaction_stoichiometry`. A step not found names `perceive_reactions` as the next call: run it once, then retry once.
+4. **Quote, do not compute.** Report formulas, masses, mmol and yields exactly as the tool printed them, with units. "Not balanced." with a suggestion is the engine's answer; offer `balance-reaction` only when the check suggests coefficients, and say "add the missing co-products first" when it suggests a co-product, which only the person can draw.
+5. **Amounts are the person's.** No tool types amounts into the grid. When the answer lacks amounts, ask in a question handoff for the masses, volumes, equivalents or scale to type into the Stoichiometry panel, then read again.
+6. **Hand off** what changed ("Mapped step 1 of Esterification: 7 atoms, one C-O bond formed; Undo removes it").
+
+## Rules
+
+- Roles come from geometry unless set by hand. `run_command {id: "set-reaction-roles", params: {role, objects}}` gives the listed object ids (fragments, text, captions, groups, images, shapes or tables; never the arrow) the role `reactant`, `product`, `agent`, `condition` or `none` in the step touching the selection, as one undo step, and marks the step as set by hand so `perceive_reactions` keeps it. Without `role` it opens a dialog for the person. Read the result back with `perceive_reactions` (it lists the step as set by hand). A step read from an RXN file keeps its roles too.
+- Reagents drawn above the arrow are not counted in the balance; a step whose atoms come from such a reagent reads as unbalanced. Say that instead of "the reaction is wrong".
+- Mapping the second of two chained steps replaces the map numbers of the structure they share. Warn before mapping a second step when the first is already mapped.
+- Coefficients are dropped from reaction SMILES and RXN (`coefficient_dropped`); text conditions are dropped from reaction SMILES (`conditions_dropped`). Pass the warnings on.
+
+## Gate
+
+- [ ] Every step-level call used ids returned by `perceive_reactions` in this session.
+- [ ] Every number reported came from a tool answer, with its unit.
+- [ ] Each changing call was reported with its undo step; no change was retried after a refusal.
+
+## Hands back
+
+Reaction and step ids, the quoted answers, and a ready or question handoff.
+
+## Owned resources
+
+None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands.
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 50bde3ab..f0f9e6e5 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
@@ -42,5 +42,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 six tools and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools.
+- [ ] The plan uses only the fourteen tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools.
- [ ] No change was attempted after a refusal.
diff --git a/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md
new file mode 100644
index 00000000..ae33befa
--- /dev/null
+++ b/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md
@@ -0,0 +1,69 @@
+---
+name: structure-analysis
+description: "Reads and edits the chemistry of an open FormChem drawing through the four MCP analysis tools (properties, check_structure, stereo, substructure) and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem."
+---
+
+# Structure analysis
+
+## Purpose
+
+Answer chemistry questions about the drawing with FormChem's own numbers, quoted with the method behind them, and make the stereo, hydrogen, abbreviation and query edits as undo steps the person sees. Hands back fragment, atom and bond ids, the tool answers quoted exactly, and a handoff naming any change.
+
+## Preconditions
+
+`get_context` has been called (`session-and-connection`) and lists the drawing. The analysis tools only read, so they never ask the person; the chemistry commands change the drawing and ask the first time, like any `run_command`.
+
+## The four analysis tools
+
+| Goal | Call | What comes back |
+| --- | --- | --- |
+| Properties | `properties {doc?, object?}` | per fragment: formula, MW, exact mass, cLogP, MR, TPSA (and with S and P), donors and acceptors (Lipinski and refined counts), rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts, elemental analysis; each row with `method` (the RDKit call) and `note` |
+| Structure check | `check_structure {doc?, object?, query?}` | issues `{code, severity, text, atoms, bonds, fix}` sorted errors first; `query: true` when the drawing is a search query |
+| Stereo | `stereo {doc?, object?}` | centres, double bonds and axes with label, `state` (defined, undefined, unknown) and group (`abs`, `and1`, `or1`), the stereo groups, the chiral flag and CXSMILES |
+| Substructure | `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | hits with the fragment id, matched atom and bond ids and the query-to-target map; `count`, `truncated` |
+
+`doc` may be left out when one drawing is open; `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`).
+
+## Chemistry commands (run_command)
+
+They act on the person's selection, or on the page when nothing is selected; the agent selects only with `select-all` or by inserting. Check `list_commands {id}` for params and the off reason first.
+
+| Command | Does |
+| --- | --- |
+| `assign-wedges` | redraws wedges and hashes of the stereocentres so they read unambiguously |
+| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | puts the selected centres into an abs, new AND or new OR group, or out of any |
+| `add-hydrogens`, `remove-hydrogens` | draws implicit H as atoms or folds them back; H that hold stereo, an isotope, a charge or a map number stay |
+| `expand-abbreviation`, `contract-abbreviation` | expands a selected label (or every one); contract opens a dialog for the person's label |
+| `set-atom-list`, the `set-query-bond-` commands, `clear-query-bond` | atom lists (a dialog) and query bonds on the selection |
+| `define-rgroup`, `enumerate-markush` | R-group definition and enumeration open dialogs for the person |
+| `copy-smarts`, `compute-properties`, `check-structure`, `search-substructure` | copy SMARTS to the person's clipboard, or open the panels; the tools above return the same data to the agent |
+
+## Procedure
+
+1. **Context.** `get_context`; name the drawing and pick fragment ids from the tool answers, never by guess.
+2. **Read with the tool, not the command.** For values, issues, labels or matches call the analysis tool; the command opens a panel the agent cannot read.
+3. **Quote with the method.** Report each value as the tool printed it, with its unit and method ("cLogP 3.07, Crippen.MolLogP; typical error 0.5 to 0.7 log units"). Never compute a property, a CIP label or a SMARTS match with your own chemistry and present it as FormChem's.
+4. **Stereo states matter.** An `undefined` centre has no label because nothing fixes it; say so instead of guessing R or S. Allene axial chirality and drawn atropisomers are not perceived in this version.
+5. **Change through commands, then read back.** After `assign-wedges`, a stereo group or `add-hydrogens`, call `stereo` or `check_structure` again and report what changed, with Undo as the way back.
+6. **Hand off** with what changed or what the person should look at (`handoff`).
+
+## Rules
+
+- A check issue with `fix` (`wedges` or `expand`) is repaired by the person's Fix button or by `assign-wedges` or `expand-abbreviation` on the selection; say which.
+- A structure check on a query drawing without `query: true` reports `query_feature` notes; they are expected, not errors.
+- Metal cations such as Na+ in a salt are not valence errors; do not report them as such.
+- Export SMARTS in the desktop app copies instead of saving until 0.7.0; dialogs (atom list, R-group, abbreviation label) belong to the person.
+
+## Gate
+
+- [ ] Every number, label and issue reported came from a tool answer in this session, with its unit and method where given.
+- [ ] Every changing command was found in `list_commands` first and reported with its undo step.
+- [ ] Undefined or unperceived stereo was named as such, never filled in.
+
+## Hands back
+
+Fragment, atom and bond ids, the quoted answers, and a ready or question handoff.
+
+## Owned resources
+
+None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue.
diff --git a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md
index 34473333..f4d176cd 100644
--- a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md
+++ b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md
@@ -7,7 +7,7 @@ description: "Checks what the person sees in FormChem when the agent cannot see
## Purpose
-Never claim a visible result you did not confirm. In 0.4.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report, and ask the person for the rest.
+Never claim a visible result you did not confirm. In 0.6.0 an agent still has no picture of the window and no render tool (it arrives in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found; `stereo`, `check_structure` and `properties` read the chemistry after a command), and ask the person for the rest.
## What you can confirm today
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 cf216927..6dc92811 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
@@ -1,6 +1,6 @@
---
name: window-commands
-description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist."
+description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist."
---
# Window commands
@@ -25,13 +25,17 @@ Most canvas commands act on the canvas selection. The agent sets the selection t
| --- | --- |
| Open this file (absolute path to a `.fchem`, `.mol`, `.sdf`, `.smi`, `.cml`, `.cdxml`) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing |
| Draw or insert a structure from SMILES | `run_command {id: "insert-smiles", params: {smiles: "[SMILES]"}}`: one undo step into the active drawing (a new one when none is open), centred in the visible page and selected; the answer names the new fragment ids and the drawing. Then `get_context` for the formula. If `list_commands {id: "insert-smiles"}` lists no `smiles` param (an older build), run it bare and post `handoff {state: "question", note: "Paste [SMILES] into the SMILES prompt and press Insert"}`; never claim the structure was drawn until the person confirms |
-| Draw from a name, a molfile text or by atoms | No command does this before 0.8.0. Offer SMILES through `insert-smiles {smiles}`, or a file through `open-recent` |
+| Insert a ring, amino acid, sugar, protecting group, reagent or glassware | `run_command {id: "insert-template", params: {id: "[template id]"}}`: one undo step, centred in view at the drawing's bond length, selected; without `id` it opens the library for the person. Ids such as `benzene`, `l-alanine` come from the engine's `GET /api/templates` |
+| Draw from a name, a molfile text or by atoms; place an arrow, a shape or a caption | No command does this before 0.8.0 (the insert-arrow, insert-shape and insert-table commands only pick the person's tool). Offer SMILES through `insert-smiles {smiles}`, a template, or a file through `open-recent` |
+| 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 |
| Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure |
| Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected |
| Save | `save`; a drawing never saved before asks the person for a name, so say so in the handoff |
-| Check the structure | `check-structure` opens a dialog for the person listing valence errors and warnings; the agent does not get the rows back. Say the dialog is open for them, or read valence errors through an extension (`extension-drawings`) |
-| Show the formula or masses | `get_context` gives the formula of each open drawing; `show-analysis` or `toggle-analysis` opens the Analysis panel (masses, m/z, elemental analysis) for the person, whose values the agent cannot read through commands |
+| Check the structure | The `check_structure` tool returns the issues with codes and ids (`structure-analysis`); `check-structure` opens the Check Structure panel for the person |
+| Show the formula, masses or properties | `get_context` gives the formula of each open drawing and the `properties` tool every value with its method (`structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person |
+| Stereo, hydrogens, abbreviations, query features, R-groups | Load `structure-analysis` for the commands and the tools that read the result |
## Rules
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 2fba324e..7f9e876c 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,12 +1,15 @@
# Commands that touch a drawing
-The window's command registry, as far as it concerns drawings, for FormChem 0.4.0. 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.6.0. 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
- Reading the catalogue
- Drawings: open, save, close
- Changing the drawing
+- Templates, objects and arrangement
+- Reactions
+- Stereo, queries and analysis
- The canvas and the view
- Registered but off until a later version
- What no command does yet
@@ -42,10 +45,58 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4.
| `distribute-h`, `distribute-v` | | spread the selected objects evenly |
| `clean-structure` | | tidies bond lengths and angles through the engine's layout service, keeping place and stereochemistry; selected atoms, or every structure on the page when nothing is selected. It refuses when the drawing changed during the call |
| `layout-structure` | | computes fresh 2D coordinates for the structures the selection touches, or every structure on the page |
-| `check-structure` | | opens a dialog for the person listing valence errors and chemistry warnings with links that select the atoms; the agent gets only "ran in the window" |
+| `check-structure` | | opens the Check Structure panel for the person (rows that select atoms, Fix, Check Again); the agent gets only "ran in the window", and reads the issues with the `check_structure` tool |
| `insert-text` | | switches the person's canvas to the text tool |
-`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` selects what it added). Each changing command is one undo step. `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group` and `ungroup` are registered but off in this build.
+`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` and `insert-template` select what they added). Each changing command is one undo step.
+
+## Templates, objects and arrangement
+
+| Command | Params | What it does |
+| --- | --- | --- |
+| `insert-template` | `id` (optional) | with `id`: inserts that template (fresh ids, the drawing's bond length) centred in the view of the active drawing, or a new one, selected, as one undo step; the engine's `GET /api/templates` lists the 206 ids (`benzene`, `l-alanine` and so on). Without `id` it opens the library for the person |
+| `bring-front`, `bring-forward`, `send-backward`, `send-back` | | change the stacking order of the selection within its page or group (Shift+Mod+], Mod+], Mod+[, Shift+Mod+[) |
+| `group`, `ungroup` | | group the selection (Mod+G) or ungroup a selected group (Shift+Mod+G) |
+| `insert-arrow`, `insert-shape`, `insert-table` | | pick the arrow, rectangle or table tool for the person; nothing is drawn until they drag |
+| `insert-image` | | asks the person for a picture file; an agent cannot answer the chooser |
+| `insert-text` | | switches the person's canvas to the text tool |
+
+## Reactions
+
+| Command | What it does |
+| --- | --- |
+| `add-reaction-arrow` | picks the reaction arrow tool for the person |
+| `perceive-reactions` | reads the reaction arrows on the page and stores each step's roles (one undo step); the `perceive_reactions` tool does the same and returns the ids |
+| `map-atoms`, `clear-mapping` | map or clear the selected or first step; `map_reaction` returns the result |
+| `check-reaction` | opens the balance dialog for the person |
+| `balance-reaction` | writes the suggested coefficients (one undo step); refused when the check suggests a missing co-product |
+| `show-stoichiometry`, `stoichiometry-grid` | open the Stoichiometry panel for the person; insert or refresh the grid table on the page |
+| `copy-reaction-smiles`, `copy-reaction-rxn` | put the step on the person's clipboard; `export_reaction` gives the agent the text |
+| `export-reaction-smiles`, `export-reaction-rxn` | save the step to a file the person chooses |
+| `paste-reaction` | lays out reaction SMILES or RXN from the person's clipboard as a drawn scheme |
+| `set-reaction-roles` | params `role` (`reactant`, `product`, `agent`, `condition`, `none`) and `objects` (ids; default the selection): sets their role in the step and marks it as set by hand, one undo step; without `role` it opens the roles dialog for the person |
+
+The step is the one whose arrow or structures are selected, else the first on the page.
+
+## Stereo, queries and analysis
+
+From 0.6.0. They act on the selection, or the page when nothing is selected, and each changing one is one undo step. The analysis tools (`properties`, `check_structure`, `stereo`, `substructure`) return what the panels show; see `structure-analysis`.
+
+| Command | What it does |
+| --- | --- |
+| `assign-wedges` | asks the engine for wedges and hashes that express the stereocentres unambiguously |
+| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | put the selected centres into abs, a new AND group or a new OR group, or out of every group |
+| `set-stereo-group`, `stereo-group-popover` | the Enhanced Stereo submenu and its popover, for the person |
+| `add-hydrogens`, `remove-hydrogens` | explicit hydrogens drawn or folded back; some stay (stereo, isotope, charge, map number) |
+| `expand-abbreviation` | expands the selected abbreviation atoms, or every abbreviation on the page |
+| `contract-abbreviation` | opens the abbreviation dialog for the person's label |
+| `set-atom-list` | opens the periodic table dialog for the person |
+| `set-query-bond-any`, `set-query-bond-single_or_double`, `set-query-bond-single_or_aromatic`, `set-query-bond-double_or_aromatic`, `clear-query-bond` | query bonds on the selected bonds (list_commands gives the exact ids) |
+| `define-rgroup`, `enumerate-markush` | open the R-group and enumeration dialogs for the person |
+| `search-substructure` | selects matches of the selected atoms, or asks the person for SMARTS |
+| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file (the desktop app copies instead until 0.7.0) |
+| `compute-properties`, `copy-analysis` | open the Analysis panel on the selection; copy its values with methods to the person's clipboard |
+| `show-stereo`, `show-stereo-groups`, `show-query-marks` | toggle the CIP labels, the enhanced stereo group labels and the query tags on the canvas |
## The canvas and the view
@@ -56,13 +107,14 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4.
| `zoom-100` | actual size (Mod+1) |
| `show-grid` | toggles the paper grid; the result says whether it is now on |
| `show-analysis` | opens the Analysis panel |
+| `find`, `show-rulers` | Edit > Find (next, previous, replace) and View > Show Rulers with guides, for the person |
| `toggle-analysis`, `analysis-panel` | shows or hides the Analysis panel (formula, masses, m/z, elemental analysis from the engine, for the selection or the whole page) |
| `tool-select`, `tool-bond`, `tool-chain`, `tool-ring`, `tool-atom`, `tool-text`, `tool-eraser`, `tool-hand`, `tool-zoom`, `tool:[id]` | pick a drawing tool for the person; they do not draw by themselves |
## Registered but off until a later version
-`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); reactions, arrows, shapes, tables and images (0.5.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. `find`, `show-rulers`, `insert-template` and the stacking and grouping commands arrive in 0.5.0, and `add-hydrogens` and `remove-hydrogens` in 0.6.0.
+`import`, `print`, `copy-smiles`, `copy-molfile`, `copy-inchi`, `copy-svg` and the whole-drawing `export-png`, `export-svg`, `export-pdf`, `export-cdxml`, `export-mol`, `export-smiles` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `demos` (0.13.0). The reaction copy and export commands and `copy-smarts` and `export-smarts` already work. Running one returns "is not available right now: Arrives in [version]". Say so; do not retry.
## What no command does yet
-Drawing atoms and bonds at given positions, selecting particular atoms, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel.
+Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, filling the person's dialogs (atom list, R-group, abbreviation label), reading the whole structure back beyond what `get_context` and the analysis tools give (the formula, SMILES and CXSMILES in `stereo`, properties, issues and substructure hits), rendering an image or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel.
diff --git a/.agents/skills/formchem-skillset/EVALS.json b/.agents/skills/formchem-skillset/EVALS.json
index 8ed80a71..46a20dac 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.4.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.6.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.",
"evals": [
{
"id": 1,
@@ -111,10 +111,62 @@
"Makes the gesture preview through client.preview while dragging and commit once with commitDraft on pointer up",
"Confirms one undo step per drag and none after Escape"
]
+ },
+ {
+ "id": 11,
+ "name": "stoichiometry-panel-and-grid-disagree",
+ "prompt": "The FormChem stoichiometry panel says 8.19 mmol but the grid drawn on the page says 9.0 mmol for the same step. Fix it.",
+ "files": [],
+ "expected_behavior": [
+ "Loads reactions and reads frontend/src/chem/stoich.ts, canvas/render/table.ts and the stoich paragraphs of docs/FORMAT.md",
+ "Keeps one window computation (chem/stoich.ts) with the scale-wins precedence of the engine's stoich.py instead of adding another",
+ "Checks AC11.1 (8.19 mmol, 9.83 mmol, 0.713 mL) in the panel, the drawn grid and GET .../stoich",
+ "Logs the reason in frontend/HASHOUT_LOG.md and adds no test files"
+ ]
+ },
+ {
+ "id": 12,
+ "name": "anchored-arrow-left-behind",
+ "prompt": "In FormChem, when I move a structure, the electron-pushing arrow anchored to its oxygen stays where it was.",
+ "files": [],
+ "expected_behavior": [
+ "Loads annotations and reads canvas/render/anchors.ts, arrow.ts and objects.ts",
+ "Checks that the arrow kind's deps list the anchored fragments so the renderer re-lays it out when they change",
+ "Verifies with a MutationObserver that one move changes only the atom's nodes and the anchored arrow, without rebuilding the layer"
+ ]
+ },
+ {
+ "id": 13,
+ "name": "new-check-code",
+ "prompt": "Add a FormChem structure check that warns when a carbon carries a +3 charge drawn as a label, with a fix that does nothing new.",
+ "files": [],
+ "expected_behavior": [
+ "Loads stereo-and-queries and opens its references/routes-and-codes.md before editing",
+ "Adds the code in backend/app/services/chem/check.py with a SEVERITY entry and no fix (FIX only names existing analysis routes such as wedges or expand)",
+ "Adds the row to routes-and-codes.md and docs/ANALYSIS.md and a backend HASHOUT entry, and does not put a transaction in the issue"
+ ]
+ },
+ {
+ "id": 14,
+ "name": "tauri-cli-bump",
+ "prompt": "The tauri crate in Cargo.lock moved to 2.13.1; update FormChem so ./build_app still builds.",
+ "files": [],
+ "expected_behavior": [
+ "Loads desktop and states the rule that @tauri-apps/cli major.minor must equal the tauri crate's",
+ "Sets @tauri-apps/cli in frontend/package.json to a 2.13 release in the same change as package-lock.json, checking the @tauri-apps/plugin-* packages against their tauri-plugin-* crates",
+ "Runs ./formchem desktop check (not a full tauri build on a small machine) and records the bump in the HASHOUT log"
+ ]
}
],
"trigger_evals": [
{"query": "add an MCP tool to formchem", "should_trigger": true},
+ {"query": "formchem shows (S) on the wrong side of the stereocentre after contracting CO2H", "should_trigger": true},
+ {"query": "fix formchem's SMARTS export for atom lists in services/chem/query.py", "should_trigger": true},
+ {"query": "formchem build_app stops with the Tauri CLI did not install", "should_trigger": true},
+ {"query": "what is the cLogP of the structure in my FormChem drawing?", "should_trigger": false},
+ {"query": "formchem's perceive reactions picks the wrong reactants for a vertical arrow", "should_trigger": true},
+ {"query": "add a new glassware template to the formchem template library", "should_trigger": true},
+ {"query": "the curved arrow in formchem's renderer draws its head on the wrong side", "should_trigger": true},
{"query": "the formchem title bar flickers when I switch themes, fix it", "should_trigger": true},
{"query": "wire the extensions router into formchem's backend/app/main.py", "should_trigger": true},
{"query": "bump formchem to 0.2.1", "should_trigger": true},
@@ -140,6 +192,7 @@
{"query": "release formVFX 0.62.0", "should_trigger": false},
{"query": "update the extension catalogue page in FormPortal", "should_trigger": false},
{"query": "scaffold a Tauri 2 shell for my new todo app", "should_trigger": false},
- {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false}
+ {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false},
+ {"query": "map the atoms of the reaction in my open FormChem drawing", "should_trigger": false}
]
}
diff --git a/.agents/skills/formchem-skillset/SKILL.md b/.agents/skills/formchem-skillset/SKILL.md
index 06cdb174..bc0400e8 100644
--- a/.agents/skills/formchem-skillset/SKILL.md
+++ b/.agents/skills/formchem-skillset/SKILL.md
@@ -1,17 +1,17 @@
---
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 (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem file package, molfile and SMILES import, the y axis), the engine document store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings per fragment), the SVG canvas renderer patching on every edit, drawing tools (bond, chain, ring: one undo step per drag), hover hotkeys, hit testing at any zoom, selection, the window shell, title bar, themes, menus, the agent dock, Form extensions, adding an MCP tool, the Tauri shell, or a release and version bump. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis (their own skillsets), and not for standalone RDKit scripts outside the repo."
+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 (docs/FORMAT.md, model.ts, model.py, ops, undo, the fchem package), the engine store, the RDKit service (SMILES, InChIKey, masses, layout, warnings, CIP and enhanced stereo, wedges, abbreviations, queries, SMARTS, R-groups, properties, the structure check, isotope patterns), reactions (perception, Indigo mapping, balance, stoichiometry, RXN, roles), the SVG canvas renderer and marks, drawing tools, hover hotkeys, hit testing, arrows, shapes, captions, templates, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell and desktop build, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck, and not for standalone RDKit scripts."
license: Apache-2.0
metadata:
author: nodemode-ai
- version: "0.4.0"
+ version: "0.6.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 as a sidecar.
-**Where FormChem is (0.4.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 adds the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. Reactions and annotations (0.5.0), stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled.
+**Where FormChem is (0.6.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 adds stereo, queries and analysis: enhanced stereo groups and the chiral flag in RDKit, the CIP report, wedge assignment, abbreviations and explicit hydrogens, query atoms and bonds, SMARTS, substructure search, V3000 query molfiles, R-groups and Markush enumeration, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the keyed marks layer, the chemistry commands and dialogs, Set Reaction Roles, and the Tauri CLI pin for the desktop build. Exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled.
## Subsystem map
@@ -23,6 +23,9 @@ Route every change to FormChem's code through this file. It maps the subsystems
| 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 and session, the actions behind File and Insert, the Analysis panel, local valence, rings, labels 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 | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.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 report, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, V3000 queries, Markush, properties, the structure check, the isotope pattern, their routes, tools, 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-edits.ts`, `app/chem-commands.ts`, `canvas/render/marks-*.ts`, the 0.6.0 dialogs in `ui/`, `docs/ANALYSIS.md` | `stereo-and-queries` |
| 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` |
@@ -39,7 +42,10 @@ 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)
+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)
+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
io/ -> registry only for the catalogue mirror
@@ -49,7 +55,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
+mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub;
+ routers/analysis imported lazily by the analysis tools
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
```
@@ -80,13 +87,16 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t
| A new field or object kind, an op or path problem, a validation error, coalescing, the `.fchem` package shape | `document-format` |
| SMILES, InChI, formula, masses, implicit hydrogens, valence errors, warnings, 2D clean-up or layout, a structure file reader or writer, the derived cache | `chemistry-engine` |
| Drawing on the canvas: how a bond, label or wedge renders, a drawing tool, a hover hotkey, snapping, hit testing, selection, zoom and pan, the tool rail, canvas right-click menus | `canvas` |
+| An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `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 |
| 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 |
| 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` |
| A new MCP tool, the commands catalogue, `./formchem agents`, skills, the manifest | `agents` |
-| Desktop build, sidecar, updater, Tauri commands, title bar overlay | `desktop` |
+| Desktop build, `build_app`, the Tauri CLI version, 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: insert a structure, run a menu command, hand off in the window | Not this pack: `formchem-harness` |
@@ -98,9 +108,10 @@ formchem-skillset/
SKILL.md this router, the subsystem map and the laws in short
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, canvas, window-shell, menus, dock,
- extensions, agents, desktop, release, clean-room
+ sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, 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
canvas/references/hover-keys.md the hover key map with the code that implements it
```
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 401642d7..b0021068 100644
--- a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md
+++ b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md
@@ -30,11 +30,11 @@ Give agents a small, honest tool surface that only describes what FormChem can d
4. Describe only what works now. A tool for a later phase lands in that phase.
5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`.
-## What agents can reach in 0.4.0
+## What agents can reach in 0.6.0
-- Six tools only. The drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present.
-- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, and the canvas commands as the 0.4.0 integration enables them) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`).
-- `mcp.py` describes 0.4.0: `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows.
+- Fourteen tools: the six of the shell; `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`), owned by `reactions`; and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure` (outside `MUTATING`, never asking), which reuse the analysis router's source rules through `_analysis_source` with a lazy import so mcp.py does not load RDKit at import, owned by `stereo-and-queries`. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, edit ops, `convert`) land in 0.8.0; do not add them early or describe them as present.
+- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands, `set-reaction-roles {role, objects}` and the 0.6.0 chemistry commands such as `assign-wedges`, `set-stereo-group-and`, `add-hydrogens` and `expand-abbreviation`) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`).
+- `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` text name the reaction tools, the analysis tools and the chemistry commands; `DRAWING_FROM = "0.8.0"` names when the atom and bond tools arrive. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows.
- `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing.
- A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window.
@@ -43,7 +43,7 @@ Give agents a small, honest tool surface that only describes what FormChem can d
- Agents in FormChem's own tabs send a live tab token in `x-formchem-inapp` and are never asked; everyone else goes through `consent.ask`. A refusal returns a sentence, never an exception.
- Window-only abilities are window tools over `/api/live` through `bridge.window_call`; the engine never fakes a window answer.
- The `handoff` live message is `{t: "handoff", agent, state, note, at}`; a window asks for the current list with `{t: "handoffs"}`.
-- The manifest is generated, never edited by hand.
+- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand; the generator writes the tools reference's `## Contents` list, which the skill validator requires past 100 lines.
## Gate
diff --git a/.agents/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md
new file mode 100644
index 00000000..c4cd61bd
--- /dev/null
+++ b/.agents/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md
@@ -0,0 +1,63 @@
+---
+name: annotations
+description: "FormChem's drawn objects beyond structures: the object kind registry in frontend/src/canvas/render (objects.ts, paint.ts, anchors.ts, arrow.ts, bracket.ts, shape.ts, line.ts, table.ts, tlc.ts, orbital.ts, image.ts, caption.ts, group.ts, bounds.ts), drawn-outline hit testing (canvas/hit-objects.ts), the annotation tools and handles in canvas/tools, captions and their x, y cache, z-order and groups (app/object-commands.ts), the template library (backend services/templates.py, data/templates, ui/template-dialog.ts, template-thumb.ts, home-templates.ts) and media upload and serving. Use when an arrow, bracket, shape, table, TLC plate, orbital, picture or caption draws, hits or moves wrong, an anchored arrow does not follow its atom, a z-order change flashes, a template is added, or a new object kind is built."
+---
+
+# Annotations
+
+## Purpose
+
+Draw every non-chemistry object from the document alone, patch it like a bond, and edit it with one transaction per gesture. Hands back a kind, tool or template change that keeps the zero-flash rule and the format contract.
+
+## Preconditions
+
+`canvas` holds the renderer, view and tool laws this builds on; `document-format` holds the object fields (FORMAT.md, Text, captions and the other kinds). Read both first.
+
+## File map
+
+| Path | Role |
+| --- | --- |
+| `canvas/render/objects.ts` | `OBJECT_KINDS` (kind to `{ view, deps?, derived? }`), `ObjectCtx`, `ObjectView {specs, box}`, `docChem`, `docCtx`, `objectView`, `objectDeps` |
+| `canvas/render/paint.ts`, `svg.ts` | shared stroke, fill, gradient, rotation and label helpers; `NodeSpec.kids` for nested gradients and clip paths |
+| `canvas/render/anchors.ts`, `arrow.ts` | anchor points (atom, lone pair, bond, between), anchored ends trimmed 0.15 bond lengths; one curve model for all 15 arrow types and 6 head kinds |
+| `canvas/render/` kind modules | `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`MediaCache`, `setMediaUrl`), `caption.ts`, `group.ts` |
+| `canvas/render/bounds.ts`, `canvas/hit-objects.ts` | `objectBox(obj, doc)` without a renderer; `hitObject` and `objectDistance` by drawn outline |
+| `canvas/render/renderer.ts` | the `objects` layer between `page` and `bonds`; `inOrder` moves only nodes out of place on a z-order change |
+| `canvas/tools/objects.ts` | `BoxTool` and the shared helpers (`snapEnd`, `boxFrom`, `fragmentAt`, `outermostGroup`, `ensureMediaMap`) |
+| `canvas/tools/` | `arrow.ts`, `curved.ts`, `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`uploadMedia`, `setMediaUploader`, `placeImage`), `caption.ts`, `handles.ts` (`objectHandles`, `dragHandle`), `transform.ts` (captions mapped last) |
+| `frontend/src/app/object-commands.ts` | `objectCommandDefs`: z-order per container, group, ungroup, `alignObjects`, `distributeObjects` |
+| `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/*.json` | the library: `catalogue`, `listing`, `fragment(id, bond_length)` with fresh ids; format in `docs/TEMPLATES.md` |
+| `frontend/src/ui/template-dialog.ts`, `template-thumb.ts`, `home-templates.ts`, `styles/templates.css` | Insert > Template, the SVG thumbnails, the Home section |
+| `backend/app/routers/documents.py` media routes, `services/store.py` `add_media`, `services/package.py` `sniff_image` | picture bytes held by the session until the window's transaction lists them |
+
+## Laws
+
+- **A kind is a registry entry, not a branch in the renderer.** A new kind adds a module with a pure `view(obj, ctx)` returning keyed specs and a box, plus `deps` for what else it reads (an anchored arrow lists its fragments, a caption its target). The renderer re-lays out on a change of the object, the style, the font epoch or the deps, and patches.
+- **Bounds and hits come from the drawing.** Tools, Arrange and hit testing use `objectBox` and `hitObject`, never a second geometry estimate; the old one read an arrow's bend in degrees as a length.
+- **One gesture, one transaction, one id.** A tool previews with a stable object id per gesture and commits once; an image commits only after the upload answered; Escape commits nothing.
+- **Captions follow their target.** With `target` and `offset` the caption is placed from the target's drawn box; `x`, `y` are a cache that `transform.ts` refreshes in the same transaction when the target moves, and moving the caption rewrites `offset`.
+- **Z-order is per container.** Page order and a group's `children` move separately with `move` ops computed on a working copy; a group's members are in no page order and are removed with the group.
+- **Templates and glassware are original data.** Nothing from another product's library (`clean-room`); fresh ids on every insert, fragments scaled to the drawing's bond length, shapes kept at size.
+- **Media is two steps.** POST stores bytes and returns the record; the window's one transaction lists `media[id]` and adds the image; the package writes only listed ids.
+
+## Procedure
+
+1. For a drawing fault, build a scratch drawing outside the repo with one of each kind and open it in the built window served by the engine; watch it under 4x CPU throttling with a MutationObserver over `.fc-app`.
+2. Change the kind module, then bounds or hits if the shape changed, then the tool.
+3. A new field is a FORMAT.md, `model.ts` and `model.py` change together (`document-format`); a new tool needs a rail group, an inline currentColor icon in `ui/icons.ts` and its strings through `t()`.
+4. Log the reason in `frontend/HASHOUT_LOG.md` (entries 108 to 124 and 127 hold the current ones).
+
+## Gate
+
+- [ ] `cd frontend && npx tsc --noEmit` is clean.
+- [ ] Drawing, moving and deleting the object each add exactly one undo step; moving an anchored atom changes only that atom's label and the arrows anchored to it.
+- [ ] A z-order command and a new object create or move only their own nodes (MutationObserver), and nothing flashes.
+- [ ] A template inserted from the dialog and from Home is one undo step; a picture survives save, close and reopen.
+
+## Hands back
+
+The changed kind, tool or template files, the contract text if a field changed, and the gate results.
+
+## Owned resources
+
+None of its own: the object fields are in `docs/FORMAT.md` and the template format in `docs/TEMPLATES.md`.
diff --git a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md
index a1a7ede7..20e43a6d 100644
--- a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md
+++ b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md
@@ -20,7 +20,9 @@ Let the person draw at the speed of thought while the document stays the only tr
| `canvas/view.ts` | `CanvasView`: mounts the renderer, owns viewport, zoom and pan, pointer and key routing, hover, selection, the band, the keyboard atom cursor, `setClient`, at most one `renderer.update` per animation frame |
| `canvas/hit.ts`, `selection.ts` | Hit testing and region selection on model geometry; selection sets and helpers |
| `canvas/text-editor.ts`, `canvas/context.ts` | The in-place label and text editor; right-click menus for atom, bond, selection and background (`deleteSelectionOps`) |
-| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest) |
+| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups |
+| Stereo and query marks (0.6.0) | `render/marks-layer.ts` (`ChemMarks`, one keyed layer cached per fragment; replaced `render/stereo.ts`), `marks-stereo.ts`, `marks-query.ts` and `canvas/marks-options.ts` belong to the `stereo-and-queries` specialist; the view toggles reach the renderer through `RenderDisplay.enhancedStereo`, `queryMarks` and `groupColours` |
+| Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text |
| `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper |
| `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key |
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 e0ab61c4..12b5a79d 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
@@ -20,13 +20,15 @@ Compute everything chemical in one place, from the drawing as the person drew it
| `chem/mass.py` | `average_mass`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `isotope_pattern`, `properties(conv)` |
| `chem/layout.py` | `compute_coords(frag, ids, bond_length, fixed)` (CoordGen, RDKit fallback), `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move) |
| `chem/io.py` | `detect`, `read_text`, `read_file` (`ParseResult` with fragments, warnings, reaction), `export`, `to_molfile`, `to_smiles`; SDF, RXN, reaction SMILES, CML, cdxml and cdx (Indigo), InChI; at most 1000 records per call |
-| `chem/abbrev.py` | 75 built-in abbreviations with attachment SMILES; `resolve`, `element_like`, `reversed_label` |
+| `chem/abbrev.py` | 106 built-in abbreviations in six categories plus the person's `abbreviations.json`; `resolve`, `element_like`, `reversed_label`, `library`, `match` |
| `chem/derive.py` | `derive_fragment(frag, expansions, rev)`, `derive_document(doc, rev, only)`, `content_key`, an LRU cache of 2048 fragments |
| `backend/app/routers/chem.py` | `POST /api/chem/parse`, `/derive`, `/layout`, `/convert`, `/properties`; 422 for bad input, 413 over 20 MB of text, at most 5000 atoms |
| `backend/app/services/store.py` | `schedule_derive` and `_derive_loop`: after each transaction, derive in a thread on a deep copy and broadcast `{t: "derived", doc, rev, derived}` |
| `frontend/src/chem/` | Window-side rules: `elements.ts` (default valences, colours), `valence.ts` (implicit H, label text and side), `rings.ts` (smallest rings, double bond side), `label-text.ts`, `formula.ts` (`quickFormula`), `graph.ts` |
| `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 |
+| 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
diff --git a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md
index 5ab65a8b..58dfb4eb 100644
--- a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md
+++ b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md
@@ -36,7 +36,7 @@ These appear in `derived.fragments[fid].warnings` after every transaction.
| `charge_imbalance` | perceive.py | The pieces of one fragment carry a net charge |
| `engine_error` | derive.py | Any exception inside the engine for this fragment; values are empty |
-Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged.
+Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged. From 0.6.0 a charged atom is judged by its charge-shifted allowed list alone (RDKit 2025.09 flags a bare Na+), and `unknown_label` no longer fires for query atoms (lists, A, Q, X, M) or a bare `*`, which count as generics.
## Stereo warnings
@@ -47,6 +47,11 @@ Valence errors are not warnings: they are the separate `valence_errors` list (`{
| `conflicting_wedges` | convert.py | Wedges on one centre imply opposite configurations |
| `misplaced_wedge` | convert.py | The narrow end of a wedge (atom `a`) is not a stereocentre |
| `unknown_ez` | convert.py | A double bond drawn crossed (`either`) or next to a wavy bond |
+| `stereo_unknown` | perceive.py | A stereocentre on a wavy bond (marked unknown on purpose) (0.6.0) |
+| `undefined_double_bond` | perceive.py | A stereogenic double bond that is neither specified nor marked crossed or wavy, usually a substituent on the bond's line; cumulated bonds are skipped (0.6.0) |
+| `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` | convert.py | A malformed `stereo_groups` entry, an atom in two groups, or a grouped atom that is not a stereocentre (dropped from the group) (0.6.0) |
+
+The 0.6.0 analysis services (wedges, contract and expand, hydrogens, SMARTS, V3000, Markush, properties) and the structure check codes belong to the `stereo-and-queries` specialist, which lists them.
## Identifier warnings
diff --git a/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md
index 73aa0d56..0bd95c76 100644
--- a/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md
+++ b/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md
@@ -31,8 +31,14 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t
- Releases are built by formcompiler from `tauri.conf.json`; do not hand-build release artifacts.
- Do not run cargo build, tauri build or pyinstaller on a shared or small machine unless the task says so.
+## The Tauri CLI pin
+
+`@tauri-apps/cli` is a pinned dev dependency in `frontend/package.json` (2.12.6). The rule: its major.minor equals the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.7), and each `@tauri-apps/plugin-*` package shares major.minor with its `tauri-plugin-*` crate; bump them together in one change, with `package-lock.json`. Tauri refuses to build across minor versions. Until 0.6.0 package.json did not list the CLI, so `npm ci` installed no `tauri` binary and `./build_app` stopped with "the Tauri CLI did not install"; with the pin, the owner's `./build_app` on macOS arm64 (Python 3.14) built the app.
+
+`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck`, and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it.
+
## Gate
-- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable).
+- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable, CLI and crate share major.minor).
- [ ] The desktop dev run opens the window without a white flash and the engine answers `/api/health` on its port.
- [ ] Quitting the app ends the engine process on every platform touched.
diff --git a/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md
new file mode 100644
index 00000000..361ff088
--- /dev/null
+++ b/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md
@@ -0,0 +1,62 @@
+---
+name: reactions
+description: "FormChem's reaction code: perception of roles around reaction arrows (services/chem/geometry.py, reactions.py), Indigo atom mapping (mapping.py), balance and co-product suggestions (balance.py), stoichiometry in the engine (stoich.py) and the window (frontend/src/chem/stoich.ts, stoich-ops.ts, ui/stoich-panel.ts), reaction SMILES and RXN export and scheme import (rxnio.py, scheme.py, importers.py), the routes in routers/reactions.py, the derived reactions slot, the four MCP reaction tools, and the Reaction menu (app/reaction-commands.ts, engine/reactions-api.ts). Use when a step gets the wrong roles, a mapping or balance is wrong, the stoichiometry panel and the drawn grid disagree, an RXN round trip loses something, or a reaction route or command is added."
+---
+
+# Reactions
+
+## Purpose
+
+Keep one reading of a drawn reaction across the engine, the window and agents. The engine computes roles, mapping, balance and exchange formats from the drawing and writes them as ordinary transactions; the window computes stoichiometry for instant display by the same rules. Hands back changed modules with their contract text in `docs/FORMAT.md` and `docs/REACTIONS.md` in step.
+
+## Preconditions
+
+Read `docs/FORMAT.md` (Reactions on a page, the table `stoich` rule, the derived cache) and `docs/REACTIONS.md` (rules, routes, shapes). Load `document-format` before building ops by hand and `clean-room` before any new reaction feature.
+
+## File map
+
+| Path | Role |
+| --- | --- |
+| `backend/app/services/chem/geometry.py` | `object_box` for every kind (text by a 0.55 em per character estimate), `Frame(tail, head)` with `along`, `across`, `project` |
+| `chem/reactions.py` | `REACTION_ARROWS`, the constants `BAND_BONDS` 1.5, `ROW_BONDS` 2.5, `END_BONDS` 0.5, `JOIN_BONDS` 1.0; `infer_step`, `perceive_page`, `perceive_ops`, `preview`, `find_step`, `ReactionError` (422) and `NotFound` (404) |
+| `chem/mapping.py` | `map_ops(doc, step, mode, centres)` (`discard`, `keep`, `alter`), `clear_ops`; the order search and scoring |
+| `chem/balance.py` | `check`, `solve` (exact fractions), co-product candidates, `resonance`, `coefficient_ops` |
+| `chem/stoich.py` | `compute(doc, reaction, step, derived)`, `grid`, `table_ops`, unit formatting at three significant figures |
+| `chem/rxnio.py`, `chem/scheme.py` | export to `smiles`, `rxn`, `rxnv3000`; import and layout of reaction SMILES, RXN, CML and CDXML as a scheme (`insert_ops`) |
+| `chem/derive.py` `reaction_checks` | the derived `reactions` slot: step id to balance check, at most 64 steps |
+| `backend/app/routers/reactions.py` | every reaction route; `_commit` returns `{changed, tx, rev}` |
+| `backend/app/routers/mcp.py` | `t_perceive_reactions`, `t_map_reaction`, `t_export_reaction`, `t_reaction_stoichiometry`, `_apply` |
+| `frontend/src/chem/stoich.ts`, `chem/stoich-ops.ts` | the window's only stoichiometry computation (`computeStoich`, `stepFor`, `averageMass`) and the ops for one typed cell |
+| `frontend/src/ui/stoich-panel.ts`, `styles/stoich.css` | the panel in row 2 of `.fc-workspace` |
+| `frontend/src/canvas/render/table.ts` | draws a `stoich` table live from `computeStoich` |
+| `frontend/src/engine/reactions-api.ts`, `app/reaction-commands.ts` | the typed route client and the Reaction menu commands |
+| `frontend/src/chem/reaction-roles.ts`, `ui/roles-dialog.ts` | Set Reaction Roles (0.6.0): `reactionRoleOps` moves changed ids between role lists, sets `explicit: true` and drops coefficients and `stoich` entries that no longer fit, in one transaction; `canTakeRole` (fragments, text, captions, groups, images, shapes, tables, never the arrow); the keyed roles dialog. Window-side, no engine route |
+
+## Laws
+
+- **One reading of stoichiometry.** The engine's `stoich.py` and the window's `chem/stoich.ts` follow the same precedence: `scale_mmol` is the reference when present, else the limiting reagent's typed amount over its equiv, else the first amount; typed amounts beat typed equivalents. Never add a third computation; the renderer's own copy was deleted for disagreeing. Only typed values are stored, and the window's write rules (mass, volume or equiv replaces the other two; scale and the limiting reagent's amount replace each other) keep the two readings equal.
+- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true` (set by Set Reaction Roles, an agent's `set-reaction-roles {role, objects}`, or a reaction file); re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md.
+- **Routes are transactions.** A changing route builds ops on a copy and applies them with `STORE.apply`, returning `{changed, tx, rev}` and broadcasting the tx with the caller's `client`; no change means `changed: false` and no undo step. Agents go through `_apply` with origin `agent`.
+- **Map numbers are atom data.** `Atom.map` and `Bond.reacting` are the only places mapping lives, so chained steps share the numbers of a shared structure.
+- **Exchange keeps what the format can carry.** Kekulise RXN, keep reaction SMILES aromatic, put conditions on RXN line 4, report what is dropped as a warning code.
+
+## Procedure
+
+1. Reproduce with a scratch engine (`FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]`) and the route from `docs/REACTIONS.md`; the esterification (acetic acid + ethanol, H2SO4 above the arrow, ethyl acetate + water) and the two-step benzoic acid to N-ethylbenzamide scheme are the reference drawings.
+2. Change the service, then the route or tool, then the window client, in that order; a new answer field goes into `docs/REACTIONS.md`, a stored field into FORMAT.md, `model.ts` and `model.py` together.
+3. Log the reason in `backend/HASHOUT_LOG.md` or `frontend/HASHOUT_LOG.md` (entries 63 to 76 and 125 to 131 hold the current ones).
+
+## Gate
+
+- [ ] Esterification: perceive gives reactants acetic acid and ethanol, agent H2SO4, conditions text; a second perceive answers `changed: false`; map gives `complete`, one bond broken and one formed; check is balanced.
+- [ ] AC11.1: 1.00 g benzoic acid, 1.2 equiv thionyl chloride at 1.64 g/mL gives 8.19 mmol, 9.83 mmol, 0.713 mL in the route, the panel and the drawn grid. AC11.2: 1000 mg of 1151 mg theoretical is 86.9 %.
+- [ ] An RXN exported and imported again keeps roles, map numbers and the conditions text.
+- [ ] `backend/venv/bin/python -m compileall -q backend/app` and `cd frontend && npx tsc --noEmit` are clean; after any MCP change `./formchem agents sync --check` passes.
+
+## Hands back
+
+The changed modules, the contract text updated in the same change, and the gate results.
+
+## Owned resources
+
+None of its own: the rules and routes are in `docs/REACTIONS.md` at the repository root, which this file points to instead of copying.
diff --git a/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md
new file mode 100644
index 00000000..cb3ba469
--- /dev/null
+++ b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md
@@ -0,0 +1,53 @@
+---
+name: stereo-and-queries
+description: "FormChem's 0.6.0 stereo, query and analysis layer: enhanced stereo groups and the chiral flag into RDKit, the CIP stereo report, wedge assignment, the abbreviation library with contract and expand, explicit hydrogens, query atoms and bonds as one SMARTS-built query molecule, SMARTS in and out, substructure search, V3000 query molfiles with R-group blocks, Markush enumeration, properties with method labels, the structure check codes, the isotope pattern, the /api/analysis router, the four analysis MCP tools, and the window side (analysis-api.ts, chem-edits, chem-commands, the keyed marks layer, the dialogs, the check panel, the properties section and isotope plot). Use when a CIP label, stereo group, wedge, abbreviation, query, SMARTS, R-group, property, check issue or isotope peak is wrong, or a route, command, mark or check code is added."
+---
+
+# Stereo and queries
+
+## Purpose
+
+Keep the chemistry of 0.6.0 in one shape: the engine (RDKit) computes and proposes, the window commits one transaction per command, and every number carries its method. The doc is `docs/ANALYSIS.md`; the reasons are in `backend/HASHOUT_LOG.md` 78 to 98 and `frontend/HASHOUT_LOG.md` 133 to 148.
+
+## File map
+
+| Path | Role |
+| --- | --- |
+| `backend/app/services/chem/convert.py` | `_read_groups`, `apply_groups` (stereo groups and `chiral` into RDKit after perception), `groups_from_mol`, `_query_label` (query atoms and bare `*` are generics) |
+| `chem/stereo.py` | `report` (centres, double bonds, axes, state, group label, CXSMILES), `regroup`, `groups_tx`, `preview`, `rewedge` (from the drawing, wanted CIP or 3D) |
+| `chem/perceive.py` | `stereo_unknown`, `undefined_double_bond`, `not_ez_bonds` (cumulenes), the charged-atom valence rule |
+| `chem/abbrev.py`, `chem/superatom.py` | 106 built-ins plus `abbreviations.json`; `match`, `PREFERRED`; `contract` and `expand` keeping ids |
+| `chem/hydrogens.py` | `add_hydrogens`, `remove_hydrogens` |
+| `chem/query.py`, `chem/search.py` | `query_mol`, `to_smarts`, `from_smarts`, `parse_atom_smarts`; `substructure` |
+| `chem/v3000.py`, `chem/markush.py` | query molfile `write` and `read` (FormChem's own RGROUP reader); `member_attachments`, `enumerate_structures` |
+| `chem/props.py`, `chem/check.py`, `chem/isotopes.py` | `compute` with `method` and `note`; `check` with `SEVERITY`, `FIX`, `SKIP`; `from_counts`, `pattern`, `parse_formula` |
+| `backend/app/routers/analysis.py` | every `/api/analysis` route; `source` (stateless or `doc`), `finish` (`apply`), `_ids_of` |
+| `backend/app/routers/mcp.py` | `t_properties`, `t_check_structure`, `t_stereo`, `t_substructure`, `_analysis_source` (lazy router import) |
+| `frontend/src/engine/analysis-api.ts` | the only caller of `/api/analysis`; `sourceFor`, defensive readers |
+| `frontend/src/app/chem-edits.ts`, `app/chem-commands.ts` | window-side op builders; `registerChemCommands`, `CHEM_MENU_ITEMS`, `chemContextItems` |
+| `frontend/src/canvas/render/marks-layer.ts`, `marks-stereo.ts`, `marks-query.ts`, `canvas/marks-options.ts` | `ChemMarks` keyed layer and its view toggles |
+| `frontend/src/ui/` | `periodic-grid`, `atom-list-dialog`, `rgroup-dialog`, `abbreviation-dialog`, `stereo-popover`, `query-menus`, `structure-check`, `analysis-properties`, `isotope-plot`, `markush-dialog` |
+| `references/routes-and-codes.md` | the routes with their bodies and answers, the check codes by severity, the warning codes of each service. Open before adding a route, a code or a reader |
+
+## Rules
+
+- **Plain fields in the window, RDKit in the engine.** Atom lists, generic queries, query bonds and topology, stereo groups, the chiral flag and R-group definitions are field edits FORMAT defines: build them in `chem-edits.ts` and commit at once. Anything that needs perception (hydrogens, contract, expand, wedges, the check, properties, search, Markush, SMARTS) is an engine route that answers `tx: {label, ops}`.
+- **One transaction per command.** The window commits the engine's ops once, across fragments, and only if every fragment record it sent is still current; otherwise it says the drawing changed. A route with `doc` and `apply: true` applies on the engine side instead. Never commit per fragment.
+- **Groups go in after perception.** `apply_groups` runs after stereo perception so only real centres are grouped; anything that changes `stereo_groups` or `chiral` must stay in `derive.FRAGMENT_FIELDS` or cached CXSMILES goes stale.
+- **Chiral flag 0 reads absolute.** A deliberate deviation from the clean-room spec (most files write 0 for enantiomers); do not "fix" it without the owner.
+- **Ids survive contract and expand.** Expansion-internal ids are not live document ids (`_ids_of`); expand restores them unless they clash.
+- **Every property names its method.** A new property row has `method` (the RDKit call) and `note` (in words), and the window's `PROPERTY_ROWS` gets a reserved width.
+- **A fix is a command name.** A check issue names its repairing route in `fix`, never a transaction; add the code to `SEVERITY` (and `FIX` if repairable) and to the window's row text.
+- **Marks are keyed.** New marks are specs in `marks-stereo.ts` or `marks-query.ts`, cached per fragment by `ChemMarks`; explicit fills, no CSS colours; never rebuild the layer.
+- **Agents read through tools, change through commands.** Analysis tools stay read-only and outside `MUTATING`; a changing chemistry command is a window command agents reach with `run_command`.
+
+## Known gaps (do not paper over)
+
+Allene axial chirality and drawn atropisomers are not perceived; link nodes and variable attachment are not built; SMARTS import draws aromatic rings as single bonds (fix: order 1.5 when both ends are aromatic); Markush `count` is before dedup and if-then; Export SMARTS copies in the desktop shell until 0.7.0.
+
+## Gate
+
+- [ ] `backend/venv/bin/python -m compileall -q backend/app` is clean; `cd frontend && npx tsc --noEmit` is clean.
+- [ ] A scratch script outside the repo checks the AC5.3 CIP table (L-alanine S, meso-tartaric R and S, pentane-2,3,4-triol S, r, R) and ibuprofen properties (cLogP 3.07, TPSA 37.3) and isotopes (CH2Cl2 M+2 63.92, C6H5Br M+2 97.45).
+- [ ] Contract then expand gives back the same atom ids and coordinates; each command added exactly one undo step.
+- [ ] Under 4x CPU throttling a mark toggle or a property refresh patches nodes only (MutationObserver), and the properties section keeps its height.
diff --git a/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md
new file mode 100644
index 00000000..a90f8fb6
--- /dev/null
+++ b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md
@@ -0,0 +1,60 @@
+# Analysis routes and codes
+
+The `/api/analysis` routes of `backend/app/routers/analysis.py`, the structure check codes of `chem/check.py` and the warning codes of each 0.6.0 service, as of 0.6.0. `docs/ANALYSIS.md` has the full answer shapes; when this page and the code differ, the code wins and this page is the bug.
+
+## Contents
+
+- Request rules
+- Routes
+- Check codes by severity
+- Service warning codes
+
+## Request rules
+
+- Source, stateless: `fragment`, optional `expansions`, optional `members` (fragment id to fragment). From a document: `doc` plus `object` or `objects`; expansions and members come from the document.
+- Changing routes answer `tx: {label, ops}` (paths from the document root). `doc` with `apply: true` applies it (origin `user`) and adds `applied: {tx, rev}` or `applied: null`.
+- Errors: 422 `{detail}` sentence, 404 unknown doc or object, 409 `{detail: {message, errors}}`, 413 over 20 MB. A per-fragment read puts `{error}` in a failing fragment's slot.
+- Validators are chem.py's (`_fragment`, `_expansions`, `_bond_length`, `_num`, `MAX_TEXT`); reuse them for a new route so messages match.
+
+## Routes
+
+| Route | Changes | Key answer fields |
+| --- | --- | --- |
+| `GET abbreviations` | no | `abbreviations [{label, reversed, smiles, category, source}]`, `user_file`, `user_errors` |
+| `POST properties` | no | `fragments {fid: {rows, values, lipinski, veber, elemental_analysis, excluded, engine, warnings}}` |
+| `POST cip` | no | `fragments {fid: {atoms, bonds, centres, double_bonds, axes, chiral, stereo_groups, smiles, cxsmiles, warnings}}` |
+| `POST check` (`query?`) | no | `fragments {fid: {issues, counts, engine}}` |
+| `POST stereo-groups` (`set?`, `chiral?`) | tx when asked | `groups`, `chiral`, `cxsmiles`, `warnings` |
+| `POST wedges` (`atoms?`, `cip?`, `coords3d?`) | tx | `changed`, `cip`, `warnings` |
+| `POST expand` (`atoms?`, `bond_length?`) | tx | `expanded {abbreviation atom: [ids]}` |
+| `POST contract` (`atoms`, `label?`) | tx | `atom`, `expansion`, `label` |
+| `POST add-h`, `POST remove-h` (`atoms?`) | tx | `added`; `removed`, `kept` |
+| `POST smarts/export` (`atoms?`) | no | `smarts` |
+| `POST smarts/import` (`text`) | no | `fragments [fragment]` |
+| `POST substructure` | no | `hits [{object, atoms, bonds, map}]`, `count`, `by_object`, `truncated`, `smarts` |
+| `POST molfile`, `POST molfile/import` | no | `text`; `fragments [scaffold, member...]` |
+| `POST markush` (`limit?`, `force?`) | no | `count`, `structures [{smiles, formula, choice}]`, `truncated`, `groups` |
+| `POST isotope-pattern` (`threshold?`), `GET isotope-pattern?formula=` | no | `formula`, `monoisotopic`, `average`, `peaks [{mass, mz, abundance, fraction}]`, `adducts [{ion, charge, mz}]` |
+
+## Check codes by severity
+
+| Severity | Codes |
+| --- | --- |
+| error | `valence`, `bad_bond`, `engine_error`, `bad_expansion` |
+| warning | `hypervalent`, `unknown_label`, `misplaced_wedge`, `ambiguous_wedge`, `conflicting_wedges`, `wedge_between_centres`, `ring_double_bond_stereo`, `stereo_ignored`, `undefined_double_bond`, `unusual_charge`, `unknown_isotope`, `abbreviation_bonds`, `abbreviation_valence`, `overlapping_atoms`, `short_bond`, `long_bond`, `aromatic_outside_ring`, `cannot_kekulise`, `unsupported_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre`, `rgroup_undefined`, `rgroup_member_missing`, `rgroup_bonds`, `cip_failed` |
+| info | `undefined_stereocentre`, `stereo_unknown`, `unknown_ez`, `charge_imbalance`, `query_feature`, `uncommon_isotope`, `crossing_bonds`, `label_collides`, `rgroup_unused`, `rgroup_attachment_guessed` |
+
+`fix: "wedges"` for the wedge codes, `fix: "expand"` for the abbreviation codes. `SKIP` drops `query_ignored` and the InChI remarks.
+
+## Service warning codes
+
+| Service | Codes |
+| --- | --- |
+| derive and perceive | `stereo_unknown`, `undefined_double_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` |
+| wedges | `cip_unreachable`, `wedge_mismatch` |
+| contract, expand | `label_mismatch`, `stereo_dropped`, `abbreviation_bonds` |
+| hydrogens | `stereo_changed`, `hydrogens_kept` |
+| SMARTS | `smarts_rgroups`, `smarts_stereo_groups`, `abbreviations_expanded`, `smarts_any_atom`, `bad_smarts`, `smarts_opaque`, `smarts_chirality`, `smarts_bond_simplified` |
+| V3000 | `v3000_query_lossy` |
+| Markush | `enumeration_truncated` |
+| properties, isotopes | `property_failed`, `incomplete` |
diff --git a/.claude/skills/formchem-harness/EVALS.json b/.claude/skills/formchem-harness/EVALS.json
index b9836b2d..079543e0 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, version 0.4.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.4.0 has drawings but no direct agent drawing tools (0.8.0); agents work through run_command and Form extensions, and several evals check that the agent stays inside that.",
+ "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.6.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.6.0 has drawings, four reaction tools and four read-only analysis tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction and analysis tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 17 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O.",
"evals": [
{
"id": 1,
@@ -138,10 +138,79 @@
"Calls extensions_list and uses an extension command only if one states that it reads the drawing or checks structures",
"Reports valence errors only from that extension's answer; with no suitable extension, says the agent cannot read the rows and points the person at the Check Structure dialog instead of computing valence itself"
]
+ },
+ {
+ "id": 13,
+ "name": "map-and-export-the-drawn-reaction",
+ "prompt": "Map the atoms of the esterification I drew in FormChem and give me the reaction SMILES.",
+ "files": [],
+ "expected_behavior": [
+ "Calls get_context, then perceive_reactions, and keeps the reaction and step ids it returns",
+ "Calls map_reaction with those ids (mode left at discard) and reports the mapped count and the bonds broken and formed from its answer",
+ "Calls export_reaction with format smiles and quotes the text exactly, passing on any conditions_dropped warning",
+ "Ends with a ready handoff naming the drawing and that Undo removes the mapping"
+ ]
+ },
+ {
+ "id": 14,
+ "name": "yield-without-amounts",
+ "prompt": "What is the theoretical yield of my FormChem reaction?",
+ "files": [],
+ "expected_behavior": [
+ "Calls perceive_reactions, then reaction_stoichiometry for the step",
+ "Quotes the theoretical yield with its unit only when the answer gives one, never computing it from its own molecular weights",
+ "When no amounts are typed, posts a question handoff asking the person to type a mass, volume, equivalents or scale in the Stoichiometry panel, and says no tool can type them"
+ ]
+ },
+ {
+ "id": 15,
+ "name": "druglike-properties-with-methods",
+ "prompt": "Is the structure in my FormChem drawing drug-like? Give me cLogP and TPSA.",
+ "files": [],
+ "expected_behavior": [
+ "Calls get_context, then the properties tool (not compute-properties through run_command)",
+ "Quotes cLogP 3.07 and TPSA 37.3 with their units and the methods the tool names (Crippen.MolLogP, rdMolDescriptors.CalcTPSA), and the Lipinski and Veber verdicts as the tool gives them",
+ "Does not compute any value with its own chemistry and present it as FormChem's",
+ "Posts no approval-gated call for this read-only question"
+ ]
+ },
+ {
+ "id": 16,
+ "name": "racemic-and-group",
+ "prompt": "In FormChem, mark the stereocentre of my ibuprofen as racemic and tell me what the CXSMILES becomes.",
+ "files": [],
+ "expected_behavior": [
+ "Calls stereo first to find the centre and its current label S",
+ "Says the command acts on the canvas selection and either asks the person to select the centre or explains what select-all would include, then runs set-stereo-group-and once",
+ "Calls stereo again and quotes the new CXSMILES with its &1 group exactly as returned",
+ "Ends with a ready handoff saying the change is one undo step"
+ ]
+ },
+ {
+ "id": 17,
+ "name": "find-carboxylic-acids",
+ "prompt": "Which structures in my FormChem drawing have a carboxylic acid?",
+ "files": [],
+ "expected_behavior": [
+ "Calls substructure with a SMARTS such as C(=O)[OH] (or [CX3](=O)[OX2H1])",
+ "Reports the hit count and the fragment ids from the answer, naming the structures by what get_context or the tools say",
+ "Does not run search-substructure through run_command to get the answer, since its result is a selection the agent cannot read"
+ ]
}
],
"trigger_evals": [
{"query": "what can FormChem do at the moment", "should_trigger": true},
+ {"query": "what is the cLogP and TPSA of the molecule in my FormChem drawing?", "should_trigger": true},
+ {"query": "is the stereocentre in my formchem drawing R or S?", "should_trigger": true},
+ {"query": "run a structure check on my FormChem drawing and list the warnings", "should_trigger": true},
+ {"query": "find every carboxylic acid in my formchem drawing with SMARTS", "should_trigger": true},
+ {"query": "make water an agent instead of a product in my FormChem reaction", "should_trigger": true},
+ {"query": "add enhanced stereo group support to formchem's backend/app/services/chem/stereo.py", "should_trigger": false},
+ {"query": "compute the Lipinski properties of this SMILES with an RDKit script", "should_trigger": false},
+ {"query": "map the atoms of the reaction in my formchem drawing", "should_trigger": true},
+ {"query": "export the drawn reaction in FormChem as an RXN file", "should_trigger": true},
+ {"query": "what is the limiting reagent in my formchem scheme?", "should_trigger": true},
+ {"query": "insert a cyclohexane chair template in FormChem", "should_trigger": true},
{"query": "open preferences in formchem", "should_trigger": true},
{"query": "is the formchem engine running? I get connection refused", "should_trigger": true},
{"query": "run the hello command of my formchem extension", "should_trigger": true},
@@ -167,6 +236,8 @@
{"query": "run the show-grid command in formvis", "should_trigger": false},
{"query": "install the molecule tools extension from FormPortal", "should_trigger": false},
{"query": "convert this SDF file to SMILES with RDKit in a Python script", "should_trigger": false},
- {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false}
+ {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false},
+ {"query": "fix the perception distances in formchem's services/chem/reactions.py", "should_trigger": false},
+ {"query": "balance this equation for me: Fe + O2 -> Fe2O3", "should_trigger": false}
]
}
diff --git a/.claude/skills/formchem-harness/SKILL.md b/.claude/skills/formchem-harness/SKILL.md
index e8eb6343..5c7d6f83 100644
--- a/.claude/skills/formchem-harness/SKILL.md
+++ b/.claude/skills/formchem-harness/SKILL.md
@@ -1,25 +1,25 @@
---
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 or insert a structure from SMILES, clean up a drawing, undo, select all, zoom, run a FormChem menu command or extension, read or change the open fchem drawing through an extension, check a structure for valence errors, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff) are available. Covers connecting on 127.0.0.1:8220 when the tools do not show up, the approval question, the commands catalogue, the extension drawing contract and handoff. There are no direct drawing tools before 0.8.0, so it also covers saying so plainly. Not for changing FormChem's source code (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for 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: insert a structure from SMILES or a template, undo, run a menu command or extension, read the open fchem drawing, perceive or map a reaction, export reaction SMILES or RXN, read stoichiometry, set reaction roles, get cLogP, TPSA or Lipinski, check a structure, read R/S labels and stereo groups, find a substructure by SMARTS, add hydrogens, contract an abbreviation, define an R-group, or asks what FormChem can do, and FormChem is named or its tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry, properties, check_structure, stereo, substructure) are available. Covers 127.0.0.1:8220, approval, handoff and what waits for 0.8.0. 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.4.0"
+ version: "0.6.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.
-## What exists today (0.4.0)
+## What exists today (0.6.0)
-FormChem 0.4.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws with tools and hover keys. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help.
+FormChem 0.6.0 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 where the person draws structures with tools and hover keys. 0.5.0 added reactions and annotations (arrows, brackets, shapes, tables, TLC plates, captions, reaction perception, atom mapping, balance, the Stoichiometry panel, 206 templates, Find and rulers). 0.6.0 adds stereo, queries and analysis: CIP labels and enhanced stereo groups, Assign Wedges, abbreviations, explicit hydrogens, atom lists and query bonds, R-groups and Markush enumeration, substructure search and SMARTS, calculated properties with their methods, the isotope pattern, the Check Structure panel and Set Reaction Roles. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help.
-The MCP server still has six tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server.
+The MCP server has fourteen tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server.
-**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected), undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, clean up, lay out, check structure and zoom (`window-commands`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`).
+**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out and zoom (`window-commands`), plus the chemistry commands (wedges, stereo groups, hydrogens, abbreviations, query features, R-groups). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry and balance, and set roles with `set-reaction-roles {role, objects}` (`reactions`). Through the analysis tools: properties with their methods, the structure check, CIP labels and stereo groups, and substructure hits by id (`structure-analysis`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`).
-**What it cannot do yet.** There are no direct drawing tools: no drawing atoms and bonds by call, no reading SMILES or InChIKey back through MCP (the formula in `get_context` is all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work.
+**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading the whole structure or its InChIKey back through MCP (the formula in `get_context`, the SMILES and CXSMILES in `stereo` and the other tools' answers are all), no rendering, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work.
## Doctrine (applies to every route)
@@ -39,6 +39,8 @@ formchem-harness/
sub-skills/
session-and-connection/ connecting, get_context, the approval question, errors
window-commands/ drawing work through run_command; references/command-catalogue.md
+ reactions/ the four reaction tools, the Reaction menu commands and Set Reaction Roles
+ structure-analysis/ the four analysis tools and the stereo, hydrogen, abbreviation and query commands
extension-drawings/ reading and changing the drawing through a Form extension
handoff/ handoff states, notes, clearing, what the person sees
visual-qa/ checking what the person sees without a render tool
@@ -52,12 +54,14 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere
| --- | --- |
| No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` |
| "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` |
-| Draw or insert a structure from SMILES, open a drawing or structure file, undo, save, select all, clean up, zoom | `window-commands` |
-| Read atoms, bonds, SMILES, InChIKey or valence errors from the open drawing, change it by id, check a structure | `extension-drawings` (and `window-commands` when no extension fits) |
+| Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` |
+| The reaction in the drawing: its steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` |
+| Properties (cLogP, TPSA, Lipinski), a structure check, R or S, stereo groups, a substructure or SMARTS match, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` |
+| Read atoms, bonds, InChIKey or valence errors from the open drawing, change it by id | `extension-drawings` (and `window-commands` when no extension fits) |
| Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` |
| Tell the person you are done, ask them something, clear your note | `handoff` |
| Check what the person sees, did the command work, which commands are on | `visual-qa` |
-| Draw atom by atom, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists |
+| Draw atom by atom, place an arrow or shape, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists |
| Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` |
## When something fails
@@ -74,11 +78,15 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere
| "takes no parameters" | The command does not accept arguments in this build | Run it without `params`; if it prompts, ask the person to fill the prompt |
| "Could not read the SMILES" | `insert-smiles {smiles}` got a string the engine cannot parse; nothing was inserted | Check the SMILES, fix it once, or ask the person |
| "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path |
+| "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it |
+| An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns |
+| "Give smarts, or query_object" or "is not a fragment of this drawing" | `substructure` has no pattern, or the query fragment id is wrong | Pass a SMARTS or a fragment id from the tools' answers |
+| A fragment slot holding `error` in an analysis answer | The engine could not read that fragment; the others are fine | Report it for that fragment and go on with the rest |
## Done means
- `get_context` was called first and its answer shaped the plan.
-- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, and requests beyond the commands were answered with "the drawing tools arrive in 0.8.0".
+- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, reaction numbers were quoted from the reaction tools, and requests beyond them were answered with "the drawing tools arrive in 0.8.0".
- Every command run returned without `isError`, or its error was reported to the person.
- 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 d73cfc33..cfef0fe0 100644
--- a/.claude/skills/formchem-harness/references/tools.md
+++ b/.claude/skills/formchem-harness/references/tools.md
@@ -1,9 +1,28 @@
# FormChem MCP tools
-Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 6 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`; edit the server, never this file. 14 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.
+## Contents
+
+- Tool kinds (the table below)
+- get_context
+- list_commands
+- run_command
+- extensions_list
+- extension_command
+- handoff
+- perceive_reactions
+- map_reaction
+- export_reaction
+- reaction_stoichiometry
+- properties
+- check_structure
+- stereo
+- substructure
+- Resource
+
| Tool | Kind |
| --- | --- |
| `get_context` | read-only |
@@ -12,10 +31,18 @@ Read-only tools never ask the person. An approval-gated tool asks the person in
| `extensions_list` | read-only |
| `extension_command` | approval-gated |
| `handoff` | approval-gated when it changes something |
+| `perceive_reactions` | approval-gated |
+| `map_reaction` | approval-gated |
+| `export_reaction` | read-only |
+| `reaction_stoichiometry` | read-only |
+| `properties` | read-only |
+| `check_structure` | read-only |
+| `stereo` | read-only |
+| `substructure` | read-only |
## get_context
-FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; dedicated drawing tools arrive in 0.8.0.
+FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in 0.8.0.
Arguments: none.
@@ -65,6 +92,88 @@ Tells the person where your work stands: working (still on it), ready (done, for
| `state` | working or ready or question or clear | no | |
| `note` | string | no | One short line for the person |
+## perceive_reactions
+
+Works out the reaction steps of a drawing from where its structures sit around the reaction arrows (before the tail: reactants, after the head: products, beside the arrow: agents and conditions text; plus signs join) and writes them to the drawing as one undo step. Steps someone set by hand are kept. Returns every reaction with its step ids.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Drawing id from get_context; may be left out when one drawing is open |
+| `page` | string | no | Page id; all pages when left out |
+
+## map_reaction
+
+Maps the atoms of one reaction step (reactant atom to product atom numbers) and marks the bonds broken, formed or changed in order, as one undo step. mode discard (default) maps from scratch, keep keeps the numbers already drawn, alter may change them, clear removes the mapping.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | |
+| `reaction` | string | no | Reaction id from perceive_reactions; the first reaction when left out |
+| `step` | string | no | Step id; the first step when left out |
+| `mode` | discard or keep or alter or clear | no | |
+
+## export_reaction
+
+One reaction step as reaction SMILES (format smiles) or an RXN file (rxn for V2000, rxnv3000), with its map numbers. Does not change the drawing.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | |
+| `reaction` | string | no | |
+| `step` | string | no | |
+| `format` | smiles or rxn or rxnv3000 | no | |
+
+## reaction_stoichiometry
+
+The stoichiometry of one reaction step worked out from the amounts the person typed in its grid and the molecular weights: moles, equivalents, masses, volumes, the limiting reagent, theoretical yields and the percent yield, plus the balance check. Does not change the drawing.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | |
+| `reaction` | string | no | |
+| `step` | string | no | |
+
+## properties
+
+Drug-like properties of the structures in an open drawing, per fragment: formula, MW, exact mass, cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis; every value names the RDKit method behind it.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `object` | string | no | One fragment id; absent: every fragment |
+
+## check_structure
+
+Checks the structures of an open drawing: valence errors, unusual charges, wedge problems, overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing and R-group gaps; each issue has a code, a severity (error, warning, info) and the atom and bond ids it concerns.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `object` | string | no | One fragment id; absent: every fragment |
+| `query` | boolean | no | True when the drawing is a search query, so query features are not reported |
+
+## stereo
+
+Stereochemistry of an open drawing per fragment: each stereocentre, stereogenic double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), whether it is defined, undefined or unknown, its enhanced stereo group (abs, and1, or1) and the CXSMILES that carries the groups.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `object` | string | no | One fragment id; absent: every fragment |
+
+## substructure
+
+Searches the fragments of an open drawing for a substructure given as SMARTS or as a query fragment drawn in the same drawing; returns every hit with its fragment id and the matched atom and bond ids.
+
+| Argument | Type | Required | Notes |
+| --- | --- | --- | --- |
+| `doc` | string | no | Document id from get_context (optional when one drawing is open) |
+| `smarts` | string | no | SMARTS pattern, such as C(=O)[OH] |
+| `query_object` | string | no | A fragment of the drawing to use as the query instead of smarts |
+| `objects` | array of string | no | Fragment ids to search; absent: all |
+| `chirality` | boolean | no | |
+| `max_hits` | integer | no | Most hits to return (default 1000) |
+
## 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/extension-drawings/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md
index 86da271d..98f99df2 100644
--- a/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md
+++ b/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md
@@ -17,7 +17,7 @@ Use an extension as the agent's hands on the drawing until FormChem has its own
## What an extension sees
- `document.read {what: "all"}`: a head (`id`, `title`, `rev`, `dirty`, `path`, `page`, `writable`, `mode`, `format`, `format_version`), the whole `document`, and `derived` when the engine's cache matches `rev`. `what` may also be `page`, `selection` or `json`.
-- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). This is the honest way to check a structure before `check-structure` arrives in 0.6.0.
+- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). From 0.6.0 the `check_structure` tool returns the full structure check by code and id (`structure-analysis`); the derived cache stays the way to read InChIKey and valence errors inside an extension.
- With no drawing open: `writable: false`, `page: null`. Check both before offering a change.
## What an extension can change
diff --git a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md
index 3707b779..0775514f 100644
--- a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md
+++ b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md
@@ -31,9 +31,9 @@ A handoff with a state changes what the person sees, so the first one from an ou
- A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?"
- No emoji, no markdown, no links the person cannot click.
-## In 0.4.0
+## In 0.6.0
-A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead").
+A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed", "Assigned wedges in Ibuprofen; the centre reads S". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead").
## Procedure
diff --git a/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md
new file mode 100644
index 00000000..90c83d04
--- /dev/null
+++ b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md
@@ -0,0 +1,59 @@
+---
+name: reactions
+description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem."
+---
+
+# Reactions
+
+## Purpose
+
+Answer reaction questions from what FormChem computes, not from the agent's own chemistry, and make reaction changes as undo steps the person sees. Hands back reaction and step ids, the engine's answers quoted as numbers, and a handoff naming what changed.
+
+## Preconditions
+
+`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. An agent cannot draw arrows or place structures by position before 0.8.0; `insert-smiles` and `insert-template` put things in the middle of the view, so a scheme is the person's to arrange.
+
+## Tools and commands
+
+| Goal | Call | Changes the drawing |
+| --- | --- | --- |
+| Find the steps and their roles | `perceive_reactions {doc?, page?}`: lists every reaction and step id, reactants, products, agents and conditions; steps set by hand say "(set by hand)" and are kept | yes, one undo step; "No change" when nothing moved |
+| Map atoms | `map_reaction {doc?, reaction?, step?, mode?}`: `discard` (default) maps from scratch, `keep` keeps drawn numbers, `alter` may change them, `clear` removes them; the answer gives map numbers and bonds broken and formed | yes, one undo step |
+| The reaction as text | `export_reaction {doc?, reaction?, step?, format?}`: `smiles`, `rxn` (V2000) or `rxnv3000`, with map numbers | no |
+| Amounts and yields | `reaction_stoichiometry {doc?, reaction?, step?}`: rows with mmol, equiv, mass, volume, the limiting reagent, the theoretical and percent yield, and the balance check | no |
+| Balance coefficients | `run_command {id: "balance-reaction"}` on the selected or first step; `check-reaction` opens the balance dialog for the person | yes, one undo step |
+| Insert a template | `run_command {id: "insert-template", params: {id: "[template id]"}}`; the ids come from the engine's `GET /api/templates` | yes, one undo step |
+| Paste a reaction | `paste-reaction` reads the person's clipboard; an agent cannot fill the clipboard, so it is the person's | yes |
+| The grid on the page | `stoichiometry-grid` inserts or refreshes the grid for the selected or first step; `show-stoichiometry` opens the panel for the person | yes for the grid |
+
+`doc` may be left out when one drawing is open; `reaction` and `step` default to the first. The two changing tools ask the person the first time like any change.
+
+## Procedure
+
+1. **Context.** `get_context`; name the drawing by title.
+2. **Steps first.** `perceive_reactions` before any step-level tool. Keep the reaction and step ids it returns; never guess ids. "No reaction arrow has structures before or after it" means the scheme is not drawn as FormChem reads it (structures within 2.5 bond lengths of the arrow's line, reagents within 1.5 of the arrow): say so and ask the person to move them.
+3. **One step at a time.** Pass the ids to `map_reaction`, `export_reaction` or `reaction_stoichiometry`. A step not found names `perceive_reactions` as the next call: run it once, then retry once.
+4. **Quote, do not compute.** Report formulas, masses, mmol and yields exactly as the tool printed them, with units. "Not balanced." with a suggestion is the engine's answer; offer `balance-reaction` only when the check suggests coefficients, and say "add the missing co-products first" when it suggests a co-product, which only the person can draw.
+5. **Amounts are the person's.** No tool types amounts into the grid. When the answer lacks amounts, ask in a question handoff for the masses, volumes, equivalents or scale to type into the Stoichiometry panel, then read again.
+6. **Hand off** what changed ("Mapped step 1 of Esterification: 7 atoms, one C-O bond formed; Undo removes it").
+
+## Rules
+
+- Roles come from geometry unless set by hand. `run_command {id: "set-reaction-roles", params: {role, objects}}` gives the listed object ids (fragments, text, captions, groups, images, shapes or tables; never the arrow) the role `reactant`, `product`, `agent`, `condition` or `none` in the step touching the selection, as one undo step, and marks the step as set by hand so `perceive_reactions` keeps it. Without `role` it opens a dialog for the person. Read the result back with `perceive_reactions` (it lists the step as set by hand). A step read from an RXN file keeps its roles too.
+- Reagents drawn above the arrow are not counted in the balance; a step whose atoms come from such a reagent reads as unbalanced. Say that instead of "the reaction is wrong".
+- Mapping the second of two chained steps replaces the map numbers of the structure they share. Warn before mapping a second step when the first is already mapped.
+- Coefficients are dropped from reaction SMILES and RXN (`coefficient_dropped`); text conditions are dropped from reaction SMILES (`conditions_dropped`). Pass the warnings on.
+
+## Gate
+
+- [ ] Every step-level call used ids returned by `perceive_reactions` in this session.
+- [ ] Every number reported came from a tool answer, with its unit.
+- [ ] Each changing call was reported with its undo step; no change was retried after a refusal.
+
+## Hands back
+
+Reaction and step ids, the quoted answers, and a ready or question handoff.
+
+## Owned resources
+
+None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands.
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 50bde3ab..f0f9e6e5 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
@@ -42,5 +42,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 six tools and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools.
+- [ ] The plan uses only the fourteen tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools.
- [ ] No change was attempted after a refusal.
diff --git a/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md
new file mode 100644
index 00000000..ae33befa
--- /dev/null
+++ b/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md
@@ -0,0 +1,69 @@
+---
+name: structure-analysis
+description: "Reads and edits the chemistry of an open FormChem drawing through the four MCP analysis tools (properties, check_structure, stereo, substructure) and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem."
+---
+
+# Structure analysis
+
+## Purpose
+
+Answer chemistry questions about the drawing with FormChem's own numbers, quoted with the method behind them, and make the stereo, hydrogen, abbreviation and query edits as undo steps the person sees. Hands back fragment, atom and bond ids, the tool answers quoted exactly, and a handoff naming any change.
+
+## Preconditions
+
+`get_context` has been called (`session-and-connection`) and lists the drawing. The analysis tools only read, so they never ask the person; the chemistry commands change the drawing and ask the first time, like any `run_command`.
+
+## The four analysis tools
+
+| Goal | Call | What comes back |
+| --- | --- | --- |
+| Properties | `properties {doc?, object?}` | per fragment: formula, MW, exact mass, cLogP, MR, TPSA (and with S and P), donors and acceptors (Lipinski and refined counts), rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts, elemental analysis; each row with `method` (the RDKit call) and `note` |
+| Structure check | `check_structure {doc?, object?, query?}` | issues `{code, severity, text, atoms, bonds, fix}` sorted errors first; `query: true` when the drawing is a search query |
+| Stereo | `stereo {doc?, object?}` | centres, double bonds and axes with label, `state` (defined, undefined, unknown) and group (`abs`, `and1`, `or1`), the stereo groups, the chiral flag and CXSMILES |
+| Substructure | `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | hits with the fragment id, matched atom and bond ids and the query-to-target map; `count`, `truncated` |
+
+`doc` may be left out when one drawing is open; `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`).
+
+## Chemistry commands (run_command)
+
+They act on the person's selection, or on the page when nothing is selected; the agent selects only with `select-all` or by inserting. Check `list_commands {id}` for params and the off reason first.
+
+| Command | Does |
+| --- | --- |
+| `assign-wedges` | redraws wedges and hashes of the stereocentres so they read unambiguously |
+| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | puts the selected centres into an abs, new AND or new OR group, or out of any |
+| `add-hydrogens`, `remove-hydrogens` | draws implicit H as atoms or folds them back; H that hold stereo, an isotope, a charge or a map number stay |
+| `expand-abbreviation`, `contract-abbreviation` | expands a selected label (or every one); contract opens a dialog for the person's label |
+| `set-atom-list`, the `set-query-bond-` commands, `clear-query-bond` | atom lists (a dialog) and query bonds on the selection |
+| `define-rgroup`, `enumerate-markush` | R-group definition and enumeration open dialogs for the person |
+| `copy-smarts`, `compute-properties`, `check-structure`, `search-substructure` | copy SMARTS to the person's clipboard, or open the panels; the tools above return the same data to the agent |
+
+## Procedure
+
+1. **Context.** `get_context`; name the drawing and pick fragment ids from the tool answers, never by guess.
+2. **Read with the tool, not the command.** For values, issues, labels or matches call the analysis tool; the command opens a panel the agent cannot read.
+3. **Quote with the method.** Report each value as the tool printed it, with its unit and method ("cLogP 3.07, Crippen.MolLogP; typical error 0.5 to 0.7 log units"). Never compute a property, a CIP label or a SMARTS match with your own chemistry and present it as FormChem's.
+4. **Stereo states matter.** An `undefined` centre has no label because nothing fixes it; say so instead of guessing R or S. Allene axial chirality and drawn atropisomers are not perceived in this version.
+5. **Change through commands, then read back.** After `assign-wedges`, a stereo group or `add-hydrogens`, call `stereo` or `check_structure` again and report what changed, with Undo as the way back.
+6. **Hand off** with what changed or what the person should look at (`handoff`).
+
+## Rules
+
+- A check issue with `fix` (`wedges` or `expand`) is repaired by the person's Fix button or by `assign-wedges` or `expand-abbreviation` on the selection; say which.
+- A structure check on a query drawing without `query: true` reports `query_feature` notes; they are expected, not errors.
+- Metal cations such as Na+ in a salt are not valence errors; do not report them as such.
+- Export SMARTS in the desktop app copies instead of saving until 0.7.0; dialogs (atom list, R-group, abbreviation label) belong to the person.
+
+## Gate
+
+- [ ] Every number, label and issue reported came from a tool answer in this session, with its unit and method where given.
+- [ ] Every changing command was found in `list_commands` first and reported with its undo step.
+- [ ] Undefined or unperceived stereo was named as such, never filled in.
+
+## Hands back
+
+Fragment, atom and bond ids, the quoted answers, and a ready or question handoff.
+
+## Owned resources
+
+None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue.
diff --git a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md
index 34473333..f4d176cd 100644
--- a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md
+++ b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md
@@ -7,7 +7,7 @@ description: "Checks what the person sees in FormChem when the agent cannot see
## Purpose
-Never claim a visible result you did not confirm. In 0.4.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report, and ask the person for the rest.
+Never claim a visible result you did not confirm. In 0.6.0 an agent still has no picture of the window and no render tool (it arrives in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found; `stereo`, `check_structure` and `properties` read the chemistry after a command), and ask the person for the rest.
## What you can confirm today
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 cf216927..6dc92811 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
@@ -1,6 +1,6 @@
---
name: window-commands
-description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist."
+description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist."
---
# Window commands
@@ -25,13 +25,17 @@ Most canvas commands act on the canvas selection. The agent sets the selection t
| --- | --- |
| Open this file (absolute path to a `.fchem`, `.mol`, `.sdf`, `.smi`, `.cml`, `.cdxml`) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing |
| Draw or insert a structure from SMILES | `run_command {id: "insert-smiles", params: {smiles: "[SMILES]"}}`: one undo step into the active drawing (a new one when none is open), centred in the visible page and selected; the answer names the new fragment ids and the drawing. Then `get_context` for the formula. If `list_commands {id: "insert-smiles"}` lists no `smiles` param (an older build), run it bare and post `handoff {state: "question", note: "Paste [SMILES] into the SMILES prompt and press Insert"}`; never claim the structure was drawn until the person confirms |
-| Draw from a name, a molfile text or by atoms | No command does this before 0.8.0. Offer SMILES through `insert-smiles {smiles}`, or a file through `open-recent` |
+| Insert a ring, amino acid, sugar, protecting group, reagent or glassware | `run_command {id: "insert-template", params: {id: "[template id]"}}`: one undo step, centred in view at the drawing's bond length, selected; without `id` it opens the library for the person. Ids such as `benzene`, `l-alanine` come from the engine's `GET /api/templates` |
+| Draw from a name, a molfile text or by atoms; place an arrow, a shape or a caption | No command does this before 0.8.0 (the insert-arrow, insert-shape and insert-table commands only pick the person's tool). Offer SMILES through `insert-smiles {smiles}`, a template, or a file through `open-recent` |
+| 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 |
| Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure |
| Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected |
| Save | `save`; a drawing never saved before asks the person for a name, so say so in the handoff |
-| Check the structure | `check-structure` opens a dialog for the person listing valence errors and warnings; the agent does not get the rows back. Say the dialog is open for them, or read valence errors through an extension (`extension-drawings`) |
-| Show the formula or masses | `get_context` gives the formula of each open drawing; `show-analysis` or `toggle-analysis` opens the Analysis panel (masses, m/z, elemental analysis) for the person, whose values the agent cannot read through commands |
+| Check the structure | The `check_structure` tool returns the issues with codes and ids (`structure-analysis`); `check-structure` opens the Check Structure panel for the person |
+| Show the formula, masses or properties | `get_context` gives the formula of each open drawing and the `properties` tool every value with its method (`structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person |
+| Stereo, hydrogens, abbreviations, query features, R-groups | Load `structure-analysis` for the commands and the tools that read the result |
## Rules
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 2fba324e..7f9e876c 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,12 +1,15 @@
# Commands that touch a drawing
-The window's command registry, as far as it concerns drawings, for FormChem 0.4.0. 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.6.0. 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
- Reading the catalogue
- Drawings: open, save, close
- Changing the drawing
+- Templates, objects and arrangement
+- Reactions
+- Stereo, queries and analysis
- The canvas and the view
- Registered but off until a later version
- What no command does yet
@@ -42,10 +45,58 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4.
| `distribute-h`, `distribute-v` | | spread the selected objects evenly |
| `clean-structure` | | tidies bond lengths and angles through the engine's layout service, keeping place and stereochemistry; selected atoms, or every structure on the page when nothing is selected. It refuses when the drawing changed during the call |
| `layout-structure` | | computes fresh 2D coordinates for the structures the selection touches, or every structure on the page |
-| `check-structure` | | opens a dialog for the person listing valence errors and chemistry warnings with links that select the atoms; the agent gets only "ran in the window" |
+| `check-structure` | | opens the Check Structure panel for the person (rows that select atoms, Fix, Check Again); the agent gets only "ran in the window", and reads the issues with the `check_structure` tool |
| `insert-text` | | switches the person's canvas to the text tool |
-`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` selects what it added). Each changing command is one undo step. `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group` and `ungroup` are registered but off in this build.
+`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` and `insert-template` select what they added). Each changing command is one undo step.
+
+## Templates, objects and arrangement
+
+| Command | Params | What it does |
+| --- | --- | --- |
+| `insert-template` | `id` (optional) | with `id`: inserts that template (fresh ids, the drawing's bond length) centred in the view of the active drawing, or a new one, selected, as one undo step; the engine's `GET /api/templates` lists the 206 ids (`benzene`, `l-alanine` and so on). Without `id` it opens the library for the person |
+| `bring-front`, `bring-forward`, `send-backward`, `send-back` | | change the stacking order of the selection within its page or group (Shift+Mod+], Mod+], Mod+[, Shift+Mod+[) |
+| `group`, `ungroup` | | group the selection (Mod+G) or ungroup a selected group (Shift+Mod+G) |
+| `insert-arrow`, `insert-shape`, `insert-table` | | pick the arrow, rectangle or table tool for the person; nothing is drawn until they drag |
+| `insert-image` | | asks the person for a picture file; an agent cannot answer the chooser |
+| `insert-text` | | switches the person's canvas to the text tool |
+
+## Reactions
+
+| Command | What it does |
+| --- | --- |
+| `add-reaction-arrow` | picks the reaction arrow tool for the person |
+| `perceive-reactions` | reads the reaction arrows on the page and stores each step's roles (one undo step); the `perceive_reactions` tool does the same and returns the ids |
+| `map-atoms`, `clear-mapping` | map or clear the selected or first step; `map_reaction` returns the result |
+| `check-reaction` | opens the balance dialog for the person |
+| `balance-reaction` | writes the suggested coefficients (one undo step); refused when the check suggests a missing co-product |
+| `show-stoichiometry`, `stoichiometry-grid` | open the Stoichiometry panel for the person; insert or refresh the grid table on the page |
+| `copy-reaction-smiles`, `copy-reaction-rxn` | put the step on the person's clipboard; `export_reaction` gives the agent the text |
+| `export-reaction-smiles`, `export-reaction-rxn` | save the step to a file the person chooses |
+| `paste-reaction` | lays out reaction SMILES or RXN from the person's clipboard as a drawn scheme |
+| `set-reaction-roles` | params `role` (`reactant`, `product`, `agent`, `condition`, `none`) and `objects` (ids; default the selection): sets their role in the step and marks it as set by hand, one undo step; without `role` it opens the roles dialog for the person |
+
+The step is the one whose arrow or structures are selected, else the first on the page.
+
+## Stereo, queries and analysis
+
+From 0.6.0. They act on the selection, or the page when nothing is selected, and each changing one is one undo step. The analysis tools (`properties`, `check_structure`, `stereo`, `substructure`) return what the panels show; see `structure-analysis`.
+
+| Command | What it does |
+| --- | --- |
+| `assign-wedges` | asks the engine for wedges and hashes that express the stereocentres unambiguously |
+| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | put the selected centres into abs, a new AND group or a new OR group, or out of every group |
+| `set-stereo-group`, `stereo-group-popover` | the Enhanced Stereo submenu and its popover, for the person |
+| `add-hydrogens`, `remove-hydrogens` | explicit hydrogens drawn or folded back; some stay (stereo, isotope, charge, map number) |
+| `expand-abbreviation` | expands the selected abbreviation atoms, or every abbreviation on the page |
+| `contract-abbreviation` | opens the abbreviation dialog for the person's label |
+| `set-atom-list` | opens the periodic table dialog for the person |
+| `set-query-bond-any`, `set-query-bond-single_or_double`, `set-query-bond-single_or_aromatic`, `set-query-bond-double_or_aromatic`, `clear-query-bond` | query bonds on the selected bonds (list_commands gives the exact ids) |
+| `define-rgroup`, `enumerate-markush` | open the R-group and enumeration dialogs for the person |
+| `search-substructure` | selects matches of the selected atoms, or asks the person for SMARTS |
+| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file (the desktop app copies instead until 0.7.0) |
+| `compute-properties`, `copy-analysis` | open the Analysis panel on the selection; copy its values with methods to the person's clipboard |
+| `show-stereo`, `show-stereo-groups`, `show-query-marks` | toggle the CIP labels, the enhanced stereo group labels and the query tags on the canvas |
## The canvas and the view
@@ -56,13 +107,14 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4.
| `zoom-100` | actual size (Mod+1) |
| `show-grid` | toggles the paper grid; the result says whether it is now on |
| `show-analysis` | opens the Analysis panel |
+| `find`, `show-rulers` | Edit > Find (next, previous, replace) and View > Show Rulers with guides, for the person |
| `toggle-analysis`, `analysis-panel` | shows or hides the Analysis panel (formula, masses, m/z, elemental analysis from the engine, for the selection or the whole page) |
| `tool-select`, `tool-bond`, `tool-chain`, `tool-ring`, `tool-atom`, `tool-text`, `tool-eraser`, `tool-hand`, `tool-zoom`, `tool:[id]` | pick a drawing tool for the person; they do not draw by themselves |
## Registered but off until a later version
-`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); reactions, arrows, shapes, tables and images (0.5.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. `find`, `show-rulers`, `insert-template` and the stacking and grouping commands arrive in 0.5.0, and `add-hydrogens` and `remove-hydrogens` in 0.6.0.
+`import`, `print`, `copy-smiles`, `copy-molfile`, `copy-inchi`, `copy-svg` and the whole-drawing `export-png`, `export-svg`, `export-pdf`, `export-cdxml`, `export-mol`, `export-smiles` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `demos` (0.13.0). The reaction copy and export commands and `copy-smarts` and `export-smarts` already work. Running one returns "is not available right now: Arrives in [version]". Say so; do not retry.
## What no command does yet
-Drawing atoms and bonds at given positions, selecting particular atoms, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel.
+Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, filling the person's dialogs (atom list, R-group, abbreviation label), reading the whole structure back beyond what `get_context` and the analysis tools give (the formula, SMILES and CXSMILES in `stereo`, properties, issues and substructure hits), rendering an image or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel.
diff --git a/.claude/skills/formchem-skillset/EVALS.json b/.claude/skills/formchem-skillset/EVALS.json
index 8ed80a71..46a20dac 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.4.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.6.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.",
"evals": [
{
"id": 1,
@@ -111,10 +111,62 @@
"Makes the gesture preview through client.preview while dragging and commit once with commitDraft on pointer up",
"Confirms one undo step per drag and none after Escape"
]
+ },
+ {
+ "id": 11,
+ "name": "stoichiometry-panel-and-grid-disagree",
+ "prompt": "The FormChem stoichiometry panel says 8.19 mmol but the grid drawn on the page says 9.0 mmol for the same step. Fix it.",
+ "files": [],
+ "expected_behavior": [
+ "Loads reactions and reads frontend/src/chem/stoich.ts, canvas/render/table.ts and the stoich paragraphs of docs/FORMAT.md",
+ "Keeps one window computation (chem/stoich.ts) with the scale-wins precedence of the engine's stoich.py instead of adding another",
+ "Checks AC11.1 (8.19 mmol, 9.83 mmol, 0.713 mL) in the panel, the drawn grid and GET .../stoich",
+ "Logs the reason in frontend/HASHOUT_LOG.md and adds no test files"
+ ]
+ },
+ {
+ "id": 12,
+ "name": "anchored-arrow-left-behind",
+ "prompt": "In FormChem, when I move a structure, the electron-pushing arrow anchored to its oxygen stays where it was.",
+ "files": [],
+ "expected_behavior": [
+ "Loads annotations and reads canvas/render/anchors.ts, arrow.ts and objects.ts",
+ "Checks that the arrow kind's deps list the anchored fragments so the renderer re-lays it out when they change",
+ "Verifies with a MutationObserver that one move changes only the atom's nodes and the anchored arrow, without rebuilding the layer"
+ ]
+ },
+ {
+ "id": 13,
+ "name": "new-check-code",
+ "prompt": "Add a FormChem structure check that warns when a carbon carries a +3 charge drawn as a label, with a fix that does nothing new.",
+ "files": [],
+ "expected_behavior": [
+ "Loads stereo-and-queries and opens its references/routes-and-codes.md before editing",
+ "Adds the code in backend/app/services/chem/check.py with a SEVERITY entry and no fix (FIX only names existing analysis routes such as wedges or expand)",
+ "Adds the row to routes-and-codes.md and docs/ANALYSIS.md and a backend HASHOUT entry, and does not put a transaction in the issue"
+ ]
+ },
+ {
+ "id": 14,
+ "name": "tauri-cli-bump",
+ "prompt": "The tauri crate in Cargo.lock moved to 2.13.1; update FormChem so ./build_app still builds.",
+ "files": [],
+ "expected_behavior": [
+ "Loads desktop and states the rule that @tauri-apps/cli major.minor must equal the tauri crate's",
+ "Sets @tauri-apps/cli in frontend/package.json to a 2.13 release in the same change as package-lock.json, checking the @tauri-apps/plugin-* packages against their tauri-plugin-* crates",
+ "Runs ./formchem desktop check (not a full tauri build on a small machine) and records the bump in the HASHOUT log"
+ ]
}
],
"trigger_evals": [
{"query": "add an MCP tool to formchem", "should_trigger": true},
+ {"query": "formchem shows (S) on the wrong side of the stereocentre after contracting CO2H", "should_trigger": true},
+ {"query": "fix formchem's SMARTS export for atom lists in services/chem/query.py", "should_trigger": true},
+ {"query": "formchem build_app stops with the Tauri CLI did not install", "should_trigger": true},
+ {"query": "what is the cLogP of the structure in my FormChem drawing?", "should_trigger": false},
+ {"query": "formchem's perceive reactions picks the wrong reactants for a vertical arrow", "should_trigger": true},
+ {"query": "add a new glassware template to the formchem template library", "should_trigger": true},
+ {"query": "the curved arrow in formchem's renderer draws its head on the wrong side", "should_trigger": true},
{"query": "the formchem title bar flickers when I switch themes, fix it", "should_trigger": true},
{"query": "wire the extensions router into formchem's backend/app/main.py", "should_trigger": true},
{"query": "bump formchem to 0.2.1", "should_trigger": true},
@@ -140,6 +192,7 @@
{"query": "release formVFX 0.62.0", "should_trigger": false},
{"query": "update the extension catalogue page in FormPortal", "should_trigger": false},
{"query": "scaffold a Tauri 2 shell for my new todo app", "should_trigger": false},
- {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false}
+ {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false},
+ {"query": "map the atoms of the reaction in my open FormChem drawing", "should_trigger": false}
]
}
diff --git a/.claude/skills/formchem-skillset/SKILL.md b/.claude/skills/formchem-skillset/SKILL.md
index 06cdb174..bc0400e8 100644
--- a/.claude/skills/formchem-skillset/SKILL.md
+++ b/.claude/skills/formchem-skillset/SKILL.md
@@ -1,17 +1,17 @@
---
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 (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem file package, molfile and SMILES import, the y axis), the engine document store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings per fragment), the SVG canvas renderer patching on every edit, drawing tools (bond, chain, ring: one undo step per drag), hover hotkeys, hit testing at any zoom, selection, the window shell, title bar, themes, menus, the agent dock, Form extensions, adding an MCP tool, the Tauri shell, or a release and version bump. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis (their own skillsets), and not for standalone RDKit scripts outside the repo."
+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 (docs/FORMAT.md, model.ts, model.py, ops, undo, the fchem package), the engine store, the RDKit service (SMILES, InChIKey, masses, layout, warnings, CIP and enhanced stereo, wedges, abbreviations, queries, SMARTS, R-groups, properties, the structure check, isotope patterns), reactions (perception, Indigo mapping, balance, stoichiometry, RXN, roles), the SVG canvas renderer and marks, drawing tools, hover hotkeys, hit testing, arrows, shapes, captions, templates, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell and desktop build, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck, and not for standalone RDKit scripts."
license: Apache-2.0
metadata:
author: nodemode-ai
- version: "0.4.0"
+ version: "0.6.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 as a sidecar.
-**Where FormChem is (0.4.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 adds the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. Reactions and annotations (0.5.0), stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled.
+**Where FormChem is (0.6.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 adds stereo, queries and analysis: enhanced stereo groups and the chiral flag in RDKit, the CIP report, wedge assignment, abbreviations and explicit hydrogens, query atoms and bonds, SMARTS, substructure search, V3000 query molfiles, R-groups and Markush enumeration, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the keyed marks layer, the chemistry commands and dialogs, Set Reaction Roles, and the Tauri CLI pin for the desktop build. Exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled.
## Subsystem map
@@ -23,6 +23,9 @@ Route every change to FormChem's code through this file. It maps the subsystems
| 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 and session, the actions behind File and Insert, the Analysis panel, local valence, rings, labels 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 | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.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 report, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, V3000 queries, Markush, properties, the structure check, the isotope pattern, their routes, tools, 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-edits.ts`, `app/chem-commands.ts`, `canvas/render/marks-*.ts`, the 0.6.0 dialogs in `ui/`, `docs/ANALYSIS.md` | `stereo-and-queries` |
| 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` |
@@ -39,7 +42,10 @@ 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)
+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)
+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
io/ -> registry only for the catalogue mirror
@@ -49,7 +55,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
+mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub;
+ routers/analysis imported lazily by the analysis tools
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
```
@@ -80,13 +87,16 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t
| A new field or object kind, an op or path problem, a validation error, coalescing, the `.fchem` package shape | `document-format` |
| SMILES, InChI, formula, masses, implicit hydrogens, valence errors, warnings, 2D clean-up or layout, a structure file reader or writer, the derived cache | `chemistry-engine` |
| Drawing on the canvas: how a bond, label or wedge renders, a drawing tool, a hover hotkey, snapping, hit testing, selection, zoom and pan, the tool rail, canvas right-click menus | `canvas` |
+| An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `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 |
| 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 |
| 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` |
| A new MCP tool, the commands catalogue, `./formchem agents`, skills, the manifest | `agents` |
-| Desktop build, sidecar, updater, Tauri commands, title bar overlay | `desktop` |
+| Desktop build, `build_app`, the Tauri CLI version, 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: insert a structure, run a menu command, hand off in the window | Not this pack: `formchem-harness` |
@@ -98,9 +108,10 @@ formchem-skillset/
SKILL.md this router, the subsystem map and the laws in short
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, canvas, window-shell, menus, dock,
- extensions, agents, desktop, release, clean-room
+ sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, 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
canvas/references/hover-keys.md the hover key map with the code that implements it
```
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 401642d7..b0021068 100644
--- a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md
+++ b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md
@@ -30,11 +30,11 @@ Give agents a small, honest tool surface that only describes what FormChem can d
4. Describe only what works now. A tool for a later phase lands in that phase.
5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`.
-## What agents can reach in 0.4.0
+## What agents can reach in 0.6.0
-- Six tools only. The drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present.
-- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, and the canvas commands as the 0.4.0 integration enables them) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`).
-- `mcp.py` describes 0.4.0: `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows.
+- Fourteen tools: the six of the shell; `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`), owned by `reactions`; and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure` (outside `MUTATING`, never asking), which reuse the analysis router's source rules through `_analysis_source` with a lazy import so mcp.py does not load RDKit at import, owned by `stereo-and-queries`. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, edit ops, `convert`) land in 0.8.0; do not add them early or describe them as present.
+- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands, `set-reaction-roles {role, objects}` and the 0.6.0 chemistry commands such as `assign-wedges`, `set-stereo-group-and`, `add-hydrogens` and `expand-abbreviation`) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`).
+- `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` text name the reaction tools, the analysis tools and the chemistry commands; `DRAWING_FROM = "0.8.0"` names when the atom and bond tools arrive. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows.
- `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing.
- A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window.
@@ -43,7 +43,7 @@ Give agents a small, honest tool surface that only describes what FormChem can d
- Agents in FormChem's own tabs send a live tab token in `x-formchem-inapp` and are never asked; everyone else goes through `consent.ask`. A refusal returns a sentence, never an exception.
- Window-only abilities are window tools over `/api/live` through `bridge.window_call`; the engine never fakes a window answer.
- The `handoff` live message is `{t: "handoff", agent, state, note, at}`; a window asks for the current list with `{t: "handoffs"}`.
-- The manifest is generated, never edited by hand.
+- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand; the generator writes the tools reference's `## Contents` list, which the skill validator requires past 100 lines.
## Gate
diff --git a/.claude/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md
new file mode 100644
index 00000000..c4cd61bd
--- /dev/null
+++ b/.claude/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md
@@ -0,0 +1,63 @@
+---
+name: annotations
+description: "FormChem's drawn objects beyond structures: the object kind registry in frontend/src/canvas/render (objects.ts, paint.ts, anchors.ts, arrow.ts, bracket.ts, shape.ts, line.ts, table.ts, tlc.ts, orbital.ts, image.ts, caption.ts, group.ts, bounds.ts), drawn-outline hit testing (canvas/hit-objects.ts), the annotation tools and handles in canvas/tools, captions and their x, y cache, z-order and groups (app/object-commands.ts), the template library (backend services/templates.py, data/templates, ui/template-dialog.ts, template-thumb.ts, home-templates.ts) and media upload and serving. Use when an arrow, bracket, shape, table, TLC plate, orbital, picture or caption draws, hits or moves wrong, an anchored arrow does not follow its atom, a z-order change flashes, a template is added, or a new object kind is built."
+---
+
+# Annotations
+
+## Purpose
+
+Draw every non-chemistry object from the document alone, patch it like a bond, and edit it with one transaction per gesture. Hands back a kind, tool or template change that keeps the zero-flash rule and the format contract.
+
+## Preconditions
+
+`canvas` holds the renderer, view and tool laws this builds on; `document-format` holds the object fields (FORMAT.md, Text, captions and the other kinds). Read both first.
+
+## File map
+
+| Path | Role |
+| --- | --- |
+| `canvas/render/objects.ts` | `OBJECT_KINDS` (kind to `{ view, deps?, derived? }`), `ObjectCtx`, `ObjectView {specs, box}`, `docChem`, `docCtx`, `objectView`, `objectDeps` |
+| `canvas/render/paint.ts`, `svg.ts` | shared stroke, fill, gradient, rotation and label helpers; `NodeSpec.kids` for nested gradients and clip paths |
+| `canvas/render/anchors.ts`, `arrow.ts` | anchor points (atom, lone pair, bond, between), anchored ends trimmed 0.15 bond lengths; one curve model for all 15 arrow types and 6 head kinds |
+| `canvas/render/` kind modules | `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`MediaCache`, `setMediaUrl`), `caption.ts`, `group.ts` |
+| `canvas/render/bounds.ts`, `canvas/hit-objects.ts` | `objectBox(obj, doc)` without a renderer; `hitObject` and `objectDistance` by drawn outline |
+| `canvas/render/renderer.ts` | the `objects` layer between `page` and `bonds`; `inOrder` moves only nodes out of place on a z-order change |
+| `canvas/tools/objects.ts` | `BoxTool` and the shared helpers (`snapEnd`, `boxFrom`, `fragmentAt`, `outermostGroup`, `ensureMediaMap`) |
+| `canvas/tools/` | `arrow.ts`, `curved.ts`, `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`uploadMedia`, `setMediaUploader`, `placeImage`), `caption.ts`, `handles.ts` (`objectHandles`, `dragHandle`), `transform.ts` (captions mapped last) |
+| `frontend/src/app/object-commands.ts` | `objectCommandDefs`: z-order per container, group, ungroup, `alignObjects`, `distributeObjects` |
+| `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/*.json` | the library: `catalogue`, `listing`, `fragment(id, bond_length)` with fresh ids; format in `docs/TEMPLATES.md` |
+| `frontend/src/ui/template-dialog.ts`, `template-thumb.ts`, `home-templates.ts`, `styles/templates.css` | Insert > Template, the SVG thumbnails, the Home section |
+| `backend/app/routers/documents.py` media routes, `services/store.py` `add_media`, `services/package.py` `sniff_image` | picture bytes held by the session until the window's transaction lists them |
+
+## Laws
+
+- **A kind is a registry entry, not a branch in the renderer.** A new kind adds a module with a pure `view(obj, ctx)` returning keyed specs and a box, plus `deps` for what else it reads (an anchored arrow lists its fragments, a caption its target). The renderer re-lays out on a change of the object, the style, the font epoch or the deps, and patches.
+- **Bounds and hits come from the drawing.** Tools, Arrange and hit testing use `objectBox` and `hitObject`, never a second geometry estimate; the old one read an arrow's bend in degrees as a length.
+- **One gesture, one transaction, one id.** A tool previews with a stable object id per gesture and commits once; an image commits only after the upload answered; Escape commits nothing.
+- **Captions follow their target.** With `target` and `offset` the caption is placed from the target's drawn box; `x`, `y` are a cache that `transform.ts` refreshes in the same transaction when the target moves, and moving the caption rewrites `offset`.
+- **Z-order is per container.** Page order and a group's `children` move separately with `move` ops computed on a working copy; a group's members are in no page order and are removed with the group.
+- **Templates and glassware are original data.** Nothing from another product's library (`clean-room`); fresh ids on every insert, fragments scaled to the drawing's bond length, shapes kept at size.
+- **Media is two steps.** POST stores bytes and returns the record; the window's one transaction lists `media[id]` and adds the image; the package writes only listed ids.
+
+## Procedure
+
+1. For a drawing fault, build a scratch drawing outside the repo with one of each kind and open it in the built window served by the engine; watch it under 4x CPU throttling with a MutationObserver over `.fc-app`.
+2. Change the kind module, then bounds or hits if the shape changed, then the tool.
+3. A new field is a FORMAT.md, `model.ts` and `model.py` change together (`document-format`); a new tool needs a rail group, an inline currentColor icon in `ui/icons.ts` and its strings through `t()`.
+4. Log the reason in `frontend/HASHOUT_LOG.md` (entries 108 to 124 and 127 hold the current ones).
+
+## Gate
+
+- [ ] `cd frontend && npx tsc --noEmit` is clean.
+- [ ] Drawing, moving and deleting the object each add exactly one undo step; moving an anchored atom changes only that atom's label and the arrows anchored to it.
+- [ ] A z-order command and a new object create or move only their own nodes (MutationObserver), and nothing flashes.
+- [ ] A template inserted from the dialog and from Home is one undo step; a picture survives save, close and reopen.
+
+## Hands back
+
+The changed kind, tool or template files, the contract text if a field changed, and the gate results.
+
+## Owned resources
+
+None of its own: the object fields are in `docs/FORMAT.md` and the template format in `docs/TEMPLATES.md`.
diff --git a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md
index a1a7ede7..20e43a6d 100644
--- a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md
+++ b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md
@@ -20,7 +20,9 @@ Let the person draw at the speed of thought while the document stays the only tr
| `canvas/view.ts` | `CanvasView`: mounts the renderer, owns viewport, zoom and pan, pointer and key routing, hover, selection, the band, the keyboard atom cursor, `setClient`, at most one `renderer.update` per animation frame |
| `canvas/hit.ts`, `selection.ts` | Hit testing and region selection on model geometry; selection sets and helpers |
| `canvas/text-editor.ts`, `canvas/context.ts` | The in-place label and text editor; right-click menus for atom, bond, selection and background (`deleteSelectionOps`) |
-| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest) |
+| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups |
+| Stereo and query marks (0.6.0) | `render/marks-layer.ts` (`ChemMarks`, one keyed layer cached per fragment; replaced `render/stereo.ts`), `marks-stereo.ts`, `marks-query.ts` and `canvas/marks-options.ts` belong to the `stereo-and-queries` specialist; the view toggles reach the renderer through `RenderDisplay.enhancedStereo`, `queryMarks` and `groupColours` |
+| Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text |
| `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper |
| `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key |
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 e0ab61c4..12b5a79d 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
@@ -20,13 +20,15 @@ Compute everything chemical in one place, from the drawing as the person drew it
| `chem/mass.py` | `average_mass`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `isotope_pattern`, `properties(conv)` |
| `chem/layout.py` | `compute_coords(frag, ids, bond_length, fixed)` (CoordGen, RDKit fallback), `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move) |
| `chem/io.py` | `detect`, `read_text`, `read_file` (`ParseResult` with fragments, warnings, reaction), `export`, `to_molfile`, `to_smiles`; SDF, RXN, reaction SMILES, CML, cdxml and cdx (Indigo), InChI; at most 1000 records per call |
-| `chem/abbrev.py` | 75 built-in abbreviations with attachment SMILES; `resolve`, `element_like`, `reversed_label` |
+| `chem/abbrev.py` | 106 built-in abbreviations in six categories plus the person's `abbreviations.json`; `resolve`, `element_like`, `reversed_label`, `library`, `match` |
| `chem/derive.py` | `derive_fragment(frag, expansions, rev)`, `derive_document(doc, rev, only)`, `content_key`, an LRU cache of 2048 fragments |
| `backend/app/routers/chem.py` | `POST /api/chem/parse`, `/derive`, `/layout`, `/convert`, `/properties`; 422 for bad input, 413 over 20 MB of text, at most 5000 atoms |
| `backend/app/services/store.py` | `schedule_derive` and `_derive_loop`: after each transaction, derive in a thread on a deep copy and broadcast `{t: "derived", doc, rev, derived}` |
| `frontend/src/chem/` | Window-side rules: `elements.ts` (default valences, colours), `valence.ts` (implicit H, label text and side), `rings.ts` (smallest rings, double bond side), `label-text.ts`, `formula.ts` (`quickFormula`), `graph.ts` |
| `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 |
+| 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
diff --git a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md
index 5ab65a8b..58dfb4eb 100644
--- a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md
+++ b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md
@@ -36,7 +36,7 @@ These appear in `derived.fragments[fid].warnings` after every transaction.
| `charge_imbalance` | perceive.py | The pieces of one fragment carry a net charge |
| `engine_error` | derive.py | Any exception inside the engine for this fragment; values are empty |
-Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged.
+Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged. From 0.6.0 a charged atom is judged by its charge-shifted allowed list alone (RDKit 2025.09 flags a bare Na+), and `unknown_label` no longer fires for query atoms (lists, A, Q, X, M) or a bare `*`, which count as generics.
## Stereo warnings
@@ -47,6 +47,11 @@ Valence errors are not warnings: they are the separate `valence_errors` list (`{
| `conflicting_wedges` | convert.py | Wedges on one centre imply opposite configurations |
| `misplaced_wedge` | convert.py | The narrow end of a wedge (atom `a`) is not a stereocentre |
| `unknown_ez` | convert.py | A double bond drawn crossed (`either`) or next to a wavy bond |
+| `stereo_unknown` | perceive.py | A stereocentre on a wavy bond (marked unknown on purpose) (0.6.0) |
+| `undefined_double_bond` | perceive.py | A stereogenic double bond that is neither specified nor marked crossed or wavy, usually a substituent on the bond's line; cumulated bonds are skipped (0.6.0) |
+| `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` | convert.py | A malformed `stereo_groups` entry, an atom in two groups, or a grouped atom that is not a stereocentre (dropped from the group) (0.6.0) |
+
+The 0.6.0 analysis services (wedges, contract and expand, hydrogens, SMARTS, V3000, Markush, properties) and the structure check codes belong to the `stereo-and-queries` specialist, which lists them.
## Identifier warnings
diff --git a/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md
index 73aa0d56..0bd95c76 100644
--- a/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md
+++ b/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md
@@ -31,8 +31,14 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t
- Releases are built by formcompiler from `tauri.conf.json`; do not hand-build release artifacts.
- Do not run cargo build, tauri build or pyinstaller on a shared or small machine unless the task says so.
+## The Tauri CLI pin
+
+`@tauri-apps/cli` is a pinned dev dependency in `frontend/package.json` (2.12.6). The rule: its major.minor equals the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.7), and each `@tauri-apps/plugin-*` package shares major.minor with its `tauri-plugin-*` crate; bump them together in one change, with `package-lock.json`. Tauri refuses to build across minor versions. Until 0.6.0 package.json did not list the CLI, so `npm ci` installed no `tauri` binary and `./build_app` stopped with "the Tauri CLI did not install"; with the pin, the owner's `./build_app` on macOS arm64 (Python 3.14) built the app.
+
+`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck`, and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it.
+
## Gate
-- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable).
+- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable, CLI and crate share major.minor).
- [ ] The desktop dev run opens the window without a white flash and the engine answers `/api/health` on its port.
- [ ] Quitting the app ends the engine process on every platform touched.
diff --git a/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md
new file mode 100644
index 00000000..361ff088
--- /dev/null
+++ b/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md
@@ -0,0 +1,62 @@
+---
+name: reactions
+description: "FormChem's reaction code: perception of roles around reaction arrows (services/chem/geometry.py, reactions.py), Indigo atom mapping (mapping.py), balance and co-product suggestions (balance.py), stoichiometry in the engine (stoich.py) and the window (frontend/src/chem/stoich.ts, stoich-ops.ts, ui/stoich-panel.ts), reaction SMILES and RXN export and scheme import (rxnio.py, scheme.py, importers.py), the routes in routers/reactions.py, the derived reactions slot, the four MCP reaction tools, and the Reaction menu (app/reaction-commands.ts, engine/reactions-api.ts). Use when a step gets the wrong roles, a mapping or balance is wrong, the stoichiometry panel and the drawn grid disagree, an RXN round trip loses something, or a reaction route or command is added."
+---
+
+# Reactions
+
+## Purpose
+
+Keep one reading of a drawn reaction across the engine, the window and agents. The engine computes roles, mapping, balance and exchange formats from the drawing and writes them as ordinary transactions; the window computes stoichiometry for instant display by the same rules. Hands back changed modules with their contract text in `docs/FORMAT.md` and `docs/REACTIONS.md` in step.
+
+## Preconditions
+
+Read `docs/FORMAT.md` (Reactions on a page, the table `stoich` rule, the derived cache) and `docs/REACTIONS.md` (rules, routes, shapes). Load `document-format` before building ops by hand and `clean-room` before any new reaction feature.
+
+## File map
+
+| Path | Role |
+| --- | --- |
+| `backend/app/services/chem/geometry.py` | `object_box` for every kind (text by a 0.55 em per character estimate), `Frame(tail, head)` with `along`, `across`, `project` |
+| `chem/reactions.py` | `REACTION_ARROWS`, the constants `BAND_BONDS` 1.5, `ROW_BONDS` 2.5, `END_BONDS` 0.5, `JOIN_BONDS` 1.0; `infer_step`, `perceive_page`, `perceive_ops`, `preview`, `find_step`, `ReactionError` (422) and `NotFound` (404) |
+| `chem/mapping.py` | `map_ops(doc, step, mode, centres)` (`discard`, `keep`, `alter`), `clear_ops`; the order search and scoring |
+| `chem/balance.py` | `check`, `solve` (exact fractions), co-product candidates, `resonance`, `coefficient_ops` |
+| `chem/stoich.py` | `compute(doc, reaction, step, derived)`, `grid`, `table_ops`, unit formatting at three significant figures |
+| `chem/rxnio.py`, `chem/scheme.py` | export to `smiles`, `rxn`, `rxnv3000`; import and layout of reaction SMILES, RXN, CML and CDXML as a scheme (`insert_ops`) |
+| `chem/derive.py` `reaction_checks` | the derived `reactions` slot: step id to balance check, at most 64 steps |
+| `backend/app/routers/reactions.py` | every reaction route; `_commit` returns `{changed, tx, rev}` |
+| `backend/app/routers/mcp.py` | `t_perceive_reactions`, `t_map_reaction`, `t_export_reaction`, `t_reaction_stoichiometry`, `_apply` |
+| `frontend/src/chem/stoich.ts`, `chem/stoich-ops.ts` | the window's only stoichiometry computation (`computeStoich`, `stepFor`, `averageMass`) and the ops for one typed cell |
+| `frontend/src/ui/stoich-panel.ts`, `styles/stoich.css` | the panel in row 2 of `.fc-workspace` |
+| `frontend/src/canvas/render/table.ts` | draws a `stoich` table live from `computeStoich` |
+| `frontend/src/engine/reactions-api.ts`, `app/reaction-commands.ts` | the typed route client and the Reaction menu commands |
+| `frontend/src/chem/reaction-roles.ts`, `ui/roles-dialog.ts` | Set Reaction Roles (0.6.0): `reactionRoleOps` moves changed ids between role lists, sets `explicit: true` and drops coefficients and `stoich` entries that no longer fit, in one transaction; `canTakeRole` (fragments, text, captions, groups, images, shapes, tables, never the arrow); the keyed roles dialog. Window-side, no engine route |
+
+## Laws
+
+- **One reading of stoichiometry.** The engine's `stoich.py` and the window's `chem/stoich.ts` follow the same precedence: `scale_mmol` is the reference when present, else the limiting reagent's typed amount over its equiv, else the first amount; typed amounts beat typed equivalents. Never add a third computation; the renderer's own copy was deleted for disagreeing. Only typed values are stored, and the window's write rules (mass, volume or equiv replaces the other two; scale and the limiting reagent's amount replace each other) keep the two readings equal.
+- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true` (set by Set Reaction Roles, an agent's `set-reaction-roles {role, objects}`, or a reaction file); re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md.
+- **Routes are transactions.** A changing route builds ops on a copy and applies them with `STORE.apply`, returning `{changed, tx, rev}` and broadcasting the tx with the caller's `client`; no change means `changed: false` and no undo step. Agents go through `_apply` with origin `agent`.
+- **Map numbers are atom data.** `Atom.map` and `Bond.reacting` are the only places mapping lives, so chained steps share the numbers of a shared structure.
+- **Exchange keeps what the format can carry.** Kekulise RXN, keep reaction SMILES aromatic, put conditions on RXN line 4, report what is dropped as a warning code.
+
+## Procedure
+
+1. Reproduce with a scratch engine (`FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]`) and the route from `docs/REACTIONS.md`; the esterification (acetic acid + ethanol, H2SO4 above the arrow, ethyl acetate + water) and the two-step benzoic acid to N-ethylbenzamide scheme are the reference drawings.
+2. Change the service, then the route or tool, then the window client, in that order; a new answer field goes into `docs/REACTIONS.md`, a stored field into FORMAT.md, `model.ts` and `model.py` together.
+3. Log the reason in `backend/HASHOUT_LOG.md` or `frontend/HASHOUT_LOG.md` (entries 63 to 76 and 125 to 131 hold the current ones).
+
+## Gate
+
+- [ ] Esterification: perceive gives reactants acetic acid and ethanol, agent H2SO4, conditions text; a second perceive answers `changed: false`; map gives `complete`, one bond broken and one formed; check is balanced.
+- [ ] AC11.1: 1.00 g benzoic acid, 1.2 equiv thionyl chloride at 1.64 g/mL gives 8.19 mmol, 9.83 mmol, 0.713 mL in the route, the panel and the drawn grid. AC11.2: 1000 mg of 1151 mg theoretical is 86.9 %.
+- [ ] An RXN exported and imported again keeps roles, map numbers and the conditions text.
+- [ ] `backend/venv/bin/python -m compileall -q backend/app` and `cd frontend && npx tsc --noEmit` are clean; after any MCP change `./formchem agents sync --check` passes.
+
+## Hands back
+
+The changed modules, the contract text updated in the same change, and the gate results.
+
+## Owned resources
+
+None of its own: the rules and routes are in `docs/REACTIONS.md` at the repository root, which this file points to instead of copying.
diff --git a/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md
new file mode 100644
index 00000000..cb3ba469
--- /dev/null
+++ b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md
@@ -0,0 +1,53 @@
+---
+name: stereo-and-queries
+description: "FormChem's 0.6.0 stereo, query and analysis layer: enhanced stereo groups and the chiral flag into RDKit, the CIP stereo report, wedge assignment, the abbreviation library with contract and expand, explicit hydrogens, query atoms and bonds as one SMARTS-built query molecule, SMARTS in and out, substructure search, V3000 query molfiles with R-group blocks, Markush enumeration, properties with method labels, the structure check codes, the isotope pattern, the /api/analysis router, the four analysis MCP tools, and the window side (analysis-api.ts, chem-edits, chem-commands, the keyed marks layer, the dialogs, the check panel, the properties section and isotope plot). Use when a CIP label, stereo group, wedge, abbreviation, query, SMARTS, R-group, property, check issue or isotope peak is wrong, or a route, command, mark or check code is added."
+---
+
+# Stereo and queries
+
+## Purpose
+
+Keep the chemistry of 0.6.0 in one shape: the engine (RDKit) computes and proposes, the window commits one transaction per command, and every number carries its method. The doc is `docs/ANALYSIS.md`; the reasons are in `backend/HASHOUT_LOG.md` 78 to 98 and `frontend/HASHOUT_LOG.md` 133 to 148.
+
+## File map
+
+| Path | Role |
+| --- | --- |
+| `backend/app/services/chem/convert.py` | `_read_groups`, `apply_groups` (stereo groups and `chiral` into RDKit after perception), `groups_from_mol`, `_query_label` (query atoms and bare `*` are generics) |
+| `chem/stereo.py` | `report` (centres, double bonds, axes, state, group label, CXSMILES), `regroup`, `groups_tx`, `preview`, `rewedge` (from the drawing, wanted CIP or 3D) |
+| `chem/perceive.py` | `stereo_unknown`, `undefined_double_bond`, `not_ez_bonds` (cumulenes), the charged-atom valence rule |
+| `chem/abbrev.py`, `chem/superatom.py` | 106 built-ins plus `abbreviations.json`; `match`, `PREFERRED`; `contract` and `expand` keeping ids |
+| `chem/hydrogens.py` | `add_hydrogens`, `remove_hydrogens` |
+| `chem/query.py`, `chem/search.py` | `query_mol`, `to_smarts`, `from_smarts`, `parse_atom_smarts`; `substructure` |
+| `chem/v3000.py`, `chem/markush.py` | query molfile `write` and `read` (FormChem's own RGROUP reader); `member_attachments`, `enumerate_structures` |
+| `chem/props.py`, `chem/check.py`, `chem/isotopes.py` | `compute` with `method` and `note`; `check` with `SEVERITY`, `FIX`, `SKIP`; `from_counts`, `pattern`, `parse_formula` |
+| `backend/app/routers/analysis.py` | every `/api/analysis` route; `source` (stateless or `doc`), `finish` (`apply`), `_ids_of` |
+| `backend/app/routers/mcp.py` | `t_properties`, `t_check_structure`, `t_stereo`, `t_substructure`, `_analysis_source` (lazy router import) |
+| `frontend/src/engine/analysis-api.ts` | the only caller of `/api/analysis`; `sourceFor`, defensive readers |
+| `frontend/src/app/chem-edits.ts`, `app/chem-commands.ts` | window-side op builders; `registerChemCommands`, `CHEM_MENU_ITEMS`, `chemContextItems` |
+| `frontend/src/canvas/render/marks-layer.ts`, `marks-stereo.ts`, `marks-query.ts`, `canvas/marks-options.ts` | `ChemMarks` keyed layer and its view toggles |
+| `frontend/src/ui/` | `periodic-grid`, `atom-list-dialog`, `rgroup-dialog`, `abbreviation-dialog`, `stereo-popover`, `query-menus`, `structure-check`, `analysis-properties`, `isotope-plot`, `markush-dialog` |
+| `references/routes-and-codes.md` | the routes with their bodies and answers, the check codes by severity, the warning codes of each service. Open before adding a route, a code or a reader |
+
+## Rules
+
+- **Plain fields in the window, RDKit in the engine.** Atom lists, generic queries, query bonds and topology, stereo groups, the chiral flag and R-group definitions are field edits FORMAT defines: build them in `chem-edits.ts` and commit at once. Anything that needs perception (hydrogens, contract, expand, wedges, the check, properties, search, Markush, SMARTS) is an engine route that answers `tx: {label, ops}`.
+- **One transaction per command.** The window commits the engine's ops once, across fragments, and only if every fragment record it sent is still current; otherwise it says the drawing changed. A route with `doc` and `apply: true` applies on the engine side instead. Never commit per fragment.
+- **Groups go in after perception.** `apply_groups` runs after stereo perception so only real centres are grouped; anything that changes `stereo_groups` or `chiral` must stay in `derive.FRAGMENT_FIELDS` or cached CXSMILES goes stale.
+- **Chiral flag 0 reads absolute.** A deliberate deviation from the clean-room spec (most files write 0 for enantiomers); do not "fix" it without the owner.
+- **Ids survive contract and expand.** Expansion-internal ids are not live document ids (`_ids_of`); expand restores them unless they clash.
+- **Every property names its method.** A new property row has `method` (the RDKit call) and `note` (in words), and the window's `PROPERTY_ROWS` gets a reserved width.
+- **A fix is a command name.** A check issue names its repairing route in `fix`, never a transaction; add the code to `SEVERITY` (and `FIX` if repairable) and to the window's row text.
+- **Marks are keyed.** New marks are specs in `marks-stereo.ts` or `marks-query.ts`, cached per fragment by `ChemMarks`; explicit fills, no CSS colours; never rebuild the layer.
+- **Agents read through tools, change through commands.** Analysis tools stay read-only and outside `MUTATING`; a changing chemistry command is a window command agents reach with `run_command`.
+
+## Known gaps (do not paper over)
+
+Allene axial chirality and drawn atropisomers are not perceived; link nodes and variable attachment are not built; SMARTS import draws aromatic rings as single bonds (fix: order 1.5 when both ends are aromatic); Markush `count` is before dedup and if-then; Export SMARTS copies in the desktop shell until 0.7.0.
+
+## Gate
+
+- [ ] `backend/venv/bin/python -m compileall -q backend/app` is clean; `cd frontend && npx tsc --noEmit` is clean.
+- [ ] A scratch script outside the repo checks the AC5.3 CIP table (L-alanine S, meso-tartaric R and S, pentane-2,3,4-triol S, r, R) and ibuprofen properties (cLogP 3.07, TPSA 37.3) and isotopes (CH2Cl2 M+2 63.92, C6H5Br M+2 97.45).
+- [ ] Contract then expand gives back the same atom ids and coordinates; each command added exactly one undo step.
+- [ ] Under 4x CPU throttling a mark toggle or a property refresh patches nodes only (MutationObserver), and the properties section keeps its height.
diff --git a/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md
new file mode 100644
index 00000000..a90f8fb6
--- /dev/null
+++ b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md
@@ -0,0 +1,60 @@
+# Analysis routes and codes
+
+The `/api/analysis` routes of `backend/app/routers/analysis.py`, the structure check codes of `chem/check.py` and the warning codes of each 0.6.0 service, as of 0.6.0. `docs/ANALYSIS.md` has the full answer shapes; when this page and the code differ, the code wins and this page is the bug.
+
+## Contents
+
+- Request rules
+- Routes
+- Check codes by severity
+- Service warning codes
+
+## Request rules
+
+- Source, stateless: `fragment`, optional `expansions`, optional `members` (fragment id to fragment). From a document: `doc` plus `object` or `objects`; expansions and members come from the document.
+- Changing routes answer `tx: {label, ops}` (paths from the document root). `doc` with `apply: true` applies it (origin `user`) and adds `applied: {tx, rev}` or `applied: null`.
+- Errors: 422 `{detail}` sentence, 404 unknown doc or object, 409 `{detail: {message, errors}}`, 413 over 20 MB. A per-fragment read puts `{error}` in a failing fragment's slot.
+- Validators are chem.py's (`_fragment`, `_expansions`, `_bond_length`, `_num`, `MAX_TEXT`); reuse them for a new route so messages match.
+
+## Routes
+
+| Route | Changes | Key answer fields |
+| --- | --- | --- |
+| `GET abbreviations` | no | `abbreviations [{label, reversed, smiles, category, source}]`, `user_file`, `user_errors` |
+| `POST properties` | no | `fragments {fid: {rows, values, lipinski, veber, elemental_analysis, excluded, engine, warnings}}` |
+| `POST cip` | no | `fragments {fid: {atoms, bonds, centres, double_bonds, axes, chiral, stereo_groups, smiles, cxsmiles, warnings}}` |
+| `POST check` (`query?`) | no | `fragments {fid: {issues, counts, engine}}` |
+| `POST stereo-groups` (`set?`, `chiral?`) | tx when asked | `groups`, `chiral`, `cxsmiles`, `warnings` |
+| `POST wedges` (`atoms?`, `cip?`, `coords3d?`) | tx | `changed`, `cip`, `warnings` |
+| `POST expand` (`atoms?`, `bond_length?`) | tx | `expanded {abbreviation atom: [ids]}` |
+| `POST contract` (`atoms`, `label?`) | tx | `atom`, `expansion`, `label` |
+| `POST add-h`, `POST remove-h` (`atoms?`) | tx | `added`; `removed`, `kept` |
+| `POST smarts/export` (`atoms?`) | no | `smarts` |
+| `POST smarts/import` (`text`) | no | `fragments [fragment]` |
+| `POST substructure` | no | `hits [{object, atoms, bonds, map}]`, `count`, `by_object`, `truncated`, `smarts` |
+| `POST molfile`, `POST molfile/import` | no | `text`; `fragments [scaffold, member...]` |
+| `POST markush` (`limit?`, `force?`) | no | `count`, `structures [{smiles, formula, choice}]`, `truncated`, `groups` |
+| `POST isotope-pattern` (`threshold?`), `GET isotope-pattern?formula=` | no | `formula`, `monoisotopic`, `average`, `peaks [{mass, mz, abundance, fraction}]`, `adducts [{ion, charge, mz}]` |
+
+## Check codes by severity
+
+| Severity | Codes |
+| --- | --- |
+| error | `valence`, `bad_bond`, `engine_error`, `bad_expansion` |
+| warning | `hypervalent`, `unknown_label`, `misplaced_wedge`, `ambiguous_wedge`, `conflicting_wedges`, `wedge_between_centres`, `ring_double_bond_stereo`, `stereo_ignored`, `undefined_double_bond`, `unusual_charge`, `unknown_isotope`, `abbreviation_bonds`, `abbreviation_valence`, `overlapping_atoms`, `short_bond`, `long_bond`, `aromatic_outside_ring`, `cannot_kekulise`, `unsupported_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre`, `rgroup_undefined`, `rgroup_member_missing`, `rgroup_bonds`, `cip_failed` |
+| info | `undefined_stereocentre`, `stereo_unknown`, `unknown_ez`, `charge_imbalance`, `query_feature`, `uncommon_isotope`, `crossing_bonds`, `label_collides`, `rgroup_unused`, `rgroup_attachment_guessed` |
+
+`fix: "wedges"` for the wedge codes, `fix: "expand"` for the abbreviation codes. `SKIP` drops `query_ignored` and the InChI remarks.
+
+## Service warning codes
+
+| Service | Codes |
+| --- | --- |
+| derive and perceive | `stereo_unknown`, `undefined_double_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` |
+| wedges | `cip_unreachable`, `wedge_mismatch` |
+| contract, expand | `label_mismatch`, `stereo_dropped`, `abbreviation_bonds` |
+| hydrogens | `stereo_changed`, `hydrogens_kept` |
+| SMARTS | `smarts_rgroups`, `smarts_stereo_groups`, `abbreviations_expanded`, `smarts_any_atom`, `bad_smarts`, `smarts_opaque`, `smarts_chirality`, `smarts_bond_simplified` |
+| V3000 | `v3000_query_lossy` |
+| Markush | `enumeration_truncated` |
+| properties, isotopes | `property_failed`, `incomplete` |
diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md
index 74e12c77..8c29b749 100644
--- a/.docs/wiki/Agents.md
+++ b/.docs/wiki/Agents.md
@@ -15,14 +15,27 @@ FormChem's engine is an MCP server (`backend/app/routers/mcp.py`), over HTTP at
## Tools
-Six tools: `get_context` (version, window, agent access, the open drawings, catalogue size, your last handoff), `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff` (working, ready or question, with a note). The first three read; `run_command`, `extension_command` and `handoff` with a state change something and go through the consent question. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and the MCP tools, so anything a person can click an agent can run.
+Fourteen tools: `get_context` (version, window, agent access, the open drawings, catalogue size, your last handoff), `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` (working, ready or question, with a note), from 0.5.0 four reaction tools and from 0.6.0 four analysis tools:
+
+| Tool | Kind | What it does |
+| --- | --- | --- |
+| `perceive_reactions {doc?, page?}` | changes the drawing | reads the reaction arrows and stores each step's reactants, products, agents and conditions (one undo step); steps set by hand are kept; lists reaction and step ids |
+| `map_reaction {doc?, reaction?, step?, mode?}` | changes the drawing | maps reactant atoms to product atoms and marks bonds broken, formed and changed (`mode`: `discard`, `keep`, `alter`, or `clear` to remove) |
+| `export_reaction {doc?, reaction?, step?, format?}` | reads | a step as reaction SMILES (`smiles`) or RXN (`rxn`, `rxnv3000`) with its map numbers |
+| `reaction_stoichiometry {doc?, reaction?, step?}` | reads | moles, equivalents, masses, volumes, the limiting reagent and yields from the amounts in the step, with the balance check |
+| `properties {doc?, object?}` | reads | per fragment: formula, MW, exact mass, cLogP, molar refractivity, TPSA (also with S and P), donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis, each with the RDKit method behind it |
+| `check_structure {doc?, object?, query?}` | reads | the structure check: issues with a code, a severity (error, warning, info), the atom and bond ids, and the fix the window can run; `query: true` leaves out query-feature notes |
+| `stereo {doc?, object?}` | reads | each stereocentre, double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), defined, undefined or unknown, its enhanced stereo group and the CXSMILES |
+| `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | reads | every hit of a SMARTS pattern, or of a fragment of the drawing drawn as the query, with its fragment id and the matched atom and bond ids |
+
+`doc` may be left out when one drawing is open; `reaction` and `step` default to the first, and `object` (absent) means every fragment. `get_context`, `list_commands`, `extensions_list`, `export_reaction`, `reaction_stoichiometry` and the four analysis tools read; `run_command`, `extension_command`, `perceive_reactions`, `map_reaction` and `handoff` with a state change something and go through the consent question. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and the MCP tools, so anything a person can click an agent can run.
## Working on drawings
`get_context` lists every drawing open in the window, oldest first, as text and in `structuredContent.documents`:
```
-Documents: 1 open in the window (change them with run_command and the window's commands; dedicated drawing tools arrive in 0.8.0)
+Documents: 1 open in the window (change them with run_command and the window's commands, write reactions with perceive_reactions and map_reaction, read them with export_reaction, reaction_stoichiometry, properties, check_structure, stereo and substructure; atom and bond tools arrive in 0.8.0)
- d4n2k8q0z "Untitled" (unsaved changes) · rev 1 · 1 fragment · C6H6O · not saved yet
```
@@ -35,11 +48,16 @@ An agent changes drawings with the window's own commands, so every change is one
| Add a structure | `run_command {id: "insert-smiles", params: {smiles: "c1ccccc1O"}}`: into the active drawing (a new one when none is open), centred in view, selected; the answer names the new fragment ids |
| Open a file | `run_command {id: "open-recent", params: {path: "/abs/path/file.mol"}}` (a `.fchem`, or a structure file as a new drawing) |
| Tidy or lay out | `clean-structure` or `layout-structure`: the selection, or every structure on the page |
-| Arrange the selection | `select-all`, then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h`, `distribute-v` |
-| Check | `check-structure` opens a dialog for the person; formula and masses are in the Analysis panel (`show-analysis`) |
+| Arrange the selection | `select-all`, then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h`, `distribute-v`, `bring-front`, `send-back`, `group`, `ungroup` |
+| Insert a template | `run_command {id: "insert-template", params: {id: "benzene"}}`: one undo step, centred in view at the drawing's bond length; `GET /api/templates` lists the ids |
+| Reactions | `perceive-reactions`, `map-atoms`, `clear-mapping`, `balance-reaction` through `run_command`, or the four reaction tools above, which also return the results; `check-reaction` and the Stoichiometry panel (`show-stoichiometry`) open for the person |
+| Reaction roles | `set-reaction-roles {role, objects}` gives objects a role in the selected step (reactant, product, agent, condition or none) without the dialog |
+| Stereo, hydrogens, abbreviations | `assign-wedges`, `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group`, `add-hydrogens`, `remove-hydrogens`, `expand-abbreviation`, `contract-abbreviation` on the selection; read the result back with `stereo` |
+| Queries and R-groups | `set-atom-list`, the `set-query-bond-` commands, `define-rgroup`, `enumerate-markush`, `copy-smarts`; search with the `substructure` tool |
+| Check and properties | the `check_structure` and `properties` tools return the issues and values; `check-structure` and `compute-properties` open the panels for the person |
| Undo, save | `undo`, `redo`, `save` (a drawing without a file asks the person for a name) |
-Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. Dedicated drawing tools for agents (atoms and bonds by id, reading structures back, rendering, conversion) arrive in 0.8.0.
+Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. Beyond the reaction and analysis tools, dedicated drawing tools for agents (atoms and bonds by id, reading whole structures back, rendering, conversion) arrive in 0.8.0. The engine's HTTP routes for reactions, analysis, templates and media are listed in [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md), [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md), [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md) and [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md).
## Consent
diff --git a/.docs/wiki/Analysis.md b/.docs/wiki/Analysis.md
new file mode 100644
index 00000000..ebe59b82
--- /dev/null
+++ b/.docs/wiki/Analysis.md
@@ -0,0 +1,43 @@
+# Analysis
+
+From 0.6.0 the Analysis panel computes drug-like properties and the isotope pattern with the method behind every number, and Check Structure lists problems with a code for each. The engine side, with every route, is [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md).
+
+## The Analysis panel
+
+Open it with Analysis > Show Analysis. It follows the selection, or the whole page when nothing is selected, and is worked out only while it is open.
+
+| Row | Method (the row's tooltip) |
+| --- | --- |
+| Formula | Hill order with charge, abbreviations expanded |
+| Molecular weight | standard atomic weights (CIAAW conventional values) |
+| Exact mass | monoisotopic mass from the most abundant isotope of each element |
+| m/z | exact mass over the charge, electron mass corrected (charged species only) |
+| Elemental analysis | mass percent of each element |
+| cLogP | Wildman and Crippen 1999 atom contributions (typical error 0.5 to 0.7 log units) |
+| tPSA | topological polar surface area from N and O (Ertl 2000), in Ų |
+| Molar refractivity | Wildman and Crippen atom contributions, in cm³/mol |
+| H-bond donors, acceptors | Lipinski counting (N-H and O-H; N and O) |
+| Rotatable bonds | non-ring single bonds between non-terminal heavy atoms |
+| Lipinski rule of five | MW at most 500, cLogP at most 5, donors at most 5, acceptors at most 10; passes with at most one violation |
+
+Hover a row to read its method. Values stay in place while new ones load, so the panel never jumps. For ibuprofen the panel reads C13H18O2, 206.28, 206.1307, cLogP 3.07, tPSA 37.30 and a Lipinski pass.
+
+Under the rows, the isotope pattern is drawn as sticks with the base peak in the accent colour; hover a stick for its mass and abundance. Below it are the monoisotopic mass and the m/z of [M+H]+, [M+Na]+ and [M-H]- (an ion shows its own m/z instead). The pattern is exact, merged at 0.01 Da and cut at 0.1 percent of the base peak: dichloromethane shows M+2 at about 64 percent of M, bromobenzene M+2 at about 97 percent.
+
+Analysis > Copy Analysis (or the panel's Copy button) puts every value with its method, the peaks and the adducts on the clipboard as text. Analysis > Compute Properties opens the panel on the selection.
+
+## Check Structure
+
+Structure > Check Structure opens a panel that stays open while you work. It lists errors, warnings and notes for the selected structures, or every structure on the page:
+
+| Kind | Examples |
+| --- | --- |
+| Errors | valence errors, bonds that cannot be read, a broken abbreviation |
+| Warnings | unusual charges, misplaced, ambiguous or conflicting wedges, a wedge between two centres, undefined double bonds, overlapping atoms, very short or long bonds, unknown labels or isotopes, aromatic bonds outside a ring, stereo groups on atoms that are not centres, R-group gaps |
+| Notes | undefined stereocentres, wavy-bond centres, charge imbalance, query features, uncommon isotopes, crossing bonds, labels such as Ac or Pr that are also element symbols |
+
+Click a row to select its atoms and bonds on the canvas. Rows with Fix repair the problem as one undo step: wedge problems are redrawn by Assign Wedges, abbreviation problems expanded. Check Again runs the check once more and keeps the list in place. Metal cations in salts, such as Na+, are not valence errors. An atom with "ignore warnings" set drops the issues that concern only it.
+
+## For agents
+
+The MCP tools `properties`, `check_structure`, `stereo` and `substructure` give agents the same numbers, issues, CIP labels and matches as JSON with atom and bond ids, without asking the person, because they only read. `properties` adds rings, aromatic rings, fraction Csp3, stereocentres, refined donor and acceptor counts, TPSA with S and P, and the Veber rules. See [Agents](Agents).
diff --git a/.docs/wiki/Annotations.md b/.docs/wiki/Annotations.md
new file mode 100644
index 00000000..43793657
--- /dev/null
+++ b/.docs/wiki/Annotations.md
@@ -0,0 +1,62 @@
+# Annotations
+
+Everything on the page that is not a structure: arrows, symbols, brackets, shapes, tables, TLC plates, orbitals, pictures and captions, plus arranging and grouping them, the template library, Find and the rulers. All of it arrived in 0.5.0. Each gesture is one undo step, and `Escape` cancels a gesture in progress. How each object is stored is in [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md).
+
+## The tools
+
+| Key | Group | Tools | What a click or drag does |
+| --- | --- | --- | --- |
+| `W` | Arrows | Reaction, equilibrium, retrosynthetic, resonance, no-go, dashed, line, electron-pushing, fishhook | Drag from tail to head; a click places an arrow four bond lengths long. `Shift` snaps to 15 degrees, `Alt` picks the other kind (equilibrium to unbalanced, resonance to reversible, no-go cross to slash, forward to dashed). |
+| `P` | Symbols | Plus, equals, adduct dot | Click to place; the sign snaps to the centre line of the structure beside it (`Alt` places it exactly). |
+| `K` | Brackets | Round, square, curly | Drag around atoms; a click on a structure brackets all of it. A repeat unit with two crossing bonds is labelled `n`. Double-click a bracket to change its label. |
+| `G` | Shapes | Rectangle, rounded rectangle, ellipse, polygon, line and polyline | Drag a box (`Shift` square, `Alt` from the centre) or click for a default size. Lines: drag for a line, or click point by point and double-click (or click the first point) to finish a polyline. |
+| | Table | Table | Drag to size: the cell count follows the drag (48 by 18 pt cells); `Shift` styles the first row as a header. |
+| | TLC | TLC plate | Drag a plate; it gets one lane per 20 pt of width. Click on a plate to add a spot to the nearest lane at that height (Rf to 0.01). |
+| | Image | Image | Choose a PNG, JPEG, GIF, WebP or SVG file; a click places it at its natural size (at most 240 pt), a drag fits it into the box. Also Insert > Image... |
+| `O` | Orbitals | p, s, d, dz2, sp, sigma, pi | Click to place, drag to size and turn; dropped on an atom, it stays on that atom. |
+| `T` | Text | Text, Caption | `Shift+T` steps to Caption: click a structure to attach its name under it; `Ctrl`-click (`Cmd` on macOS) adds the next compound number in bold. |
+
+Insert > Arrow, Shape and Table pick the same tools.
+
+## Electron-pushing arrows
+
+Start the drag on an atom, on a bond, or (when the atom shows lone pairs) on its lone pair; hold `Ctrl` or `Cmd` at the press to start on the atom itself. End on an atom, a bond, or in the space between two atoms where a new bond forms. The arrow bends 90 degrees away from the structure (`Alt` flips the bulge); the fishhook draws a half head (`Shift` for the other side). Both ends follow their atoms when the structure moves. Hover an atom and press `:` to add lone pairs first.
+
+## Handles
+
+With the selection tool, a single selected object shows its handles: an arrow's tail, head and bend (the round handle), a line's points, or eight handles around a shape, picture, bracket, table or TLC plate. Drag one to reshape; `Shift` snaps arrow ends to 15 degrees and the bend to 15 degree steps. Dragging an anchored arrow end frees it. Pictures keep their proportions; tables scale their columns and rows.
+
+## Captions
+
+A caption belongs to its structure: move the structure and the caption follows; drag the caption and it stays where you put it relative to the structure. Compound numbers count up from the highest number already on the page.
+
+## Arrange and group
+
+| Command | Keys |
+| --- | --- |
+| Arrange > Bring to Front | `Ctrl+Shift+]` |
+| Bring Forward | `Ctrl+]` |
+| Send Backward | `Ctrl+[` |
+| Send to Back | `Ctrl+Shift+[` |
+| Group | `Ctrl+G` |
+| Ungroup | `Ctrl+Shift+G` |
+
+Align, distribute, flip and rotate work on objects as on structures. A click on any member of a group selects the whole group; `Alt`-click or a double-click reaches the member. Deleting a group deletes its members. Shapes and pictures are drawn behind structures, so a filled box never hides a label.
+
+## Templates
+
+Insert > Template... opens the library: 206 original templates in nine categories (rings, polycycles, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and solvents, glassware), with search by name and tag. Home shows the same library on Start and on its Templates page. A click inserts the template in the middle of the view as one undo step, at the drawing's bond length, and selects it; with no drawing open, a new one is made.
+
+Your own templates: put JSON files in `~/formchem/templates` (or `FORMCHEM_DATA_DIR/templates`) in the format of [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md); they show with the built-in ones.
+
+## Find
+
+Edit > Find... (`Ctrl+F`) searches text objects, captions, table cells, atom labels (with their hydrogens, so `OH` also finds `HO`), abbreviations, element symbols, formulas (`C2H6O` finds ethanol and dimethyl ether) and SMILES (compared in canonical form). The bar shows "n of m"; `Enter`, `Shift+Enter`, `F3` and `Shift+F3` step through the matches, and the view pans only when a match is off screen. Match Case narrows the search. Replace (`Ctrl+Alt+F`) changes text objects, captions and table cells and keeps their formatting; Replace All is one undo step. `Escape` closes the bar. Stoichiometry tables bound to a reaction are not searched, because their numbers are worked out rather than stored.
+
+## Rulers
+
+View > Show Rulers shows rulers along the top and left edges of the canvas; they lie over the edges, so turning them on does not move the drawing, and the setting is remembered. They count in the drawing's units; click the corner square to switch between pt, mm, cm and in for this window. Drag out of a ruler to place a guide, drag a guide back onto the ruler to remove it, or use View > Clear Guides. Guides belong to the window and are not saved in the file, and tools do not snap to them yet.
+
+## Not yet
+
+`Enter` does not finish a polyline. Templates cannot be fused onto an atom or a bond yet, and land in the middle of the view even if something is there. Bracket tilt for slanted bonds, table cell editing, dragging TLC spots and choosing an orbital's phase or fill come later.
diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md
index c0adf8d8..9def3f86 100644
--- a/.docs/wiki/Architecture.md
+++ b/.docs/wiki/Architecture.md
@@ -1,10 +1,11 @@
# Architecture
```
-frontend/ vanilla TypeScript and Vite: engine/ (model, ops, document client, session), chem/ (valence, rings, formula), canvas/ (view, tools, render/),
- app/ (menus, shell and canvas commands, documents, window tools), ui/ (shell, menus, Home, Preferences, tool rail, Analysis panel), dock/, extensions/, styles/
-backend/ FastAPI engine: core/ (config, guard, window key, seal), routers/ (system, live, library, commands, documents, chem, terminal, chat, extensions, mcp),
- services/ (model, ops, store, history, package, importers, chem/ on RDKit)
+frontend/ vanilla TypeScript and Vite: engine/ (model, ops, document client, session, reactions-api), chem/ (valence, rings, formula, stoich),
+ canvas/ (view, hit testing, tools, render/ with one module per object kind), app/ (menus, shell, canvas, object and reaction commands,
+ documents, window tools), ui/ (shell, menus, Home, Preferences, tool rail, Analysis and Stoichiometry panels, template library), dock/, extensions/, styles/
+backend/ FastAPI engine: core/ (config, guard, window key, seal), routers/ (system, live, library, commands, documents, chem, reactions, templates,
+ terminal, chat, extensions, mcp), services/ (model, ops, store, history, package, importers, templates, chem/ on RDKit and Indigo), data/templates/
src-tauri/ the desktop shell; the engine runs as a frozen sidecar
```
@@ -18,8 +19,8 @@ The engine holds every open document in its store (`backend/app/services/store.p
2. **The window applies it at once.** `EngineDocumentClient.commit` validates and applies the ops to the mirror, marks the transaction pending and sends it on the live socket (or over HTTP when the socket is down). The person sees the change in the same frame.
3. **The engine applies it for good.** The store normalises the ops, applies them, validates the result (rolling the whole transaction back on any failure), raises the revision, records the inverse for undo, merges a stream of small edits that share a coalescing key, and schedules autosave and version snapshots (`history.py`).
4. **Everyone hears about it.** The engine broadcasts the transaction with the new revision to every window and agent. The sending window drops it from its pending list; other windows apply it to their mirror. After a dropped connection a window resyncs from a snapshot and resends what was still pending.
-5. **The derived cache follows.** After each transaction the engine derives the chemistry of the changed fragments in a worker thread with RDKit (`services/chem/derive.py`, cached per fragment): canonical SMILES and CXSMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors and warnings. It broadcasts the result keyed by fragment id and revision. It is never saved: it is rebuilt whenever a drawing opens.
-6. **The renderer patches.** The canvas (`canvas/render/`) draws in SVG keyed by object, atom and bond id. Ops share structure, so the renderer compares records by reference, re-lays out only the changed atoms and their neighbours, and patches the attributes of the nodes whose drawing changed; it never rebuilds the canvas. Until the derived cache for the current revision arrives, it draws implicit hydrogens and double-bond sides from the window's own tables (`frontend/src/chem/`); then it adopts the engine's values. Hit testing works on the model geometry, not on DOM nodes.
+5. **The derived cache follows.** After each transaction the engine derives the chemistry of the changed fragments in a worker thread with RDKit (`services/chem/derive.py`, cached per fragment): canonical SMILES and CXSMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors and warnings, plus the balance check of every reaction step. It broadcasts the result keyed by fragment id and revision. It is never saved: it is rebuilt whenever a drawing opens.
+6. **The renderer patches.** The canvas (`canvas/render/`) draws in SVG keyed by object, atom and bond id; every object kind (arrows, symbols, brackets, shapes, lines, tables, TLC plates, orbitals, images, captions, groups) goes through one registry, and a change of stacking order moves only the nodes out of place. Ops share structure, so the renderer compares records by reference, re-lays out only the changed atoms and their neighbours, and patches the attributes of the nodes whose drawing changed; it never rebuilds the canvas. Until the derived cache for the current revision arrives, it draws implicit hydrogens and double-bond sides from the window's own tables (`frontend/src/chem/`); then it adopts the engine's values. Hit testing works on the model geometry, not on DOM nodes.
Undo and redo are engine operations: the engine applies the recorded inverse as a new transaction with origin `history` and broadcasts it like any other.
@@ -38,3 +39,5 @@ Vanilla TypeScript, no UI framework. Every colour, space and z-index comes from
## Chemistry core
RDKit (structure model, canonical SMILES, InChI, stereo, coordinates) and Indigo (chemical drawing formats) are pinned in `backend/requirements.txt`. The engine's chemistry service (`backend/app/services/chem/`, routes under `/api/chem`) is the authority for sanitising, valence, aromaticity, identifiers, formula and masses, 2D clean-up and layout, and reading SMILES, molfile, SDF, RXN, CML and CDXML. The window only computes what it must draw at once without the engine.
+
+From 0.5.0 the same service reads reactions: perception of roles around the arrows, atom mapping with Indigo, balance, stoichiometry, and reaction SMILES and RXN exchange, under `/api/documents/{id}/reactions` ([`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md)). Each changing reaction route applies one transaction through the store and broadcasts it like any other. The window computes stoichiometry itself for the panel and the drawn grid with the same rules (`frontend/src/chem/stoich.ts`). The template library (`/api/templates`) is data in `backend/app/data/templates` built once and cached, and pictures enter a drawing through `/api/documents/{id}/media`.
diff --git a/.docs/wiki/Desktop.md b/.docs/wiki/Desktop.md
index a96a783e..c273566f 100644
--- a/.docs/wiki/Desktop.md
+++ b/.docs/wiki/Desktop.md
@@ -20,3 +20,23 @@ The desktop app is a thin Tauri 2 shell around the same window, with the engine
- Signing identities are held by formcompiler; local builds are unsigned.
Run it from source with `./formchem desktop dev`; `./formchem desktop build` makes a local bundle. Released builds come only from formcompiler (see [Releasing](Releasing)).
+
+## Building on this machine
+
+`./build_app` (or `build_app.bat` on Windows) builds the desktop app from a fresh checkout in one step and writes everything it does to `build_app.log`. In order it checks and prepares:
+
+| Step | What it checks or does |
+| --- | --- |
+| System | macOS: the Xcode Command Line Tools; Linux: WebKitGTK 4.1 and the build packages |
+| Python | 3.12 or newer (it tries `python3.14`, `python3.13`, `python3.12`, then `python3`); an older venv is recreated |
+| Node.js | 20.19 or newer |
+| Rust | rustc and cargo from the same install (rustup expected), building for this machine's architecture |
+| Notices | `THIRD-PARTY-NOTICES.txt` must exist (`python3 setup/notices.py` after `./formchem install`) |
+| Engine packages | `backend/requirements*.txt` into `backend/venv`, reinstalled when the files or Python change |
+| Window packages | `npm ci` in `frontend/`, rerun when `package-lock.json` or Node change |
+| Tauri CLI | `frontend/node_modules/.bin/tauri` must exist, and its major.minor must equal the `tauri` crate's in `src-tauri/Cargo.lock`; each `@tauri-apps/plugin-*` package must share major.minor with its `tauri-plugin-*` crate |
+| Build | the window (`npm run build`), the engine frozen by PyInstaller with the window, the notices and the template library, a `--selfcheck` of the frozen engine, then the Tauri bundle (`.app` and `.dmg` on macOS, `.deb`, `.rpm` or AppImage on Linux) |
+
+**The Tauri CLI pin.** `@tauri-apps/cli` is a dev dependency in `frontend/package.json`, pinned at 2.12.6 because the `tauri` crate in `Cargo.lock` is 2.12.7: the CLI's major.minor must always equal the crate's, so a crate update to 2.13 needs the CLI at 2.13 in the same change. Before 0.6.0 package.json did not list the CLI at all and the build stopped with "the Tauri CLI did not install"; the message now names package.json. With the pin, the owner's `./build_app` on macOS (Apple silicon, Python 3.14) built the app. `./formchem desktop check` runs the same version comparison without building.
+
+`--reinstall` reinstalls both package sets, `--clean` removes earlier build output, `--bundles` picks the bundle kinds and `--config` merges an extra Tauri config (formcompiler's contract mode).
diff --git a/.docs/wiki/Drawing.md b/.docs/wiki/Drawing.md
index 930c7208..1c17ae0e 100644
--- a/.docs/wiki/Drawing.md
+++ b/.docs/wiki/Drawing.md
@@ -17,8 +17,9 @@ Press a tool's key with the pointer away from atoms and bonds, or click it on th
| `E` | Eraser | Eraser | Click or drag across atoms, bonds and objects to remove them. |
| `H` | Hand | Hand | Drag to pan (holding `Space` pans with any tool). |
| `Z` | Zoom | Zoom | Click to zoom in at the point, `Alt`-click to zoom out. `Ctrl` with the wheel zooms anywhere; View has Zoom In (`Ctrl+=`), Zoom Out (`Ctrl+-`), Zoom to Fit (`Ctrl+0`) and Actual Size (`Ctrl+1`). |
+| `W` `P` `K` `G` `O` | Arrows, Symbols, Brackets, Shapes, Orbitals | and Table, TLC, Image, Caption (in Text) | The annotation tools of 0.5.0; see [Annotations](Annotations). Reaction arrows and plus signs make a scheme FormChem can read; see [Reactions](Reactions). |
-Right-click an atom, a bond or the paper for its context menu. Structure has Clean Up Structure, Lay Out Structure, Check Structure and the flips; Arrange has align, distribute and Rotate 90 Degrees; Edit has Duplicate (`Ctrl+D`), Delete and Select All (`Ctrl+A`).
+Right-click an atom, a bond or the paper for its context menu; from 0.6.0 the atom and bond menus also hold Atom Query, Enhanced Stereo, Query Bond and Define R-Group, and a selection of several atoms Contract Abbreviation. Structure has Clean Up Structure, Lay Out Structure, the abbreviation and explicit hydrogen commands, Assign Wedges, the Enhanced Stereo and Query submenus, Check Structure, Compute Properties and the flips (see [Stereo and Queries](Stereo-and-Queries) and [Analysis](Analysis)); Arrange has the stacking order, align, distribute, Rotate 90 Degrees, Group and Ungroup; Edit has Duplicate (`Ctrl+D`), Delete, Select All (`Ctrl+A`), Find, Find Substructure and Copy as SMARTS. With the selection tool, a selected arrow, line or box shows handles to reshape it.
## Hover keys
@@ -68,8 +69,8 @@ While the pointer rests on an atom or a bond, its hover keys win over the tool k
5. Every hover key works on the atom or bond under the cursor: `O` for oxygen, `2` for a double bond, `Shift+6` for a ring, `4` for a chain of four, `Enter` then typing for a label.
6. The context-menu key or `Shift+F10` opens the menu of the atom or bond under the cursor. `Escape` leaves the cursor.
-Structures can also come in without drawing: Insert > Structure from SMILES, or File > Open for molfile, SDF, RXN, SMILES, InChI, CML and CDXML files.
+Structures can also come in without drawing: Insert > Structure from SMILES, Insert > Template... (206 rings, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and glassware), Reaction > Insert Reaction from Clipboard, or File > Open for molfile, SDF, RXN, SMILES, InChI, CML and CDXML files (RXN files and reactions in CML or CDXML open as drawn schemes).
## Styles
-New drawings start from the default style chosen in Preferences > Drawing (Journal standard (1996), Journal variant B, Large screen or New document) with the bond length, line width, bold width and label size set there on top; choosing a style fills those numbers in from it. Preferences > Drawing and Chemistry also switch element colours, carbon labels, aromatic circles, valence warnings and stereo labels for the view.
+New drawings start from the default style chosen in Preferences > Drawing (Journal standard (1996), Journal variant B, Large screen or New document) with the bond length, line width, bold width and label size set there on top; choosing a style fills those numbers in from it. Preferences > Drawing and Chemistry also switch element colours, carbon labels, aromatic circles, valence warnings and stereo labels for the view. The View menu has Show Stereochemistry (CIP labels), Show Enhanced Stereo Groups (abs, and1, or1 under the labels) and Show Query Features (the purple query tags); the last two are choices of this window, not of the drawing.
diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md
index c84ef7a3..d7371c97 100644
--- a/.docs/wiki/Home.md
+++ b/.docs/wiki/Home.md
@@ -2,12 +2,16 @@
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, and 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel.
+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.
| Page | What it covers |
| --- | --- |
| [Getting Started](Getting-Started) | Install, boot, your first structure, the dispatcher commands, ports and the data folder |
| [Drawing](Drawing) | The tools, the hover keys, drawing with the keyboard alone, and styles |
+| [Annotations](Annotations) | Arrows, symbols, brackets, shapes, tables, TLC plates, orbitals, pictures, captions, arranging and grouping, templates, Find and rulers |
+| [Reactions](Reactions) | Reaction schemes, roles, atom mapping, balance, stoichiometry, RXN and reaction SMILES |
+| [Stereo and Queries](Stereo-and-Queries) | CIP labels, enhanced stereo groups, wedges, abbreviations, query atoms and bonds, substructure search, SMARTS, R-groups and Markush structures |
+| [Analysis](Analysis) | Calculated properties with their methods, the isotope pattern, Copy Analysis and Check Structure |
| [Agents](Agents) | The MCP server, agent configs, skills and consent |
| [Terminal](Terminal) | The terminal and agent dock |
| [Extensions](Extensions) | Form extensions in FormChem |
diff --git a/.docs/wiki/Project-Format.md b/.docs/wiki/Project-Format.md
index 5aaec615..e61a18a7 100644
--- a/.docs/wiki/Project-Format.md
+++ b/.docs/wiki/Project-Format.md
@@ -20,10 +20,18 @@ The engine writes the package to a temporary file in the same folder and renames
- `pages` is a list; each page has a size, margins and an `order` of object ids.
- `objects` is a map by id. A fragment (`kind: "fragment"`) holds `atoms` and `bonds` maps; text objects carry runs of styled text.
- Ids are short random strings, stable for life and never reused in a document. Agents, extensions and the renderer address everything by id.
+- From 0.5.0 the other object kinds are drawn: `arrow` (15 types, heads at either end, a signed `bend`, and `anchors` that tie an end to an atom, a lone pair, a bond or the space between two atoms), `plus`, `bracket`, `shape`, `line`, `table`, `tlc`, `orbital`, `image` and `caption`. A `group` lists its `children` back to front; members are in no page `order`.
+- A `caption` has a `target` (the structure it belongs to) and an `offset` from the target's bottom centre; its `x`, `y` are a cache kept in step whenever the target or the caption moves. Compound numbers are `number: {auto: true, value: "1"}`.
+- `page.reactions` lists reactions and their steps: the arrow, the reactant, product, agent and condition object ids, `explicit` (roles set by hand or by a file, kept by perception), optional `coefficients`, and optional `stoich`, the amounts you typed in the Stoichiometry panel (`scale_mmol`, `limiting`, `product`, `isolated_mg`, and per component `equiv`, `mass_mg`, `volume_ml`, `density_g_ml`, `conc_m`, `purity_pct`, `mw`). Moles, masses implied by equivalents, the limiting reagent and yields are worked out, never stored. A `table` with `stoich: {reaction, step}` is a stoichiometry grid. Atom map numbers are `map` on atoms and reacting marks `reacting` on bonds.
+- From 0.6.0 a fragment may carry `stereo_groups` (enhanced stereo: `{kind: "abs"}`, `{kind: "and", n: 1, atoms: [...]}`, `{kind: "or", n: 2, atoms: [...]}`) and `chiral` (`absolute`, `relative` or `racemic`). For the chemistry, `relative` puts every stereocentre in no group into one OR group and `racemic` into one AND group, each with the next free number; `absolute` also sets the molfile chiral flag.
+- An atom's `query` holds its query features: `list` and `not`, `generic` (A, AH, Q, QH, X, XH, M, MH), `ring_bonds`, `subst`, `unsat`, `h_min`, `aromatic`, and from 0.6.0 `smarts`, the SMARTS text of an atom query the other fields cannot express (SMARTS import writes it; it wins over the other fields). A bond's `query` is `any`, `single_or_double`, `single_or_aromatic` or `double_or_aromatic`, and `topology` is `ring` or `chain`.
+- `rgroups` on a scaffold fragment define its R-groups by number: `members` (fragment ids), `occurrence`, `rest_h`, `if_then`, and `attach`, a map of member fragment id to its attachment atom ids. A member without an `attach` entry attaches at its atoms with `data.attach` 1 or 2, else at its `*` stubs (no label, one bond, standing for the R atom), else at its first atom.
+- `expansions` hold what an abbreviation atom stands for (its atoms, bonds, attachment atoms and reversed label); `source` is `builtin` when the expansion came from the shipped library and `user` otherwise.
+- `media` maps a media id to `{name, mime, bytes, w, h, sha256}`; an `image` object names the id. The bytes go into the package as `media/[id].[ext]`, and only ids listed in `media` are written.
## What is not in the file
-The engine's chemistry (canonical SMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors, warnings) is a derived cache. It is rebuilt when a drawing opens and broadcast after every change, keyed by fragment id and document revision, and never saved. Undo history is kept per open drawing by the engine and is not saved either.
+The engine's chemistry (canonical SMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors, warnings, from 0.5.0 the balance check of every reaction step, and CIP labels that follow the stereo groups and the chiral flag) is a derived cache. It is rebuilt when a drawing opens and broadcast after every change, keyed by fragment id and document revision, and never saved. Undo history is kept per open drawing by the engine and is not saved either.
## Changes are transactions
@@ -31,4 +39,4 @@ Every change is a transaction: a list of `set`, `ins`, `del` and `move` ops on J
## Other formats
-Molfile, SDF, RXN, SMILES and CXSMILES, InChI, CML and CDXML files open as new, unsaved drawings laid out at the drawing's bond length. Exporting to them arrives in 0.7.0.
+Molfile, SDF, RXN, SMILES and CXSMILES, InChI, CML and CDXML files open as new, unsaved drawings laid out at the drawing's bond length; RXN files and CML or CDXML files with a reaction open as drawn schemes with their roles set. A reaction step exports as reaction SMILES or RXN (V2000 or V3000) from 0.5.0 ([Reactions](Reactions)); exporting whole drawings to the other formats arrives in 0.7.0. From 0.6.0 the engine also writes and reads V3000 molfiles with query features, enhanced stereo and R-group blocks, and SMARTS for query structures ([Stereo and Queries](Stereo-and-Queries)); a molfile with its chiral flag at 0 opens with its centres absolute. Templates use the document format too ([`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md)).
diff --git a/.docs/wiki/Reactions.md b/.docs/wiki/Reactions.md
new file mode 100644
index 00000000..a0d981df
--- /dev/null
+++ b/.docs/wiki/Reactions.md
@@ -0,0 +1,75 @@
+# Reactions
+
+From 0.5.0 FormChem reads a drawn scheme as a reaction: which structures react, which are reagents, what the conditions are. It can then map the atoms, check the balance and work out the amounts. Everything here is in the Reaction menu, and every change it makes is one undo step. The engine side, with every route, is [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md).
+
+## Draw the scheme
+
+1. Draw or insert the structures (Insert > Structure from SMILES, a template, or the drawing tools).
+2. Pick the arrow tool (`W`, or Reaction > Add Reaction Arrow) and drag from the reactants towards the products. `Shift` snaps to 15 degrees; `Alt` draws the arrow's other kind (an equilibrium becomes unbalanced, a forward arrow dashed).
+3. Put plus signs between structures with the symbol tool (`P`); a plus snaps to the centre line of the structure beside it.
+4. Put reagents above or below the arrow, as structures or text (`T`), for example "reflux, 2 h".
+
+Several arrows in a row make a multi-step reaction: the product of one step is the reactant of the next.
+
+## Perceive Reactions
+
+Reaction > Perceive Reactions reads every reaction arrow on the page and stores its steps:
+
+| Role | Where it sits |
+| --- | --- |
+| Reactants | before the arrow's tail, within 2.5 bond lengths of the arrow's line |
+| Products | after the arrow's head, within the same distance |
+| Reagents | between the tail and the head, within 1.5 bond lengths of the arrow |
+| Conditions | text in that same band |
+
+The nearest structure on each side takes the role; the next one joins it only across a plus sign or a gap under one bond length. Captions never take a role. Resonance, electron-pushing, fishhook, plain, fragmentation and dissociation arrows are not reaction steps; a retrosynthetic arrow reads from right to left.
+
+Running it again keeps the same reaction ids, your amounts and coefficients, and changes nothing when nothing moved. Steps read from a reaction file keep the roles the file gave, and so do steps whose roles you set by hand.
+
+## Set Reaction Roles
+
+When perception reads a role wrongly (water drawn after the arrow that should count as a reagent, a catalyst structure on the line), select the structures or text and choose Reaction > Set Reaction Roles.... The dialog lists the step's members and the selected objects, one row each with a role: Reactant, Product, Agent, Condition or None. Apply changes them as one undo step and marks the step's roles as set by hand, so Perceive Reactions keeps them from then on. Coefficients and stoichiometry amounts of an object that left its side are removed in the same step. Structures, text, captions, groups, pictures, shapes and tables can take a role; the arrow cannot. The command works on the step touching the selection, and perceives the page first when it has no step. Agents run it without the dialog: `run_command {id: "set-reaction-roles", params: {role: "agent", objects: [...]}}`.
+
+## Map Atoms
+
+Reaction > Map Atoms numbers each reactant atom with the product atom it becomes and marks the bonds that break, form or change order (it perceives first when the page has no step yet). The toast says whether every atom was mapped. Clear Atom Mapping removes the numbers and marks. Map numbers show next to the atoms.
+
+A command acts on the step whose arrow or structures you selected, or the first step on the page.
+
+## Check and balance
+
+Reaction > Check Balance... opens a dialog with the count of each element on both sides, the charge and the mass. When the step is not balanced it suggests coefficients (such as 2 A + B) or a missing co-product such as water or HCl. Balance Reaction, or the Balance button in the dialog, writes the coefficients. Reagents drawn above the arrow are not counted.
+
+A resonance arrow between two structures that are not resonance forms (different formula, charge or skeleton) shows a warning.
+
+## Stoichiometry
+
+View > Stoichiometry Panel (also in the Reaction menu) opens a grid under the canvas for the selected step:
+
+- Type a mass, or a volume with its density, or a volume with a solution's concentration, or equivalents, for each reactant and reagent; purity and a molecular weight of your own (for a salt or hydrate) are optional.
+- Or type a scale in mmol for the reaction.
+- The grid shows moles, equivalents, masses and volumes, marks the limiting reagent, and gives the theoretical yield. Type the isolated mass of the product for the percent yield.
+
+What you type is stored in the drawing; everything else is worked out. Typing a mass, a volume or equivalents for a component replaces the other two for that component, and a scale and the limiting reagent's own amount replace each other, so there is always one source for each number. Reaction > Insert Stoichiometry Table puts the grid on the page as a table under the reaction; inserting it again refreshes the same table.
+
+Example: 1.00 g benzoic acid with 1.2 equiv thionyl chloride at 1.64 g/mL gives 8.19 mmol and 9.83 mmol, so 0.713 mL of thionyl chloride.
+
+## Copy, export, paste and open
+
+- Reaction > Copy Reaction As > SMILES or RXN puts the step on the clipboard, with its map numbers.
+- Reaction > Export Reaction writes a `.rxn` or reaction SMILES file; the RXN keeps the title and the conditions line.
+- Reaction > Insert Reaction from Clipboard lays out pasted reaction SMILES or an RXN as a drawn scheme with an arrow, plus signs and the conditions under the arrow.
+- File > Open opens `.rxn` files, and CML or CDXML files holding a reaction, as drawn schemes.
+
+Coefficients have no place in reaction SMILES or RXN and are left out.
+
+## For agents
+
+Four MCP tools: `perceive_reactions`, `map_reaction` (with `mode: "clear"` to remove a mapping), `export_reaction` and `reaction_stoichiometry`. The first two change the drawing and ask you first, like any agent change. See [Agents](Agents).
+
+## Known limits
+
+- A structure that is the product of one step and the reactant of the next has one set of map numbers; mapping the second step replaces the first step's numbers.
+- A step whose atoms come from a reagent drawn above the arrow reads as unbalanced.
+- A `.smi` file with reaction SMILES does not open as a reaction; paste its text with Insert Reaction from Clipboard.
+- Perception reads top-level objects only (a group counts as one) and reads a bent arrow by its ends.
diff --git a/.docs/wiki/Stereo-and-Queries.md b/.docs/wiki/Stereo-and-Queries.md
new file mode 100644
index 00000000..32ce51f4
--- /dev/null
+++ b/.docs/wiki/Stereo-and-Queries.md
@@ -0,0 +1,71 @@
+# Stereo and Queries
+
+From 0.6.0 FormChem reads and edits stereochemistry in depth and draws query structures: atom lists, generic atoms, query bonds, R-groups and Markush structures. Every command here is one undo step. The engine side, with every route, is [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md).
+
+## Stereo labels
+
+Draw stereocentres with wedges and hashes (bond tool `B`, or hover a bond and press `W` or `H`). View > Show Stereochemistry draws the labels the engine works out with the CIP rules:
+
+| Label | Where it shows |
+| --- | --- |
+| (R), (S) | under the centre's label or position |
+| (r), (s) | pseudo-asymmetric centres, such as C3 of pentane-2,3,4-triol |
+| (E), (Z) | beside a stereogenic double bond |
+
+A centre without a wedge, or a double bond with a substituent on its line, is undefined and gets no label; a wavy bond marks it unknown on purpose. Isotopes count, so a CHD centre is a stereocentre. Allene axial chirality and atropisomers (a hindered biaryl) are not perceived in this version.
+
+Structure > Assign Wedges redraws the wedges of the selected centres (or every defined centre) the way the chemistry reads them: one wedge per centre, on a bond outside a ring where possible, with its narrow end on the centre. Use it after a clean-up or an import that left wedges in awkward places.
+
+## Enhanced stereo
+
+Enhanced stereo says what is known about a mixture:
+
+| Group | Means | Shown as |
+| --- | --- | --- |
+| abs | this configuration, as drawn | abs |
+| AND n | both configurations of these centres are present (a racemate when the group holds every centre) | and1, and2 |
+| OR n | one configuration, not known which | or1, or2 |
+
+Select stereocentres and use Structure > Enhanced Stereo: Absolute (abs), New AND Group, New OR Group or Clear Stereo Group. Stereo Group... opens a small popover with the kind, the group number and the groups already in the drawing as chips: click a chip to join it. The same items are on the atom right-click menu. View > Show Enhanced Stereo Groups draws the group labels under the CIP labels, in a colour per group when group colours are on.
+
+The structure's chiral flag (absolute, relative or racemic) shows under it. Relative puts every centre that is in no group into one OR group, racemic into one AND group. A molfile with its chiral flag at 0 opens with its centres absolute, as most programs mean it.
+
+## Abbreviations
+
+Select a group of atoms (for example the CO2H of a carboxylic acid, without the carbon it hangs on) and choose Structure > Contract Abbreviation.... The dialog searches the library of 106 abbreviations (Me to TBS, Ts, Boc, Fmoc, CO2Et and the rest) and proposes the match; type a new label to use your own. Expand Abbreviation on a selected label such as OTs or Ph (or with nothing selected, on every abbreviation on the page) draws its atoms back, laid out along the attachment bond on the side with more room; after a contract, expand returns the same atoms to the same place. Your own abbreviations go in `abbreviations.json` in the FormChem data folder: a list of `{"label": "PMB", "smiles": "*Cc1ccc(OC)cc1"}` entries, the `*` marking the attachment.
+
+Structure > Add Explicit Hydrogens draws the implicit hydrogens as atoms (of the selection, or everything), and Remove Explicit Hydrogens folds them back. Hydrogens that carry stereo, an isotope, a charge or a map number are kept.
+
+## Query atoms and bonds
+
+A query structure describes what to search for. Right-click an atom for Atom Query, or use Structure > Query:
+
+| Feature | Tag on the canvas | Means |
+| --- | --- | --- |
+| Atom List... | `[C,N,O]` or `not [Cl,Br]` | any of these elements, or none of them (pick from the periodic table) |
+| Any Atom (A) | A | any atom except hydrogen |
+| Any Heteroatom (Q) | Q | any atom except carbon and hydrogen |
+| Any Halogen (X) | X | F, Cl, Br, I or At |
+| Any Metal (M) | M | any metal |
+| Aromatic, Aliphatic | arom, aliph | the atom must or must not be aromatic |
+| Unsaturated | u | the atom has a double, triple or aromatic bond |
+| Substitution as Drawn | s* | exactly as many heavy neighbours as drawn |
+| Ring Bonds as Drawn | rb2 | exactly as many ring bonds as drawn |
+
+The hover keys `A`, `Q`, `X` and `M` set the generic atoms directly. Right-click a bond for Query Bond: Any Bond, Single or Double (S/D), Single or Aromatic (S/A), Double or Aromatic (D/A), In a Ring, In a Chain, or Clear Bond Query; the hover key `0` sets any bond. Query features are drawn as small purple tags; View > Show Query Features hides or shows them. Check Structure notes query features in a drawing that is not meant as a query.
+
+## Find Substructure and SMARTS
+
+Edit > Find Substructure... searches every structure on the page and selects the matches. With atoms of one structure selected, those atoms (and the bonds among them) are the query; with nothing selected it asks for a SMARTS pattern such as `C(=O)[OH]`. The toast says how many matches in how many structures.
+
+Copy as SMARTS (Edit or Structure > Query) copies the selected atoms, or every structure on the page, as SMARTS with its query features; Export SMARTS... saves a `.sma` file (in the desktop app it copies instead, until 0.7.0).
+
+## R-groups and Markush structures
+
+1. Draw the scaffold and each substituent as its own structure. Mark where a substituent attaches with an attachment point: a `*` atom with one bond.
+2. Select the scaffold atom that varies and choose Structure > Query > Define R-Group... (or right-click it). The atom becomes R1 (the next free number).
+3. In the dialog, pick the members, the occurrence (`1`, a range such as `1-3`, or `>0`), whether unfilled positions are hydrogen (Rest H), and an if-then condition (R1 only when R2 is present).
+
+The canvas writes `R1 =` beside each member, a wavy mark at its attachment and a summary line under the scaffold. Structure > Query > Enumerate R-Groups... lists every structure the definition stands for, with its SMILES and formula; Copy SMILES copies them all. Molfiles in V3000 carry the R-group definitions in and out.
+
+Not built yet: link nodes and variable attachment (a substituent on any position of a ring).
diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md
index ad54eaf6..b36e1ab9 100644
--- a/.docs/wiki/_Sidebar.md
+++ b/.docs/wiki/_Sidebar.md
@@ -3,6 +3,10 @@
- [Home](Home)
- [Getting Started](Getting-Started)
- [Drawing](Drawing)
+- [Annotations](Annotations)
+- [Reactions](Reactions)
+- [Stereo and Queries](Stereo-and-Queries)
+- [Analysis](Analysis)
- [Agents](Agents)
- [Terminal](Terminal)
- [Extensions](Extensions)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9df4c667..8483ff03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,115 @@
Versions follow `v*.*.*` with dots. Dates are US Eastern.
+## 0.6.0 · 2026-12-03
+
+Stereo, queries and analysis: FormChem now reads and edits stereochemistry in depth, draws query structures and R-groups, and computes properties, structure checks and isotope patterns with the method behind every number.
+
+### New
+
+- (R) and (S), (r) and (s), and (E) and (Z) labels are worked out by the engine with the new CIP rules, including pseudo-asymmetric centres and isotopes such as a CHD centre. View > Show Stereochemistry draws them under the atom or beside the bond.
+- Enhanced stereo groups: Structure > Enhanced Stereo puts the selected centres into an absolute, AND or OR group, and Stereo Group... opens a small popover with the group number and the groups already in the drawing. View > Show Enhanced Stereo Groups labels them abs, and1 or or2, in colour if you like. The chiral flag (absolute, relative or racemic) shows under the structure.
+- Structure > Assign Wedges redraws the wedges and hashes of the stereocentres the way the chemistry reads them, with one wedge per centre placed on a bond outside the ring where possible.
+- Abbreviations: a library of 106 (alkyl, aryl, protecting groups, silyl and sulfonyl groups, functional groups). Contract Abbreviation... turns the selected group into a label such as CO2H or OTs, picked from the library or typed, and Expand Abbreviation puts the atoms back where they were, with their old ids. Your own abbreviations go in `abbreviations.json` in the FormChem data folder.
+- Add Explicit Hydrogens and Remove Explicit Hydrogens, spread into the open space around each atom. Hydrogens that carry stereo, an isotope, a charge or a map number are kept.
+- Query structures: Atom List... picks elements from a periodic table, as "any of these" or "none of these". The Query menu and the atom and bond right-click menus set any atom (A), any heteroatom (Q), any halogen (X), any metal (M), aromatic or aliphatic, unsaturated, substitution and ring bonds as drawn, and query bonds (any, single or double, single or aromatic, double or aromatic, in a ring or in a chain). Query features are drawn as small purple tags (View > Show Query Features).
+- R-groups and Markush structures: Define R-Group... turns an atom into R1, R2 and so on, with its members, occurrence (such as 1, 1-3 or >0), rest H and an if-then condition. Enumerate R-Groups... lists every structure the definition stands for, with its SMILES and formula, and copies them.
+- Edit > Find Substructure... finds a SMARTS pattern, or the atoms you selected, in every structure on the page and selects the matches. Copy as SMARTS and Export SMARTS write the selection or a query structure as SMARTS.
+- The Analysis panel has a Properties section: formula, molecular weight, exact mass, m/z, elemental analysis, cLogP, TPSA, molar refractivity, H-bond donors and acceptors, rotatable bonds and the Lipinski rule of five. Hover a row to see the method behind it, such as Crippen's cLogP with its typical error. Agents also get rings, fraction Csp3, stereocentres and the Veber rules.
+- The isotope pattern of the selection is drawn as a stick plot in the Analysis panel, with the monoisotopic mass and the m/z of [M+H]+, [M+Na]+ and [M-H]-. Copy Analysis puts every value with its method and the peaks on the clipboard.
+- Check Structure opens a panel that lists errors, warnings and notes with a code for each (valence, unusual charges, misplaced or ambiguous wedges, undefined stereocentres and double bonds, overlapping atoms, crossing bonds, unusual bond lengths, uncommon isotopes, R-group gaps and more). Click a row to select its atoms; Fix repairs wedges or expands an abbreviation as one undo step; Check Again keeps the list in place.
+- Reaction > Set Reaction Roles... lists the members of the selected step and the selected structures and text, each with a role (reactant, product, agent, condition or none). Apply changes the roles as one undo step and marks them as set by hand, so Perceive Reactions keeps them.
+- Molfiles in V3000 carry query atoms and bonds, enhanced stereo groups and R-group definitions in and out.
+- Agents get four analysis tools: `properties`, `check_structure`, `stereo` and `substructure`. The new chemistry commands (hydrogens, abbreviations, wedges, stereo groups, atom lists, R-groups, reaction roles, SMARTS) also run through `run_command`.
+
+### Improved
+
+- The stereo and query marks find the free side of an atom and turn aside when a neighbouring label is in the way.
+- Every new menu item, dialog, panel and message is translated into all 25 languages.
+
+### Changed
+
+- The Structure menu now holds the abbreviation, hydrogen, wedge, Enhanced Stereo and Query commands. Show Stereochemistry moved to the View menu, and Compute Properties and Copy Analysis are in the Analysis menu.
+- Check Structure is a panel that stays open while you work instead of a dialog.
+- The Analysis panel's formula, masses and elemental analysis now come from the engine, with their methods; they are worked out only while the panel is open.
+- A molfile whose chiral flag is 0 opens with its stereocentres absolute, as most drawing programs and databases mean it, rather than as a racemate.
+
+### Fixed
+
+- The desktop build stopped with "the Tauri CLI did not install", because the window's packages never listed the Tauri CLI. It is now pinned at 2.12.6, matching the Tauri crate 2.12, and the message says what to check. With the pin, `./build_app` built the desktop app on macOS (Apple silicon, Python 3.14).
+- `./build_app` left the template library out of the engine it froze, so Insert > Template was empty in a desktop app built that way.
+- Sodium and other metal cations in salts, such as Na+, were reported as valence errors.
+- Query atoms (A, Q, X, M and atom lists) and a bare `*` attachment point were reported as unknown labels.
+- The Analysis panel's formula counted deuterium as hydrogen.
+
+### Known issues
+
+- Allene axial chirality and atropisomers (such as a hindered biaryl) are not perceived, so they get no label.
+- Link nodes and variable attachment (a substituent on any position of a ring) are not built yet.
+- A SMARTS pattern with aromatic atoms brought in as a drawing shows its ring with single bonds, although it matches aromatic rings.
+- In the desktop app Export SMARTS copies the SMARTS to the clipboard instead of saving a file, until the file formats arrive in 0.7.0.
+- The macOS native menu with the new Structure and View items was not run in this build.
+- Enumerate R-Groups can count more structures than it lists, because the count is taken before duplicates and if-then conditions are removed.
+
+### Under the hood
+
+- Enhanced stereo groups and the chiral flag go into RDKit with the structure, so SMILES, CXSMILES and the derived cache carry them.
+- The engine has new analysis routes under `/api/analysis` (properties, CIP, structure check, stereo groups, wedges, abbreviations, hydrogens, SMARTS, substructure search, V3000 query molfiles, Markush enumeration and the isotope pattern). Each command that changes the drawing returns one transaction for the window to commit as one undo step. They are documented in `docs/ANALYSIS.md`.
+- The canvas draws stereo, enhanced group and query marks through one keyed layer, so a change patches only its own marks.
+- The drawing format gains SMARTS atom queries, R-group attachment atoms, the expansion's library source and the chemistry of the chiral flag.
+
+## 0.5.0 · 2026-12-03
+
+Reactions and annotations: draw a scheme with arrows, plus signs and conditions, and FormChem reads it as a reaction, maps its atoms, checks its balance and works out the amounts.
+
+### New
+
+- Reaction arrows of every kind: forward, equilibrium (also unbalanced), reversible, resonance, retrosynthetic, no-go, dashed, plain, fragmentation and dissociation, with full, half, open or hollow heads at either end. `Shift` snaps the angle to 15 degrees and `Alt` draws the arrow's other kind.
+- Electron-pushing and fishhook arrows start on an atom, a lone pair or a bond and end on an atom, a bond or between two atoms where a new bond forms. They bulge away from the structure and follow it when it moves.
+- Plus, equals and adduct dot signs that snap to the centre line of the structure beside them.
+- Round, square and curly brackets. A bracket dragged around a repeat unit with two crossing bonds is labelled `n`; double-click a bracket to change its label.
+- Rectangles, rounded rectangles, ellipses, polygons, lines and smooth polylines, with dashes, solid or gradient fills, opacity and shadows.
+- Tables, TLC plates with lanes, spots and Rf values (click a plate to add a spot), and s, p, d, dz2, sp, sigma and pi orbitals that can sit on an atom.
+- Insert > Image places a PNG, JPEG, GIF, WebP or SVG picture; it is saved inside the `.fchem` file.
+- Captions attach to a structure and move with it; `Ctrl`-click with the caption tool adds the next compound number in bold.
+- The selection tool shows handles: drag an arrow's ends or its bend, a line's points, or the eight handles of a box to resize it.
+- Arrange has Bring to Front, Bring Forward, Send Backward, Send to Back, Group (`Ctrl+G`) and Ungroup (`Ctrl+Shift+G`). A click on a member selects its group; `Alt`-click or a double-click reaches the member.
+- Reaction > Perceive Reactions reads the reactants, products, reagents and conditions from where they sit around each arrow, including schemes of several steps.
+- Map Atoms numbers the reactant atoms onto the product atoms and marks the bonds broken, formed and changed; Clear Atom Mapping removes the numbers.
+- Check Balance shows the element, charge and mass balance of a step and suggests coefficients or a missing co-product such as water or HCl; Balance Reaction applies the coefficients.
+- The Stoichiometry panel (View or Reaction > Stoichiometry Panel): type a mass, a volume with its density, a solution's concentration, equivalents or a scale, and read the moles, the limiting reagent, the theoretical yield and the percent yield. Insert Stoichiometry Table puts the grid on the page, and inserting it again refreshes the same table.
+- Copy a reaction as reaction SMILES or RXN, export it to a file, and Insert Reaction from Clipboard to lay out a pasted reaction as a drawn scheme. RXN files and CML or CDXML files with a reaction open as drawn schemes, with their conditions line kept.
+- A template library of 206 original templates in nine categories (rings, polycycles, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and solvents, glassware), from Insert > Template and the Templates section on Home. Your own templates go in the `templates` folder of the FormChem data folder.
+- Edit > Find (`Ctrl+F`) searches text, captions, table cells, atom labels, abbreviations, element symbols, formulas such as `C2H6O` and SMILES. `Enter` or `F3` steps through the matches, and Replace (`Ctrl+Alt+F`) changes text, captions and table cells; Replace All is one undo step.
+- View > Show Rulers shows rulers along the top and left of the canvas in the drawing's units (click the corner to switch between pt, mm, cm and in). Drag a guide out of a ruler, drag it back to remove it, or use Clear Guides.
+- Agents get four reaction tools: `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`.
+
+### Improved
+
+- The tool rail has new groups with their own icons: Arrows (`W`), Symbols (`P`), Brackets (`K`), Shapes (`G`), Table, TLC, Image and Orbitals (`O`).
+- Arrows, lines and outlined shapes are picked by what is drawn, so a click near a curved arrow no longer grabs it from far away.
+- Every new menu item, tool name, panel and message is translated into all 25 languages. The headings of a stoichiometry table drawn on the page stay in English, because they are part of the drawing.
+
+### Fixed
+
+- A drawing opened from Home stayed blank until the pointer moved over the canvas.
+
+### Known issues
+
+- Set Reaction Roles arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing.
+- When a structure is the product of one step and the reactant of the next, mapping the second step replaces the first step's map numbers.
+- The balance check counts reactants and products only, so a step whose atoms come from a reagent drawn above the arrow reads as unbalanced.
+- A `.smi` file holding reaction SMILES does not open as a reaction; paste its text with Insert Reaction from Clipboard.
+- `Enter` does not finish a polyline; double-click or click its first point.
+- Templates land in the middle of the view and can overlap what is there, and cannot yet be fused onto an atom or a bond. Insert > Image puts the picture's corner, not its centre, in the middle of the view.
+
+### Under the hood
+
+- Every drawn object kind goes through one registry in the renderer, and a change of stacking order moves only the nodes whose place changed.
+- The engine reads reactions with RDKit and maps atoms with Indigo. The window and the engine work out stoichiometry by one rule: a typed scale wins over the limiting reagent's own amount.
+- The chemistry the engine sends after each change now carries the balance check of every reaction step.
+- The reaction routes, the stoichiometry rules and the template format are documented beside the drawing format.
+
## 0.4.0 · 2026-12-02
You can draw. FormChem now has its drawing canvas, so structures can be built with the mouse and the keyboard and look ready for a journal.
diff --git a/README.md b/README.md
index 8a5d08c8..2792eb7f 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@
with an MCP server so an agent works in the same window you see. Local-first, no account.
-
+
@@ -28,7 +28,7 @@
## Features
-FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas with the mouse or the keyboard, and the chemistry engine checks and measures every change.
+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.
@@ -38,11 +38,21 @@ FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas wit
Chemistry engine
RDKit in the engine works out canonical SMILES, CXSMILES, InChI, InChIKey, formula and masses after each change, flags valence problems on the canvas, and powers Clean Up, Lay Out and Check Structure.
-
Analysis panel
Formula, molecular weight, exact mass, m/z for charged species and elemental analysis for the selection or the whole page, with the formula in the status bar.
+
Analysis panel
Formula, masses, m/z and elemental analysis, plus cLogP, TPSA, molar refractivity, donors, acceptors, rotatable bonds and the rule of five, each with its method, and the isotope pattern with adduct m/z. Copy Analysis takes it all as text.
Arrange and style
Duplicate, delete, flip, rotate, align and distribute the selection; Drawing preferences set the default style and its bond length, widths and label size; element colours, carbon labels and stereo labels on request.
-
MCP server
Six tools over HTTP and stdio: agents see the open drawings with their formulas, insert structures from SMILES and run the same commands as the menus.
+
Reactions
Perceive Reactions reads reactants, products, reagents and conditions around each arrow, multi-step schemes included. Atom mapping with reacting bonds, balance checks with suggested coefficients, and reaction SMILES and RXN in and out.
+
Annotations
Fifteen arrow types and anchored electron-pushing arrows, plus signs, brackets, shapes, lines, tables, TLC plates, orbitals, pictures and attached captions, with handles, stacking order and groups.
+
Stoichiometry and templates
A stoichiometry panel for moles, equivalents, the limiting reagent and yields, insertable as a table, and 206 original templates from rings to glassware. Find and rulers with guides.
+
+
+
Stereochemistry
CIP labels from the new rules (R, S, r, s, E, Z), enhanced stereo groups (abs, AND, OR) and the chiral flag, Assign Wedges, and abbreviations from a library of 106 that contract and expand without losing an atom.
+
Queries and R-groups
Atom lists, generic atoms and query bonds drawn as tags, Find Substructure by selection or SMARTS, SMARTS and V3000 query molfiles, and R-group definitions with Markush enumeration.
+
Structure check
A panel of errors, warnings and notes with a code each, from valence and charges to wedges, overlaps and R-group gaps. Click a row to select its atoms, or fix wedges and abbreviations in one step.
+
+
+
MCP server
Fourteen tools over HTTP and stdio: agents see the open drawings with their formulas, run the same commands as the menus, perceive, map, export and measure reactions, and read properties, structure checks, stereo and substructure hits.
The family shell
Home, Preferences, twelve menus with full keyboard use, 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.
@@ -50,8 +60,6 @@ FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas wit
### Coming next
-- Reactions, arrows and annotations
-- Stereochemistry, query structures and analysis
- Reading and writing the common chemical file formats
- Names, predicted spectra and spectrum viewing
- 3D models of molecules
@@ -59,7 +67,7 @@ FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas wit
## Built for agents
-The engine's MCP server drives the same command catalogue as the window through six tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`. Reading is always open; the window asks before an outside agent changes anything. `get_context` lists the open drawings with their formulas, and `run_command insert-smiles {"smiles": "c1ccccc1O"}` puts a structure on the canvas as one undo step. Dedicated drawing tools for agents arrive in 0.8.0.
+The engine's MCP server drives the same command catalogue as the window through `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus four reaction tools (`perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`) and four analysis tools (`properties`, `check_structure`, `stereo`, `substructure`). Reading is always open; the window asks before an outside agent changes anything. `get_context` lists the open drawings with their formulas, and `run_command insert-smiles {"smiles": "c1ccccc1O"}` puts a structure on the canvas as one undo step. Dedicated drawing tools for agents arrive in 0.8.0.
```sh
./formchem agents install # writes .mcp.json, .codex/config.toml, .cursor/mcp.json and Antigravity's ~/.gemini/config/mcp_config.json, installs the skills
@@ -96,7 +104,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; reactions, export, stereo tools and 3D come in later versions. Nothing is built or released for download yet.
+> **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; file export, names, spectra and 3D come in later versions. 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.
@@ -104,7 +112,7 @@ cd formchem
| Path | What it is |
|---|---|
-| `backend/` | FastAPI engine: documents, live channel, terminal dock, extensions, MCP |
+| `backend/` | FastAPI engine: documents, chemistry, reactions and analysis, templates, live channel, terminal dock, extensions, MCP |
| `frontend/` | Vanilla TypeScript and Vite window: the drawing canvas and tools, shell, menus, Home, Preferences, dock |
| `setup/` | Install, boot, build, freeze and agent setup scripts |
| `src-tauri/` | Desktop shell and the engine sidecar |
diff --git a/agents/manifest.json b/agents/manifest.json
index 8a3672a5..3ff9a4a9 100644
--- a/agents/manifest.json
+++ b/agents/manifest.json
@@ -9,17 +9,33 @@
"run_command",
"extensions_list",
"extension_command",
- "handoff"
+ "handoff",
+ "perceive_reactions",
+ "map_reaction",
+ "export_reaction",
+ "reaction_stoichiometry",
+ "properties",
+ "check_structure",
+ "stereo",
+ "substructure"
],
"read_only": [
"get_context",
"list_commands",
- "extensions_list"
+ "extensions_list",
+ "export_reaction",
+ "reaction_stoichiometry",
+ "properties",
+ "check_structure",
+ "stereo",
+ "substructure"
],
"approval_gated": [
"run_command",
"extension_command",
- "handoff"
+ "handoff",
+ "perceive_reactions",
+ "map_reaction"
],
"transports": [
"stdio",
@@ -32,7 +48,9 @@
"sub_skills": [
"extension-drawings",
"handoff",
+ "reactions",
"session-and-connection",
+ "structure-analysis",
"visual-qa",
"window-commands"
]
@@ -41,6 +59,7 @@
"name": "formchem-skillset",
"sub_skills": [
"agents",
+ "annotations",
"canvas",
"chemistry-engine",
"clean-room",
@@ -50,7 +69,9 @@
"engine",
"extensions",
"menus",
+ "reactions",
"release",
+ "stereo-and-queries",
"window-shell"
]
}
diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md
index 4904c701..7dc23de5 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.4.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, and from 0.3.0 it records the chemistry engine, the document store and the file format, 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.6.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, 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
@@ -10,15 +10,23 @@ backend/app/main.py app, middleware order, discovery file (engine.json)
backend/app/core/ config.py (ports, data dirs, settings store), local_guard.py, window_key.py, seal.py,
startup.py, runtime.py, ids.py
backend/app/routers/ system (health, version, capabilities, settings, notices, window key and ticket), live (WebSocket),
- library, commands, terminal, chat, extensions, mcp, documents (0.3.0), chem (0.3.0)
+ library, commands, terminal, chat, extensions, mcp, documents (0.3.0, media 0.5.0), chem (0.3.0),
+ reactions (0.5.0), templates (0.5.0), analysis (0.6.0)
backend/app/core/files.py safe file names and free names for saves and imports (0.3.0)
backend/app/services/ hub.py (client and agent table), bridge.py (window tools over the live channel), library.py,
terminal.py, consent.py, claude_code.py, agent_programs.py, agent_lookup.py (vendored),
formext_host.py (vendored), chat/
model.py, ops.py (the format contract and transactions, 0.3.0), store.py (open documents,
undo, derive loop), package.py (.fchem zip), history.py (autosave, versions), importers.py
+ templates.py (the template library, 0.5.0)
backend/app/services/chem/ abbrev, convert, perceive, ids, mass, layout, io, derive (RDKit and Indigo, 0.3.0)
+ geometry, reactions, rxnio, scheme, mapping, balance, stoich (reactions, 0.5.0)
+ stereo, superatom, hydrogens, query, search, v3000, markush, props, check, isotopes (analysis, 0.6.0)
+backend/app/data/templates/ 206 original templates in nine category files (0.5.0)
docs/FORMAT.md the document format, the single source for both languages (0.3.0)
+docs/REACTIONS.md reaction perception, mapping, balance, stoichiometry and their routes (0.5.0)
+docs/ANALYSIS.md stereo, queries, R-groups, properties, the structure check, the isotope pattern and their routes (0.6.0)
+docs/TEMPLATES.md the template file format and API (0.5.0)
backend/requirements*.txt pins for the engine and for the desktop freeze
formchem, formchem.bat one dispatcher for install, boot, serve, build, desktop, doctor, clean
setup/ the commands behind the dispatcher, plus notices.py, i18n_tool.py, catalogue.py
@@ -89,6 +97,42 @@ build_app, build_app.bat desktop bundle build, teed to build_app.log
60. The skill packs describe what the code does, not the plan · .claude/skills, .agents/skills, agents/manifest.json
61. get_context lists open drawings and says what agents can do today · routers/mcp.py
62. The notices generator reads the flat font layout · setup/notices.py
+63. Page geometry for reactions is an estimate in points · services/chem/geometry.py
+64. Perception works in the arrow's own frame · services/chem/reactions.py
+65. Re-perceiving keeps ids, explicit steps and writes nothing when equal · services/chem/reactions.py perceive_ops
+66. Reaction SMILES and RXN from one builder · services/chem/rxnio.py
+67. Reaction files open as drawn schemes · services/chem/scheme.py, services/importers.py
+68. Mapping tries molecule orders and keeps the best score · services/chem/mapping.py
+69. Balance solves exactly and suggests co-products · services/chem/balance.py
+70. Stoichiometry: typed amounts win, a typed scale wins over them · services/chem/stoich.py
+71. The reactions router: one transaction per changing route · routers/reactions.py
+72. Media bytes are held by the session, listed by the window's transaction · routers/documents.py, services/store.py, services/package.py
+73. The template library is data, built once and cached · services/templates.py, routers/templates.py, data/templates
+74. The derived cache carries each step's balance check · services/chem/derive.py reaction_checks
+75. Four reaction tools on the MCP server · routers/mcp.py
+76. Wiring the phase 5 routers and the frozen engine · app/main.py, setup/freeze_backend, setup/freeze_backend.bat
+77. The generated tools reference carries a contents list · setup/agents.py tools_text
+78. Stereo groups and the chiral flag go into RDKit with the molecule · services/chem/convert.py, services/chem/derive.py
+79. A molfile chiral flag of 0 reads as absolute · services/chem/convert.py from_mol
+80. The stereo report, and the stereo the engine does not perceive · services/chem/stereo.py report, services/chem/perceive.py
+81. Wedges are placed by RDKit for the configuration wanted · services/chem/stereo.py rewedge
+82. The abbreviation library is data, with the person's file on top · services/chem/abbrev.py
+83. Contract and expand keep atom ids · services/chem/superatom.py, routers/analysis.py _ids_of
+84. Explicit hydrogens go into the widest gaps and keep the configuration · services/chem/hydrogens.py
+85. A query is one RDKit query molecule built from SMARTS primitives · services/chem/query.py query_mol
+86. SMARTS in and out · services/chem/query.py to_smarts, from_smarts
+87. Substructure hits come back as ids · services/chem/search.py
+88. FormChem writes V3000 query molfiles and reads R-group blocks itself · services/chem/v3000.py
+89. Markush enumeration and the attachment fallback order · services/chem/markush.py
+90. Every property names its method · services/chem/props.py
+91. The structure check has codes, severities and named fixes · services/chem/check.py
+92. Metal cations are not valence errors · services/chem/perceive.py _valence
+93. Query atoms and bare stars are generics, not unknown labels · services/chem/convert.py _query_label, services/chem/v3000.py
+94. The isotope pattern is a convolution merged at 0.01 Da · services/chem/isotopes.py
+95. The analysis router: a fragment or a document in, one transaction out · routers/analysis.py, app/main.py
+96. Four analysis tools on the MCP server · routers/mcp.py
+97. build_app names package.json when the Tauri CLI is missing · build_app
+98. build_app bundles the template library when it freezes the engine · build_app
## 1. Ports and the data folder are FormChem's own · _v0.1.0 (app/core/config.py)
@@ -337,3 +381,147 @@ The MCP text still said there were no documents. `get_context` now lists each op
## 62. The notices generator reads the flat font layout · _v0.4.0 (setup/notices.py)
The bundled fonts sit flat in `frontend/public/fonts` with `Arimo-OFL.txt` and `Tinos-OFL.txt`, but the generator only looked for `fonts/full//OFL.txt`, so THIRD-PARTY-NOTICES.txt carried no font licences. It now reads both layouts (a `Family-OFL.txt` file and an optional `Family-VERSION` file beside the fonts, or the old folder), and the notices were regenerated with both families. The licence is SIL OFL 1.1: Arimo and Tinos moved from `apache/` to `ofl/` in google/fonts in April 2026, so the Apache-2.0 named in the brief and in the first FORMAT.md is out of date; OFL allows bundling with software as long as the licence and copyright travel with the files.
+
+## 63. Page geometry for reactions is an estimate in points · _v0.5.0 (services/chem/geometry.py)
+
+Perception, layout and the grid need boxes for every object without a renderer. `object_box(doc, oid, style)` covers every kind: fragments from atom positions (`fragment_box`), text by an estimate of 0.55 em per character and 1.2 line height with sub and superscripts at 75 percent (`text_box`), arrows from their ends plus the arc's midpoint when bent (`arrow_box`), groups as the union of their children, and boxed kinds from `x`, `y`, `w`, `h` and `rot`. The estimate errs a little wide, which is the safe side for "is this near the arrow". `Frame(tail, head)` gives `along(p)` and `across(p)` and `project(box) -> (s0, s1, t0, t1)`, the coordinates every perception rule is written in. The window's render/bounds.ts measures the drawn text instead, so the two can differ by a fraction of a character; nothing compares them.
+
+## 64. Perception works in the arrow's own frame · _v0.5.0 (services/chem/reactions.py)
+
+Measuring along the shaft (s from the tail) and across it (t) makes tilted and vertical arrows work with the same rules. The constants are bond lengths of the drawing: `BAND_BONDS = 1.5` (agents and conditions: centre between the ends, within 1.5 of the shaft, from clean-room spec A section 11), `ROW_BONDS = 2.5` (reactants and products reach within 2.5 of the shaft's line), `END_BONDS = 0.5` (an object may overlap an end by half a bond), `JOIN_BONDS = 1.0`. Walking away from the tail (or head), the nearest structure takes the role and the next joins only across a plus sign in the gap or a gap under one bond length, so in A + B -> C + D -> E the second step's reactants are C and D, and a step stops at another arrow. Captions never take a role; text takes one only as conditions in the band, or as a reactant or product when `formula` is true. Resonance, curved, fishhook, arc, plain, fragmentation and dissociation arrows are not steps; a retro arrow swaps the sides; an arrow with `head: none` and a tail head points backwards. Steps whose products are another step's reactants chain into one reaction, ordered by chain depth then arrow position; separate arrows are separate reactions, top to bottom, left to right. Only top-level page objects are looked at (a group is one object) and a bent arrow is read by its chord. FORMAT states the distances.
+
+## 65. Re-perceiving keeps ids, explicit steps and writes nothing when equal · _v0.5.0 (services/chem/reactions.py perceive_ops, preview)
+
+Perception is one `set` of `["pages", {id}, "reactions"]` labelled "Perceive reactions". Running it again keeps reaction and step ids (matched by arrow), keeps `coefficients` and `stoich` filtered to the ids still in the step, and returns no op when the result equals what is stored, so a second run answers `changed: false` and adds no undo step. A step with `explicit: true` is copied verbatim, even when its arrow was deleted (reported in the summary's `stale`), because the person or an agent set it on purpose. `preview` runs the same code without writing, for `GET .../reactions/preview`.
+
+## 66. Reaction SMILES and RXN from one builder · _v0.5.0 (services/chem/rxnio.py)
+
+`build(doc, step)` turns a step into an RDKit ChemicalReaction (groups expand to their fragments, agents included), and `export_step` writes `smiles`, `rxn` (V2000) or `rxnv3000`. RXN line 2 is the reaction or drawing title and line 4 the conditions text, which the importer reads back, so a round trip keeps the conditions. RXN molecules are kekulised like single molfiles, because an aromatic ring came out as bond type 4, which V2000 reserves for queries; reaction SMILES stays aromatic lower case. V3000 writes the `reacting` marks as RXCTR (broken and formed 4, order changed 8, unchanged 2, centre and stereo 1); RDKit has no V2000 writer for them. Coefficients have no place in either format and are dropped with `coefficient_dropped`; text conditions in reaction SMILES are dropped with `conditions_dropped`.
+
+## 67. Reaction files open as drawn schemes · _v0.5.0 (services/chem/scheme.py, services/importers.py)
+
+Imported reactions (RXN, reaction SMILES, CML or CDXML with a reaction) are laid out on one centre line: 1 bond length between structures and plus signs, 0.5 between the arrow ends and the structures, agents above the arrow, the arrow at least 4 bond lengths and as wide as the agents or the conditions text plus 7.2 pt each side. Structures that take no role go one row below. The step is written with `explicit: true`, because the file declared the roles. `importers.import_file` uses `scheme.layout` for reaction files and falls back to rows if layout raises; molecules with no usable coordinates (hydrogen-only species give NaN from `convert.from_mol`) are drawn in a row with a `no_coordinates` warning, the root cause being in `convert._ensure_2d` or `layout.depict`. `POST /api/chem/reactions/import` answers objects with fresh ids not checked against any drawing; `POST /api/documents/{id}/reactions/import` checks them and places the scheme under the page's content (`free_origin`). Not fixed: a `.smi` file holding reaction SMILES does not open, because `io.EXTENSIONS` maps `.smi` to `smiles` and `read_file` never detects `rsmiles`; the fix belongs in chem/io.py (a `>` in the first token).
+
+## 68. Mapping tries molecule orders and keeps the best score · _v0.5.0 (services/chem/mapping.py)
+
+Indigo's automap answer depends on the molecule order, and for the esterification some orders left a whole fragment unmapped. Discard mode therefore tries up to 24 molecule orders within 6 s (aam-timeout 3 s each), scores each by unmapped atoms, then bond edits, then hydrogen moves, keeps the best, and then swaps same-element product atoms while the score drops (up to 80 product atoms, 6 rounds). Keep and alter run once in the drawn order with the drawn numbers loaded. Map numbers are renumbered 1 to n in reactant order. The `reacting` marks (broken, formed, order) are computed from the mapping, not taken from Indigo, and a bond with an unmapped end gets none. AC11.3 holds: the acid's carbonyl carbon maps to the ester carbonyl and one C-O bond is formed (which oxygen ends in water is a tie the score cannot break). Map numbers live on atoms, so a structure that is the product of one step and the reactant of the next carries one set, and mapping the second step overwrites the first. Agents are not mapped, and atoms inside abbreviations get no number (`abbreviations_unmapped`).
+
+## 69. Balance solves exactly and suggests co-products · _v0.5.0 (services/chem/balance.py)
+
+`check(doc, step)` counts reactants and products, not agents (as the clean-room spec does), with their coefficients, by element symbol (isotopes merged), with charge and average mass. `solve(left, right)` solves the element and charge conservation system exactly with fractions; a unique positive solution with every coefficient up to 50 becomes `suggestion.coefficients`, otherwise up to two common co-products (water, HCl, HBr, CO2, SO2, N2, H2, NaCl) are tried and ranked by coefficient sum. `coefficient_ops` writes coefficient 1 as absent. The resonance check (AC11.4) takes the nearest structure on each side of a resonance arrow: a different formula or charge is `resonance_formula`, a different heavy-atom skeleton (all bonds single, no charges, hydrogens or isotopes) `resonance_connectivity`. Known effect: a step whose atoms come from a reagent drawn above the arrow (SOCl2) reads as unbalanced with no suggestion.
+
+## 70. Stoichiometry: typed amounts win, a typed scale wins over them · _v0.5.0 (services/chem/stoich.py)
+
+A typed amount (a mass, a volume with density, or a volume with concentration) wins over typed equivalents, which then only warn (`equiv_mismatch`) when they disagree by more than 1 percent. The reference is `scale_mmol`, else the typed limiting reactant's amount divided by its equiv, else the first reactant or agent with an amount; the window's chem/stoich.ts follows the same order (frontend log 125) and FORMAT states it with the clearing rules that keep the readings equal. Limiting is the typed one when it is a reactant, else the reactant with the fewest mmol per coefficient. Theoretical yield is limiting mmol over its coefficient times the product coefficient; percent yield uses `isolated_mg` for `product` (default the first product) or a product row's own `mass_mg`. Molecular weight is the component's `mw`, else the derived `mw` summed over a group's fragments. The grid (`grid`, `table_ops`) has the columns Compound, Formula, Role, MW, Equiv, Amount, Mass, Volume, Isolated, Yield, three significant figures, mass and amount switching unit at 1 (mg, g, kg; µmol, mmol, mol), volume at 0.1 (0.713 mL), formulas as subscript runs, and column widths from the same 0.55 em estimate. The window draws a live grid of seven columns; FORMAT documents both and a later change should settle on one set. AC11.1 and AC11.2 were checked through the route.
+
+## 71. The reactions router: one transaction per changing route · _v0.5.0 (routers/reactions.py)
+
+Every changing route answers `{changed, tx, rev, ...}`. `tx` is the applied transaction, broadcast on the live socket like any other with the body's `client` echoed, so the window that asked recognises its own change; `tx` is null and `changed` false when nothing changed, so no empty undo step is recorded. `origin` is `user` by default or `system`. Errors: 404 for an unknown drawing, page, reaction or step; 422 for bad input; 409 `{detail: {message, errors}}` when the store refuses the transaction; 413 for text over 20 MB. Mutating routes use the same window-key guard as documents.py. The router copies the document under the session lock, computes on the copy (mapping and reaction import in a worker thread) and commits through `STORE.apply`, so a long mapping never holds the lock. The ops are built from that copy and applied to whatever the document is when they arrive; a route does not check that the revision is unchanged, which is a gap only when the person edits the same step during a mapping. `POST .../export {format, path}` writes the export to an absolute path for the desktop window, which has no file system plugin. The routes and shapes are in docs/REACTIONS.md.
+
+## 72. Media bytes are held by the session, listed by the window's transaction · _v0.5.0 (routers/documents.py, services/store.py add_media, media_bytes, services/package.py sniff_image)
+
+`POST /api/documents/{id}/media` (window key, multipart `file`, 50 MB) does not change document.json. `Store.add_media` keeps the bytes in `Session.media` under a fresh `m` id and answers `{id, media: {name, mime, bytes, w, h, sha256}}`; the window then commits one transaction that sets `media[id]` and adds the image object. Placing a picture is therefore one undo step, and an undo leaves bytes behind that the package writer drops, because it writes only ids listed in `doc.media`. `sniff_image` reads the mime type and pixel size from the bytes themselves (PNG, JPEG SOF, GIF, WebP VP8, VP8L and VP8X; SVG by its opening tag) and anything else is a 415, so the file name never decides the type. `GET /api/documents/{doc_id}/media/{media_id}` serves the bytes with the mime from `doc.media` (else sniffed), `cache-control: private, immutable`, `nosniff` and a `default-src 'none'` CSP, so an SVG opened directly in a tab runs nothing. It is a GET, so the renderer's image elements load it without the window key. Checked: an 80 by 40 PNG gave a media record with w 80, h 40 and sha256, and after save, close and reopen the record was identical and the GET answered 200.
+
+## 73. The template library is data, built once and cached · _v0.5.0 (services/templates.py, routers/templates.py, data/templates)
+
+Templates are JSON per category in the document fragment format, each with one source: `smiles` (laid out once by RDKit through `io.read_text`), `ring` (a generator for flat-bottom regular rings, the orientation of the ring tools) or `objects` (hand-placed objects for Haworth and Fischer projections, chairs, cubane and glassware). RDKit lays out fused, bridged and stereo structures well, but projections and clip art need their exact geometry. All 206 build in about 0.2 s on the first request and are cached until a file's modification time or size changes (`_stamp`); a file over 4 MB is skipped. `fragment(id, bond_length)` answers fresh ids on every call (atoms, bonds, objects, group children, row and lane ids), so the window commits the objects as they come, and scales fragment coordinates from 14.4 pt to the drawing's bond length while shapes and lines keep their size. User templates in `FORMCHEM_DATA_DIR/templates/*.json` merge in with ids prefixed `user-`. Amino acid and nucleoside SMILES were checked with RDKit CIP (L amino acids S, cysteine R; isoleucine 2S,3S; threonine 2S,3R; adenosine 1'R,2'R,3'S,4'R). Haworth and Fischer templates carry no wedges, so the engine sees them without stereo; the skeletal glucose and fructose templates carry it. Everything is original data; docs/TEMPLATES.md is the format.
+
+## 74. The derived cache carries each step's balance check · _v0.5.0 (services/chem/derive.py reaction_checks)
+
+The balance check costs about a millisecond for a two plus two step, so `derive_document` adds a top-level `reactions` slot beside `fragments`: step id to `{balanced, elements, charge, mass, warnings}` (`CHECK_FIELDS`), at most 64 steps (`REACTION_CHECKS`), and a step whose check raises is skipped rather than failing the whole derive. `store._shape_derived` passes extra top-level keys through, so the store needed no change; FORMAT's derived table and `Derived.reactions` in model.ts describe the slot. The suggestion is not in the cache: it is only worth computing when someone asks for it.
+
+## 75. Four reaction tools on the MCP server · _v0.5.0 (routers/mcp.py)
+
+`perceive_reactions` and `map_reaction` change the drawing and are in `MUTATING`, so they go through the approval gate; `export_reaction` and `reaction_stoichiometry` are read-only. They call the same services as the routes and commit through `STORE.apply` with origin `agent` (`_apply`), so an agent's perception or mapping is one undo step the person sees. A tool that cannot find the step names `perceive_reactions` as the next step. `get_context` and the guide's opening still say that dedicated drawing tools arrive in 0.8.0; a sentence there naming the four reaction tools is still to add. `./formchem agents sync` regenerated the tools reference and the manifest with ten tools.
+
+## 76. Wiring the phase 5 routers and the frozen engine · _v0.5.0 (app/main.py, setup/freeze_backend, setup/freeze_backend.bat)
+
+The reactions and templates routers were written on their own branches and never included, so the window got 404 for every reaction and template route until main.py included both after `chem`, before the static mount at `/` (the routers carry full paths, so no prefix). `templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen, so both freeze scripts add `backend/app/data/templates` as `templates` data; without it the desktop library would be empty. Not run: pyinstaller, so the frozen sidecar with the template data is unchecked.
+
+## 77. The generated tools reference carries a contents list · _v0.5.0 (setup/agents.py tools_text)
+
+With ten tools, `.claude/skills/formchem-harness/references/tools.md` grew past 100 lines and the god-tier-skill-creator validator warned D4 (a reference file of 100 lines or more needs a `## Contents` section). The file is generated, so a hand edit would be undone by the next sync and fail `sync --check`; `tools_text` now writes `## Contents` after the opening paragraphs, listing the kinds table, every tool section from the TOOLS list and the resource, so the list follows the server as tools are added. Both packs validate with zero FAIL and zero WARN afterwards.
+
+## 78. Stereo groups and the chiral flag go into RDKit with the molecule · _v0.6.0 (services/chem/convert.py _read_groups, apply_groups, groups_from_mol; services/chem/derive.py content_key)
+
+`to_mol` reads `stereo_groups` and `chiral` while it builds the molecule (`_read_groups`), and `apply_groups` turns them into RDKit StereoGroups only after stereo perception, so only real centres are grouped; an atom that is not a centre is dropped from its group and reported as `stereo_group_not_centre`, an atom in two groups as `stereo_group_overlap`. An `and` or `or` group without `n` takes the next free number. `chiral` follows FORMAT: `relative` puts the ungrouped centres into one OR group, `racemic` into one AND group, `absolute` (or absent) leaves them absolute. `from_mol` reads groups back from CXSMILES and V3000 collections (`groups_from_mol`). Because the groups now change CXSMILES, `derive.content_key` includes `FRAGMENT_FIELDS` (`chiral`, `stereo_groups`); without it a regroup kept the cached CXSMILES of the old grouping. RDKit canonicalises enhanced stereo: an OR (or AND) group of one centre writes the same CXSMILES for R and S (`C[C@H](N)C(=O)O |o1:1|` both ways), which is right, since or1 means either enantiomer.
+
+## 79. A molfile chiral flag of 0 reads as absolute · _v0.6.0 (services/chem/convert.py from_mol)
+
+The clean-room spec says a molfile with the chiral flag at 0 holds one AND group (a racemate). PubChem and most drawing programs write 0 for single enantiomers, so following the spec would turn nearly every imported enantiomer racemic. FormChem reads flag 0 as RDKit does: absolute, no groups and no `chiral` field. Flag 1 sets `chiral: "absolute"`. This is a deliberate deviation from the spec. No import warning says so, because the import warnings belong to `io.py`, which this phase did not change.
+
+## 80. The stereo report, and the stereo the engine does not perceive · _v0.6.0 (services/chem/stereo.py report, group_labels; services/chem/perceive.py _cip, not_ez_bonds)
+
+`stereo.report` returns centres, double bonds and axes with their CIP labels from the new labeller (`CIPLabeler`, the same as derived `cip`), a `state` from `FindPotentialStereo` (`defined`, `undefined`, or `unknown` for a wavy or crossed mark), and the group label per defined centre (`abs`, `and`, `or`; ungrouped centres are `abs`). Perception adds two warnings: `stereo_unknown` (a centre on a wavy bond) and `undefined_double_bond` (a stereogenic double bond that is neither specified nor marked crossed or wavy, usually a substituent drawn on the bond's line). `not_ez_bonds` walks cumulated double bonds and keeps only the middle bond of an odd chain, because an allene's two bonds were reported as undefined E/Z double bonds. Not perceived: allene axial chirality (RDKit's SMILES reader drops the extended tetrahedral mark, and 2025.09 has no allene CIP) and atropisomers from a drawing (RDKit perceives them only with the non-legacy stereo perception from molblocks; the engine runs legacy perception, and a wedge at a biaryl axis gives only `misplaced_wedge`). The 14 supported cases of the AC5.3 table (alanine, glyceraldehyde, carvone, ibuprofen, threonine, tartaric acids, 2-butenes, both pentane-2,3,4-triols with r and s, a CHD centre, CHFClBr) were all right through the route and the window.
+
+## 81. Wedges are placed by RDKit for the configuration wanted · _v0.6.0 (services/chem/stereo.py rewedge, _from_3d, _aim)
+
+The parity comes from the drawing, from 3D coordinates (`AssignStereochemistryFrom3D` on an added conformer; abbreviations must be expanded first), or from wanted R or S labels (`_aim` flips the chiral tag and relabels with the new CIP labeller, up to four rounds, because labels can depend on each other). The wedge and hash marks on the chosen centres are cleared and RDKit's `WedgeMolBonds` picks bonds on the 2D conformer: it prefers bonds outside rings, bonds to H and to terminal atoms, one wedge per centre. A wedge whose narrow end must move swaps `a` and `b` in the same transaction. Hollow wedges stay hollow, and wavy and crossed bonds are never touched. The result is perceived again; a centre that still disagrees gives `wedge_mismatch`, a label no flip reaches gives `cip_unreachable`.
+
+## 82. The abbreviation library is data, with the person's file on top · _v0.6.0 (services/chem/abbrev.py library, user_entries, match, PREFERRED)
+
+The built-in table grew from 75 to 106 entries in six categories (alkyl, aryl, protecting group, silyl, sulfonyl, functional), each an attachment SMILES with one `*`. `abbreviations.json` in the data folder adds the person's own, as a list of `{label, smiles, reversed?, category?, prefer?}` or a map of label to the same or to a SMILES string; the SMILES needs exactly one `*` with one bond. User entries win over built-ins, and `"prefer": "abbreviation"` makes a label that is an element symbol read as the abbreviation. The file is re-read when its mtime changes (one stat per lookup), and bad entries are listed in `user_errors` rather than failing the library. A substituent is matched by canonical SMILES with `*` at the attachment and stereo removed; when several labels match, `PREFERRED` picks Pr over nPr, Bu over nBu, Ac over COMe, TBS over TBDMS, CO2H over COOH and Ms over SO2Me. Ac, Pr and Np collide with element symbols (`ELEMENT_COLLISIONS`), so the check reports `label_collides` for them.
+
+## 83. Contract and expand keep atom ids · _v0.6.0 (services/chem/superatom.py contract, expand; routers/analysis.py _ids_of)
+
+Contract keeps the selected atoms with their ids inside the expansion (coordinates relative to the first attachment atom, the outgoing bond along +x, as FORMAT says), deletes them from the fragment, adds one `*` atom with `label` and `expansion` at the first attachment atom's position and re-points the crossing bonds to it, keeping the bond ids. A wedge that started inside is dropped (`stereo_dropped`), and stereo group entries for removed atoms go too. More than one attachment bond needs a typed label. Expand rotates the stored atoms so +x points from the abbreviation atom to its first neighbour, tries both mirror images and keeps the one with fewer clashes (0.6 bond lengths) against the other atoms; a library label with no expansion record is expanded from the template laid out by `convert.from_mol` at the fragment's median bond length. The abbreviation atom's bonds attach to `attach` in order of its bonds by z then id; extra bonds join the last attachment point with `abbreviation_bonds`. `_ids_of` first counted the ids stored inside expansions as taken, so expand renamed every restored atom; expansion-internal ids are not live document ids, so only expansion keys count now and `superatom.expand` still renames on a real clash. Contract then expand of ibuprofen's CO2H gives back the same three ids at the same coordinates (0.000 pt), and in document mode the expansion record is deleted when no other atom uses it.
+
+## 84. Explicit hydrogens go into the widest gaps and keep the configuration · _v0.6.0 (services/chem/hydrogens.py add_hydrogens, remove_hydrogens, directions)
+
+Hydrogens are placed at 0.8 bond lengths (`H_LENGTH`), each new one into the gap with the largest share left (`directions`), so a terminal CH3 fans out at 90 degree steps and a CH2 in a chain gets its two H on the open side. Atoms whose label is element-like (OH, NH2) lose the label and the pinned `hydrogens`. If a centre's CIP label would change, its new H bond becomes a hash (or wedge) with the narrow end on the centre; when that cannot hold it, the reply warns `stereo_changed`. Removal keeps an H with an isotope, charge, map number, query, label, radical, any stereo mark or a bond order other than 1, and one that holds a centre's configuration, found by comparing CIP labels before and after, up to three rounds (`hydrogens_kept`). Adding and removing are each one transaction across every fragment asked for.
+
+## 85. A query is one RDKit query molecule built from SMARTS primitives · _v0.6.0 (services/chem/query.py query_mol, atom_smarts, bond_smarts)
+
+Every atom and bond becomes a SMARTS primitive and the molecule is built from them atom by atom, so search, SMARTS export and the check read one representation. Plain atoms match by element only (no charge, H count or aromaticity constraint unless the atom asks), bonds by drawn order, aromatic bonds as `:`. A list is `[#6,#7]`, a not-list `[!#6&!#7]`, A `!#1`, AH `*`, Q `!#6&!#1`, QH `!#6`, X the halogens, M every element outside a fixed non-metal set (the metalloids B, Si, Ge, As, Sb and Te count as non-metals); `ring_bonds` is `x` (4 means 4 or more), `subst` is `D` (6 or more), "as drawn" (-2) uses the drawing's own count, `unsat` is `$(*=,#,:*)`, `h_min` n is `!H0` to `!H(n-1)`, topology is `@` or `!@`, and the bond queries map through `BOND_QUERY_SMARTS`. Explicit H atoms in a query fold into H counts (`MergeQueryHs`). Chiral tags are copied, so `chirality: true` tells L- from D-alanine.
+
+## 86. SMARTS in and out · _v0.6.0 (services/chem/query.py to_smarts, from_smarts, parse_atom_smarts)
+
+Export writes the query molecule's SMARTS for a fragment or a subset of its atoms; R-group atoms become `*` (`smarts_rgroups`), stereo groups are not expressed (`smarts_stereo_groups`), abbreviations are expanded first, and "as drawn" counts become the drawn number. Import parses each atom's own SMARTS into the query fields where a primitive maps (element, aromatic, list and not-list, the generic classes, `D`, `x`, `!H`, the unsaturation recursion) and keeps anything else (other recursive SMARTS, `R`, exact `H`, valence and so on) whole in `query.smarts`, with `element` from the SMARTS where it names one (`smarts_opaque`). That field is why FORMAT gained `AtomQuery.smarts`: without it an imported pattern lost meaning on the way in. An implicit SMARTS bond becomes order 1 with `single_or_aromatic` (its SMARTS meaning), so an aromatic ring from SMARTS draws as single bonds although it matches aromatic rings; setting order 1.5 when both ends are aromatic would fix the drawing. Layout is `from_mol` on the parsed molecule at the drawing's bond length.
+
+## 87. Substructure hits come back as ids · _v0.6.0 (services/chem/search.py query_from, substructure)
+
+The pattern is SMARTS or a drawn query fragment (`query_mol`); targets are a document's fragments (minus the query fragment) or fragments sent with the call. Matches use RDKit's substructure search with `useChirality` from the `chirality` flag, and each hit is reported as the target's atom and bond ids plus a map from query atom id (or SMARTS atom index as a string) to target atom id, so the window selects hits without any index bookkeeping. `max_hits` defaults to 1000 (`MAX_HITS`) and is capped at 100000; `truncated` says when the list stopped.
+
+## 88. FormChem writes V3000 query molfiles and reads R-group blocks itself · _v0.6.0 (services/chem/v3000.py write, read, _decorate, _read_ctab)
+
+RDKit writes the CTAB and the stereo collections; FormChem then rewrites the atom type (`[C,N]`, `NOT[C,N]`, `A`, `AH`, `Q`, `QH`, `X`, `XH`, `M`, `MH`), appends RBCNT, SUBST, UNSAT, HCOUNT (h_min n as HCOUNT=n, as RDKit reads it), bond types 5 to 8 and TOPO, and inserts RGROUP blocks (RLOGIC with if-then, rest H and occurrence; one CTAB per member with ATTCHPT=1) before M END. `NOT[...]` without a space is the form both RDKit and Indigo read: the spaced form breaks Indigo's reader and a bare spaced form breaks RDKit's. RDKit's molblock reader cannot read RGROUP blocks at all, so `read` splits the blocks itself, gives each CTAB to RDKit with the query types replaced by placeholders, and puts the query fields back by atom and bond order; members come back as their own fragments laid out in rows under the scaffold, with `data.attach` on their attachment atoms. Indigo was used by hand to cross-check the output, not in code. One `v3000_query_lossy` warning names every atom a field could not carry.
+
+## 89. Markush enumeration and the attachment fallback order · _v0.6.0 (services/chem/markush.py describe, member_attachments, _stub_link, enumerate_structures)
+
+`member_attachments(member, declared)` finds where a member attaches, in FORMAT's order: the definition's `attach` entry for that member, then atoms whose `data.attach` is 1 or 2 (what V3000 import writes), then attachment stubs (a `"*"` atom with no label, no `generic` and exactly one bond, in id order), then the member's first atom. A stub stands for the R-group atom, so `_stub_link` resolves it to its neighbour, which bonds to the scaffold, and the stub is left out of the structure; a declared stub resolves the same way. Occurrence accepts `1`, `1-3`, `>0`, `<3` and comma lists; with `rest_h` false only "every site substituted" is enumerated; `if_then` n requires group n filled whenever this one is. Structures are joined with RDKit `molzip` on atom map numbers and deduplicated by canonical SMILES. `count` is the combinatorial total before if-then filtering and deduplication, so it can exceed the listed structures with `truncated` false. Over 100000 (`HARD_LIMIT`) refuses without `force`, and listing stops at `limit` (default 1000) with `enumeration_truncated`.
+
+## 90. Every property names its method · _v0.6.0 (services/chem/props.py compute, ROWS, LIPINSKI, VEBER)
+
+Each row carries `method` (the RDKit call, such as `Crippen.MolLogP`, `rdMolDescriptors.CalcTPSA`, `rdMolDescriptors.CalcNumLipinskiHBD`) and `note` (the method in words, such as "Wildman and Crippen 1999 atom contributions; typical error 0.5 to 0.7 log units"), because a number without its method is not citable. Properties are computed on the identifier molecule (abbreviations expanded, private props and explicit H removed, re-sanitised for ring info); labels and R-groups become dummy atoms and are named in an `incomplete` warning. TPSA counts N and O only (`tpsa`, Ertl's default), with S and P in `tpsa_sp`; both the Lipinski counts and RDKit's refined donor and acceptor counts are given. Lipinski passes with at most one violation, as the rule of five is usually applied; Veber is rotatable bonds at most 10 and TPSA at most 140. Rounding: mw 2, exact mass 4, cLogP, MR and TPSA 2, fraction Csp3 3 decimals. A value RDKit could not compute is null with `property_failed`. Acceptance values: ibuprofen cLogP 3.07, TPSA 37.3, MW 206.28; aspirin TPSA 63.6, HBD 1, HBA 4.
+
+## 91. The structure check has codes, severities and named fixes · _v0.6.0 (services/chem/check.py check, SEVERITY, FIX, SKIP)
+
+The check starts from the derived warnings and valence errors and adds `unusual_charge` (|charge| of 3 or more on a non-metal, carbon at 2 or more, a charged noble gas, F+, an anionic group 1 or 2 metal), `wedge_between_centres`, `ring_double_bond_stereo` (a crossed double bond in a ring under 8), `uncommon_isotope` (a known nuclide with no natural abundance, except the common labels in `COMMON_LABELS`), `crossing_bonds` (skipped over 1500 bonds), `query_feature` (unless the call says the drawing is a query), `label_collides`, and the R-group gaps (`rgroup_undefined`, `rgroup_member_missing`, `rgroup_bonds`, `rgroup_unused`, `rgroup_attachment_guessed`). Each code has one severity (`SEVERITY`: error, warning or info) and issues are sorted errors first. A fixable issue names the analysis command that repairs it in `fix` (`wedges` for the wedge codes, `expand` for abbreviation codes) instead of carrying a transaction, so the fix is computed against the drawing as it is when the person clicks. Derived-only noise (`query_ignored`, the InChI remarks) is left out (`SKIP`), and atoms with `ignore_warnings` drop the issues that name only them.
+
+## 92. Metal cations are not valence errors · _v0.6.0 (services/chem/perceive.py _valence)
+
+RDKit 2025.09 reports `HasValenceViolation` for a bare Na+, so every salt drawn as Na+ and an anion showed a valence error (it predates this phase). For a charged atom the isoelectronic allowed list alone now decides; RDKit's flag still counts for neutral atoms.
+
+## 93. Query atoms and bare stars are generics, not unknown labels · _v0.6.0 (services/chem/convert.py _query_label, _new_atom; services/chem/v3000.py)
+
+An any-atom carrying an atom list or a generic query class was reported as `unknown_label`, and so was a bare `*`, which FORMAT defines as any atom or an attachment point (every R-group member drawn with a stub showed it). Both now count as generics like R or Hal, shown literally in the formula as `[N,O]` or Q. The V3000 writer had listed one lossy warning per aromatic atom and an unknown-label warning per list atom; it now names all lossy atoms in one warning and stays quiet about atoms that are queries by design.
+
+## 94. The isotope pattern is a convolution merged at 0.01 Da · _v0.6.0 (services/chem/isotopes.py from_counts, pattern, parse_formula; routers/analysis.py isotope routes)
+
+Per element, the isotope masses and abundances come from RDKit's periodic table (through `mass.isotopes`), raised to the element count by repeated squaring (`_power`) and convolved element by element (`_convolve`). During convolution peaks within 0.001 Da (`FINE`) are merged and those under 1e-7 of the top (`KEEP`) are pruned, which keeps a 5.7 kDa peptide formula to 7 ms. The result is merged within 0.01 Da (`MERGE`, unit resolution with fine structure folded) and cut under 0.1 percent of the base peak (`THRESHOLD`, adjustable 0 to 100 on the route). Atoms with an isotope set count as one fixed mass. A charge removes the electron mass and divides m/z by |z|. Adducts for a neutral species are [M+H]+ (proton 1.007276), [M+Na]+ (Na minus an electron) and [M-H]-; an ion gets only [M]z with its sign. The formula route reads D and T and a charge suffix such as `+` or `2-`, and limits a pattern to 20000 atoms. Checked: CH2Cl2 M+2 63.92 percent, C6H5Br M+2 97.45, C60 M+1 64.9, ibuprofen 206.1307 (100), 207.1341 (14.34), 208.1367 (1.36). The older `mass.isotope_pattern` (entry 50) is unchanged and still feeds `/api/chem/properties`; the Analysis panel's plot reads the new routes.
+
+## 95. The analysis router: a fragment or a document in, one transaction out · _v0.6.0 (routers/analysis.py source, finish, run; app/main.py)
+
+Every POST takes its structure either stateless (`fragment`, optional `expansions` and `members`) or from an open document (`doc` with `object` or `objects`), in which case expansions and R-group members come from the document and new ids are checked against every id in it. Commands that change the drawing return `tx: {label, ops}` with paths from the document root, for the window to commit as one undo step after checking the fragments did not change while it waited; with `doc` and `apply: true` the engine applies it itself (origin `user`) and adds `applied: {tx, rev}`, and `apply` without `doc` is a 422. Errors match the chem router because the validators are reused (`chem._fragment`, `_expansions`, `_bond_length`, `_num`, `MAX_TEXT`): 422 with a sentence for the person, 404 for an unknown doc or object, 409 when the document refuses, 413 over 20 MB; in a per-fragment read a failing fragment gives `{error}` in its slot instead of failing the call. Routes are async and run chemistry in a worker thread (`asyncio.to_thread`) so `apply` can await the store. The router carries full `/api/analysis/...` paths, so main.py includes it after `reactions` with no prefix.
+
+## 96. Four analysis tools on the MCP server · _v0.6.0 (routers/mcp.py t_properties, t_check_structure, t_stereo, t_substructure, _analysis_source)
+
+`properties`, `check_structure`, `stereo` and `substructure` are read-only and outside `MUTATING`, so they never ask the person; `doc` may be left out when exactly one drawing is open. They reuse the analysis router's source rules through `_analysis_source`, which imports the router lazily so mcp.py does not load RDKit at import. Each answers text lines for the agent plus `structuredContent` with the same JSON as the route. `substructure` without a pattern is an `isError` that names `smarts` or `query_object`. `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` description now name the reaction and analysis tools and the chemistry commands, which closes the gap noted in entry 75; only the atom and bond tools remain for `DRAWING_FROM` (0.8.0). The server has fourteen tools; `./formchem agents sync` regenerated the tools reference and the manifest.
+
+## 97. build_app names package.json when the Tauri CLI is missing · _v0.6.0 (build_app)
+
+`frontend/package.json` never listed `@tauri-apps/cli` (frontend log 1 recorded that the build scripts would call the CLI themselves), so on a fresh checkout `npm ci` installed no `tauri` binary and `./build_app` stopped on the owner's Mac with "the Tauri CLI did not install; run ./build_app --reinstall", which a reinstall could never fix. The CLI is now a pinned dev dependency (frontend log 133), and the message says the CLI is not in `frontend/node_modules` and to check that package.json lists `@tauri-apps/cli` in devDependencies before `--reinstall`. The check after it is unchanged: the CLI's major.minor must equal the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.6 against 2.12.7 passes), and each `@tauri-apps/plugin-*` package must share major.minor with its `tauri-plugin-*` crate. `setup/install_desktop` and `desktop_check` needed no change; they already ran `npm install` and compared versions.
+
+## 98. build_app bundles the template library when it freezes the engine · _v0.6.0 (build_app freeze)
+
+Entry 76 added `backend/app/data/templates` as `templates` data to `setup/freeze_backend` and its `.bat` twin, but `build_app` runs PyInstaller itself and missed it, so a desktop app built with `./build_app` had an empty template library (`templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen). It now passes the same `--add-data`. `build_app.bat` goes through `setup/desktop_build.bat` and `freeze_backend.bat`, so Windows already had it. Not run here (no pyinstaller or Tauri on this machine). The owner ran `./build_app` on macOS arm64 (Python 3.14.6, Node 24.16, Rust 1.97.1) after the CLI pin, and the desktop app built; the frozen engine at runtime (the template library in particular) and the native macOS menu were not reported on.
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 6a9beea8..906d362f 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -1 +1 @@
-__version__ = "0.4.0"
+__version__ = "0.6.0"
diff --git a/backend/app/data/templates/amino-acids.json b/backend/app/data/templates/amino-acids.json
new file mode 100644
index 00000000..7c779af6
--- /dev/null
+++ b/backend/app/data/templates/amino-acids.json
@@ -0,0 +1,30 @@
+{
+ "category": "amino-acids",
+ "name": "Amino acids",
+ "order": 40,
+ "templates": [
+ { "id": "glycine", "name": "Glycine", "tags": ["Gly", "G", "amino acid", "nonpolar"], "smiles": "NCC(=O)O" },
+ { "id": "l-alanine", "name": "L-Alanine", "tags": ["Ala", "A", "amino acid", "nonpolar"], "smiles": "N[C@@H](C)C(=O)O" },
+ { "id": "l-valine", "name": "L-Valine", "tags": ["Val", "V", "amino acid", "nonpolar", "branched"], "smiles": "N[C@@H](C(C)C)C(=O)O" },
+ { "id": "l-leucine", "name": "L-Leucine", "tags": ["Leu", "L", "amino acid", "nonpolar", "branched"], "smiles": "N[C@@H](CC(C)C)C(=O)O" },
+ { "id": "l-isoleucine", "name": "L-Isoleucine", "tags": ["Ile", "I", "amino acid", "nonpolar", "branched"], "smiles": "N[C@@H]([C@@H](C)CC)C(=O)O" },
+ { "id": "l-proline", "name": "L-Proline", "tags": ["Pro", "P", "amino acid", "cyclic", "imino acid"], "smiles": "OC(=O)[C@@H]1CCCN1" },
+ { "id": "l-phenylalanine", "name": "L-Phenylalanine", "tags": ["Phe", "F", "amino acid", "aromatic"], "smiles": "N[C@@H](Cc1ccccc1)C(=O)O" },
+ { "id": "l-tryptophan", "name": "L-Tryptophan", "tags": ["Trp", "W", "amino acid", "aromatic", "indole"], "smiles": "N[C@@H](Cc1c[nH]c2ccccc12)C(=O)O" },
+ { "id": "l-tyrosine", "name": "L-Tyrosine", "tags": ["Tyr", "Y", "amino acid", "aromatic", "phenol"], "smiles": "N[C@@H](Cc1ccc(O)cc1)C(=O)O" },
+ { "id": "l-methionine", "name": "L-Methionine", "tags": ["Met", "M", "amino acid", "sulfur"], "smiles": "N[C@@H](CCSC)C(=O)O" },
+ { "id": "l-cysteine", "name": "L-Cysteine", "tags": ["Cys", "C", "amino acid", "sulfur", "thiol"], "smiles": "N[C@@H](CS)C(=O)O" },
+ { "id": "l-serine", "name": "L-Serine", "tags": ["Ser", "S", "amino acid", "polar", "hydroxyl"], "smiles": "N[C@@H](CO)C(=O)O" },
+ { "id": "l-threonine", "name": "L-Threonine", "tags": ["Thr", "T", "amino acid", "polar", "hydroxyl"], "smiles": "N[C@@H]([C@@H](C)O)C(=O)O" },
+ { "id": "l-asparagine", "name": "L-Asparagine", "tags": ["Asn", "N", "amino acid", "polar", "amide"], "smiles": "N[C@@H](CC(N)=O)C(=O)O" },
+ { "id": "l-glutamine", "name": "L-Glutamine", "tags": ["Gln", "Q", "amino acid", "polar", "amide"], "smiles": "N[C@@H](CCC(N)=O)C(=O)O" },
+ { "id": "l-aspartic-acid", "name": "L-Aspartic acid", "tags": ["Asp", "D", "amino acid", "acidic", "aspartate"], "smiles": "N[C@@H](CC(=O)O)C(=O)O" },
+ { "id": "l-glutamic-acid", "name": "L-Glutamic acid", "tags": ["Glu", "E", "amino acid", "acidic", "glutamate"], "smiles": "N[C@@H](CCC(=O)O)C(=O)O" },
+ { "id": "l-lysine", "name": "L-Lysine", "tags": ["Lys", "K", "amino acid", "basic"], "smiles": "N[C@@H](CCCCN)C(=O)O" },
+ { "id": "l-arginine", "name": "L-Arginine", "tags": ["Arg", "R", "amino acid", "basic", "guanidine"], "smiles": "N[C@@H](CCCNC(N)=N)C(=O)O" },
+ { "id": "l-histidine", "name": "L-Histidine", "tags": ["His", "H", "amino acid", "basic", "imidazole"], "smiles": "N[C@@H](Cc1c[nH]cn1)C(=O)O" },
+ { "id": "glycine-zwitterion", "name": "Glycine (zwitterion)", "tags": ["Gly", "zwitterion", "amino acid"], "smiles": "[NH3+]CC(=O)[O-]" },
+ { "id": "l-alanine-zwitterion", "name": "L-Alanine (zwitterion)", "tags": ["Ala", "zwitterion", "amino acid"], "smiles": "[NH3+][C@@H](C)C(=O)[O-]" },
+ { "id": "peptide-bond", "name": "Dipeptide backbone", "tags": ["peptide", "amide", "backbone", "Gly-Gly"], "smiles": "NCC(=O)NCC(=O)O" }
+ ]
+}
diff --git a/backend/app/data/templates/glassware.json b/backend/app/data/templates/glassware.json
new file mode 100644
index 00000000..645f621e
--- /dev/null
+++ b/backend/app/data/templates/glassware.json
@@ -0,0 +1,126 @@
+{
+ "category": "glassware",
+ "name": "Glassware",
+ "order": 90,
+ "templates": [
+ {
+ "id": "round-bottom-flask", "name": "Round-bottom flask", "tags": ["flask", "RBF", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s2", "s1"] },
+ { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 46, "path": "M12 0 L28 0 M14 0 L14 15.17 A16 16 0 1 0 26 15.17 L26 0", "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 46, "path": "M6.14 38 A16 16 0 0 0 33.86 38 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 }
+ ]
+ },
+ {
+ "id": "erlenmeyer-flask", "name": "Erlenmeyer flask", "tags": ["flask", "conical", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s2", "s1"] },
+ { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 44, "h": 55, "path": "M16 0 L28 0 M18 0 L18 18 L3 50 Q1 55 6 55 L38 55 Q43 55 41 50 L26 18 L26 0", "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 44, "h": 55, "path": "M7.69 40 L36.31 40 L41 50 Q43 55 38 55 L6 55 Q1 55 3 50 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 }
+ ]
+ },
+ {
+ "id": "beaker", "name": "Beaker", "tags": ["beaker", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s2", "s1", "l1", "l2", "l3"] },
+ { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 52, "path": "M0 0 Q3 1 4 4 L4 48 Q4 52 8 52 L36 52 Q40 52 40 48 L40 2", "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 52, "path": "M4 28 L40 28 L40 48 Q40 52 36 52 L8 52 Q4 52 4 48 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 },
+ { "id": "l1", "kind": "line", "points": [[30, 16], [36, 16]], "stroke": { "width": 0.6 } },
+ { "id": "l2", "kind": "line", "points": [[32, 24], [36, 24]], "stroke": { "width": 0.6 } },
+ { "id": "l3", "kind": "line", "points": [[30, 32], [36, 32]], "stroke": { "width": 0.6 } }
+ ]
+ },
+ {
+ "id": "test-tube", "name": "Test tube", "tags": ["tube", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s2", "s1"] },
+ { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 14, "h": 48, "path": "M0 0 L2 0 L2 43 A5 5 0 0 0 12 43 L12 0 L14 0", "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 14, "h": 48, "path": "M2 32 L12 32 L12 43 A5 5 0 0 1 2 43 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 }
+ ]
+ },
+ {
+ "id": "graduated-cylinder", "name": "Graduated cylinder", "tags": ["cylinder", "measuring", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s3", "s1", "s2", "l1", "l2", "l3", "l4", "l5", "l6"] },
+ { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 24, "h": 72, "path": "M2 0 Q5 0 5 3 L5 72 M19 72 L19 0", "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "round_rect", "x": 0, "y": 72, "w": 24, "h": 6, "radius": 1.5, "stroke": { "width": 1 }, "fill": null },
+ { "id": "s3", "kind": "shape", "geom": "rect", "x": 5, "y": 40, "w": 14, "h": 32, "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 },
+ { "id": "l1", "kind": "line", "points": [[14, 12], [19, 12]], "stroke": { "width": 0.6 } },
+ { "id": "l2", "kind": "line", "points": [[16, 22], [19, 22]], "stroke": { "width": 0.6 } },
+ { "id": "l3", "kind": "line", "points": [[14, 32], [19, 32]], "stroke": { "width": 0.6 } },
+ { "id": "l4", "kind": "line", "points": [[16, 42], [19, 42]], "stroke": { "width": 0.6 } },
+ { "id": "l5", "kind": "line", "points": [[14, 52], [19, 52]], "stroke": { "width": 0.6 } },
+ { "id": "l6", "kind": "line", "points": [[16, 62], [19, 62]], "stroke": { "width": 0.6 } }
+ ]
+ },
+ {
+ "id": "separatory-funnel", "name": "Separatory funnel", "tags": ["funnel", "extraction", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s1", "s2", "s3", "l1"] },
+ { "id": "s1", "kind": "shape", "geom": "round_rect", "x": 15, "y": 0, "w": 10, "h": 6, "radius": 1.5, "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 6, "w": 40, "h": 58, "path": "M17 0 L17 4 C2 12 0 40 17 52 L17 58 M23 58 L23 52 C40 40 38 12 23 4 L23 0", "stroke": { "width": 1 }, "fill": null },
+ { "id": "s3", "kind": "shape", "geom": "rect", "x": 11, "y": 64, "w": 18, "h": 4, "stroke": { "width": 1 }, "fill": null },
+ { "id": "l1", "kind": "line", "points": [[20, 68], [20, 92]], "stroke": { "width": 1.6 } }
+ ]
+ },
+ {
+ "id": "condenser", "name": "Condenser", "tags": ["condenser", "reflux", "distillation", "Liebig", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s1", "l1", "l2", "l3", "l4", "l5", "l6"] },
+ { "id": "s1", "kind": "shape", "geom": "round_rect", "x": 6, "y": 12, "w": 16, "h": 86, "radius": 3, "stroke": { "width": 1 }, "fill": null },
+ { "id": "l1", "kind": "line", "points": [[12, 0], [12, 110]], "stroke": { "width": 1 } },
+ { "id": "l2", "kind": "line", "points": [[16, 0], [16, 110]], "stroke": { "width": 1 } },
+ { "id": "l3", "kind": "line", "points": [[22, 20], [30, 20]], "stroke": { "width": 1 } },
+ { "id": "l4", "kind": "line", "points": [[22, 24], [30, 24]], "stroke": { "width": 1 } },
+ { "id": "l5", "kind": "line", "points": [[0, 86], [6, 86]], "stroke": { "width": 1 } },
+ { "id": "l6", "kind": "line", "points": [[0, 90], [6, 90]], "stroke": { "width": 1 } }
+ ]
+ },
+ {
+ "id": "filter-funnel", "name": "Filter funnel", "tags": ["funnel", "filtration", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s1", "l1"] },
+ { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 50, "path": "M0 0 L40 0 M0 0 L17 22 L17 50 M40 0 L23 22 L23 50", "stroke": { "width": 1 }, "fill": null },
+ { "id": "l1", "kind": "line", "points": [[5, 2], [20, 19], [35, 2]], "stroke": { "width": 0.6, "dash": "dash" } }
+ ]
+ },
+ {
+ "id": "buchner-funnel", "name": "Buchner funnel", "tags": ["funnel", "vacuum filtration", "glassware", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s1", "l1"] },
+ { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 44, "h": 56, "path": "M0 0 L44 0 L44 4 Q44 22 26 24 L26 30 L24 30 L24 56 L20 56 L20 30 L18 30 L18 24 Q0 22 0 4 Z", "stroke": { "width": 1 }, "fill": null },
+ { "id": "l1", "kind": "line", "points": [[3, 14], [41, 14]], "stroke": { "width": 0.8, "dash": "dot" } }
+ ]
+ },
+ {
+ "id": "thermometer", "name": "Thermometer", "tags": ["thermometer", "temperature", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s1", "s3", "s2"] },
+ { "id": "s1", "kind": "shape", "geom": "round_rect", "x": 2, "y": 0, "w": 6, "h": 82, "radius": 3, "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "ellipse", "x": 0, "y": 78, "w": 10, "h": 12, "stroke": { "width": 1 }, "fill": { "type": "solid", "color": "#d9534f" } },
+ { "id": "s3", "kind": "shape", "geom": "rect", "x": 4, "y": 34, "w": 2, "h": 46, "stroke": null, "fill": { "type": "solid", "color": "#d9534f" } }
+ ]
+ },
+ {
+ "id": "stirrer-hotplate", "name": "Stirrer hotplate", "tags": ["hotplate", "stirrer", "heating", "apparatus"],
+ "order": ["g1"],
+ "objects": [
+ { "id": "g1", "kind": "group", "children": ["s1", "s2", "s3", "s4"] },
+ { "id": "s1", "kind": "shape", "geom": "rect", "x": 0, "y": 0, "w": 70, "h": 4, "stroke": { "width": 1 }, "fill": null },
+ { "id": "s2", "kind": "shape", "geom": "round_rect", "x": 4, "y": 4, "w": 62, "h": 24, "radius": 3, "stroke": { "width": 1 }, "fill": null },
+ { "id": "s3", "kind": "shape", "geom": "ellipse", "x": 14, "y": 12, "w": 8, "h": 8, "stroke": { "width": 1 }, "fill": null },
+ { "id": "s4", "kind": "shape", "geom": "ellipse", "x": 48, "y": 12, "w": 8, "h": 8, "stroke": { "width": 1 }, "fill": null }
+ ]
+ }
+ ]
+}
diff --git a/backend/app/data/templates/heterocycles.json b/backend/app/data/templates/heterocycles.json
new file mode 100644
index 00000000..4a5bf281
--- /dev/null
+++ b/backend/app/data/templates/heterocycles.json
@@ -0,0 +1,54 @@
+{
+ "category": "heterocycles",
+ "name": "Heterocycles",
+ "order": 30,
+ "templates": [
+ { "id": "pyridine", "name": "Pyridine", "tags": ["azine", "six-membered", "aromatic", "N"], "ring": { "elements": ["C", "C", "C", "N", "C", "C"], "orders": [2, 1, 2, 1, 2, 1] } },
+ { "id": "pyrimidine", "name": "Pyrimidine", "tags": ["diazine", "1,3-diazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "C", "C", "N", "C", "N"], "orders": [2, 1, 2, 1, 2, 1] } },
+ { "id": "pyrazine", "name": "Pyrazine", "tags": ["diazine", "1,4-diazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "C", "N", "C", "C", "N"], "orders": [2, 1, 2, 1, 2, 1] } },
+ { "id": "pyridazine", "name": "Pyridazine", "tags": ["diazine", "1,2-diazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "C", "C", "N", "N", "C"], "orders": [2, 1, 2, 1, 2, 1] } },
+ { "id": "triazine", "name": "1,3,5-Triazine", "tags": ["triazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "N", "C", "N", "C", "N"], "orders": [2, 1, 2, 1, 2, 1] } },
+ { "id": "pyran-2-one", "name": "2-Pyranone", "tags": ["pyrone", "lactone", "six-membered", "O"], "smiles": "O=c1cccco1" },
+ { "id": "pyridin-2-one", "name": "2-Pyridone", "tags": ["pyridone", "lactam", "six-membered"], "smiles": "O=c1cccc[nH]1" },
+ { "id": "furan", "name": "Furan", "tags": ["five-membered", "aromatic", "O"], "ring": { "elements": ["C", "C", "C", "O", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "thiophene", "name": "Thiophene", "tags": ["five-membered", "aromatic", "S"], "ring": { "elements": ["C", "C", "C", "S", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "pyrrole", "name": "Pyrrole", "tags": ["five-membered", "aromatic", "N", "azole"], "ring": { "elements": ["C", "C", "C", "N", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "imidazole", "name": "Imidazole", "tags": ["azole", "1,3-diazole", "five-membered", "aromatic"], "ring": { "elements": ["C", "N", "C", "N", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "pyrazole", "name": "Pyrazole", "tags": ["azole", "1,2-diazole", "five-membered", "aromatic"], "ring": { "elements": ["C", "C", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "oxazole", "name": "Oxazole", "tags": ["azole", "five-membered", "aromatic", "O", "N"], "ring": { "elements": ["C", "N", "C", "O", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "isoxazole", "name": "Isoxazole", "tags": ["azole", "five-membered", "aromatic", "O", "N"], "ring": { "elements": ["C", "C", "N", "O", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "thiazole", "name": "Thiazole", "tags": ["azole", "five-membered", "aromatic", "S", "N"], "ring": { "elements": ["C", "N", "C", "S", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "triazole-1-2-3", "name": "1,2,3-Triazole", "tags": ["azole", "triazole", "click", "five-membered"], "ring": { "elements": ["C", "N", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "triazole-1-2-4", "name": "1,2,4-Triazole", "tags": ["azole", "triazole", "five-membered"], "ring": { "elements": ["N", "C", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "tetrazole", "name": "Tetrazole", "tags": ["azole", "five-membered", "carboxylic acid isostere"], "ring": { "elements": ["N", "N", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "indole", "name": "Indole", "tags": ["fused", "bicyclic", "benzopyrrole", "N"], "smiles": "c1ccc2[nH]ccc2c1" },
+ { "id": "benzofuran", "name": "Benzofuran", "tags": ["fused", "bicyclic", "O"], "smiles": "c1ccc2occc2c1" },
+ { "id": "benzothiophene", "name": "Benzothiophene", "tags": ["fused", "bicyclic", "S"], "smiles": "c1ccc2sccc2c1" },
+ { "id": "benzimidazole", "name": "Benzimidazole", "tags": ["fused", "bicyclic", "azole"], "smiles": "c1ccc2[nH]cnc2c1" },
+ { "id": "benzoxazole", "name": "Benzoxazole", "tags": ["fused", "bicyclic", "azole"], "smiles": "c1ccc2ocnc2c1" },
+ { "id": "benzothiazole", "name": "Benzothiazole", "tags": ["fused", "bicyclic", "azole"], "smiles": "c1ccc2scnc2c1" },
+ { "id": "quinoline", "name": "Quinoline", "tags": ["fused", "bicyclic", "azine", "benzopyridine"], "smiles": "c1ccc2ncccc2c1" },
+ { "id": "isoquinoline", "name": "Isoquinoline", "tags": ["fused", "bicyclic", "azine"], "smiles": "c1ccc2cnccc2c1" },
+ { "id": "quinazoline", "name": "Quinazoline", "tags": ["fused", "bicyclic", "diazine"], "smiles": "c1ccc2ncncc2c1" },
+ { "id": "quinoxaline", "name": "Quinoxaline", "tags": ["fused", "bicyclic", "diazine"], "smiles": "c1ccc2nccnc2c1" },
+ { "id": "purine", "name": "Purine", "tags": ["fused", "bicyclic", "nucleobase core", "imidazopyrimidine"], "smiles": "c1ncc2[nH]cnc2n1" },
+ { "id": "pteridine", "name": "Pteridine", "tags": ["fused", "bicyclic", "folate core"], "smiles": "c1cnc2ncncc2n1" },
+ { "id": "carbazole", "name": "Carbazole", "tags": ["fused", "tricyclic", "N"], "smiles": "c1ccc2c(c1)[nH]c1ccccc12" },
+ { "id": "acridine", "name": "Acridine", "tags": ["fused", "tricyclic", "azine"], "smiles": "c1ccc2nc3ccccc3cc2c1" },
+ { "id": "phenothiazine", "name": "Phenothiazine", "tags": ["fused", "tricyclic", "S", "N"], "smiles": "c1ccc2c(c1)Nc1ccccc1S2" },
+ { "id": "coumarin", "name": "Coumarin", "tags": ["fused", "bicyclic", "lactone", "chromen-2-one"], "smiles": "O=c1ccc2ccccc2o1" },
+ { "id": "pyrrolidine", "name": "Pyrrolidine", "tags": ["saturated", "five-membered", "amine"], "ring": { "elements": ["C", "C", "C", "N", "C"], "orders": [1, 1, 1, 1, 1] } },
+ { "id": "tetrahydrofuran", "name": "Tetrahydrofuran", "tags": ["THF", "saturated", "five-membered", "ether"], "ring": { "elements": ["C", "C", "C", "O", "C"], "orders": [1, 1, 1, 1, 1] } },
+ { "id": "tetrahydrothiophene", "name": "Tetrahydrothiophene", "tags": ["thiolane", "saturated", "five-membered"], "ring": { "elements": ["C", "C", "C", "S", "C"], "orders": [1, 1, 1, 1, 1] } },
+ { "id": "piperidine", "name": "Piperidine", "tags": ["saturated", "six-membered", "amine"], "ring": { "elements": ["C", "C", "C", "N", "C", "C"], "orders": [1, 1, 1, 1, 1, 1] } },
+ { "id": "piperazine", "name": "Piperazine", "tags": ["saturated", "six-membered", "diamine"], "ring": { "elements": ["C", "C", "N", "C", "C", "N"], "orders": [1, 1, 1, 1, 1, 1] } },
+ { "id": "morpholine", "name": "Morpholine", "tags": ["saturated", "six-membered", "amine", "ether"], "ring": { "elements": ["C", "C", "O", "C", "C", "N"], "orders": [1, 1, 1, 1, 1, 1] } },
+ { "id": "tetrahydropyran", "name": "Tetrahydropyran", "tags": ["oxane", "THP", "saturated", "six-membered"], "ring": { "elements": ["C", "C", "C", "O", "C", "C"], "orders": [1, 1, 1, 1, 1, 1] } },
+ { "id": "dioxane", "name": "1,4-Dioxane", "tags": ["saturated", "six-membered", "ether"], "ring": { "elements": ["C", "C", "O", "C", "C", "O"], "orders": [1, 1, 1, 1, 1, 1] } },
+ { "id": "aziridine", "name": "Aziridine", "tags": ["three-membered", "N"], "ring": { "elements": ["C", "C", "N"], "orders": [1, 1, 1] } },
+ { "id": "oxirane", "name": "Oxirane", "tags": ["epoxide", "three-membered", "O"], "ring": { "elements": ["C", "C", "O"], "orders": [1, 1, 1] } },
+ { "id": "azetidine", "name": "Azetidine", "tags": ["four-membered", "N"], "ring": { "elements": ["C", "C", "N", "C"], "orders": [1, 1, 1, 1] } },
+ { "id": "oxetane", "name": "Oxetane", "tags": ["four-membered", "O"], "ring": { "elements": ["C", "C", "O", "C"], "orders": [1, 1, 1, 1] } },
+ { "id": "azepane", "name": "Azepane", "tags": ["seven-membered", "N"], "ring": { "elements": ["C", "C", "C", "C", "N", "C", "C"], "orders": [1, 1, 1, 1, 1, 1, 1] } }
+ ]
+}
diff --git a/backend/app/data/templates/nucleotides.json b/backend/app/data/templates/nucleotides.json
new file mode 100644
index 00000000..3a6075bf
--- /dev/null
+++ b/backend/app/data/templates/nucleotides.json
@@ -0,0 +1,21 @@
+{
+ "category": "nucleotides",
+ "name": "Nucleotides",
+ "order": 60,
+ "templates": [
+ { "id": "adenine", "name": "Adenine", "tags": ["nucleobase", "purine", "A", "DNA", "RNA"], "smiles": "Nc1ncnc2[nH]cnc12" },
+ { "id": "guanine", "name": "Guanine", "tags": ["nucleobase", "purine", "G", "DNA", "RNA"], "smiles": "Nc1nc2[nH]cnc2c(=O)[nH]1" },
+ { "id": "cytosine", "name": "Cytosine", "tags": ["nucleobase", "pyrimidine", "C", "DNA", "RNA"], "smiles": "Nc1cc[nH]c(=O)n1" },
+ { "id": "thymine", "name": "Thymine", "tags": ["nucleobase", "pyrimidine", "T", "DNA"], "smiles": "Cc1c[nH]c(=O)[nH]c1=O" },
+ { "id": "uracil", "name": "Uracil", "tags": ["nucleobase", "pyrimidine", "U", "RNA"], "smiles": "O=c1cc[nH]c(=O)[nH]1" },
+ { "id": "adenosine", "name": "Adenosine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](CO)[C@@H](O)[C@H]1O" },
+ { "id": "guanosine", "name": "Guanosine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "Nc1nc2n(cnc2c(=O)[nH]1)[C@@H]1O[C@H](CO)[C@@H](O)[C@H]1O" },
+ { "id": "cytidine", "name": "Cytidine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "Nc1ccn([C@@H]2O[C@H](CO)[C@@H](O)[C@H]2O)c(=O)n1" },
+ { "id": "uridine", "name": "Uridine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "O=c1ccn([C@@H]2O[C@H](CO)[C@@H](O)[C@H]2O)c(=O)[nH]1" },
+ { "id": "deoxyadenosine", "name": "2'-Deoxyadenosine", "tags": ["nucleoside", "deoxyribose", "DNA"], "smiles": "Nc1ncnc2c1ncn2[C@H]1C[C@H](O)[C@@H](CO)O1" },
+ { "id": "thymidine", "name": "Thymidine", "tags": ["nucleoside", "deoxyribose", "DNA"], "smiles": "Cc1cn([C@H]2C[C@H](O)[C@@H](CO)O2)c(=O)[nH]c1=O" },
+ { "id": "amp", "name": "Adenosine monophosphate (AMP)", "tags": ["nucleotide", "phosphate", "AMP"], "smiles": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)O)[C@@H](O)[C@H]1O" },
+ { "id": "atp", "name": "Adenosine triphosphate (ATP)", "tags": ["nucleotide", "triphosphate", "ATP", "energy"], "smiles": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)OP(=O)(O)O)[C@@H](O)[C@H]1O" },
+ { "id": "phosphodiester", "name": "Phosphodiester linkage", "tags": ["backbone", "phosphate", "DNA", "RNA"], "smiles": "COP(=O)(O)OC" }
+ ]
+}
diff --git a/backend/app/data/templates/polycycles.json b/backend/app/data/templates/polycycles.json
new file mode 100644
index 00000000..200e421a
--- /dev/null
+++ b/backend/app/data/templates/polycycles.json
@@ -0,0 +1,25 @@
+{
+ "category": "polycycles",
+ "name": "Polycycles",
+ "order": 20,
+ "templates": [
+ { "id": "naphthalene", "name": "Naphthalene", "tags": ["fused", "arene", "bicyclic", "C10H8"], "smiles": "c1ccc2ccccc2c1" },
+ { "id": "anthracene", "name": "Anthracene", "tags": ["fused", "arene", "tricyclic", "acene"], "smiles": "c1ccc2cc3ccccc3cc2c1" },
+ { "id": "phenanthrene", "name": "Phenanthrene", "tags": ["fused", "arene", "tricyclic"], "smiles": "c1ccc2c(c1)ccc1ccccc12" },
+ { "id": "pyrene", "name": "Pyrene", "tags": ["fused", "arene", "tetracyclic", "PAH"], "smiles": "c1cc2ccc3cccc4ccc(c1)c2c34" },
+ { "id": "azulene", "name": "Azulene", "tags": ["fused", "non-benzenoid", "bicyclic"], "smiles": "c1ccc2cccc2cc1" },
+ { "id": "biphenyl", "name": "Biphenyl", "tags": ["arene", "biaryl"], "smiles": "c1ccc(cc1)-c1ccccc1" },
+ { "id": "fluorene", "name": "Fluorene", "tags": ["fused", "tricyclic"], "smiles": "C1c2ccccc2-c2ccccc12" },
+ { "id": "indane", "name": "Indane", "tags": ["fused", "bicyclic", "benzocyclopentane"], "smiles": "C1Cc2ccccc2C1" },
+ { "id": "indene", "name": "Indene", "tags": ["fused", "bicyclic"], "smiles": "C1C=Cc2ccccc12" },
+ { "id": "tetralin", "name": "Tetralin", "tags": ["fused", "bicyclic", "tetrahydronaphthalene"], "smiles": "C1CCc2ccccc2C1" },
+ { "id": "decalin", "name": "Decalin", "tags": ["fused", "bicyclic", "saturated"], "smiles": "C1CCC2CCCCC2C1" },
+ { "id": "norbornane", "name": "Norbornane", "tags": ["bridged", "bicyclo[2.2.1]heptane"], "smiles": "C1CC2CCC1C2" },
+ { "id": "bicyclo-2-2-2-octane", "name": "Bicyclo[2.2.2]octane", "tags": ["bridged"], "smiles": "C1CC2CCC1CC2" },
+ { "id": "adamantane", "name": "Adamantane", "tags": ["bridged", "cage", "diamondoid"], "smiles": "C1C2CC3CC1CC(C2)C3" },
+ { "id": "spiro-4-5-decane", "name": "Spiro[4.5]decane", "tags": ["spiro"], "smiles": "C1CCC2(CC1)CCCC2" },
+ { "id": "steroid", "name": "Steroid skeleton (gonane)", "tags": ["steroid", "tetracyclic", "cyclopentanoperhydrophenanthrene", "gonane"], "smiles": "C1CCC2C(C1)CCC1C2CCC2CCCC21" },
+ { "id": "estrane", "name": "Estrane", "tags": ["steroid", "tetracyclic"], "smiles": "CC12CCCC1C1CCC3CCCCC3C1CC2" },
+ { "id": "androstane", "name": "Androstane", "tags": ["steroid", "tetracyclic"], "smiles": "CC12CCCC1C1CCC3CCCCC3(C)C1CC2" }
+ ]
+}
diff --git a/backend/app/data/templates/protecting-groups.json b/backend/app/data/templates/protecting-groups.json
new file mode 100644
index 00000000..3f5448ee
--- /dev/null
+++ b/backend/app/data/templates/protecting-groups.json
@@ -0,0 +1,32 @@
+{
+ "category": "protecting-groups",
+ "name": "Protecting groups",
+ "order": 70,
+ "templates": [
+ { "id": "boc", "name": "Boc (tert-butoxycarbonyl)", "tags": ["amine protection", "carbamate", "Boc"], "smiles": "*C(=O)OC(C)(C)C" },
+ { "id": "cbz", "name": "Cbz (benzyloxycarbonyl)", "tags": ["amine protection", "carbamate", "Z", "Cbz"], "smiles": "*C(=O)OCc1ccccc1" },
+ { "id": "fmoc", "name": "Fmoc (fluorenylmethoxycarbonyl)", "tags": ["amine protection", "carbamate", "peptide synthesis"], "smiles": "*C(=O)OCC1c2ccccc2-c2ccccc21" },
+ { "id": "alloc", "name": "Alloc (allyloxycarbonyl)", "tags": ["amine protection", "carbamate"], "smiles": "*C(=O)OCC=C" },
+ { "id": "bn", "name": "Bn (benzyl)", "tags": ["alcohol protection", "amine protection", "ether"], "smiles": "*Cc1ccccc1" },
+ { "id": "pmb", "name": "PMB (p-methoxybenzyl)", "tags": ["alcohol protection", "ether", "MPM"], "smiles": "*Cc1ccc(OC)cc1" },
+ { "id": "ac", "name": "Ac (acetyl)", "tags": ["alcohol protection", "amine protection", "ester", "amide"], "smiles": "*C(C)=O" },
+ { "id": "bz", "name": "Bz (benzoyl)", "tags": ["alcohol protection", "ester"], "smiles": "*C(=O)c1ccccc1" },
+ { "id": "piv", "name": "Piv (pivaloyl)", "tags": ["alcohol protection", "ester", "Pv"], "smiles": "*C(=O)C(C)(C)C" },
+ { "id": "tms", "name": "TMS (trimethylsilyl)", "tags": ["alcohol protection", "silyl ether"], "smiles": "*[Si](C)(C)C" },
+ { "id": "tbs", "name": "TBS (tert-butyldimethylsilyl)", "tags": ["alcohol protection", "silyl ether", "TBDMS"], "smiles": "*[Si](C)(C)C(C)(C)C" },
+ { "id": "tips", "name": "TIPS (triisopropylsilyl)", "tags": ["alcohol protection", "silyl ether"], "smiles": "*[Si](C(C)C)(C(C)C)C(C)C" },
+ { "id": "tbdps", "name": "TBDPS (tert-butyldiphenylsilyl)", "tags": ["alcohol protection", "silyl ether"], "smiles": "*[Si](c1ccccc1)(c1ccccc1)C(C)(C)C" },
+ { "id": "trityl", "name": "Tr (trityl)", "tags": ["alcohol protection", "amine protection", "triphenylmethyl"], "smiles": "*C(c1ccccc1)(c1ccccc1)c1ccccc1" },
+ { "id": "mom", "name": "MOM (methoxymethyl)", "tags": ["alcohol protection", "acetal"], "smiles": "*COC" },
+ { "id": "mem", "name": "MEM (2-methoxyethoxymethyl)", "tags": ["alcohol protection", "acetal"], "smiles": "*COCCOC" },
+ { "id": "sem", "name": "SEM (2-(trimethylsilyl)ethoxymethyl)", "tags": ["alcohol protection", "amine protection", "acetal"], "smiles": "*COCC[Si](C)(C)C" },
+ { "id": "thp", "name": "THP (tetrahydropyranyl)", "tags": ["alcohol protection", "acetal"], "smiles": "*C1CCCCO1" },
+ { "id": "ts", "name": "Ts (tosyl)", "tags": ["amine protection", "sulfonyl", "leaving group"], "smiles": "*S(=O)(=O)c1ccc(C)cc1" },
+ { "id": "ms", "name": "Ms (mesyl)", "tags": ["sulfonyl", "leaving group"], "smiles": "*S(=O)(=O)C" },
+ { "id": "ns", "name": "Ns (2-nitrobenzenesulfonyl)", "tags": ["amine protection", "sulfonyl", "nosyl"], "smiles": "*S(=O)(=O)c1ccccc1[N+](=O)[O-]" },
+ { "id": "acetonide", "name": "Acetonide (isopropylidene)", "tags": ["diol protection", "ketal"], "smiles": "*OC(C)(C)O*" },
+ { "id": "benzylidene", "name": "Benzylidene acetal", "tags": ["diol protection", "acetal"], "smiles": "*OC(O*)c1ccccc1" },
+ { "id": "dioxolane", "name": "1,3-Dioxolane (ketone protection)", "tags": ["carbonyl protection", "ketal", "ethylene glycol"], "smiles": "*C1(*)OCCO1" },
+ { "id": "phthalimide", "name": "Phthalimide (Phth)", "tags": ["amine protection", "imide", "Gabriel"], "smiles": "*N1C(=O)c2ccccc2C1=O" }
+ ]
+}
diff --git a/backend/app/data/templates/reagents.json b/backend/app/data/templates/reagents.json
new file mode 100644
index 00000000..06341a53
--- /dev/null
+++ b/backend/app/data/templates/reagents.json
@@ -0,0 +1,50 @@
+{
+ "category": "reagents",
+ "name": "Reagents and solvents",
+ "order": 80,
+ "templates": [
+ { "id": "dcc", "name": "DCC", "tags": ["coupling", "carbodiimide", "dicyclohexylcarbodiimide"], "smiles": "C1CCC(CC1)N=C=NC1CCCCC1" },
+ { "id": "edc", "name": "EDC", "tags": ["coupling", "carbodiimide"], "smiles": "CCN=C=NCCCN(C)C" },
+ { "id": "hatu", "name": "HATU", "tags": ["coupling", "uronium", "peptide"], "smiles": "CN(C)C(On1nnc2cccnc21)=[N+](C)C.F[P-](F)(F)(F)(F)F" },
+ { "id": "dmap", "name": "DMAP", "tags": ["base", "acylation catalyst", "4-dimethylaminopyridine"], "smiles": "CN(C)c1ccncc1" },
+ { "id": "triethylamine", "name": "Triethylamine", "tags": ["base", "Et3N", "TEA"], "smiles": "CCN(CC)CC" },
+ { "id": "dipea", "name": "DIPEA", "tags": ["base", "Hunig's base", "iPr2NEt"], "smiles": "CCN(C(C)C)C(C)C" },
+ { "id": "dbu", "name": "DBU", "tags": ["base", "amidine"], "smiles": "C1CCC2=NCCCN2CC1" },
+ { "id": "pyridine-reagent", "name": "Pyridine", "tags": ["base", "solvent"], "smiles": "c1ccncc1" },
+ { "id": "nabh4", "name": "Sodium borohydride", "tags": ["reductant", "hydride", "NaBH4"], "smiles": "[Na+].[BH4-]" },
+ { "id": "lialh4", "name": "Lithium aluminium hydride", "tags": ["reductant", "hydride", "LAH", "LiAlH4"], "smiles": "[Li+].[AlH4-]" },
+ { "id": "dibal", "name": "DIBAL-H", "tags": ["reductant", "hydride", "diisobutylaluminium hydride"], "smiles": "CC(C)C[AlH]CC(C)C" },
+ { "id": "nah", "name": "Sodium hydride", "tags": ["base", "hydride", "NaH"], "smiles": "[Na+].[H-]" },
+ { "id": "nbuli", "name": "n-Butyllithium", "tags": ["base", "organolithium", "nBuLi"], "smiles": "[Li]CCCC" },
+ { "id": "lda", "name": "LDA", "tags": ["base", "amide", "lithium diisopropylamide"], "smiles": "[Li+].CC(C)[N-]C(C)C" },
+ { "id": "k2co3", "name": "Potassium carbonate", "tags": ["base", "K2CO3"], "smiles": "[K+].[K+].[O-]C([O-])=O" },
+ { "id": "mcpba", "name": "mCPBA", "tags": ["oxidant", "peracid", "epoxidation"], "smiles": "OOC(=O)c1cccc(Cl)c1" },
+ { "id": "tempo", "name": "TEMPO", "tags": ["oxidant", "radical", "nitroxide"], "smiles": "CC1(C)CCCC(C)(C)N1[O]" },
+ { "id": "tscl", "name": "Tosyl chloride", "tags": ["sulfonylation", "TsCl"], "smiles": "Cc1ccc(cc1)S(Cl)(=O)=O" },
+ { "id": "mscl", "name": "Mesyl chloride", "tags": ["sulfonylation", "MsCl"], "smiles": "CS(Cl)(=O)=O" },
+ { "id": "socl2", "name": "Thionyl chloride", "tags": ["chlorination", "acid chloride", "SOCl2"], "smiles": "O=S(Cl)Cl" },
+ { "id": "oxalyl-chloride", "name": "Oxalyl chloride", "tags": ["chlorination", "acid chloride", "Swern"], "smiles": "O=C(Cl)C(Cl)=O" },
+ { "id": "boc2o", "name": "Di-tert-butyl dicarbonate", "tags": ["Boc2O", "protection"], "smiles": "CC(C)(C)OC(=O)OC(=O)OC(C)(C)C" },
+ { "id": "nbs", "name": "NBS", "tags": ["bromination", "N-bromosuccinimide"], "smiles": "BrN1C(=O)CCC1=O" },
+ { "id": "tbaf", "name": "TBAF", "tags": ["fluoride", "desilylation", "tetrabutylammonium fluoride"], "smiles": "CCCC[N+](CCCC)(CCCC)CCCC.[F-]" },
+ { "id": "pph3", "name": "Triphenylphosphine", "tags": ["phosphine", "PPh3", "Wittig", "Mitsunobu"], "smiles": "c1ccc(cc1)P(c1ccccc1)c1ccccc1" },
+ { "id": "dead", "name": "DEAD", "tags": ["Mitsunobu", "azodicarboxylate"], "smiles": "CCOC(=O)N=NC(=O)OCC" },
+ { "id": "diad", "name": "DIAD", "tags": ["Mitsunobu", "azodicarboxylate"], "smiles": "CC(C)OC(=O)N=NC(=O)OC(C)C" },
+ { "id": "tfa", "name": "Trifluoroacetic acid", "tags": ["acid", "TFA", "deprotection"], "smiles": "OC(=O)C(F)(F)F" },
+ { "id": "acetic-acid", "name": "Acetic acid", "tags": ["acid", "solvent", "AcOH"], "smiles": "CC(=O)O" },
+ { "id": "water", "name": "Water", "tags": ["solvent", "H2O"], "smiles": "O" },
+ { "id": "methanol", "name": "Methanol", "tags": ["solvent", "MeOH"], "smiles": "CO" },
+ { "id": "ethanol", "name": "Ethanol", "tags": ["solvent", "EtOH"], "smiles": "CCO" },
+ { "id": "thf", "name": "THF", "tags": ["solvent", "ether", "tetrahydrofuran"], "smiles": "C1CCOC1" },
+ { "id": "diethyl-ether", "name": "Diethyl ether", "tags": ["solvent", "ether", "Et2O"], "smiles": "CCOCC" },
+ { "id": "dcm", "name": "Dichloromethane", "tags": ["solvent", "DCM", "CH2Cl2"], "smiles": "ClCCl" },
+ { "id": "chloroform", "name": "Chloroform", "tags": ["solvent", "CHCl3"], "smiles": "ClC(Cl)Cl" },
+ { "id": "dmf", "name": "DMF", "tags": ["solvent", "dimethylformamide"], "smiles": "CN(C)C=O" },
+ { "id": "dmso", "name": "DMSO", "tags": ["solvent", "dimethyl sulfoxide"], "smiles": "CS(C)=O" },
+ { "id": "acetonitrile", "name": "Acetonitrile", "tags": ["solvent", "MeCN"], "smiles": "CC#N" },
+ { "id": "ethyl-acetate", "name": "Ethyl acetate", "tags": ["solvent", "EtOAc"], "smiles": "CCOC(C)=O" },
+ { "id": "acetone", "name": "Acetone", "tags": ["solvent", "ketone"], "smiles": "CC(C)=O" },
+ { "id": "toluene", "name": "Toluene", "tags": ["solvent", "arene", "PhMe"], "smiles": "Cc1ccccc1" },
+ { "id": "hexane", "name": "Hexane", "tags": ["solvent", "alkane"], "smiles": "CCCCCC" }
+ ]
+}
diff --git a/backend/app/data/templates/rings.json b/backend/app/data/templates/rings.json
new file mode 100644
index 00000000..b33ef570
--- /dev/null
+++ b/backend/app/data/templates/rings.json
@@ -0,0 +1,88 @@
+{
+ "category": "rings",
+ "name": "Rings",
+ "order": 10,
+ "templates": [
+ { "id": "cyclopropane", "name": "Cyclopropane", "tags": ["C3", "cycloalkane", "three-membered"], "ring": { "elements": ["C", "C", "C"], "orders": [1, 1, 1] } },
+ { "id": "cyclobutane", "name": "Cyclobutane", "tags": ["C4", "cycloalkane", "four-membered"], "ring": { "elements": ["C", "C", "C", "C"], "orders": [1, 1, 1, 1] } },
+ { "id": "cyclopentane", "name": "Cyclopentane", "tags": ["C5", "cycloalkane", "five-membered"], "ring": { "elements": ["C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1] } },
+ { "id": "cyclohexane", "name": "Cyclohexane", "tags": ["C6", "cycloalkane", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1, 1] } },
+ { "id": "cycloheptane", "name": "Cycloheptane", "tags": ["C7", "cycloalkane", "seven-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1, 1, 1] } },
+ { "id": "cyclooctane", "name": "Cyclooctane", "tags": ["C8", "cycloalkane", "eight-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1, 1, 1, 1] } },
+ { "id": "benzene", "name": "Benzene", "tags": ["arene", "aromatic", "phenyl", "C6H6"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 2, 1] } },
+ { "id": "cyclopentadiene", "name": "Cyclopentadiene", "tags": ["diene", "C5H6", "five-membered"], "ring": { "elements": ["C", "C", "C", "C", "C"], "orders": [1, 2, 1, 1, 2] } },
+ { "id": "cyclohexene", "name": "Cyclohexene", "tags": ["alkene", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 1, 1, 1, 1] } },
+ { "id": "cyclohexa-1-3-diene", "name": "Cyclohexa-1,3-diene", "tags": ["diene", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 1, 1] } },
+ { "id": "cyclohexa-1-4-diene", "name": "Cyclohexa-1,4-diene", "tags": ["diene", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 1, 2, 1, 1] } },
+ { "id": "cycloheptatriene", "name": "Cycloheptatriene", "tags": ["tropylidene", "seven-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 2, 1, 1] } },
+ { "id": "cyclooctatetraene", "name": "Cyclooctatetraene", "tags": ["COT", "eight-membered", "annulene"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 2, 1, 2, 1] } },
+ {
+ "id": "chair", "name": "Cyclohexane chair", "tags": ["conformation", "chair", "perspective"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "a1": { "id": "a1", "element": "C", "x": 0, "y": 16.4 },
+ "a2": { "id": "a2", "element": "C", "x": 10.8, "y": 9 },
+ "a3": { "id": "a3", "element": "C", "x": 32.4, "y": 20.9 },
+ "a4": { "id": "a4", "element": "C", "x": 43.2, "y": 4.4 },
+ "a5": { "id": "a5", "element": "C", "x": 32.4, "y": 11.9 },
+ "a6": { "id": "a6", "element": "C", "x": 10.8, "y": 0 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1 },
+ "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1 },
+ "b3": { "id": "b3", "a": "a3", "b": "a4", "order": 1 },
+ "b4": { "id": "b4", "a": "a4", "b": "a5", "order": 1 },
+ "b5": { "id": "b5", "a": "a5", "b": "a6", "order": 1 },
+ "b6": { "id": "b6", "a": "a6", "b": "a1", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "chair-flipped", "name": "Cyclohexane chair (flipped)", "tags": ["conformation", "chair", "perspective", "ring flip"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "a1": { "id": "a1", "element": "C", "x": 43.2, "y": 16.4 },
+ "a2": { "id": "a2", "element": "C", "x": 32.4, "y": 9 },
+ "a3": { "id": "a3", "element": "C", "x": 10.8, "y": 20.9 },
+ "a4": { "id": "a4", "element": "C", "x": 0, "y": 4.4 },
+ "a5": { "id": "a5", "element": "C", "x": 10.8, "y": 11.9 },
+ "a6": { "id": "a6", "element": "C", "x": 32.4, "y": 0 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1 },
+ "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1 },
+ "b3": { "id": "b3", "a": "a3", "b": "a4", "order": 1 },
+ "b4": { "id": "b4", "a": "a4", "b": "a5", "order": 1 },
+ "b5": { "id": "b5", "a": "a5", "b": "a6", "order": 1 },
+ "b6": { "id": "b6", "a": "a6", "b": "a1", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "cubane", "name": "Cubane", "tags": ["polycycle", "perspective", "C8H8"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "a1": { "id": "a1", "element": "C", "x": 0, "y": 8 },
+ "a2": { "id": "a2", "element": "C", "x": 20, "y": 8 },
+ "a3": { "id": "a3", "element": "C", "x": 20, "y": 28 },
+ "a4": { "id": "a4", "element": "C", "x": 0, "y": 28 },
+ "a5": { "id": "a5", "element": "C", "x": 8, "y": 0 },
+ "a6": { "id": "a6", "element": "C", "x": 28, "y": 0 },
+ "a7": { "id": "a7", "element": "C", "x": 28, "y": 20 },
+ "a8": { "id": "a8", "element": "C", "x": 8, "y": 20 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1, "z": 2 },
+ "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1, "z": 2 },
+ "b3": { "id": "b3", "a": "a3", "b": "a4", "order": 1, "z": 2 },
+ "b4": { "id": "b4", "a": "a4", "b": "a1", "order": 1, "z": 2 },
+ "b5": { "id": "b5", "a": "a5", "b": "a6", "order": 1 },
+ "b6": { "id": "b6", "a": "a6", "b": "a7", "order": 1 },
+ "b7": { "id": "b7", "a": "a7", "b": "a8", "order": 1 },
+ "b8": { "id": "b8", "a": "a8", "b": "a5", "order": 1 },
+ "b9": { "id": "b9", "a": "a1", "b": "a5", "order": 1, "z": 1 },
+ "b10": { "id": "b10", "a": "a2", "b": "a6", "order": 1, "z": 1 },
+ "b11": { "id": "b11", "a": "a3", "b": "a7", "order": 1, "z": 1 },
+ "b12": { "id": "b12", "a": "a4", "b": "a8", "order": 1 } } }
+ ]
+ }
+ ]
+}
diff --git a/backend/app/data/templates/sugars.json b/backend/app/data/templates/sugars.json
new file mode 100644
index 00000000..37d03a7c
--- /dev/null
+++ b/backend/app/data/templates/sugars.json
@@ -0,0 +1,204 @@
+{
+ "category": "sugars",
+ "name": "Sugars",
+ "order": 50,
+ "templates": [
+ {
+ "id": "beta-d-glucopyranose", "name": "beta-D-Glucopyranose (Haworth)", "tags": ["glucose", "pyranose", "Haworth", "hexose", "carbohydrate"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "c1": { "id": "c1", "element": "C", "x": 56, "y": 37 },
+ "c2": { "id": "c2", "element": "C", "x": 42, "y": 52 },
+ "c3": { "id": "c3", "element": "C", "x": 14, "y": 52 },
+ "c4": { "id": "c4", "element": "C", "x": 0, "y": 37 },
+ "c5": { "id": "c5", "element": "C", "x": 14, "y": 22 },
+ "o5": { "id": "o5", "element": "O", "x": 42, "y": 22 },
+ "o1": { "id": "o1", "element": "O", "x": 56, "y": 23 },
+ "o2": { "id": "o2", "element": "O", "x": 42, "y": 66 },
+ "o3": { "id": "o3", "element": "O", "x": 14, "y": 40 },
+ "o4": { "id": "o4", "element": "O", "x": 0, "y": 51 },
+ "c6": { "id": "c6", "element": "C", "x": 14, "y": 8 },
+ "o6": { "id": "o6", "element": "O", "x": 1.53, "y": 0.8 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true },
+ "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true },
+ "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true },
+ "b4": { "id": "b4", "a": "c4", "b": "c5", "order": 1 },
+ "b5": { "id": "b5", "a": "c5", "b": "o5", "order": 1 },
+ "b6": { "id": "b6", "a": "o5", "b": "c1", "order": 1 },
+ "b7": { "id": "b7", "a": "c1", "b": "o1", "order": 1 },
+ "b8": { "id": "b8", "a": "c2", "b": "o2", "order": 1 },
+ "b9": { "id": "b9", "a": "c3", "b": "o3", "order": 1 },
+ "b10": { "id": "b10", "a": "c4", "b": "o4", "order": 1 },
+ "b11": { "id": "b11", "a": "c5", "b": "c6", "order": 1 },
+ "b12": { "id": "b12", "a": "c6", "b": "o6", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "alpha-d-glucopyranose", "name": "alpha-D-Glucopyranose (Haworth)", "tags": ["glucose", "pyranose", "Haworth", "hexose", "carbohydrate", "anomer"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "c1": { "id": "c1", "element": "C", "x": 56, "y": 37 },
+ "c2": { "id": "c2", "element": "C", "x": 42, "y": 52 },
+ "c3": { "id": "c3", "element": "C", "x": 14, "y": 52 },
+ "c4": { "id": "c4", "element": "C", "x": 0, "y": 37 },
+ "c5": { "id": "c5", "element": "C", "x": 14, "y": 22 },
+ "o5": { "id": "o5", "element": "O", "x": 42, "y": 22 },
+ "o1": { "id": "o1", "element": "O", "x": 56, "y": 51 },
+ "o2": { "id": "o2", "element": "O", "x": 42, "y": 66 },
+ "o3": { "id": "o3", "element": "O", "x": 14, "y": 40 },
+ "o4": { "id": "o4", "element": "O", "x": 0, "y": 51 },
+ "c6": { "id": "c6", "element": "C", "x": 14, "y": 8 },
+ "o6": { "id": "o6", "element": "O", "x": 1.53, "y": 0.8 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true },
+ "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true },
+ "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true },
+ "b4": { "id": "b4", "a": "c4", "b": "c5", "order": 1 },
+ "b5": { "id": "b5", "a": "c5", "b": "o5", "order": 1 },
+ "b6": { "id": "b6", "a": "o5", "b": "c1", "order": 1 },
+ "b7": { "id": "b7", "a": "c1", "b": "o1", "order": 1 },
+ "b8": { "id": "b8", "a": "c2", "b": "o2", "order": 1 },
+ "b9": { "id": "b9", "a": "c3", "b": "o3", "order": 1 },
+ "b10": { "id": "b10", "a": "c4", "b": "o4", "order": 1 },
+ "b11": { "id": "b11", "a": "c5", "b": "c6", "order": 1 },
+ "b12": { "id": "b12", "a": "c6", "b": "o6", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "pyranose-ring", "name": "Pyranose ring (Haworth)", "tags": ["pyranose", "Haworth", "skeleton", "oxane"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "c1": { "id": "c1", "element": "C", "x": 56, "y": 15 },
+ "c2": { "id": "c2", "element": "C", "x": 42, "y": 30 },
+ "c3": { "id": "c3", "element": "C", "x": 14, "y": 30 },
+ "c4": { "id": "c4", "element": "C", "x": 0, "y": 15 },
+ "c5": { "id": "c5", "element": "C", "x": 14, "y": 0 },
+ "o5": { "id": "o5", "element": "O", "x": 42, "y": 0 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true },
+ "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true },
+ "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true },
+ "b4": { "id": "b4", "a": "c4", "b": "c5", "order": 1 },
+ "b5": { "id": "b5", "a": "c5", "b": "o5", "order": 1 },
+ "b6": { "id": "b6", "a": "o5", "b": "c1", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "beta-d-ribofuranose", "name": "beta-D-Ribofuranose (Haworth)", "tags": ["ribose", "furanose", "Haworth", "pentose", "carbohydrate"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "o4": { "id": "o4", "element": "O", "x": 37, "y": 8 },
+ "c1": { "id": "c1", "element": "C", "x": 61, "y": 22 },
+ "c2": { "id": "c2", "element": "C", "x": 51, "y": 38 },
+ "c3": { "id": "c3", "element": "C", "x": 23, "y": 38 },
+ "c4": { "id": "c4", "element": "C", "x": 13, "y": 22 },
+ "o1": { "id": "o1", "element": "O", "x": 61, "y": 8 },
+ "o2": { "id": "o2", "element": "O", "x": 51, "y": 52 },
+ "o3": { "id": "o3", "element": "O", "x": 23, "y": 52 },
+ "c5": { "id": "c5", "element": "C", "x": 13, "y": 8 },
+ "o5": { "id": "o5", "element": "O", "x": 0.53, "y": 0.8 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true },
+ "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true },
+ "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true },
+ "b4": { "id": "b4", "a": "c4", "b": "o4", "order": 1 },
+ "b5": { "id": "b5", "a": "o4", "b": "c1", "order": 1 },
+ "b6": { "id": "b6", "a": "c1", "b": "o1", "order": 1 },
+ "b7": { "id": "b7", "a": "c2", "b": "o2", "order": 1 },
+ "b8": { "id": "b8", "a": "c3", "b": "o3", "order": 1 },
+ "b9": { "id": "b9", "a": "c4", "b": "c5", "order": 1 },
+ "b10": { "id": "b10", "a": "c5", "b": "o5", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "2-deoxy-beta-d-ribofuranose", "name": "2-Deoxy-beta-D-ribofuranose (Haworth)", "tags": ["deoxyribose", "furanose", "Haworth", "DNA sugar"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "o4": { "id": "o4", "element": "O", "x": 37, "y": 8 },
+ "c1": { "id": "c1", "element": "C", "x": 61, "y": 22 },
+ "c2": { "id": "c2", "element": "C", "x": 51, "y": 38 },
+ "c3": { "id": "c3", "element": "C", "x": 23, "y": 38 },
+ "c4": { "id": "c4", "element": "C", "x": 13, "y": 22 },
+ "o1": { "id": "o1", "element": "O", "x": 61, "y": 8 },
+ "o3": { "id": "o3", "element": "O", "x": 23, "y": 52 },
+ "c5": { "id": "c5", "element": "C", "x": 13, "y": 8 },
+ "o5": { "id": "o5", "element": "O", "x": 0.53, "y": 0.8 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true },
+ "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true },
+ "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true },
+ "b4": { "id": "b4", "a": "c4", "b": "o4", "order": 1 },
+ "b5": { "id": "b5", "a": "o4", "b": "c1", "order": 1 },
+ "b6": { "id": "b6", "a": "c1", "b": "o1", "order": 1 },
+ "b8": { "id": "b8", "a": "c3", "b": "o3", "order": 1 },
+ "b9": { "id": "b9", "a": "c4", "b": "c5", "order": 1 },
+ "b10": { "id": "b10", "a": "c5", "b": "o5", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "furanose-ring", "name": "Furanose ring (Haworth)", "tags": ["furanose", "Haworth", "skeleton", "oxolane"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "o4": { "id": "o4", "element": "O", "x": 24, "y": 0 },
+ "c1": { "id": "c1", "element": "C", "x": 48, "y": 14 },
+ "c2": { "id": "c2", "element": "C", "x": 38, "y": 30 },
+ "c3": { "id": "c3", "element": "C", "x": 10, "y": 30 },
+ "c4": { "id": "c4", "element": "C", "x": 0, "y": 14 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true },
+ "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true },
+ "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true },
+ "b4": { "id": "b4", "a": "c4", "b": "o4", "order": 1 },
+ "b5": { "id": "b5", "a": "o4", "b": "c1", "order": 1 } } }
+ ]
+ },
+ {
+ "id": "d-glucose-fischer", "name": "D-Glucose (Fischer)", "tags": ["glucose", "Fischer", "open chain", "aldohexose"],
+ "objects": [
+ { "id": "f1", "kind": "fragment",
+ "atoms": {
+ "c1": { "id": "c1", "element": "C", "x": 14.4, "y": 7.2 },
+ "o1": { "id": "o1", "element": "O", "x": 26.87, "y": 0 },
+ "c2": { "id": "c2", "element": "C", "x": 14.4, "y": 21.6 },
+ "c3": { "id": "c3", "element": "C", "x": 14.4, "y": 36 },
+ "c4": { "id": "c4", "element": "C", "x": 14.4, "y": 50.4 },
+ "c5": { "id": "c5", "element": "C", "x": 14.4, "y": 64.8 },
+ "c6": { "id": "c6", "element": "C", "x": 14.4, "y": 79.2 },
+ "o6": { "id": "o6", "element": "O", "x": 14.4, "y": 93.6 },
+ "h2": { "id": "h2", "element": "H", "x": 0, "y": 21.6 },
+ "o2": { "id": "o2", "element": "O", "x": 28.8, "y": 21.6 },
+ "o3": { "id": "o3", "element": "O", "x": 0, "y": 36 },
+ "h3": { "id": "h3", "element": "H", "x": 28.8, "y": 36 },
+ "h4": { "id": "h4", "element": "H", "x": 0, "y": 50.4 },
+ "o4": { "id": "o4", "element": "O", "x": 28.8, "y": 50.4 },
+ "h5": { "id": "h5", "element": "H", "x": 0, "y": 64.8 },
+ "o5": { "id": "o5", "element": "O", "x": 28.8, "y": 64.8 } },
+ "bonds": {
+ "b1": { "id": "b1", "a": "c1", "b": "o1", "order": 2 },
+ "b2": { "id": "b2", "a": "c1", "b": "c2", "order": 1 },
+ "b3": { "id": "b3", "a": "c2", "b": "c3", "order": 1 },
+ "b4": { "id": "b4", "a": "c3", "b": "c4", "order": 1 },
+ "b5": { "id": "b5", "a": "c4", "b": "c5", "order": 1 },
+ "b6": { "id": "b6", "a": "c5", "b": "c6", "order": 1 },
+ "b7": { "id": "b7", "a": "c6", "b": "o6", "order": 1 },
+ "b8": { "id": "b8", "a": "c2", "b": "h2", "order": 1 },
+ "b9": { "id": "b9", "a": "c2", "b": "o2", "order": 1 },
+ "b10": { "id": "b10", "a": "c3", "b": "o3", "order": 1 },
+ "b11": { "id": "b11", "a": "c3", "b": "h3", "order": 1 },
+ "b12": { "id": "b12", "a": "c4", "b": "h4", "order": 1 },
+ "b13": { "id": "b13", "a": "c4", "b": "o4", "order": 1 },
+ "b14": { "id": "b14", "a": "c5", "b": "h5", "order": 1 },
+ "b15": { "id": "b15", "a": "c5", "b": "o5", "order": 1 } } }
+ ]
+ },
+ { "id": "glucose-smiles", "name": "beta-D-Glucose (skeletal)", "tags": ["glucose", "pyranose", "skeletal", "stereo"], "smiles": "OC[C@H]1O[C@@H](O)[C@H](O)[C@@H](O)[C@@H]1O" },
+ { "id": "fructose-smiles", "name": "beta-D-Fructofuranose (skeletal)", "tags": ["fructose", "furanose", "ketose", "skeletal"], "smiles": "OC[C@H]1O[C@](O)(CO)[C@@H](O)[C@@H]1O" }
+ ]
+}
diff --git a/backend/app/main.py b/backend/app/main.py
index 9b514653..9eb5b571 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -13,7 +13,7 @@
from app.core import config
from app.core.local_guard import LocalGuard
from app.core.window_key import WindowKeyGuard
-from app.routers import chat, chem, commands, documents, extensions, library, live, mcp, system, terminal
+from app.routers import analysis, chat, chem, commands, documents, extensions, library, live, mcp, reactions, system, templates, terminal
from app.services import claude_code, consent, history
from app.services import terminal as terminals
from app.services.chat import engine as chat_engine
@@ -63,6 +63,9 @@ async def lifespan(this: FastAPI):
app.include_router(library.router)
app.include_router(documents.router)
app.include_router(chem.router)
+app.include_router(reactions.router)
+app.include_router(analysis.router)
+app.include_router(templates.router)
app.include_router(commands.router)
app.include_router(extensions.router)
app.include_router(terminal.router)
diff --git a/backend/app/routers/analysis.py b/backend/app/routers/analysis.py
new file mode 100644
index 00000000..e7d0f64c
--- /dev/null
+++ b/backend/app/routers/analysis.py
@@ -0,0 +1,342 @@
+import asyncio
+import copy
+from dataclasses import dataclass, field
+
+from fastapi import APIRouter, HTTPException
+
+from app.routers.chem import MAX_TEXT, _bond_length, _expansions, _fragment, _num
+from app.services import ops as opsmod
+from app.services.chem import ENGINE, abbrev, check, convert, hydrogens, isotopes, markush, props, query, search, stereo, superatom, v3000
+from app.services.store import STORE
+
+router = APIRouter()
+
+
+@dataclass
+class Source:
+ fragments: dict[str, dict]
+ expansions: dict | None = None
+ members: dict[str, dict] = field(default_factory=dict)
+ doc: str | None = None
+ has_map: bool = False
+ used: set[str] = field(default_factory=set)
+ elsewhere: set[str] = field(default_factory=set)
+
+ @property
+ def one(self) -> dict:
+ return next(iter(self.fragments.values()))
+
+
+def _ids_of(doc: dict) -> set[str]:
+ out = {doc.get("id", "")}
+ out.update(p.get("id") for p in doc.get("pages") or [] if isinstance(p, dict))
+ for key, obj in (doc.get("objects") or {}).items():
+ out.add(key)
+ if isinstance(obj, dict) and obj.get("kind") == "fragment":
+ out.update(obj.get("atoms") or {})
+ out.update(obj.get("bonds") or {})
+ out.update(doc.get("expansions") or {})
+ return out
+
+
+def _from_doc(body: dict, single: bool) -> Source:
+ 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)
+ frags = {k: o for k, o in (doc.get("objects") or {}).items() if isinstance(o, dict) and o.get("kind") == "fragment"}
+ wanted = body.get("objects")
+ if body.get("object") is not None:
+ wanted = [body.get("object")]
+ if wanted is not None:
+ if not isinstance(wanted, list) or not all(isinstance(i, str) for i in wanted):
+ raise HTTPException(422, "objects must be a list of fragment ids")
+ missing = [i for i in wanted if i not in frags]
+ if missing:
+ raise HTTPException(404, f"{missing[0]} is not a fragment of {doc_id}.")
+ chosen = {i: frags[i] for i in wanted}
+ elif single:
+ raise HTTPException(422, "name the fragment with object")
+ else:
+ chosen = frags
+ if single and len(chosen) != 1:
+ raise HTTPException(422, "this command acts on one fragment: give object")
+ elsewhere = {a.get("expansion") for k, f in frags.items() if k not in chosen for a in (f.get("atoms") or {}).values() if a.get("expansion")}
+ elsewhere |= {a.get("expansion") for e in (doc.get("expansions") or {}).values() if isinstance(e, dict) for a in (e.get("atoms") or {}).values() if a.get("expansion")}
+ return Source(chosen, doc.get("expansions") or {}, frags, doc_id, "expansions" in doc, _ids_of(doc), elsewhere - {None})
+
+
+def source(body: dict, single: bool = False) -> Source:
+ if body.get("doc") is not None:
+ if not isinstance(body.get("doc"), str):
+ raise HTTPException(422, "doc must be a document id")
+ return _from_doc(body, single)
+ frag = _fragment(body)
+ members = body.get("members") or {}
+ if not isinstance(members, dict):
+ raise HTTPException(422, "members must be a map of fragment id to fragment")
+ checked = {k: _fragment({"fragment": {"id": k, **m}}) for k, m in members.items() if isinstance(m, dict)}
+ exp = _expansions(body)
+ return Source({frag["id"]: frag}, exp, checked, None, exp is not None)
+
+
+def _unprocessable(exc: Exception) -> HTTPException:
+ return HTTPException(422, str(exc))
+
+
+async def run(fn, *args, **kwargs):
+ try:
+ return await asyncio.to_thread(fn, *args, **kwargs)
+ except HTTPException:
+ raise
+ except (ValueError, KeyError) as exc:
+ raise _unprocessable(exc)
+
+
+def _each(src: Source, fn) -> dict:
+ out = {}
+ for fid, frag in src.fragments.items():
+ try:
+ out[fid] = fn(frag)
+ except Exception as exc:
+ out[fid] = {"error": f"{type(exc).__name__}: {exc}"}
+ return {"fragments": out, "engine": ENGINE}
+
+
+@router.get("/api/analysis/abbreviations")
+def abbreviations() -> dict:
+ path = abbrev.user_path()
+ return {"abbreviations": abbrev.library(), "user_file": str(path) if path else None, "user_errors": abbrev.user_errors()}
+
+
+@router.post("/api/analysis/properties")
+async def properties(body: dict) -> dict:
+ src = source(body)
+ return await run(_each, src, lambda f: props.compute(f, src.expansions))
+
+
+@router.post("/api/analysis/cip")
+async def cip(body: dict) -> dict:
+ src = source(body)
+ return await run(_each, src, lambda f: stereo.report(f, src.expansions))
+
+
+@router.post("/api/analysis/check")
+async def check_structure(body: dict) -> dict:
+ src = source(body)
+ is_query = body.get("query") is True
+ return await run(_each, src, lambda f: check.check(f, src.expansions, src.members, is_query))
+
+
+def _atoms(body: dict, key: str = "atoms") -> list[str] | None:
+ value = body.get(key)
+ if value is None:
+ return None
+ if not isinstance(value, list) or not all(isinstance(i, str) for i in value):
+ raise HTTPException(422, f"{key} must be a list of atom ids")
+ return value
+
+
+async def finish(body: dict, src: Source, result: dict) -> dict:
+ tx = result.get("tx")
+ if body.get("apply") is not True or not tx:
+ return result
+ if src.doc is None:
+ raise HTTPException(422, "apply needs doc: send the document id instead of a fragment")
+ if not tx["ops"]:
+ return {**result, "applied": None}
+ try:
+ done = await STORE.apply(src.doc, {"label": tx["label"], "ops": tx["ops"]}, "user")
+ except opsmod.OpError as exc:
+ raise HTTPException(409, {"message": str(exc), "errors": exc.errors})
+ except KeyError:
+ raise HTTPException(404, f"The drawing {src.doc} was closed.")
+ return {**result, "applied": {"tx": done["tx"], "rev": done["rev"]}}
+
+
+@router.post("/api/analysis/stereo-groups")
+async def stereo_groups(body: dict) -> dict:
+ src = source(body, single=True)
+ frag = src.one
+ change = body.get("set")
+ groups = None
+ if change is not None:
+ if not isinstance(change, dict) or change.get("kind") not in stereo.KINDS:
+ raise HTTPException(422, "set needs kind abs, and or or, and atoms")
+ n = change.get("n")
+ if n is not None and (not isinstance(n, int) or isinstance(n, bool) or n < 1):
+ raise HTTPException(422, "n must be a group number from 1")
+ groups = stereo.regroup(frag, change["kind"], _atoms(change) or [], n)
+ set_chiral = "chiral" in body
+ flag = body.get("chiral")
+ if set_chiral and flag not in (None, *convert.CHIRAL_FLAGS):
+ raise HTTPException(422, "chiral must be absolute, relative, racemic or null")
+ out = await run(stereo.preview, frag, groups, flag, set_chiral, src.expansions)
+ if groups is not None or set_chiral:
+ out["tx"] = stereo.groups_tx(frag, groups, flag, set_chiral)
+ return await finish(body, src, out)
+
+
+@router.post("/api/analysis/wedges")
+async def wedges(body: dict) -> dict:
+ src = source(body, single=True)
+ wanted = body.get("cip")
+ if wanted is not None and (not isinstance(wanted, dict) or any(v not in ("R", "S") for v in wanted.values())):
+ raise HTTPException(422, "cip must map atom ids to R or S")
+ coords = body.get("coords3d")
+ if coords is not None and (not isinstance(coords, dict) or any(not isinstance(v, list) or len(v) != 3 or not all(_num(x) for x in v) for v in coords.values())):
+ raise HTTPException(422, "coords3d must map atom ids to [x, y, z]")
+ out = await run(stereo.rewedge, src.one, src.expansions, _atoms(body), wanted, coords)
+ return await finish(body, src, out)
+
+
+@router.post("/api/analysis/expand")
+async def expand(body: dict) -> dict:
+ src = source(body, single=True)
+ length = _bond_length(body) if body.get("bond_length") is not None else None
+ out = await run(superatom.expand, src.one, _atoms(body), src.expansions, length, src.used, src.elsewhere, src.doc is not None)
+ return await finish(body, src, out)
+
+
+@router.post("/api/analysis/contract")
+async def contract(body: dict) -> dict:
+ src = source(body, single=True)
+ atoms = _atoms(body)
+ if not atoms:
+ raise HTTPException(422, "atoms (the selected substituent) is required")
+ label = body.get("label")
+ if label is not None and (not isinstance(label, str) or not label.strip() or len(label) > 40):
+ raise HTTPException(422, "label must be a short text")
+ out = await run(superatom.contract, src.one, atoms, label.strip() if label else None, src.expansions, src.has_map, src.used)
+ return await finish(body, src, out)
+
+
+@router.post("/api/analysis/add-h")
+async def add_h(body: dict) -> dict:
+ src = source(body, single=True)
+ out = await run(hydrogens.add_hydrogens, src.one, src.expansions, _atoms(body), src.used)
+ return await finish(body, src, out)
+
+
+@router.post("/api/analysis/remove-h")
+async def remove_h(body: dict) -> dict:
+ src = source(body, single=True)
+ out = await run(hydrogens.remove_hydrogens, src.one, src.expansions, _atoms(body))
+ return await finish(body, src, out)
+
+
+def _text(body: dict) -> str:
+ text = body.get("text")
+ if not isinstance(text, str) or not text.strip():
+ raise HTTPException(422, "text is required")
+ if len(text) > MAX_TEXT:
+ raise HTTPException(413, "text is too large")
+ return text
+
+
+def _origin(body: dict) -> tuple[float, float]:
+ origin = body.get("origin")
+ if isinstance(origin, list) and len(origin) == 2 and all(_num(v) for v in origin):
+ return float(origin[0]), float(origin[1])
+ return 72.0, 72.0
+
+
+def _limit(body: dict, key: str, default: int, top: int) -> int:
+ value = body.get(key, default)
+ if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= top:
+ raise HTTPException(422, f"{key} must be a whole number from 1 to {top}")
+ return value
+
+
+@router.post("/api/analysis/smarts/export")
+async def smarts_export(body: dict) -> dict:
+ src = source(body, single=True)
+ text, notes = await run(query.to_smarts, src.one, src.expansions, _atoms(body))
+ return {"smarts": text, "warnings": notes, "engine": ENGINE}
+
+
+@router.post("/api/analysis/smarts/import")
+async def smarts_import(body: dict) -> dict:
+ frag, notes = await run(query.from_smarts, _text(body), _bond_length(body), _origin(body))
+ return {"format": "smarts", "fragments": [frag], "warnings": notes}
+
+
+@router.post("/api/analysis/substructure")
+async def substructure(body: dict) -> dict:
+ smarts = body.get("smarts")
+ if smarts is not None and (not isinstance(smarts, str) or not smarts.strip()):
+ raise HTTPException(422, "smarts must be a SMARTS string")
+ pattern = None
+ src = source({k: v for k, v in body.items() if k != "object"}) if body.get("doc") is not None else None
+ if smarts is None:
+ named = body.get("query_object")
+ if src is not None and isinstance(named, str):
+ if named not in src.members:
+ raise HTTPException(404, f"{named} is not a fragment of {src.doc}.")
+ pattern = src.members[named]
+ elif isinstance(body.get("query"), dict):
+ pattern = _fragment({"fragment": body["query"]})
+ else:
+ raise HTTPException(422, "give query (a fragment), query_object (a fragment of doc) or smarts")
+ if src is not None:
+ targets = {k: f for k, f in src.fragments.items() if not pattern or k != pattern.get("id")}
+ expansions = src.expansions
+ else:
+ given = body.get("fragments")
+ if not isinstance(given, dict) or not given:
+ raise HTTPException(422, "give doc (with optional objects) or fragments, a map of fragment id to fragment")
+ targets = {k: _fragment({"fragment": {"id": k, **f}}) for k, f in given.items() if isinstance(f, dict)}
+ expansions = _expansions(body)
+ return await run(search.substructure, targets, pattern, smarts, expansions, _limit(body, "max_hits", search.MAX_HITS, 100_000), body.get("chirality") is True)
+
+
+@router.post("/api/analysis/molfile")
+async def molfile(body: dict) -> dict:
+ src = source(body, single=True)
+ text, notes = await run(v3000.write, src.one, src.expansions, src.members)
+ return {"to": "molfile3000", "text": text, "warnings": notes, "engine": ENGINE}
+
+
+@router.post("/api/analysis/molfile/import")
+async def molfile_import(body: dict) -> dict:
+ frags, notes = await run(v3000.read, _text(body), _bond_length(body), _origin(body))
+ return {"format": "molfile3000", "fragments": frags, "warnings": notes}
+
+
+@router.post("/api/analysis/markush")
+async def enumerate_markush(body: dict) -> dict:
+ src = source(body, single=True)
+ limit = _limit(body, "limit", markush.LIMIT, markush.HARD_LIMIT)
+ out = await run(markush.enumerate_structures, src.one, src.members, src.expansions, limit, body.get("force") is True)
+ out["groups"] = markush.describe(src.one, src.members)["groups"]
+ return out
+
+
+def _threshold(value) -> float:
+ if value is None:
+ return isotopes.THRESHOLD
+ if not _num(value) or not 0 <= value <= 100:
+ raise HTTPException(422, "threshold must be a percent of the base peak from 0 to 100")
+ return float(value)
+
+
+@router.get("/api/analysis/isotope-pattern")
+async def isotope_pattern_of_formula(formula: str = "", threshold: float | None = None) -> dict:
+ if not formula.strip() or len(formula) > 2000:
+ raise HTTPException(422, "give a formula such as C13H18O2")
+ level = _threshold(threshold)
+
+ def compute() -> dict:
+ counts, charge = isotopes.parse_formula(formula)
+ return {**isotopes.from_counts(counts, charge, level), "warnings": [], "engine": ENGINE}
+ return await run(compute)
+
+
+@router.post("/api/analysis/isotope-pattern")
+async def isotope_pattern(body: dict) -> dict:
+ src = source(body)
+ level = _threshold(body.get("threshold"))
+ return await run(_each, src, lambda f: isotopes.pattern(f, src.expansions, level))
diff --git a/backend/app/routers/documents.py b/backend/app/routers/documents.py
index 1b30a4ec..e8f0d444 100644
--- a/backend/app/routers/documents.py
+++ b/backend/app/routers/documents.py
@@ -1,7 +1,7 @@
import asyncio
from pathlib import Path
-from fastapi import APIRouter, Body, Depends, HTTPException, Request
+from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response
from starlette.datastructures import UploadFile as StarletteUpload
from app.core import config, files, window_key
@@ -165,6 +165,33 @@ async def close(doc_id: str) -> dict:
return await STORE.close(doc_id)
+@router.post("/api/documents/{doc_id}/media", dependencies=GUARD)
+async def upload_media(doc_id: str, request: Request) -> dict:
+ _session(doc_id)
+ form = await request.form()
+ found = [v for v in form.getlist("file") if isinstance(v, StarletteUpload)]
+ if not found:
+ raise HTTPException(400, "Send the picture as a multipart field named file.")
+ data = await found[0].read(UPLOAD_LIMIT + 1)
+ if len(data) > UPLOAD_LIMIT:
+ raise HTTPException(413, f"The picture is larger than {UPLOAD_LIMIT // (1024 * 1024)} MB.")
+ try:
+ return STORE.add_media(doc_id, data, Path(found[0].filename or "").name)
+ except StoreError as exc:
+ raise HTTPException(415, str(exc))
+
+
+@router.get("/api/documents/{doc_id}/media/{media_id}")
+def get_media(doc_id: str, media_id: str) -> Response:
+ _session(doc_id)
+ try:
+ data, mime = STORE.media_bytes(doc_id, media_id)
+ except StoreError as exc:
+ raise HTTPException(404, str(exc))
+ return Response(data, media_type=mime, headers={"cache-control": "private, max-age=31536000, immutable", "x-content-type-options": "nosniff",
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'"})
+
+
@router.get("/api/documents/{doc_id}/versions")
def versions(doc_id: str) -> dict:
_session(doc_id)
diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py
index 82bdee12..8fe1f043 100644
--- a/backend/app/routers/mcp.py
+++ b/backend/app/routers/mcp.py
@@ -1,3 +1,5 @@
+import asyncio
+import copy
import json
import time
import uuid
@@ -21,27 +23,32 @@
INSTRUCTIONS = ("FormChem is the structure drawing suite of the FormAI family, running on this computer; the person watches it in the FormChem window. "
"Drawings exist: get_context lists the documents open in the window (id, title, path, unsaved changes, revision, fragments, formula). "
f"Change them through run_command with the window's own commands (list_commands first; insert-smiles {{smiles}} adds a structure, clean-structure, align and the rest act on the person's selection) "
- f"and through Form extensions; dedicated drawing tools for agents arrive in {DRAWING_FROM}. "
+ "and through Form extensions. Reaction tools work on a drawing directly: perceive_reactions and map_reaction write the reaction steps and the atom mapping (one undo step each); "
+ "export_reaction and reaction_stoichiometry read them. Analysis tools read a drawing: properties, check_structure, stereo (CIP labels and enhanced stereo groups) and substructure (SMARTS or a drawn query). "
+ f"Tools that add atoms and bonds by id arrive in {DRAWING_FROM}. "
"Workflow: get_context first; list_commands and run_command reach the window's menu commands; extensions_list and extension_command reach Form extensions; "
"handoff {state: ready or question, note} tells the person where your work stands in the window. Commands, extensions and a handoff change what the person sees, "
"so the first one asks the person in the window to allow agents. Details: resource formchem://guide.")
WORKFLOW = [
"1. get_context -> window open or not, agents allowed or not, open drawings, catalogue size, your last handoff",
"2. list_commands {text} -> command ids; run_command {id} runs one in the window as the person's click would",
- "3. extensions_list -> Form extensions and their commands; extension_command {id, command} runs one in the window",
- "4. handoff {state: ready, note} when you are done; state question when you need the person's input",
+ "3. reactions: perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry; analysis: properties, check_structure, stereo, substructure",
+ "4. extensions_list -> Form extensions and their commands; extension_command {id, command} runs one in the window",
+ "5. handoff {state: ready, note} when you are done; state question when you need the person's input",
]
GUIDE = f"""# FormChem agent guide
FormChem is a chemical structure drawing suite and a member of the FormAI family. The engine on this computer serves this MCP server; the person works in the FormChem window and sees every change there.
## What exists in this version
-FormChem {config.VERSION} draws. Drawings are documents the engine owns (docs/FORMAT.md): the person opens them in the window, draws on the canvas with the tool rail and hover keys, and the engine's chemistry (RDKit) works out SMILES, InChIKey, formula, masses and elemental analysis after every change, shown in the Analysis panel. Files in molfile, SDF, RXN, SMILES, CML and CDXML open as new drawings.
+FormChem {config.VERSION} draws. Drawings are documents the engine owns (docs/FORMAT.md): the person opens them in the window, draws on the canvas with the tool rail and hover keys, and the engine's chemistry (RDKit) works out SMILES, InChIKey, formula, masses, elemental analysis and CIP labels after every change, shown in the Analysis panel with the calculated properties and the isotope pattern. Drawings hold reaction schemes with perceived or hand-set roles, stereo groups, query atoms and bonds, abbreviations and R-group definitions. Files in molfile, SDF, RXN, SMILES, CML and CDXML open as new drawings.
How an agent changes a drawing today:
-- run_command with the window's own commands, the same ones the menus run. Call list_commands first: it gives each id, its params and whether it is on right now. insert-smiles {{"smiles": "c1ccccc1O"}} adds a structure to the active drawing (or a new one) and selects it; new-document, open-recent {{"path"}}, save, undo, redo, select-all, delete, duplicate, flip-horizontal, flip-vertical, rotate-90, align-*, distribute-*, clean-structure, layout-structure, check-structure and the zoom commands act on the active drawing and the person's selection. Each command is one undo step.
+- run_command with the window's own commands, the same ones the menus run. Call list_commands first: it gives each id, its params and whether it is on right now. insert-smiles {{"smiles": "c1ccccc1O"}} adds a structure to the active drawing (or a new one) and selects it; new-document, open-recent {{"path"}}, save, undo, redo, select-all, delete, duplicate, flip-horizontal, flip-vertical, rotate-90, align-*, distribute-*, clean-structure, layout-structure, check-structure and the zoom commands act on the active drawing and the person's selection. Chemistry commands work the same way: add-hydrogens, remove-hydrogens, expand-abbreviation, contract-abbreviation, assign-wedges, set-stereo-group-and, set-atom-list, define-rgroup, enumerate-markush, set-reaction-roles {{"role", "objects"}}, copy-smarts and compute-properties. Each command is one undo step.
+- The reaction tools below write reaction steps and atom mapping straight into a drawing and read reactions and stoichiometry back.
+- The analysis tools below read a drawing: properties, the structure check, CIP stereo and substructure hits. They never change it.
- Form extensions, through extension_command: an extension may read the drawing and apply transactions to it.
-Dedicated drawing tools for agents (adding atoms and bonds by id, reading the document directly) arrive in {DRAWING_FROM}. Until then, say plainly what you can do with the commands above.
+Tools that add atoms and bonds by id and read the whole document arrive in {DRAWING_FROM}. Until then, say plainly what you can do with the commands and tools above.
## Tools
- get_context: app, version, whether a window is open, whether agents are allowed, the documents open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the size of the command catalogue and your last handoff. Call it first.
@@ -50,6 +57,14 @@
- extensions_list: the Form extensions FormChem found (installed by FormPortal or run from a folder by form.ext), their state and their commands.
- extension_command {{id, command, args?}}: runs a command an extension contributes, in the open window. The window asks the person to allow the extension the first time.
- handoff {{state?, note?}}: tells the person where your work stands: working, ready (done, for them to look at), question (you need their input; say what in note) or clear. It shows in the window. With no state it lists the current handoffs.
+- perceive_reactions {{doc?, page?}}: works out the reaction steps from the arrows and the structures around them and writes them to the drawing (one undo step); steps set by hand are kept. Returns reaction and step ids.
+- map_reaction {{doc?, reaction?, step?, mode?}}: maps reactant atoms to product atoms and marks broken, formed and changed bonds (one undo step); mode clear removes the mapping.
+- export_reaction {{doc?, reaction?, step?, format?}}: a step as reaction SMILES or RXN (V2000 or V3000). Read only.
+- reaction_stoichiometry {{doc?, reaction?, step?}}: moles, equivalents, masses, volumes, limiting reagent and yields from the amounts in the step's grid, with the balance check. Read only.
+- properties {{doc?, object?}}: drug-like properties per fragment (cLogP, TPSA, donors, acceptors, rotatable bonds, rings, Lipinski, Veber), each with the RDKit method behind it. Read only.
+- check_structure {{doc?, object?, query?}}: the structure check: issues with a code, a severity and the atom and bond ids. Read only.
+- stereo {{doc?, object?}}: stereocentres, double bonds and axes with CIP labels, defined or not, and their enhanced stereo groups. Read only.
+- substructure {{doc?, smarts | query_object, objects?, chirality?, max_hits?}}: substructure hits across the drawing's fragments by atom and bond id. Read only.
## Asking the person
run_command, extension_command and handoff with a state change what the person sees, so the first such call from an agent asks the person in the FormChem window: Deny, Allow once or Always allow. With no window open there is nobody to ask, and the call is refused with a sentence saying so. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are already trusted and are never asked.
@@ -83,7 +98,8 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None =
_S = {"type": "string"}
TOOLS = [
_tool("get_context", "FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), "
- f"the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; dedicated drawing tools arrive in {DRAWING_FROM}.", {}, read=True),
+ f"the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; "
+ f"properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in {DRAWING_FROM}.", {}, read=True),
_tool("list_commands", "The window's command catalogue, the same commands as the menus, title bar and palette: id, label, group and what it does; commands of a later version are listed as off. "
"text narrows by words (all must match), group by one group; id returns one command in full.",
{"text": _S, "group": _S, "id": _S, "limit": {"type": "integer", "description": "Most rows to return (default 60)"}}, read=True),
@@ -99,9 +115,38 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None =
_tool("handoff", "Tells the person where your work stands: working (still on it), ready (done, for them to look at) or question (you need their input, say what in note); clear removes your handoff. "
"It shows in the FormChem window. With no state, lists the current handoffs.",
{"state": {"type": "string", "enum": list(HANDOFF_STATES)}, "note": {"type": "string", "description": "One short line for the person"}}),
+ _tool("perceive_reactions", "Works out the reaction steps of a drawing from where its structures sit around the reaction arrows (before the tail: reactants, after the head: products, beside the arrow: agents and conditions text; "
+ "plus signs join) and writes them to the drawing as one undo step. Steps someone set by hand are kept. Returns every reaction with its step ids.",
+ {"doc": {"type": "string", "description": "Drawing id from get_context; may be left out when one drawing is open"}, "page": {"type": "string", "description": "Page id; all pages when left out"}}),
+ _tool("map_reaction", "Maps the atoms of one reaction step (reactant atom to product atom numbers) and marks the bonds broken, formed or changed in order, as one undo step. "
+ "mode discard (default) maps from scratch, keep keeps the numbers already drawn, alter may change them, clear removes the mapping.",
+ {"doc": {"type": "string"}, "reaction": {"type": "string", "description": "Reaction id from perceive_reactions; the first reaction when left out"},
+ "step": {"type": "string", "description": "Step id; the first step when left out"}, "mode": {"type": "string", "enum": ["discard", "keep", "alter", "clear"]}}),
+ _tool("export_reaction", "One reaction step as reaction SMILES (format smiles) or an RXN file (rxn for V2000, rxnv3000), with its map numbers. Does not change the drawing.",
+ {"doc": {"type": "string"}, "reaction": {"type": "string"}, "step": {"type": "string"}, "format": {"type": "string", "enum": ["smiles", "rxn", "rxnv3000"]}}, read=True),
+ _tool("reaction_stoichiometry", "The stoichiometry of one reaction step worked out from the amounts the person typed in its grid and the molecular weights: moles, equivalents, masses, volumes, "
+ "the limiting reagent, theoretical yields and the percent yield, plus the balance check. Does not change the drawing.",
+ {"doc": {"type": "string"}, "reaction": {"type": "string"}, "step": {"type": "string"}}, read=True),
+ _tool("properties", "Drug-like properties of the structures in an open drawing, per fragment: formula, MW, exact mass, cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, "
+ "rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis; every value names the RDKit method behind it.",
+ {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "object": {"type": "string", "description": "One fragment id; absent: every fragment"}},
+ read=True),
+ _tool("check_structure", "Checks the structures of an open drawing: valence errors, unusual charges, wedge problems, overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing "
+ "and R-group gaps; each issue has a code, a severity (error, warning, info) and the atom and bond ids it concerns.",
+ {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "object": {"type": "string", "description": "One fragment id; absent: every fragment"},
+ "query": {"type": "boolean", "description": "True when the drawing is a search query, so query features are not reported"}}, read=True),
+ _tool("stereo", "Stereochemistry of an open drawing per fragment: each stereocentre, stereogenic double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), whether it is defined, undefined or unknown, "
+ "its enhanced stereo group (abs, and1, or1) and the CXSMILES that carries the groups.",
+ {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "object": {"type": "string", "description": "One fragment id; absent: every fragment"}},
+ read=True),
+ _tool("substructure", "Searches the fragments of an open drawing for a substructure given as SMARTS or as a query fragment drawn in the same drawing; returns every hit with its fragment id and the matched atom and bond ids.",
+ {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "smarts": {"type": "string", "description": "SMARTS pattern, such as C(=O)[OH]"},
+ "query_object": {"type": "string", "description": "A fragment of the drawing to use as the query instead of smarts"},
+ "objects": {"type": "array", "items": {"type": "string"}, "description": "Fragment ids to search; absent: all"},
+ "chirality": {"type": "boolean"}, "max_hits": {"type": "integer", "description": "Most hits to return (default 1000)"}}, read=True),
]
NAMES = {t["name"] for t in TOOLS}
-MUTATING = {"run_command", "extension_command"}
+MUTATING = {"run_command", "extension_command", "perceive_reactions", "map_reaction"}
def _ok(text: str, data: dict | None = None) -> dict:
@@ -221,7 +266,8 @@ async def t_get_context(a: Agent, args: dict) -> dict:
lines.append("Agents: " + ("blocked by the person (Preferences)" if blocked else "allowed" if allowed else "not yet allowed (your first change asks the person in the window)"))
docs = _documents()
if docs:
- lines.append(f"Documents: {len(docs)} open in the window (change them with run_command and the window's commands; dedicated drawing tools arrive in {DRAWING_FROM})")
+ lines.append(f"Documents: {len(docs)} open in the window (change them with run_command and the window's commands, write reactions with perceive_reactions and map_reaction, "
+ f"read them with export_reaction, reaction_stoichiometry, properties, check_structure, stereo and substructure; atom and bond tools arrive in {DRAWING_FROM})")
lines.extend(_document_line(d) for d in docs)
else:
lines.append("Documents: none open (run_command new-document, insert-smiles {smiles} or open-recent {path} opens one)")
@@ -339,6 +385,213 @@ async def t_handoff(a: Agent, args: dict) -> dict:
return _ok("\n".join(_handoff_line(h) for h in items) if items else "No handoff from any agent.", {"handoffs": items})
+def _drawing(args: dict) -> tuple[str, dict]:
+ from app.services.store import STORE
+ wanted = str(args.get("doc") or "").strip()
+ if not wanted:
+ open_ids = list(STORE.sessions)
+ if len(open_ids) != 1:
+ raise ToolError("Give doc, a drawing id from get_context." if open_ids else "No drawing is open. Open or create one first (run_command new-document or open-recent).")
+ wanted = open_ids[0]
+ try:
+ s = STORE.get(wanted)
+ except KeyError:
+ raise ToolError(f"No open drawing has the id {wanted}. get_context lists the open drawings.") from None
+ with s.lock:
+ return wanted, copy.deepcopy(s.doc)
+
+
+def _reaction_step(doc: dict, args: dict) -> tuple[dict, dict, dict]:
+ from app.services.chem import reactions
+ try:
+ return reactions.find_step(doc, str(args.get("reaction") or "") or None, str(args.get("step") or "") or None)
+ except reactions.ReactionError as exc:
+ raise ToolError(f"{exc} perceive_reactions lists the reactions and their step ids.") from None
+
+
+async def _apply(a: Agent, doc_id: str, label: str, ops: list[dict]) -> dict | None:
+ from app.services import ops as opsmod
+ from app.services.store import STORE
+ if not ops:
+ return None
+ try:
+ return await STORE.apply(doc_id, {"label": label, "ops": ops}, "agent", agent=a.name)
+ except opsmod.OpError as exc:
+ raise ToolError(f"The drawing refused the change: {exc}. Call get_context and try again.") from None
+
+
+async def t_perceive_reactions(a: Agent, args: dict) -> dict:
+ from app.services.chem import reactions
+ doc_id, doc = _drawing(args)
+ page = str(args.get("page") or "").strip()
+ try:
+ ops, summaries = await asyncio.to_thread(reactions.perceive_ops, doc, [page] if page else None)
+ except reactions.ReactionError as exc:
+ raise ToolError(str(exc)) from None
+ done = await _apply(a, doc_id, "Perceive reactions", ops)
+ _, after = _drawing({"doc": doc_id})
+ lines = [f"{'Wrote' if done else 'No change to'} the reactions of {doc_id}" + (f" (rev {done['rev']}, one undo step)." if done else ".")]
+ listing = []
+ for p in after.get("pages") or []:
+ for r in p.get("reactions") or []:
+ for n, st in enumerate(r.get("steps") or []):
+ lines.append(f"- reaction {r['id']} step {n + 1} {st['id']}{' (set by hand)' if st.get('explicit') else ''}: "
+ f"{' + '.join(st.get('reactants') or []) or 'nothing'} -> {' + '.join(st.get('products') or []) or 'nothing'}"
+ + (f" · agents {', '.join(st['agents'])}" if st.get("agents") else "") + (f" · conditions {', '.join(st['conditions'])}" if st.get("conditions") else ""))
+ listing.append({"page": p.get("id"), **r})
+ if not listing:
+ lines.append("No reaction arrow has structures before or after it.")
+ return _ok("\n".join(lines), {"doc": doc_id, "changed": bool(done), "rev": done["rev"] if done else None, "summary": summaries, "reactions": listing})
+
+
+async def t_map_reaction(a: Agent, args: dict) -> dict:
+ from app.services.chem import mapping, reactions
+ doc_id, doc = _drawing(args)
+ _, reaction, step = _reaction_step(doc, args)
+ mode = str(args.get("mode") or "discard")
+ try:
+ ops, info = await asyncio.to_thread(mapping.map_ops, doc, step, mode)
+ except reactions.ReactionError as exc:
+ raise ToolError(str(exc)) from None
+ done = await _apply(a, doc_id, "Clear mapping" if mode == "clear" else "Map atoms", ops)
+ if mode == "clear":
+ text = f"Cleared {info['cleared']} map numbers in step {step['id']}." if done else f"Step {step['id']} had no map numbers."
+ else:
+ c = info.get("centres") or {}
+ text = (f"Mapped step {step['id']} of reaction {reaction['id']}: {info['quality']}, {info['mapped']} map numbers; "
+ f"{c.get('broken', 0)} bonds broken, {c.get('formed', 0)} formed, {c.get('order', 0)} changed in order." + ("" if done else " The drawing already showed this mapping."))
+ return _ok(text, {"doc": doc_id, "reaction": reaction["id"], "step": step["id"], "changed": bool(done), "rev": done["rev"] if done else None, "mapping": info})
+
+
+async def t_export_reaction(a: Agent, args: dict) -> dict:
+ from app.services.chem import reactions, rxnio
+ doc_id, doc = _drawing(args)
+ _, reaction, step = _reaction_step(doc, args)
+ fmt = str(args.get("format") or "smiles")
+ try:
+ text, warnings = rxnio.export_step(doc, step, fmt, str(doc.get("title") or ""))
+ except reactions.ReactionError as exc:
+ raise ToolError(str(exc)) from None
+ notes = "".join(f"\nNote: {w['text']}" for w in warnings)
+ return _ok(text + notes, {"doc": doc_id, "reaction": reaction["id"], "step": step["id"], "format": fmt, "text": text, "warnings": warnings})
+
+
+async def t_reaction_stoichiometry(a: Agent, args: dict) -> dict:
+ from app.services.chem import balance, stoich
+ from app.services.store import STORE
+ doc_id, doc = _drawing(args)
+ _, reaction, step = _reaction_step(doc, args)
+ derived = await asyncio.to_thread(STORE.derive_now, doc_id)
+ view = stoich.compute(doc, reaction, step, derived)
+ checked = balance.check(doc, step)
+ lines = [f"Step {step['id']} of reaction {reaction['id']}" + (f", limiting reagent {view['limiting']}" if view["limiting"] else "") + ":"]
+ for r in view["rows"]:
+ parts = [r["role"], r["label"], f"MW {r['mw']:.2f}" if r["mw"] else "MW unknown"]
+ if r.get("equiv"):
+ parts.append(f"{stoich.sig3(r['equiv'])} equiv")
+ for value in (stoich.amount_text(r["mmol"]), stoich.mass_text(r["mass_mg"]), stoich.volume_text(r.get("volume_ml"))):
+ if value:
+ parts.append(value)
+ if r.get("yield_pct") is not None:
+ parts.append(f"yield {r['yield_pct']:.1f}%")
+ lines.append("- " + " · ".join(parts))
+ lines.append("Balanced." if checked["balanced"] else "Not balanced.")
+ lines.extend(f"Note: {w['text']}" for w in view["warnings"] + checked["warnings"])
+ return _ok("\n".join(lines), {"doc": doc_id, "stoich": view, "check": checked})
+
+
+def _analysis_source(args: dict, single: bool = False, keep: tuple = ()):
+ from fastapi import HTTPException
+ from app.routers import analysis
+ doc = str(args.get("doc") or "").strip()
+ if not doc:
+ docs = _documents()
+ if len(docs) != 1:
+ raise ToolError("Give doc, a document id from get_context." if docs else "No drawing is open. Open one in the FormChem window, then retry.")
+ doc = docs[0]["id"]
+ body = {"doc": doc, **{k: args[k] for k in ("object", *keep) if args.get(k) is not None}}
+ try:
+ return analysis.source(body, single), body
+ except HTTPException as exc:
+ raise ToolError(str(exc.detail)) from None
+
+
+async def _per_fragment(args: dict, fn) -> dict:
+ from app.routers import analysis
+ src, _ = _analysis_source(args)
+ if not src.fragments:
+ raise ToolError("This drawing has no structures yet.")
+ return await asyncio.to_thread(analysis._each, src, lambda f: fn(f, src))
+
+
+async def t_properties(a: Agent, args: dict) -> dict:
+ from app.services.chem import props
+ out = await _per_fragment(args, lambda f, src: props.compute(f, src.expansions))
+ lines = []
+ for fid, r in out["fragments"].items():
+ if "error" in r:
+ lines.append(f"{fid}: {r['error']}")
+ continue
+ v = r["values"]
+ lines.append(f"{fid}: {v['formula']} · MW {v['mw']} · exact {v['exact_mass']} · cLogP {v['clogp']} (Crippen.MolLogP) · MR {v['mr']} · TPSA {v['tpsa']} · HBD {v['hbd']} · HBA {v['hba']} · "
+ f"rotatable {v['rotatable_bonds']} · rings {v['rings']} ({v['aromatic_rings']} aromatic) · Fsp3 {v['fraction_csp3']} · Lipinski {'pass' if r['lipinski']['pass'] else 'fail'} "
+ f"({r['lipinski']['violations']} violation{'' if r['lipinski']['violations'] == 1 else 's'}) · Veber {'pass' if r['veber']['pass'] else 'fail'}")
+ return _ok("\n".join(lines), out)
+
+
+async def t_check_structure(a: Agent, args: dict) -> dict:
+ from app.services.chem import check
+ is_query = args.get("query") is True
+ out = await _per_fragment(args, lambda f, src: check.check(f, src.expansions, src.members, is_query))
+ lines = []
+ for fid, r in out["fragments"].items():
+ if "error" in r:
+ lines.append(f"{fid}: {r['error']}")
+ continue
+ c = r["counts"]
+ lines.append(f"{fid}: {c['error']} error(s), {c['warning']} warning(s), {c['info']} note(s)")
+ lines.extend(f" {i['severity']} {i['code']}: {_clip(i['text'], 160)}" + (f" atoms {', '.join(i['atoms'][:8])}" if i.get("atoms") else "")
+ + (f" bonds {', '.join(i['bonds'][:8])}" if i.get("bonds") else "") for i in r["issues"])
+ return _ok("\n".join(lines), out)
+
+
+async def t_stereo(a: Agent, args: dict) -> dict:
+ from app.services.chem import stereo
+ out = await _per_fragment(args, lambda f, src: stereo.report(f, src.expansions))
+ lines = []
+ for fid, r in out["fragments"].items():
+ if "error" in r:
+ lines.append(f"{fid}: {r['error']}")
+ continue
+ parts = [f"{c['atom']} {c['label'] or '?'} ({c['state']}{', ' + c['group'] if c.get('group') else ''})" for c in r["centres"]]
+ parts += [f"{b['bond']} {b['label'] or '?'} ({b['state']})" for b in r["double_bonds"] + r["axes"]]
+ lines.append(f"{fid}: " + ("; ".join(parts) if parts else "no stereogenic units") + f" · {r['cxsmiles']}")
+ return _ok("\n".join(lines), out)
+
+
+async def t_substructure(a: Agent, args: dict) -> dict:
+ from app.services.chem import search
+ smarts = args.get("smarts")
+ named = args.get("query_object")
+ if not smarts and not named:
+ raise ToolError("Give smarts, or query_object (a fragment of the drawing drawn as the query).")
+ src, _ = _analysis_source(args, keep=("objects",))
+ pattern = None
+ if not smarts:
+ pattern = src.members.get(str(named))
+ if pattern is None:
+ raise ToolError(f"{named} is not a fragment of this drawing.")
+ targets = {k: f for k, f in src.fragments.items() if not pattern or k != pattern.get("id")}
+ limit = max(1, min(100_000, int(args.get("max_hits") or search.MAX_HITS)))
+ try:
+ out = await asyncio.to_thread(search.substructure, targets, pattern, str(smarts) if smarts else None, src.expansions, limit, args.get("chirality") is True)
+ except ValueError as exc:
+ raise ToolError(str(exc)) from None
+ lines = [f"{out['count']} hit{'' if out['count'] == 1 else 's'}" + (" (more were cut off)" if out["truncated"] else "") + f" for {out['smarts']}"]
+ lines.extend(f"- {h['object']}: atoms {', '.join(h['atoms'][:12])}" for h in out["hits"][:50])
+ return _ok("\n".join(lines), out)
+
+
async def _send_handoffs(client: Client, msg: dict) -> None:
await client.send({"t": "handoffs", "items": _handoff_list()})
diff --git a/backend/app/routers/reactions.py b/backend/app/routers/reactions.py
new file mode 100644
index 00000000..29527015
--- /dev/null
+++ b/backend/app/routers/reactions.py
@@ -0,0 +1,263 @@
+import asyncio
+import copy
+import math
+from pathlib import Path
+
+from fastapi import APIRouter, Body, Depends, HTTPException, Request
+
+from app.core import files, window_key
+from app.services import ops as opsmod
+from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, balance, mapping, reactions, rxnio, scheme, stoich
+from app.services.store import STORE
+
+router = APIRouter()
+MAX_TEXT = 20 * 1024 * 1024
+
+
+def _guard(request: Request) -> None:
+ window_key.require(request)
+
+
+GUARD = [Depends(_guard)]
+
+
+def _snapshot(doc_id: str) -> tuple[object, dict]:
+ try:
+ s = STORE.get(doc_id)
+ except KeyError:
+ raise HTTPException(404, f"No open drawing has the id {doc_id}.")
+ with s.lock:
+ return s, copy.deepcopy(s.doc)
+
+
+def _failed(exc: reactions.ReactionError) -> HTTPException:
+ return HTTPException(exc.status, str(exc))
+
+
+def _client(body: dict) -> str | None:
+ found = body.get("client")
+ return found if isinstance(found, str) and found else None
+
+
+def _origin(body: dict) -> str:
+ return body.get("origin") if body.get("origin") in ("user", "system") else "user"
+
+
+def _page_ids(value: object) -> list[str] | None:
+ if value is None:
+ return None
+ if isinstance(value, str) and value:
+ return [value]
+ raise HTTPException(422, "page must be a page id")
+
+
+async def _commit(doc_id: str, label: str, ops: list[dict], body: dict, rev: int) -> dict:
+ if not ops:
+ return {"changed": False, "tx": None, "rev": rev}
+ try:
+ result = await STORE.apply(doc_id, {"label": label, "ops": ops}, _origin(body), client=_client(body))
+ except opsmod.OpError as exc:
+ raise HTTPException(409, {"message": str(exc), "errors": exc.errors})
+ except KeyError:
+ raise HTTPException(404, f"The drawing {doc_id} was closed.")
+ return {"changed": True, "tx": result["tx"], "rev": result["rev"]}
+
+
+def _listing(doc: dict) -> list[dict]:
+ return [{"page": p.get("id"), "reactions": p.get("reactions") or []} for p in doc.get("pages") or [] if isinstance(p, dict)]
+
+
+@router.get("/api/documents/{doc_id}/reactions")
+def list_reactions(doc_id: str) -> dict:
+ s, doc = _snapshot(doc_id)
+ return {"rev": s.rev, "pages": _listing(doc)}
+
+
+@router.get("/api/documents/{doc_id}/reactions/preview")
+def preview_reactions(doc_id: str, page: str | None = None) -> dict:
+ s, doc = _snapshot(doc_id)
+ try:
+ found = reactions.preview(doc, _page_ids(page))
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+ return {"rev": s.rev, "pages": [{**{k: v for k, v in p.items() if k != "list"}, "reactions": p["list"]} for p in found]}
+
+
+@router.post("/api/documents/{doc_id}/reactions/perceive", dependencies=GUARD)
+async def perceive_reactions(doc_id: str, body: dict = Body(default={})) -> dict:
+ s, doc = _snapshot(doc_id)
+ try:
+ ops, summaries = await asyncio.to_thread(reactions.perceive_ops, doc, _page_ids(body.get("page")))
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+ out = await _commit(doc_id, "Perceive reactions", ops, body, s.rev)
+ _, after = _snapshot(doc_id)
+ return {**out, "summary": summaries, "pages": _listing(after)}
+
+
+def _step(doc: dict, reaction_id: str, step_id: str) -> tuple[dict, dict, dict]:
+ try:
+ return reactions.find_step(doc, reaction_id, step_id)
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+
+
+STEP = "/api/documents/{doc_id}/reactions/{reaction_id}/steps/{step_id}"
+
+
+@router.post(STEP + "/map", dependencies=GUARD)
+async def map_step(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(default={})) -> dict:
+ s, doc = _snapshot(doc_id)
+ _, _, step = _step(doc, reaction_id, step_id)
+ mode = body.get("mode", "discard")
+ if mode not in ("discard", "keep", "alter"):
+ raise HTTPException(422, "mode must be discard, keep or alter")
+ try:
+ ops, info = await asyncio.to_thread(mapping.map_ops, doc, step, mode, body.get("centres", True) is not False)
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+ return {**await _commit(doc_id, "Map atoms", ops, body, s.rev), "mapping": info}
+
+
+@router.delete(STEP + "/map", dependencies=GUARD)
+async def clear_map(doc_id: str, reaction_id: str, step_id: str, centres: bool = True, client: str | None = None) -> dict:
+ s, doc = _snapshot(doc_id)
+ _, _, step = _step(doc, reaction_id, step_id)
+ ops, info = mapping.clear_ops(doc, step, centres)
+ return {**await _commit(doc_id, "Clear mapping", ops, {"client": client}, s.rev), "mapping": info}
+
+
+@router.get(STEP + "/export")
+def export_step(doc_id: str, reaction_id: str, step_id: str, format: str = "rxn") -> dict:
+ _, doc = _snapshot(doc_id)
+ _, reaction, step = _step(doc, reaction_id, step_id)
+ title = reaction.get("name") or step.get("name") or doc.get("title") or ""
+ try:
+ text, warnings = rxnio.export_step(doc, step, format, str(title))
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+ return {"format": format, "text": text, "warnings": warnings, "engine": ENGINE}
+
+
+@router.post(STEP + "/export", dependencies=GUARD)
+async def export_step_file(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(...)) -> dict:
+ path = body.get("path")
+ if not isinstance(path, str) or not Path(path.strip()).expanduser().is_absolute():
+ raise HTTPException(422, "Give the absolute path of the file to write.")
+ fmt = body.get("format") if isinstance(body.get("format"), str) else "rxn"
+ found = export_step(doc_id, reaction_id, step_id, fmt)
+ try:
+ written = await asyncio.to_thread(files.write_atomic, path.strip(), found["text"].encode("utf-8"))
+ except OSError as exc:
+ raise HTTPException(400, f"Could not write {Path(path).name}: {exc.strerror or exc}.")
+ return {**found, "path": str(written)}
+
+
+def _text(body: dict) -> str:
+ text = body.get("text")
+ if not isinstance(text, str) or not text.strip():
+ raise HTTPException(422, "text is required")
+ if len(text) > MAX_TEXT:
+ raise HTTPException(413, "text is too large")
+ return text
+
+
+def _point(value: object) -> tuple[float, float] | None:
+ if isinstance(value, list) and len(value) == 2 and all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) for v in value):
+ return (float(value[0]), float(value[1]))
+ return None
+
+
+@router.post("/api/chem/reactions/import")
+def import_reaction(body: dict = Body(...)) -> dict:
+ text = _text(body)
+ length = body.get("bond_length", DEFAULT_BOND_LENGTH)
+ if isinstance(length, bool) or not isinstance(length, (int, float)) or not 1 <= length <= 500:
+ raise HTTPException(422, "bond_length must be a number of points from 1 to 500")
+ try:
+ return scheme.parse(text, body.get("format"), float(length), _point(body.get("origin")) or (72.0, 72.0))
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+
+
+@router.post("/api/documents/{doc_id}/reactions/import", dependencies=GUARD)
+async def insert_reaction(doc_id: str, body: dict = Body(...)) -> dict:
+ text = _text(body)
+ s, doc = _snapshot(doc_id)
+ try:
+ page = reactions.page_of(doc, body.get("page") if isinstance(body.get("page"), str) else None)
+ ops, found = await asyncio.to_thread(scheme.insert_ops, doc, page, text, body.get("format"), _point(body.get("origin")))
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+ out = await _commit(doc_id, "Insert reaction", ops, body, s.rev)
+ return {**out, "page": page["id"], "format": found["format"], "objects": [o["id"] for o in found["objects"]],
+ "reaction": found["reaction"], "warnings": found["warnings"]}
+
+
+@router.get("/api/documents/{doc_id}/reactions/check")
+def check_reactions(doc_id: str, page: str | None = None) -> dict:
+ s, doc = _snapshot(doc_id)
+ try:
+ pages = [reactions.page_of(doc, page)] if page else [p for p in doc.get("pages") or [] if isinstance(p, dict)]
+ except reactions.ReactionError as exc:
+ raise _failed(exc)
+ out = []
+ for p in pages:
+ steps = [{"reaction": r.get("id"), **balance.check(doc, st)} for r in p.get("reactions") or [] if isinstance(r, dict)
+ for st in r.get("steps") or [] if isinstance(st, dict)]
+ out.append({"page": p.get("id"), "steps": steps, "resonance": balance.resonance(doc, p)})
+ return {"rev": s.rev, "pages": out}
+
+
+@router.get(STEP + "/check")
+def check_step(doc_id: str, reaction_id: str, step_id: str) -> dict:
+ s, doc = _snapshot(doc_id)
+ _, _, step = _step(doc, reaction_id, step_id)
+ return {"rev": s.rev, "reaction": reaction_id, **balance.check(doc, step)}
+
+
+@router.post(STEP + "/balance", dependencies=GUARD)
+async def balance_step(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(default={})) -> dict:
+ s, doc = _snapshot(doc_id)
+ page, _, step = _step(doc, reaction_id, step_id)
+ wanted = body.get("coefficients")
+ if wanted is None:
+ found = balance.check(doc, step)
+ wanted = ((found.get("suggestion") or {}).get("coefficients"))
+ if wanted is None:
+ raise HTTPException(422, "This step has no balancing coefficients to apply: " + (
+ "it is already balanced." if found["balanced"] else "add the missing co-products first (see check)."))
+ elif not isinstance(wanted, dict) or not all(isinstance(k, str) and isinstance(v, int) and not isinstance(v, bool) and 1 <= v <= 999 for k, v in wanted.items()):
+ raise HTTPException(422, "coefficients must map object ids to whole numbers from 1 to 999")
+ ops = balance.coefficient_ops(reactions.step_path(page["id"], reaction_id, step_id), step, wanted)
+ out = await _commit(doc_id, "Balance reaction", ops, body, s.rev)
+ _, after = _snapshot(doc_id)
+ _, _, step = _step(after, reaction_id, step_id)
+ return {**out, "coefficients": step.get("coefficients") or {}, "check": balance.check(after, step)}
+
+
+async def _view(doc_id: str, reaction_id: str, step_id: str) -> tuple[object, dict, dict, dict, dict]:
+ s, doc = _snapshot(doc_id)
+ page, reaction, step = _step(doc, reaction_id, step_id)
+ try:
+ derived = await asyncio.to_thread(STORE.derive_now, doc_id)
+ except Exception:
+ derived = None
+ if derived is None or derived.get("rev") != s.rev:
+ s, doc = _snapshot(doc_id)
+ page, reaction, step = _step(doc, reaction_id, step_id)
+ return s, doc, page, reaction, stoich.compute(doc, reaction, step, derived)
+
+
+@router.get(STEP + "/stoich")
+async def step_stoich(doc_id: str, reaction_id: str, step_id: str) -> dict:
+ s, _, _, _, view = await _view(doc_id, reaction_id, step_id)
+ return {"rev": s.rev, **view}
+
+
+@router.post(STEP + "/stoich-table", dependencies=GUARD)
+async def step_stoich_table(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(default={})) -> dict:
+ s, doc, page, _, view = await _view(doc_id, reaction_id, step_id)
+ ops, table = stoich.table_ops(doc, page, view, reactions.used_ids(doc), _point(body.get("at")))
+ out = await _commit(doc_id, "Stoichiometry grid", ops, body, s.rev)
+ return {**out, "table": table["id"], "stoich": view}
diff --git a/backend/app/routers/templates.py b/backend/app/routers/templates.py
new file mode 100644
index 00000000..d54b4359
--- /dev/null
+++ b/backend/app/routers/templates.py
@@ -0,0 +1,31 @@
+import math
+
+from fastapi import APIRouter, HTTPException
+
+from app.services import templates
+
+router = APIRouter()
+
+
+def _bond_length(value: float | None) -> float | None:
+ if value is None:
+ return None
+ if not math.isfinite(value) or not 1 <= value <= 500:
+ raise HTTPException(422, "bond_length must be a number of points from 1 to 500")
+ return value
+
+
+@router.get("/api/templates")
+def list_templates(objects: bool = False) -> dict:
+ return templates.listing(with_objects=objects)
+
+
+@router.get("/api/templates/{template_id}")
+def get_template(template_id: str, bond_length: float | None = None) -> dict:
+ try:
+ found = templates.fragment(template_id, _bond_length(bond_length))
+ except ValueError as exc:
+ raise HTTPException(422, str(exc))
+ if found is None:
+ raise HTTPException(404, f"no template {template_id}")
+ return found
diff --git a/backend/app/services/chem/abbrev.py b/backend/app/services/chem/abbrev.py
index 1cb6e5c0..0d4de1d5 100644
--- a/backend/app/services/chem/abbrev.py
+++ b/backend/app/services/chem/abbrev.py
@@ -1,5 +1,7 @@
+import json
import re
from functools import lru_cache
+from pathlib import Path
from rdkit import Chem
@@ -81,8 +83,51 @@
"SO2Cl": ("*S(=O)(=O)Cl", "ClO2S"),
"SO3H": ("*S(=O)(=O)O", "HO3S"),
"N3": ("*N=[N+]=[N-]", "N3"),
+ "Hex": ("*CCCCCC", "Hex"),
+ "Vin": ("*C=C", "Vin"),
+ "All": ("*CC=C", "All"),
+ "Mes": ("*c1c(C)cc(C)cc1C", "Mes"),
+ "Tol": ("*c1ccc(C)cc1", "Tol"),
+ "PMP": ("*c1ccc(OC)cc1", "PMP"),
+ "C6F5": ("*c1c(F)c(F)c(F)c(F)c1F", "F5C6"),
+ "Py": ("*c1ccccn1", "Py"),
+ "DMB": ("*Cc1ccc(OC)cc1OC", "DMB"),
+ "SEM": ("*COCC[Si](C)(C)C", "SEM"),
+ "MEM": ("*COCCOC", "MEM"),
+ "BOM": ("*COCc1ccccc1", "BOM"),
+ "Troc": ("*C(=O)OCC(Cl)(Cl)Cl", "Troc"),
+ "Alloc": ("*C(=O)OCC=C", "Alloc"),
+ "Teoc": ("*C(=O)OCC[Si](C)(C)C", "Teoc"),
+ "Ns": ("*S(=O)(=O)c1ccc([N+](=O)[O-])cc1", "Ns"),
+ "Bs": ("*S(=O)(=O)c1ccc(Br)cc1", "Bs"),
+ "Nf": ("*S(=O)(=O)C(F)(F)C(F)(F)C(F)(F)C(F)(F)F", "Nf"),
+ "Bpin": ("*B1OC(C)(C)C(C)(C)O1", "pinB"),
+ "SO2Me": ("*S(C)(=O)=O", "MeO2S"),
+ "SO2Ph": ("*S(=O)(=O)c1ccccc1", "PhO2S"),
+ "OCF3": ("*OC(F)(F)F", "F3CO"),
+ "SCF3": ("*SC(F)(F)F", "F3CS"),
+ "NHPh": ("*Nc1ccccc1", "PhHN"),
+ "NPh2": ("*N(c1ccccc1)c1ccccc1", "Ph2N"),
+ "NMeBoc": ("*N(C)C(=O)OC(C)(C)C", "BocMeN"),
+ "CONMe2": ("*C(=O)N(C)C", "Me2NOC"),
+ "CONHMe": ("*C(=O)NC", "MeHNOC"),
+ "CO2Bn": ("*C(=O)OCc1ccccc1", "BnO2C"),
+ "CO2Ph": ("*C(=O)Oc1ccccc1", "PhO2C"),
+ "OCOCF3": ("*OC(=O)C(F)(F)F", "F3COCO"),
}
+CATEGORIES: dict[str, tuple[str, ...]] = {
+ "alkyl": ("Me", "Et", "Pr", "nPr", "iPr", "Bu", "nBu", "iBu", "sBu", "tBu", "Np", "Cy", "Hex", "Vin", "All", "CF3", "CCl3"),
+ "aryl": ("Ph", "Bn", "Mes", "Tol", "PMP", "C6F5", "Py"),
+ "protecting group": ("Ac", "Bz", "Piv", "Tr", "PMB", "DMB", "MOM", "MEM", "SEM", "BOM", "THP", "Boc", "Cbz", "Fmoc", "Troc", "Alloc", "Teoc",
+ "OAc", "OBz", "OBoc", "OMOM", "OTHP", "OPMB", "OBn", "NHAc", "NHBoc", "NHCbz", "NHFmoc", "NMeBoc", "OCOCF3"),
+ "silyl": ("TMS", "TES", "TBS", "TBDMS", "TIPS", "TBDPS", "OTMS", "OTBS", "OTIPS", "OTBDPS"),
+ "sulfonyl": ("Ts", "Ms", "Tf", "Ns", "Bs", "Nf", "OTs", "OMs", "OTf", "NHTs", "SO2Cl", "SO3H", "SO2Me", "SO2Ph"),
+}
+PREFERRED = ("Pr", "Bu", "Ac", "TBS", "CO2H", "Ms")
+USER_FILE = "abbreviations.json"
+_user: dict = {"key": None, "entries": {}, "errors": []}
+
ELEMENT_COLLISIONS = {"Ac", "Pr", "Np"}
_ELEMENT_LIKE = re.compile(r"^\d*(H\d*)?([A-Z][a-z]?)(H\d*)?(\d*[+-]+\d*)?$")
@@ -95,22 +140,128 @@ def element_like(label: str, element: str) -> bool:
return bool(m) and m.group(2) == element
+def user_path() -> Path | None:
+ try:
+ from app.core import config
+ return config.data_dir() / USER_FILE
+ except Exception:
+ return None
+
+
+def _attachment_ok(smiles: str) -> bool:
+ mol = Chem.MolFromSmiles(smiles)
+ if mol is None:
+ return False
+ stars = [a for a in mol.GetAtoms() if a.GetAtomicNum() == 0]
+ return len(stars) == 1 and stars[0].GetDegree() == 1 and mol.GetNumAtoms() > 1
+
+
+def _read_user(path: Path) -> tuple[dict, list[str]]:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ rows = raw.get("abbreviations", raw) if isinstance(raw, dict) else raw
+ if isinstance(rows, dict):
+ rows = [{"label": k, **v} if isinstance(v, dict) else {"label": k, "smiles": v} for k, v in rows.items()]
+ if not isinstance(rows, list):
+ return {}, ["the file must hold a list of {label, smiles, reversed?, category?, prefer?} entries"]
+ out, errors = {}, []
+ for row in rows:
+ label = row.get("label") if isinstance(row, dict) else None
+ smiles = row.get("smiles") if isinstance(row, dict) else None
+ if not isinstance(label, str) or not label.strip() or not isinstance(smiles, str):
+ errors.append(f"entry {row!r:.60} needs a label and a smiles")
+ continue
+ if not _attachment_ok(smiles):
+ errors.append(f"{label}: the smiles needs exactly one * as its attachment point")
+ continue
+ rev = row.get("reversed")
+ out[label.strip()] = {"smiles": smiles, "reversed": rev if isinstance(rev, str) and rev else label.strip(),
+ "category": str(row.get("category") or "user"), "prefer": row.get("prefer") == "abbreviation"}
+ return out, errors
+
+
+def user_entries() -> dict:
+ path = user_path()
+ try:
+ key = (str(path), path.stat().st_mtime_ns) if path is not None else None
+ except OSError:
+ key = None
+ if key != _user["key"]:
+ entries, errors = {}, []
+ if key is not None:
+ try:
+ entries, errors = _read_user(path)
+ except (OSError, ValueError) as exc:
+ errors = [f"{USER_FILE} cannot be read: {exc}"]
+ _user.update(key=key, entries=entries, errors=errors)
+ return _user["entries"]
+
+
+def user_errors() -> list[str]:
+ user_entries()
+ return list(_user["errors"])
+
+
+def entry(label: str) -> tuple[str, str] | None:
+ found = user_entries().get(label)
+ if found:
+ return found["smiles"], found["reversed"]
+ return ABBREVIATIONS.get(label)
+
+
+def category(label: str) -> str:
+ found = user_entries().get(label)
+ if found:
+ return found["category"]
+ return next((k for k, labels in CATEGORIES.items() if label in labels), "functional")
+
+
+def library() -> list[dict]:
+ rows = {label: {"label": label, "reversed": rev, "smiles": smi, "category": category(label), "source": "builtin"}
+ for label, (smi, rev) in ABBREVIATIONS.items()}
+ for label, e in user_entries().items():
+ rows[label] = {"label": label, "reversed": e["reversed"], "smiles": e["smiles"], "category": e["category"], "source": "user"}
+ return sorted(rows.values(), key=lambda r: (r["category"], r["label"].lower()))
+
+
def resolve(label: str | None, element: str, neighbour_elements: list[str]) -> str | None:
- if not label or label not in ABBREVIATIONS:
+ found = entry(label) if label else None
+ if not found:
return None
if label == element and label in ELEMENTS:
- if label not in ELEMENT_COLLISIONS:
+ mine = user_entries().get(label)
+ if label not in ELEMENT_COLLISIONS and not (mine and mine["prefer"]):
return None
- if label == "Np" and neighbour_elements != ["C"]:
+ if label == "Np" and not mine and neighbour_elements != ["C"]:
return None
elif element != "*" and element_like(label, element):
return None
- return ABBREVIATIONS[label][0]
+ return found[0]
def reversed_label(label: str) -> str:
- entry = ABBREVIATIONS.get(label)
- return entry[1] if entry else label
+ found = entry(label)
+ return found[1] if found else label
+
+
+def canonical(smiles: str) -> str | None:
+ mol = Chem.MolFromSmiles(smiles)
+ return Chem.MolToSmiles(mol) if mol is not None else None
+
+
+def match(smiles: str) -> str | None:
+ key = canonical(smiles)
+ if key is None:
+ return None
+ for label, e in user_entries().items():
+ if canonical(e["smiles"]) == key:
+ return label
+ hits = [label for label, (smi, _) in ABBREVIATIONS.items() if _canonical_builtin(smi) == key]
+ return next((h for h in hits if h in PREFERRED), hits[0] if hits else None)
+
+
+@lru_cache(maxsize=512)
+def _canonical_builtin(smiles: str) -> str | None:
+ return canonical(smiles)
@lru_cache(maxsize=256)
diff --git a/backend/app/services/chem/balance.py b/backend/app/services/chem/balance.py
new file mode 100644
index 00000000..019a17b8
--- /dev/null
+++ b/backend/app/services/chem/balance.py
@@ -0,0 +1,242 @@
+import itertools
+import math
+from fractions import Fraction
+
+from rdkit import Chem
+
+from app.services import model
+from app.services.chem import geometry, ids, mass, perceive, warning
+from app.services.chem.reactions import ROW_BONDS, END_BONDS, _items, _walk, bond_length, coefficient, direction
+from app.services.chem.rxnio import fragments_in, plain_text
+
+PT = Chem.GetPeriodicTable()
+MASS_TOLERANCE = 0.01
+MAX_COEFFICIENT = 50
+CO_PRODUCTS = (
+ ("water", "O", {"H": 2, "O": 1}),
+ ("hydrogen chloride", "Cl", {"H": 1, "Cl": 1}),
+ ("hydrogen bromide", "Br", {"H": 1, "Br": 1}),
+ ("carbon dioxide", "O=C=O", {"C": 1, "O": 2}),
+ ("sulfur dioxide", "O=S=O", {"S": 1, "O": 2}),
+ ("nitrogen", "N#N", {"N": 2}),
+ ("hydrogen", "[H][H]", {"H": 2}),
+ ("sodium chloride", "[Na+].[Cl-]", {"Na": 1, "Cl": 1}),
+)
+
+
+def _hill_key(symbols: set[str]):
+ has_c = "C" in symbols
+ return lambda s: (0 if has_c and s == "C" else 1 if has_c and s == "H" else 2, s)
+
+
+def species(doc: dict, oid: str) -> dict | None:
+ frags = fragments_in(doc, oid)
+ if not frags:
+ return None
+ counts: dict[str, int] = {}
+ charge = 0
+ generic: list[str] = []
+ mw = 0.0
+ formulas = []
+ for frag in frags:
+ conv = perceive.prepare(frag, doc.get("expansions"))
+ found, labels, q = ids.formula_counts(conv.mol)
+ for (z, _iso), n in found.items():
+ sym = PT.GetElementSymbol(z)
+ counts[sym] = counts.get(sym, 0) + n
+ charge += q
+ generic.extend(labels)
+ mw += mass.average_mass(conv.mol)
+ formulas.append(ids.formula(conv.mol))
+ return {"counts": counts, "charge": charge, "generic": generic, "mw": round(mw, 4), "formula": ".".join(f for f in formulas if f)}
+
+
+def _nullspace(rows: list[list[Fraction]], n: int) -> list[list[Fraction]]:
+ m = [list(r) for r in rows]
+ pivots: list[int] = []
+ r = 0
+ for c in range(n):
+ p = next((i for i in range(r, len(m)) if m[i][c] != 0), None)
+ if p is None:
+ continue
+ m[r], m[p] = m[p], m[r]
+ lead = m[r][c]
+ m[r] = [v / lead for v in m[r]]
+ for i in range(len(m)):
+ if i != r and m[i][c] != 0:
+ k = m[i][c]
+ m[i] = [a - k * b for a, b in zip(m[i], m[r])]
+ pivots.append(c)
+ r += 1
+ if r == len(m):
+ break
+ free = [c for c in range(n) if c not in pivots]
+ basis = []
+ for f in free:
+ v = [Fraction(0)] * n
+ v[f] = Fraction(1)
+ for i, c in enumerate(pivots):
+ v[c] = -m[i][f]
+ basis.append(v)
+ return basis
+
+
+def solve(left: list[dict], right: list[dict]) -> list[int] | None:
+ cols = left + right
+ if not cols:
+ return None
+ symbols = sorted({s for c in cols for s in c["counts"]})
+ sign = [1] * len(left) + [-1] * len(right)
+ rows = [[Fraction(sign[j] * cols[j]["counts"].get(s, 0)) for j in range(len(cols))] for s in symbols]
+ rows.append([Fraction(sign[j] * cols[j]["charge"]) for j in range(len(cols))])
+ basis = _nullspace(rows, len(cols))
+ if len(basis) != 1:
+ return None
+ v = basis[0]
+ if all(x <= 0 for x in v):
+ v = [-x for x in v]
+ if any(x <= 0 for x in v):
+ return None
+ scale = math.lcm(*(x.denominator for x in v))
+ ints = [int(x * scale) for x in v]
+ g = math.gcd(*ints)
+ ints = [i // g for i in ints]
+ return ints if max(ints) <= MAX_COEFFICIENT else None
+
+
+def _co_products(left: list[dict], right: list[dict]) -> list[dict]:
+ extra = [{"counts": counts, "charge": 0, "name": name, "smiles": smiles} for name, smiles, counts in CO_PRODUCTS]
+ for size in (1, 2):
+ found = []
+ for combo in itertools.combinations(extra, size):
+ ints = solve(left, right + list(combo))
+ if ints is not None:
+ found.append({"add": [{"name": c["name"], "smiles": c["smiles"], "coefficient": ints[len(left) + len(right) + k]} for k, c in enumerate(combo)],
+ "coefficients": ints[: len(left) + len(right)]})
+ if found:
+ found.sort(key=lambda o: sum(o["coefficients"]) + sum(a["coefficient"] for a in o["add"]))
+ return found[:3]
+ return []
+
+
+def _n(v: float) -> int | float:
+ return int(v) if float(v).is_integer() else round(v, 4)
+
+
+def _side_text(diff: dict[str, int], more: bool) -> str:
+ parts = [f"{abs(n)} {s}" for s, n in diff.items() if (n > 0) == more and n]
+ return ", ".join(parts)
+
+
+def check(doc: dict, step: dict) -> dict:
+ objects = doc.get("objects") or {}
+ rows: list[dict] = []
+ notes: list[dict] = []
+ left: list[dict] = []
+ right: list[dict] = []
+ for key, role, side in (("reactants", "reactant", left), ("products", "product", right)):
+ for oid in step.get(key) or []:
+ found = species(doc, oid)
+ if found is None:
+ notes.append(warning("not_a_structure", f"The {role} {plain_text(objects.get(oid)) or oid} is not a structure, so it is not counted."))
+ continue
+ found.update({"id": oid, "role": role, "coefficient": _n(coefficient(step, oid))})
+ side.append(found)
+ rows.append(found)
+ if found["generic"]:
+ notes.append(warning("generic_atoms", f"{', '.join(sorted(set(found['generic'])))} in {oid} cannot be counted, so the balance is approximate."))
+ symbols: set[str] = {s for r in rows for s in r["counts"]}
+ total = lambda side, s: _n(sum(r["coefficient"] * r["counts"].get(s, 0) for r in side))
+ elements = [{"element": s, "left": total(left, s), "right": total(right, s), "diff": _n(total(right, s) - total(left, s))} for s in sorted(symbols, key=_hill_key(symbols))]
+ charge = {"left": _n(sum(r["coefficient"] * r["charge"] for r in left)), "right": _n(sum(r["coefficient"] * r["charge"] for r in right))}
+ charge["diff"] = _n(charge["right"] - charge["left"])
+ mass_left = round(sum(r["coefficient"] * r["mw"] for r in left), 4)
+ mass_right = round(sum(r["coefficient"] * r["mw"] for r in right), 4)
+ masses = {"left": mass_left, "right": mass_right, "diff": round(mass_right - mass_left, 4)}
+ diff = {e["element"]: e["diff"] for e in elements}
+ balanced = bool(left and right) and not any(diff.values()) and not charge["diff"]
+ if left and right and not balanced:
+ lost, gained = _side_text(diff, False), _side_text(diff, True)
+ text = "Not balanced." + (f" More on the left: {lost}." if lost else "") + (f" More on the right: {gained}." if gained else "")
+ if charge["diff"]:
+ text += f" Charge {charge['left']:+g} on the left, {charge['right']:+g} on the right."
+ notes.append(warning("unbalanced", text))
+ if left and right and abs(masses["diff"]) > MASS_TOLERANCE:
+ notes.append(warning("mass_balance", f"The products weigh {abs(masses['diff']):.2f} g/mol {'more' if masses['diff'] > 0 else 'less'} than the reactants."))
+ suggestion = None
+ if left and right and not balanced:
+ ints = solve(left, right)
+ if ints is not None:
+ suggestion = {"coefficients": {r["id"]: n for r, n in zip(left + right, ints)}}
+ else:
+ options = _co_products(left, right)
+ if options:
+ suggestion = {"co_products": [{"add": o["add"], "coefficients": {r["id"]: n for r, n in zip(left + right, o["coefficients"])}} for o in options]}
+ species_rows = [{k: r[k] for k in ("id", "role", "coefficient", "formula", "mw", "charge")} for r in rows]
+ return {"step": step.get("id"), "balanced": balanced, "species": species_rows, "elements": elements, "charge": charge,
+ "mass": masses, "suggestion": suggestion, "warnings": notes}
+
+
+def _skeleton(doc: dict, oid: str) -> str:
+ parts = []
+ for frag in fragments_in(doc, oid):
+ mol = Chem.RWMol(perceive.prepare(frag, doc.get("expansions")).mol)
+ for b in mol.GetBonds():
+ b.SetBondType(Chem.BondType.SINGLE)
+ b.SetIsAromatic(False)
+ for a in mol.GetAtoms():
+ a.SetFormalCharge(0)
+ a.SetIsAromatic(False)
+ a.SetNumRadicalElectrons(0)
+ a.SetNumExplicitHs(0)
+ a.SetNoImplicit(True)
+ a.SetAtomMapNum(0)
+ a.SetIsotope(0)
+ parts.append(Chem.MolToSmiles(mol, canonical=True))
+ return ".".join(sorted(parts))
+
+
+def resonance(doc: dict, page: dict) -> list[dict]:
+ style = model.resolve_style(doc)
+ out = []
+ for oid in page.get("order") or []:
+ arrow = (doc.get("objects") or {}).get(oid)
+ if not isinstance(arrow, dict) or arrow.get("kind") != "arrow" or arrow.get("type") != "resonance" or geometry.arrow_points(arrow) is None:
+ continue
+ tail, head = direction(arrow)
+ frame = geometry.Frame(tail, head)
+ bl = bond_length(doc)
+ row = [i for i in _items(doc, page, oid, frame, style) if i.t1 >= -ROW_BONDS * bl and i.t0 <= ROW_BONDS * bl]
+ before = _walk([i for i in row if i.s1 <= END_BONDS * bl], False, bl)[-1:]
+ after = _walk([i for i in row if i.s0 >= frame.length - END_BONDS * bl], True, bl)[:1]
+ if not before or not after:
+ continue
+ a, b = species(doc, before[0]), species(doc, after[0])
+ if a is None or b is None:
+ continue
+ if a["counts"] != b["counts"] or a["charge"] != b["charge"]:
+ out.append({**warning("resonance_formula", f"The structures on either side of this resonance arrow differ in formula ({a['formula']} and {b['formula']}), so they are not resonance forms."),
+ "arrow": oid, "objects": [before[0], after[0]]})
+ elif _skeleton(doc, before[0]) != _skeleton(doc, after[0]):
+ out.append({**warning("resonance_connectivity", "The structures on either side of this resonance arrow are connected differently; resonance forms differ only in where the electrons are."),
+ "arrow": oid, "objects": [before[0], after[0]]})
+ return out
+
+
+def coefficient_ops(path: list, step: dict, wanted: dict[str, int]) -> list[dict]:
+ roles = set(step.get("reactants") or []) | set(step.get("products") or []) | set(step.get("agents") or [])
+ merged = {k: v for k, v in (step.get("coefficients") or {}).items() if k in roles}
+ for oid, n in wanted.items():
+ if oid in roles:
+ if n == 1:
+ merged.pop(oid, None)
+ else:
+ merged[oid] = n
+ if merged == (step.get("coefficients") or {}):
+ return []
+ op: dict = {"op": "set", "path": [*path, "coefficients"]}
+ if merged:
+ op["value"] = merged
+ elif "coefficients" not in step:
+ return []
+ return [op]
diff --git a/backend/app/services/chem/check.py b/backend/app/services/chem/check.py
new file mode 100644
index 00000000..0262ea5f
--- /dev/null
+++ b/backend/app/services/chem/check.py
@@ -0,0 +1,140 @@
+from rdkit import Chem
+
+from app.services.chem import ENGINE, abbrev, convert, markush, perceive, query, warning
+
+PT = Chem.GetPeriodicTable()
+ERROR, WARN, INFO = "error", "warning", "info"
+SEVERITY = {
+ "valence": ERROR, "bad_bond": ERROR, "engine_error": ERROR, "bad_expansion": ERROR,
+ "hypervalent": WARN, "unknown_label": WARN, "misplaced_wedge": WARN, "ambiguous_wedge": WARN, "conflicting_wedges": WARN,
+ "unknown_isotope": WARN, "abbreviation_bonds": WARN, "abbreviation_valence": WARN, "overlapping_atoms": WARN, "short_bond": WARN,
+ "long_bond": WARN, "aromatic_outside_ring": WARN, "cannot_kekulise": WARN, "bad_stereo_group": WARN, "stereo_group_overlap": WARN,
+ "stereo_group_not_centre": WARN, "undefined_double_bond": WARN, "unusual_charge": WARN, "wedge_between_centres": WARN,
+ "ring_double_bond_stereo": WARN, "stereo_ignored": WARN, "unsupported_bond": WARN, "rgroup_undefined": WARN, "rgroup_member_missing": WARN,
+ "rgroup_bonds": WARN, "cip_failed": WARN,
+ "undefined_stereocentre": INFO, "stereo_unknown": INFO, "unknown_ez": INFO, "charge_imbalance": INFO, "query_feature": INFO,
+ "uncommon_isotope": INFO, "crossing_bonds": INFO, "label_collides": INFO, "rgroup_unused": INFO, "rgroup_attachment_guessed": INFO,
+}
+FIX = {"misplaced_wedge": "wedges", "ambiguous_wedge": "wedges", "conflicting_wedges": "wedges", "wedge_between_centres": "wedges",
+ "undefined_stereocentre": "wedges", "abbreviation_valence": "expand", "abbreviation_bonds": "expand"}
+SKIP = {"query_ignored", "inchi_warning", "inchi_unavailable", "inchi_failed"}
+COMMON_LABELS = {(1, 2), (1, 3), (6, 11), (6, 13), (6, 14), (7, 15), (8, 17), (8, 18), (9, 18), (15, 32), (15, 33), (16, 35), (53, 123), (53, 125), (53, 131)}
+CROSSING_LIMIT = 1500
+
+
+def _issue(w: dict) -> dict:
+ out = {"code": w["code"], "severity": SEVERITY.get(w["code"], WARN), "text": w.get("text", "")}
+ for key in ("atoms", "bonds"):
+ if w.get(key):
+ out[key] = list(w[key])
+ if w["code"] in FIX:
+ out["fix"] = FIX[w["code"]]
+ return out
+
+
+def _charges(frag: dict, conv: convert.Conversion) -> list[dict]:
+ odd = []
+ for a in conv.mol.GetAtoms():
+ if not conv.drawn[a.GetIdx()]:
+ continue
+ q, z = a.GetFormalCharge(), a.GetAtomicNum()
+ if not q or z == 0:
+ continue
+ group = PT.GetNOuterElecs(z)
+ metal = z not in query.NONMETALS
+ if abs(q) >= 3 and not metal or z == 6 and abs(q) >= 2 or z in (2, 10, 18, 36, 54, 86) or z == 9 and q > 0 or metal and q < 0 and group <= 2:
+ odd.append(conv.owner[a.GetIdx()])
+ return [warning("unusual_charge", "Unusual formal charge for this element.", odd)] if odd else []
+
+
+def _stereo(frag: dict, conv: convert.Conversion) -> list[dict]:
+ out = []
+ mol = conv.mol
+ centres = {i for i in range(mol.GetNumAtoms()) if mol.GetAtomWithIdx(i).GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED}
+ both = []
+ for bi in conv.wedged:
+ b = mol.GetBondWithIdx(bi)
+ if b.GetBeginAtomIdx() in centres and b.GetEndAtomIdx() in centres and conv.bond_id(bi):
+ both.append(conv.bond_id(bi))
+ if both:
+ out.append(warning("wedge_between_centres", "This wedge joins two stereocentres; it is read at its narrow end only.", bonds=both))
+ ring = []
+ ri = mol.GetRingInfo()
+ for bi in conv.either:
+ if any(len(r) < 8 and bi in r for r in ri.BondRings()) and conv.bond_id(bi):
+ ring.append(conv.bond_id(bi))
+ if ring:
+ out.append(warning("ring_double_bond_stereo", "A double bond in a ring smaller than eight atoms cannot carry E/Z; the crossed mark means nothing here.", bonds=ring))
+ return out
+
+
+def _isotopes(conv: convert.Conversion) -> list[dict]:
+ rare = []
+ for a in conv.mol.GetAtoms():
+ z, iso = a.GetAtomicNum(), a.GetIsotope()
+ if not iso or not z or not conv.drawn[a.GetIdx()] or (z, iso) in COMMON_LABELS:
+ continue
+ if PT.GetMassForIsotope(z, iso) > 0 and PT.GetAbundanceForIsotope(z, iso) <= 0:
+ rare.append(conv.owner[a.GetIdx()])
+ return [warning("uncommon_isotope", "A known nuclide that does not occur naturally; check the mass number.", rare)] if rare else []
+
+
+def _segments_cross(p, q, r, s) -> bool:
+ def orient(a, b, c):
+ v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
+ return 0 if abs(v) < 1e-9 else (1 if v > 0 else -1)
+ return orient(p, q, r) * orient(p, q, s) < 0 and orient(r, s, p) * orient(r, s, q) < 0
+
+
+def _crossings(frag: dict) -> list[dict]:
+ atoms = frag.get("atoms") or {}
+ bonds = [b for b in (frag.get("bonds") or {}).values() if b["a"] in atoms and b["b"] in atoms]
+ if len(bonds) > CROSSING_LIMIT:
+ return []
+ pts = {k: (a["x"], a["y"]) for k, a in atoms.items()}
+ hit: set[str] = set()
+ for i, b in enumerate(bonds):
+ for c in bonds[i + 1:]:
+ if {b["a"], b["b"]} & {c["a"], c["b"]}:
+ continue
+ if _segments_cross(pts[b["a"]], pts[b["b"]], pts[c["a"]], pts[c["b"]]):
+ hit.update((b["id"], c["id"]))
+ return [warning("crossing_bonds", "Bonds cross each other.", bonds=hit)] if hit else []
+
+
+def _queries(frag: dict) -> list[dict]:
+ atoms = [k for k, a in (frag.get("atoms") or {}).items() if query.is_query_atom(a)]
+ bonds = [k for k, b in (frag.get("bonds") or {}).items() if query.is_query_bond(b)]
+ if not atoms and not bonds:
+ return []
+ return [warning("query_feature", "Query features in a drawing that is not a query: chemistry ignores them.", atoms, bonds)]
+
+
+def _labels(frag: dict) -> list[dict]:
+ hits = [k for k, a in (frag.get("atoms") or {}).items() if a.get("label") in abbrev.ELEMENT_COLLISIONS and a.get("element") == a.get("label")]
+ return [warning("label_collides", "This label is also an element symbol; it is read as the abbreviation (acetyl, propyl, neopentyl).", hits)] if hits else []
+
+
+def check(frag: dict, expansions: dict | None = None, members: dict[str, dict] | None = None, is_query: bool = False) -> dict:
+ if not frag.get("atoms"):
+ return {"issues": [], "counts": {ERROR: 0, WARN: 0, INFO: 0}, "engine": ENGINE}
+ conv = perceive.prepare(frag, expansions)
+ p = perceive.perceive(frag, expansions, conv)
+ found: list[dict] = []
+ for v in p.valence_errors:
+ found.append({"code": "valence", "text": f"Valence {v['valence']} is more than allowed ({', '.join(str(x) for x in v['allowed'])}).", "atoms": [v["atom"]]})
+ found.extend(w for w in p.warnings if w.get("code") not in SKIP)
+ ignored = {k for k, a in frag["atoms"].items() if a.get("ignore_warnings")}
+ extra = _charges(frag, conv) + _stereo(frag, conv) + _isotopes(conv) + _crossings(frag) + _labels(frag)
+ if not is_query:
+ extra += _queries(frag)
+ if frag.get("rgroups") or any(a.get("element") == "R#" for a in frag["atoms"].values()):
+ extra += markush.describe(frag, members or {})["warnings"]
+ found.extend(w for w in extra if not w.get("atoms") or not set(w["atoms"]) <= ignored)
+ issues = [_issue(w) for w in found]
+ rank = {ERROR: 0, WARN: 1, INFO: 2}
+ issues.sort(key=lambda i: rank[i["severity"]])
+ counts = {ERROR: 0, WARN: 0, INFO: 0}
+ for i in issues:
+ counts[i["severity"]] += 1
+ return {"issues": issues, "counts": counts, "engine": ENGINE}
diff --git a/backend/app/services/chem/convert.py b/backend/app/services/chem/convert.py
index ccae2f36..4c53a081 100644
--- a/backend/app/services/chem/convert.py
+++ b/backend/app/services/chem/convert.py
@@ -40,6 +40,8 @@ class Conversion:
wedged: list[int] = field(default_factory=list)
wavy: list[int] = field(default_factory=list)
either: list[int] = field(default_factory=list)
+ groups: list[tuple[str, int, list[int]]] = field(default_factory=list)
+ chiral: str | None = None
def atom_id(self, idx: int) -> str:
return self.owner[idx]
@@ -66,6 +68,13 @@ def _order_key(order: Any) -> Any:
return order
+def _query_label(a: dict) -> str:
+ q = a.get("query") if isinstance(a.get("query"), dict) else {}
+ if q.get("list"):
+ return ("not" if q.get("not") else "") + "[" + ",".join(str(s) for s in q["list"]) + "]"
+ return str(q.get("generic") or "")
+
+
def _new_atom(a: dict, conv: Conversion) -> Chem.Atom:
aid = a["id"]
el = a.get("element", "C")
@@ -79,11 +88,12 @@ def _new_atom(a: dict, conv: Conversion) -> Chem.Atom:
conv.generic.append(aid)
elif el == "*" or el not in ELEMENTS:
atom = Chem.Atom(0)
- label = a.get("label") or a.get("generic") or ""
+ asked = _query_label(a)
+ label = a.get("label") or a.get("generic") or asked
if label:
atom.SetProp("dummyLabel", label)
atom.SetProp("atomLabel", label)
- if a.get("generic") or label in ("R", "R'", "R''", "X", "Ar", "Alk", "Het", "Hal", "M", "G"):
+ if a.get("generic") or asked or label in ("R", "R'", "R''", "X", "Ar", "Alk", "Het", "Hal", "M", "G") or (el == "*" and label in (None, "", "*")):
conv.generic.append(aid)
else:
conv.unknown.append(aid)
@@ -211,6 +221,7 @@ def to_mol(frag: dict, expansions: dict | None = None, expand: bool = True, dept
conv.warnings.append(warning("query_ignored", "Bond query features are not used for chemistry yet.", bonds=[bid]))
_set_bond_stereo(conv, rb, bid, b.get("stereo") or "none")
conv.bond_ids.append(bid)
+ _read_groups(conv, frag)
conf = Chem.Conformer(conv.mol.GetNumAtoms())
for i, (x, y) in enumerate(conv.pos):
@@ -221,6 +232,62 @@ def to_mol(frag: dict, expansions: dict | None = None, expand: bool = True, dept
WEDGE_DIRS = {"wedge": Chem.BondDir.BEGINWEDGE, "hollow": Chem.BondDir.BEGINWEDGE, "hash": Chem.BondDir.BEGINDASH}
+SG = Chem.StereoGroupType
+GROUP_TYPES = {"abs": SG.STEREO_ABSOLUTE, "and": SG.STEREO_AND, "or": SG.STEREO_OR}
+GROUP_KINDS = {v: k for k, v in GROUP_TYPES.items()}
+CHIRAL_FLAGS = ("absolute", "relative", "racemic")
+
+
+def _read_groups(conv: Conversion, frag: dict) -> None:
+ flag = frag.get("chiral")
+ conv.chiral = flag if flag in CHIRAL_FLAGS else None
+ seen: set[int] = set()
+ for i, g in enumerate(frag.get("stereo_groups") or []):
+ kind = g.get("kind") if isinstance(g, dict) else None
+ if kind not in GROUP_TYPES:
+ conv.warnings.append(warning("bad_stereo_group", f"Stereo group {i + 1} has no kind abs, and or or; it is ignored."))
+ continue
+ n = g.get("n") if isinstance(g.get("n"), int) and not isinstance(g.get("n"), bool) and g.get("n") > 0 else 0
+ idx = []
+ for aid in g.get("atoms") or []:
+ j = conv.index.get(aid) if isinstance(aid, str) else None
+ if j is None or not conv.drawn[j]:
+ continue
+ if j in seen:
+ conv.warnings.append(warning("stereo_group_overlap", "This atom is in more than one stereo group; the first group wins.", [aid]))
+ continue
+ seen.add(j)
+ idx.append(j)
+ if idx:
+ conv.groups.append((kind, n, idx))
+
+
+def apply_groups(conv: Conversion) -> None:
+ mol = conv.mol
+ centres = {a.GetIdx() for a in mol.GetAtoms() if a.GetChiralTag() in (Chem.ChiralType.CHI_TETRAHEDRAL_CW, Chem.ChiralType.CHI_TETRAHEDRAL_CCW)}
+ if conv.chiral == "absolute":
+ mol.SetIntProp("_MolFileChiralFlag", 1)
+ if not conv.groups and conv.chiral not in ("relative", "racemic"):
+ return
+ used = {k: {n for kind, n, _ in conv.groups if kind == k and n} for k in ("and", "or")}
+ out, grouped = [], set()
+ for kind, n, idx in conv.groups:
+ atoms = [i for i in idx if i in centres]
+ stray = [conv.owner[i] for i in idx if i not in centres]
+ if stray:
+ conv.warnings.append(warning("stereo_group_not_centre", "Atoms in a stereo group that are not defined stereocentres are left out of it.", stray))
+ if not atoms:
+ continue
+ if kind != "abs" and not n:
+ n = max(used[kind], default=0) + 1
+ used[kind].add(n)
+ grouped.update(atoms)
+ out.append(Chem.CreateStereoGroup(GROUP_TYPES[kind], mol, atoms, readId=n))
+ rest = sorted(centres - grouped)
+ if rest and conv.chiral in ("relative", "racemic"):
+ kind = "or" if conv.chiral == "relative" else "and"
+ out.append(Chem.CreateStereoGroup(GROUP_TYPES[kind], mol, rest, readId=max(used[kind], default=0) + 1))
+ mol.SetStereoGroups(out)
def _set_bond_stereo(conv: Conversion, rb: Chem.Bond, bid: str, stereo: str) -> None:
@@ -333,6 +400,10 @@ def assign_stereo(conv: Conversion) -> None:
if centre.GetChiralTag() == Chem.ChiralType.CHI_UNSPECIFIED and conv.bond_ids[bi]:
conv.warnings.append(warning("misplaced_wedge", "The narrow end of this wedge is not at a stereocentre.",
[conv.owner[centre.GetIdx()]], [conv.bond_ids[bi]]))
+ try:
+ apply_groups(conv)
+ except Exception as exc:
+ conv.problems.append({"code": "stereo_groups_failed", "text": str(exc)})
def _wedges_from_mol(mol: Chem.Mol) -> dict[int, tuple[str, int]]:
@@ -469,10 +540,32 @@ def fresh(prefix: str) -> str:
if stereo:
rec["stereo"] = stereo[0]
frag["bonds"][bid] = rec
+ groups = groups_from_mol(mol, ids)
+ if groups:
+ frag["stereo_groups"] = groups
+ if mol.HasProp("_MolFileChiralFlag") and mol.GetIntProp("_MolFileChiralFlag") == 1:
+ frag["chiral"] = "absolute"
_pin_hydrogens(mol, frag, ids)
return frag
+def groups_from_mol(mol: Chem.Mol, ids: list[str]) -> list[dict]:
+ out: list[dict] = []
+ counters = {"and": 0, "or": 0}
+ for g in mol.GetStereoGroups():
+ kind = GROUP_KINDS.get(g.GetGroupType())
+ atoms = [ids[a.GetIdx()] for a in g.GetAtoms() if a.GetIdx() < len(ids)]
+ if kind is None or not atoms:
+ continue
+ rec: dict = {"kind": kind}
+ if kind != "abs":
+ counters[kind] += 1
+ rec["n"] = g.GetReadId() or g.GetWriteId() or counters[kind]
+ rec["atoms"] = atoms
+ out.append(rec)
+ return out
+
+
def _pin_hydrogens(mol: Chem.Mol, frag: dict, ids: list[str]) -> None:
probe = to_mol(frag, expand=False)
try:
diff --git a/backend/app/services/chem/derive.py b/backend/app/services/chem/derive.py
index a245301d..c292eb35 100644
--- a/backend/app/services/chem/derive.py
+++ b/backend/app/services/chem/derive.py
@@ -7,8 +7,11 @@
from app.services.chem import ENGINE, ids, mass, perceive, warning
CACHE_SIZE = 2048
+REACTION_CHECKS = 64
+CHECK_FIELDS = ("balanced", "elements", "charge", "mass", "warnings")
ATOM_FIELDS = ("element", "charge", "isotope", "radical", "hydrogens", "label", "expansion", "generic", "rgroup", "map", "query", "ignore_warnings")
BOND_FIELDS = ("a", "b", "order", "stereo", "query", "topology")
+FRAGMENT_FIELDS = ("chiral", "stereo_groups")
_cache: "OrderedDict[str, dict]" = OrderedDict()
_lock = threading.Lock()
@@ -24,6 +27,7 @@ def content_key(frag: dict, expansions: dict | None = None) -> str:
[[k, *(atoms[k].get(f) for f in ATOM_FIELDS), round(atoms[k].get("x", 0.0) - x0, 3), round(atoms[k].get("y", 0.0) - y0, 3)] for k in sorted(atoms)],
[[k, *(bonds[k].get(f) for f in BOND_FIELDS)] for k in sorted(bonds)],
[(expansions or {}).get(e) for e in used],
+ [frag.get(f) for f in FRAGMENT_FIELDS],
]
return hashlib.sha1(json.dumps(body, sort_keys=True, default=str).encode()).hexdigest()
@@ -85,16 +89,35 @@ def fragments_of(doc: dict) -> dict[str, dict]:
return {k: o for k, o in (doc.get("objects") or {}).items() if isinstance(o, dict) and o.get("kind") == "fragment"}
+def reaction_checks(doc: dict) -> dict:
+ from app.services.chem import balance
+ out: dict = {}
+ for page in doc.get("pages") or []:
+ for reaction in page.get("reactions") or []:
+ for step in reaction.get("steps") or []:
+ if len(out) >= REACTION_CHECKS or not isinstance(step, dict) or not isinstance(step.get("id"), str):
+ continue
+ try:
+ found = balance.check(doc, step)
+ except Exception:
+ continue
+ out[step["id"]] = {k: found[k] for k in CHECK_FIELDS if k in found}
+ return out
+
+
def derive_document(doc: dict, rev: int = 0, only: list[str] | None = None) -> dict:
expansions = doc.get("expansions") or {}
frags = fragments_of(doc)
chosen = frags if only is None else {k: v for k, v in frags.items() if k in set(only)}
- return {
+ out = {
"doc": doc.get("id", ""),
"rev": rev,
"engine": ENGINE,
"fragments": {fid: derive_fragment(f, expansions, rev) for fid, f in chosen.items()},
}
+ if only is None:
+ out["reactions"] = reaction_checks(doc)
+ return out
def clear_cache() -> None:
diff --git a/backend/app/services/chem/geometry.py b/backend/app/services/chem/geometry.py
new file mode 100644
index 00000000..69a53cdb
--- /dev/null
+++ b/backend/app/services/chem/geometry.py
@@ -0,0 +1,186 @@
+import math
+
+Box = tuple[float, float, float, float]
+
+TEXT_ADVANCE = 0.55
+LINE_HEIGHT = 1.2
+LABEL_PAD = 0.4
+DEFAULT_FONT = 10.0
+
+
+def _num(v: object) -> bool:
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
+
+
+def union(boxes: list[Box]) -> Box | None:
+ found = [b for b in boxes if b is not None]
+ if not found:
+ return None
+ return (min(b[0] for b in found), min(b[1] for b in found), max(b[2] for b in found), max(b[3] for b in found))
+
+
+def centre(box: Box) -> tuple[float, float]:
+ return ((box[0] + box[2]) / 2, (box[1] + box[3]) / 2)
+
+
+def _rect(obj: dict) -> Box | None:
+ x, y, w, h = obj.get("x"), obj.get("y"), obj.get("w"), obj.get("h")
+ if not all(_num(v) for v in (x, y, w, h)):
+ return None
+ rot = obj.get("rot")
+ if not _num(rot) or not rot:
+ return (x, y, x + w, y + h)
+ cx, cy = x + w / 2, y + h / 2
+ t = math.radians(rot)
+ c, s = math.cos(t), math.sin(t)
+ pts = [(cx + dx * c + dy * s, cy - dx * s + dy * c) for dx in (-w / 2, w / 2) for dy in (-h / 2, h / 2)]
+ return (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts))
+
+
+def fragment_box(frag: dict, style: dict) -> Box | None:
+ atoms = [a for a in (frag.get("atoms") or {}).values() if isinstance(a, dict) and _num(a.get("x")) and _num(a.get("y"))]
+ if not atoms:
+ return None
+ size = float((style.get("label_font") or {}).get("size") or DEFAULT_FONT)
+ boxes = []
+ for a in atoms:
+ if a.get("element") != "C" or a.get("label") or a.get("show_carbon") == "always" or len(atoms) == 1:
+ shown = str(a.get("label") or a.get("element") or "")
+ half = max(1, len(shown)) * size * TEXT_ADVANCE / 2 + LABEL_PAD
+ boxes.append((a["x"] - half, a["y"] - size * 0.6, a["x"] + half, a["y"] + size * 0.6))
+ else:
+ boxes.append((a["x"], a["y"], a["x"], a["y"]))
+ return union(boxes)
+
+
+def _run_size(run: dict, style: dict) -> float:
+ if _num(run.get("size")):
+ return float(run["size"])
+ return float((style.get("caption_font") or {}).get("size") or DEFAULT_FONT)
+
+
+def text_box(obj: dict, style: dict) -> Box | None:
+ x, y = obj.get("x"), obj.get("y")
+ if not _num(x) or not _num(y):
+ return None
+ lines: list[float] = [0.0]
+ heights: list[float] = [0.0]
+ for run in obj.get("runs") or []:
+ if not isinstance(run, dict):
+ continue
+ size = _run_size(run, style) * (0.75 if run.get("sub") or run.get("sup") else 1.0)
+ parts = str(run.get("t") or "").split("\n")
+ for n, part in enumerate(parts):
+ if n:
+ lines.append(0.0)
+ heights.append(0.0)
+ lines[-1] += len(part) * size * TEXT_ADVANCE
+ heights[-1] = max(heights[-1], size)
+ base = float((style.get("caption_font") or {}).get("size") or DEFAULT_FONT)
+ width = float(obj["w"]) if _num(obj.get("w")) and obj["w"] > 0 else max(lines)
+ height = sum((h or base) * LINE_HEIGHT for h in heights)
+ align = obj.get("align") or "l"
+ left = x
+ if not _num(obj.get("w")):
+ left = x - width / 2 if align == "c" else x - width if align == "r" else x
+ return _rect({"x": left, "y": y, "w": width, "h": height, "rot": obj.get("rot")})
+
+
+def arrow_points(obj: dict) -> tuple[tuple[float, float], tuple[float, float]] | None:
+ vals = [obj.get(k) for k in ("x1", "y1", "x2", "y2")]
+ if not all(_num(v) for v in vals):
+ return None
+ return (float(vals[0]), float(vals[1])), (float(vals[2]), float(vals[3]))
+
+
+def arrow_box(obj: dict) -> Box | None:
+ ends = arrow_points(obj)
+ if ends is None:
+ return None
+ (x1, y1), (x2, y2) = ends
+ pts = [(x1, y1), (x2, y2)]
+ bend = obj.get("bend")
+ if _num(bend) and bend:
+ mx, my = (x1 + x2) / 2, (y1 + y2) / 2
+ dx, dy = x2 - x1, y2 - y1
+ sag = math.tan(math.radians(bend) / 4) * math.hypot(dx, dy) / 2
+ length = math.hypot(dx, dy) or 1.0
+ pts.append((mx + dy / length * sag, my - dx / length * sag))
+ return (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts))
+
+
+def plus_box(obj: dict, style: dict) -> Box | None:
+ x, y = obj.get("x"), obj.get("y")
+ if not _num(x) or not _num(y):
+ return None
+ size = float(obj["size"]) if _num(obj.get("size")) else 0.6 * float(style.get("bond_length") or 14.4)
+ return (x - size / 2, y - size / 2, x + size / 2, y + size / 2)
+
+
+def table_box(obj: dict) -> Box | None:
+ x, y = obj.get("x"), obj.get("y")
+ if not _num(x) or not _num(y):
+ return None
+ w = sum(float(c) for c in obj.get("cols") or [] if _num(c))
+ h = sum(float(r.get("h") or 0) for r in obj.get("rows") or [] if isinstance(r, dict) and _num(r.get("h") or 0))
+ return (x, y, x + w, y + h)
+
+
+def object_box(doc: dict, oid: str, style: dict, depth: int = 0) -> Box | None:
+ obj = (doc.get("objects") or {}).get(oid)
+ if not isinstance(obj, dict) or depth > 32:
+ return None
+ kind = obj.get("kind")
+ if kind == "fragment":
+ return fragment_box(obj, style)
+ if kind in ("text", "caption"):
+ return text_box(obj, style)
+ if kind == "arrow":
+ return arrow_box(obj)
+ if kind == "plus":
+ return plus_box(obj, style)
+ if kind == "group":
+ return union([object_box(doc, c, style, depth + 1) for c in obj.get("children") or [] if isinstance(c, str)])
+ if kind == "table":
+ return table_box(obj)
+ if kind == "line":
+ pts = [p for p in obj.get("points") or [] if isinstance(p, list) and len(p) == 2 and all(_num(v) for v in p)]
+ return (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts)) if pts else None
+ if kind == "orbital":
+ x, y, size = obj.get("x"), obj.get("y"), obj.get("size")
+ if all(_num(v) for v in (x, y, size)):
+ return (x - size, y - size, x + size, y + size)
+ return None
+ return _rect(obj)
+
+
+def has_fragment(doc: dict, oid: str, depth: int = 0) -> bool:
+ obj = (doc.get("objects") or {}).get(oid)
+ if not isinstance(obj, dict) or depth > 32:
+ return False
+ if obj.get("kind") == "fragment":
+ return bool(obj.get("atoms"))
+ if obj.get("kind") == "group":
+ return any(has_fragment(doc, c, depth + 1) for c in obj.get("children") or [] if isinstance(c, str))
+ return False
+
+
+class Frame:
+ def __init__(self, tail: tuple[float, float], head: tuple[float, float]):
+ self.tail = tail
+ dx, dy = head[0] - tail[0], head[1] - tail[1]
+ self.length = math.hypot(dx, dy)
+ k = self.length or 1.0
+ self.ux, self.uy = dx / k, dy / k
+
+ def along(self, p: tuple[float, float]) -> float:
+ return (p[0] - self.tail[0]) * self.ux + (p[1] - self.tail[1]) * self.uy
+
+ def across(self, p: tuple[float, float]) -> float:
+ return (p[0] - self.tail[0]) * self.uy - (p[1] - self.tail[1]) * self.ux
+
+ def project(self, box: Box) -> tuple[float, float, float, float]:
+ corners = [(box[0], box[1]), (box[2], box[1]), (box[0], box[3]), (box[2], box[3])]
+ s = [self.along(c) for c in corners]
+ t = [self.across(c) for c in corners]
+ return min(s), max(s), min(t), max(t)
diff --git a/backend/app/services/chem/hydrogens.py b/backend/app/services/chem/hydrogens.py
new file mode 100644
index 00000000..82ecc55a
--- /dev/null
+++ b/backend/app/services/chem/hydrogens.py
@@ -0,0 +1,153 @@
+import math
+
+from app.services.chem import abbrev, convert, derive, perceive, warning
+from app.services.model import new_id
+from app.services.ops import atom_path, bond_path
+
+Point = tuple[float, float]
+H_LENGTH = 0.8
+
+
+def _angle(p: dict, q: dict) -> float:
+ return math.atan2(q["y"] - p["y"], q["x"] - p["x"]) % (2 * math.pi)
+
+
+def directions(taken: list[float], n: int) -> list[float]:
+ if n <= 0:
+ return []
+ if not taken:
+ return [2 * math.pi * i / n for i in range(n)]
+ ordered = sorted(taken)
+ gaps = [(ordered[i], ((ordered[(i + 1) % len(ordered)] - ordered[i]) % (2 * math.pi)) or 2 * math.pi) for i in range(len(ordered))]
+ share = [0] * len(gaps)
+ for _ in range(n):
+ best = max(range(len(gaps)), key=lambda i: gaps[i][1] / (share[i] + 2))
+ share[best] += 1
+ out = []
+ for (start, width), k in zip(gaps, share):
+ out.extend((start + width * (i + 1) / (k + 1)) % (2 * math.pi) for i in range(k))
+ return out
+
+
+def _cip(frag: dict, expansions: dict | None) -> dict[str, str]:
+ return {k: v for k, v in derive.compute_fragment(frag, expansions).get("cip", {}).items() if k in frag["atoms"]}
+
+
+def _used(frag: dict, extra: set[str] | None) -> set[str]:
+ return set(extra or ()) | set(frag.get("atoms") or {}) | set(frag.get("bonds") or {})
+
+
+def _fresh(prefix: str, used: set[str]) -> str:
+ while True:
+ i = new_id(prefix)
+ if i not in used:
+ used.add(i)
+ return i
+
+
+def add_hydrogens(frag: dict, expansions: dict | None = None, atoms: list[str] | None = None, used: set[str] | None = None) -> dict:
+ fid = frag["id"]
+ frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {}
+ conv = perceive.prepare(frag, expansions)
+ length = convert.median_bond_length(frag) * H_LENGTH
+ scope = set(frag_atoms) if atoms is None else {a for a in atoms if a in frag_atoms}
+ taken = _used(frag, used)
+ trial = {**frag, "atoms": dict(frag_atoms), "bonds": dict(frag_bonds)}
+ new_atoms: dict[str, dict] = {}
+ new_bonds: dict[str, dict] = {}
+ cleared: dict[str, list[str]] = {}
+ added: dict[str, list[str]] = {}
+ for aid in sorted(scope):
+ a = frag_atoms[aid]
+ i = conv.index.get(aid)
+ if i is None or not conv.drawn[i] or a.get("element") in ("H", "*", "R#") or aid in conv.expanded:
+ continue
+ n = conv.mol.GetAtomWithIdx(i).GetTotalNumHs()
+ if n <= 0:
+ continue
+ angles = [_angle(a, frag_atoms[b["b"] if b["a"] == aid else b["a"]]) for b in frag_bonds.values() if aid in (b["a"], b["b"])]
+ added[aid] = []
+ for t in directions(angles, n):
+ hid, bid = _fresh("a", taken), _fresh("b", taken)
+ new_atoms[hid] = {"id": hid, "element": "H", "x": round(a["x"] + length * math.cos(t), 3), "y": round(a["y"] + length * math.sin(t), 3)}
+ new_bonds[bid] = {"id": bid, "a": aid, "b": hid, "order": 1}
+ added[aid].append(hid)
+ fields = [f for f in ("hydrogens",) if f in a]
+ if a.get("label") and abbrev.element_like(a["label"], a.get("element", "C")):
+ fields.append("label")
+ if fields:
+ cleared[aid] = fields
+ if not added:
+ raise ValueError("no chosen atom has implicit hydrogens to draw")
+ trial["atoms"].update({k: {kk: vv for kk, vv in v.items() if kk not in cleared.get(k, ())} for k, v in frag_atoms.items() if k in cleared})
+ trial["atoms"].update(new_atoms)
+ trial["bonds"].update(new_bonds)
+ notes: list[dict] = []
+ before = _cip(frag, expansions)
+ for centre, label in before.items():
+ if centre not in added or _cip(trial, expansions).get(centre) == label:
+ continue
+ bid = next(k for k, b in new_bonds.items() if b["a"] == centre)
+ for mark in ("hash", "wedge"):
+ new_bonds[bid] = {**new_bonds[bid], "stereo": mark}
+ trial["bonds"][bid] = new_bonds[bid]
+ if _cip(trial, expansions).get(centre) == label:
+ break
+ else:
+ new_bonds[bid] = {k: v for k, v in new_bonds[bid].items() if k != "stereo"}
+ trial["bonds"][bid] = new_bonds[bid]
+ notes.append(warning("stereo_changed", "Drawing the hydrogens changed how this centre reads; check its wedges.", [centre]))
+ ops = [{"op": "set", "path": atom_path(fid, k), "value": v} for k, v in new_atoms.items()]
+ ops += [{"op": "set", "path": bond_path(fid, k), "value": v} for k, v in new_bonds.items()]
+ ops += [{"op": "set", "path": atom_path(fid, aid, f)} for aid, fs in sorted(cleared.items()) for f in fs]
+ return {"tx": {"label": "Add explicit hydrogens", "ops": ops}, "added": added, "warnings": notes}
+
+
+def _removable(h: dict, link: dict) -> bool:
+ if any(h.get(f) for f in ("isotope", "charge", "map", "query", "label")) or (h.get("radical") or "none") != "none":
+ return False
+ if link.get("order", 1) != 1 or (link.get("stereo") or "none") != "none":
+ return False
+ return True
+
+
+def remove_hydrogens(frag: dict, expansions: dict | None = None, atoms: list[str] | None = None) -> dict:
+ fid = frag["id"]
+ frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {}
+ scope = set(frag_atoms) if atoms is None else {a for a in atoms if a in frag_atoms}
+ gone: dict[str, tuple[str, str]] = {}
+ kept: list[str] = []
+ for hid, h in sorted(frag_atoms.items()):
+ if h.get("element") != "H":
+ continue
+ links = [b for b in frag_bonds.values() if hid in (b["a"], b["b"])]
+ heavy = [frag_atoms[b["b"] if b["a"] == hid else b["a"]] for b in links]
+ if hid not in scope and not any(x["id"] in scope for x in heavy):
+ continue
+ if len(links) != 1 or heavy[0].get("element") == "H" or not _removable(h, links[0]):
+ kept.append(hid)
+ continue
+ gone[hid] = (links[0]["id"], heavy[0]["id"])
+ before = _cip(frag, expansions)
+ for _ in range(3):
+ trial = {**frag, "atoms": {k: v for k, v in frag_atoms.items() if k not in gone},
+ "bonds": {k: b for k, b in frag_bonds.items() if k not in {g[0] for g in gone.values()}}}
+ after = _cip(trial, expansions)
+ changed = {c for c, v in before.items() if c in trial["atoms"] and after.get(c) != v}
+ back = [hid for hid, (_, heavy) in gone.items() if heavy in changed]
+ if not back:
+ break
+ for hid in back:
+ gone.pop(hid)
+ kept.append(hid)
+ if not gone:
+ raise ValueError("no explicit hydrogen here can be removed without losing information")
+ ops = [{"op": "set", "path": bond_path(fid, bid)} for bid, _ in gone.values()]
+ ops += [{"op": "set", "path": atom_path(fid, hid)} for hid in sorted(gone)]
+ pinned: dict[str, int] = {}
+ for _, heavy in gone.values():
+ if isinstance(frag_atoms[heavy].get("hydrogens"), int):
+ pinned[heavy] = pinned.get(heavy, frag_atoms[heavy]["hydrogens"]) + 1
+ ops += [{"op": "set", "path": atom_path(fid, aid, "hydrogens"), "value": min(12, n)} for aid, n in sorted(pinned.items())]
+ notes = [warning("hydrogens_kept", "These hydrogens carry an isotope, charge, map number, stereo or bridge two atoms, or hold a stereocentre's configuration, so they stay.", kept)] if kept else []
+ return {"tx": {"label": "Remove explicit hydrogens", "ops": ops}, "removed": sorted(gone), "kept": sorted(kept), "warnings": notes}
diff --git a/backend/app/services/chem/isotopes.py b/backend/app/services/chem/isotopes.py
new file mode 100644
index 00000000..dbcfd979
--- /dev/null
+++ b/backend/app/services/chem/isotopes.py
@@ -0,0 +1,151 @@
+import re
+
+from rdkit import Chem
+
+from app.services.chem import ids, mass, perceive, warning
+
+PT = Chem.GetPeriodicTable()
+PROTON = 1.007276466812
+SODIUM_ION = 22.98976928 - mass.ELECTRON_MASS
+FINE = 1e-3
+KEEP = 1e-7
+THRESHOLD = 0.1
+MERGE = 0.01
+MAX_ATOMS = 20000
+
+Peaks = list[tuple[float, float]]
+
+ADDUCTS = (("[M+H]+", PROTON, 1), ("[M+Na]+", SODIUM_ION, 1), ("[M-H]-", -PROTON, -1))
+
+
+def _merge(peaks: Peaks, width: float) -> Peaks:
+ out: Peaks = []
+ for m, p in sorted(peaks):
+ if out and m - out[-1][0] <= width:
+ m0, p0 = out[-1]
+ total = p0 + p
+ out[-1] = ((m0 * p0 + m * p) / total, total)
+ else:
+ out.append((m, p))
+ return out
+
+
+def _prune(peaks: Peaks) -> Peaks:
+ top = max(p for _, p in peaks)
+ return [(m, p) for m, p in peaks if p >= top * KEEP]
+
+
+def _convolve(a: Peaks, b: Peaks) -> Peaks:
+ return _prune(_merge([(ma + mb, pa * pb) for ma, pa in a for mb, pb in b], FINE))
+
+
+def _power(base: Peaks, n: int) -> Peaks:
+ out: Peaks = [(0.0, 1.0)]
+ while n:
+ if n & 1:
+ out = _convolve(out, base)
+ n >>= 1
+ if n:
+ base = _convolve(base, base)
+ return out
+
+
+def _element(z: int, iso: int) -> Peaks:
+ if iso:
+ m = PT.GetMassForIsotope(z, iso)
+ return [(m if m > 0 else float(iso), 1.0)]
+ return [(m, p) for _, m, p in mass.isotopes(z)]
+
+
+def from_counts(counts: dict[tuple[int, int], int], charge: int = 0, threshold: float = THRESHOLD, merge: float = MERGE) -> dict:
+ if sum(counts.values()) > MAX_ATOMS:
+ raise ValueError(f"the isotope pattern is limited to {MAX_ATOMS} atoms")
+ dist: Peaks = [(0.0, 1.0)]
+ for (z, iso), n in sorted(counts.items()):
+ if n > 0:
+ dist = _convolve(dist, _power(_element(z, iso), n))
+ total = sum(p for _, p in dist)
+ shift = charge * mass.ELECTRON_MASS
+ average = sum(m * p for m, p in dist) / total - shift if counts else 0.0
+ merged = _merge(dist, merge)
+ top = max(p for _, p in merged)
+ z_abs = abs(charge) or 1
+ peaks = []
+ for m, p in merged:
+ rel = p / top * 100
+ if rel + 1e-12 < threshold:
+ continue
+ neutral = m - shift
+ peaks.append({"mass": round(neutral, 4), "mz": round(neutral / z_abs, 4), "abundance": round(rel, 2), "fraction": round(p / total, 6)})
+ mono = sum(n * (_element(z, iso)[0][0] if iso else PT.GetMostCommonIsotopeMass(z)) for (z, iso), n in counts.items()) - shift
+ adducts = []
+ if charge == 0 and counts:
+ for name, delta, z_ion in ADDUCTS:
+ adducts.append({"ion": name, "charge": z_ion, "mz": round(mono + delta, 4)})
+ else:
+ adducts.append({"ion": f"[M]{'' if z_abs == 1 else z_abs}{'+' if charge > 0 else '-'}", "charge": charge, "mz": round(mono / z_abs, 4)})
+ return {
+ "formula": ids.hill(counts, [], charge),
+ "charge": charge,
+ "monoisotopic": round(mono, 4),
+ "average": round(average, 4),
+ "peaks": peaks,
+ "adducts": adducts,
+ "threshold": threshold,
+ "merge": merge,
+ "method": "convolution of RDKit isotope masses and abundances; peaks within 0.01 Da merged, peaks under 0.1 % of the base peak dropped",
+ }
+
+
+def pattern(frag: dict, expansions: dict | None = None, threshold: float = THRESHOLD, merge: float = MERGE) -> dict:
+ conv = perceive.prepare(frag, expansions)
+ counts, labels, charge = ids.formula_counts(conv.mol)
+ if not counts:
+ raise ValueError("the structure has no atoms with an element")
+ out = from_counts(counts, charge, threshold, merge)
+ notes = []
+ excluded = sorted({conv.owner[a.GetIdx()] for a in conv.mol.GetAtoms() if a.GetAtomicNum() == 0})
+ if excluded or labels:
+ notes.append(warning("incomplete", f"{len(excluded) or len(labels)} label(s) or R-group(s) are not counted in the isotope pattern.", excluded))
+ out["warnings"] = notes
+ return out
+
+
+FORMULA_PART = re.compile(r"([A-Z][a-z]?)(\d*)")
+HYDROGEN_ISOTOPES = {"D": 2, "T": 3}
+
+
+def _atomic_number(symbol: str) -> int:
+ try:
+ return PT.GetAtomicNumber(symbol)
+ except RuntimeError:
+ return 0
+CHARGE_TAIL = re.compile(r"([+-])(\d*)$|(\d+)([+-])$")
+
+
+def parse_formula(text: str) -> tuple[dict[tuple[int, int], int], int]:
+ body = text.strip().replace(" ", "")
+ charge = 0
+ tail = CHARGE_TAIL.search(body)
+ if tail:
+ sign = tail.group(1) or tail.group(4)
+ n = int(tail.group(2) or tail.group(3) or 1)
+ charge = n if sign == "+" else -n
+ body = body[: tail.start()]
+ if not body:
+ raise ValueError("give a formula such as C13H18O2")
+ counts: dict[tuple[int, int], int] = {}
+ pos = 0
+ for m in FORMULA_PART.finditer(body):
+ if m.start() != pos:
+ break
+ pos = m.end()
+ symbol = m.group(1)
+ iso = HYDROGEN_ISOTOPES.get(symbol, 0)
+ z = 1 if iso else _atomic_number(symbol)
+ if z <= 0:
+ raise ValueError(f"{symbol} is not an element")
+ counts[(z, iso)] = counts.get((z, iso), 0) + (int(m.group(2)) if m.group(2) else 1)
+ if pos != len(body):
+ raise ValueError(f"cannot read the formula at '{body[pos:]}'")
+ return counts, charge
diff --git a/backend/app/services/chem/mapping.py b/backend/app/services/chem/mapping.py
new file mode 100644
index 00000000..76be40d1
--- /dev/null
+++ b/backend/app/services/chem/mapping.py
@@ -0,0 +1,239 @@
+import itertools
+import time
+
+from rdkit import Chem
+
+from app.services.chem import ids as idsmod, perceive, warning
+from app.services.chem.reactions import ReactionError
+from app.services.chem.rxnio import fragments_in
+
+MODES = ("discard", "keep", "alter", "clear")
+MAX_ORDERS = 24
+BUDGET_SECONDS = 6.0
+TIMEOUT_MS = 3000
+POLISH_ATOMS = 80
+POLISH_ROUNDS = 6
+
+
+class _Mol:
+ def __init__(self, frag: dict, role: str, expansions: dict | None, keep: bool):
+ self.frag = frag
+ self.role = role
+ self.conv = perceive.prepare(frag, expansions)
+ mol = Chem.RWMol(self.conv.mol)
+ for a in mol.GetAtoms():
+ for prop in idsmod.PRIVATE_PROPS:
+ if a.HasProp(prop):
+ a.ClearProp(prop)
+ if not keep:
+ a.SetAtomMapNum(0)
+ try:
+ self.block = Chem.MolToMolBlock(mol, kekulize=True)
+ except Exception:
+ self.block = Chem.MolToMolBlock(mol, kekulize=False)
+
+ def hydrogens(self, idx: int) -> int:
+ return self.conv.mol.GetAtomWithIdx(idx).GetTotalNumHs()
+
+ def bonds(self) -> list[tuple[int, int, float, str | None]]:
+ return [(b.GetBeginAtomIdx(), b.GetEndAtomIdx(), b.GetBondTypeAsDouble(), self.conv.bond_id(b.GetIdx())) for b in self.conv.mol.GetBonds()]
+
+
+def _indigo():
+ from indigo import Indigo
+ ind = Indigo()
+ ind.setOption("ignore-stereochemistry-errors", True)
+ ind.setOption("aam-timeout", TIMEOUT_MS)
+ return ind
+
+
+def _run(ind, reactants: list[_Mol], products: list[_Mol], mode: str) -> tuple[list[list[int]], list[list[int]]]:
+ rxn = ind.createReaction()
+ for m in reactants:
+ rxn.addReactant(ind.loadMolecule(m.block))
+ for m in products:
+ rxn.addProduct(ind.loadMolecule(m.block))
+ rxn.automap(mode)
+ left = [[rxn.atomMappingNumber(a) for a in mol.iterateAtoms()] for mol in rxn.iterateReactants()]
+ right = [[rxn.atomMappingNumber(a) for a in mol.iterateAtoms()] for mol in rxn.iterateProducts()]
+ return left, right
+
+
+def _side_bonds(mols: list[_Mol], maps: list[list[int]]) -> dict[frozenset, float]:
+ out: dict[frozenset, float] = {}
+ for m, nums in zip(mols, maps):
+ for i, j, order, _ in m.bonds():
+ if nums[i] and nums[j]:
+ out[frozenset((nums[i], nums[j]))] = order
+ return out
+
+
+def _score(reactants: list[_Mol], products: list[_Mol], left: list[list[int]], right: list[list[int]]) -> tuple[int, int, int]:
+ unmapped = sum(1 for nums in left + right for n in nums if not n)
+ a, b = _side_bonds(reactants, left), _side_bonds(products, right)
+ edits = len(a.keys() ^ b.keys()) + sum(1 for k in a.keys() & b.keys() if a[k] != b[k])
+ h_left = {n: m.hydrogens(i) for m, nums in zip(reactants, left) for i, n in enumerate(nums) if n}
+ h_right = {n: m.hydrogens(i) for m, nums in zip(products, right) for i, n in enumerate(nums) if n}
+ moved = sum(abs(h_left[n] - h_right[n]) for n in h_left.keys() & h_right.keys())
+ return unmapped, edits, moved
+
+
+def _orders(n_left: int, n_right: int, search: bool):
+ if not search:
+ return [(tuple(range(n_left)), tuple(range(n_right)))]
+ return list(itertools.islice(itertools.product(itertools.permutations(range(n_left)), itertools.permutations(range(n_right))), MAX_ORDERS))
+
+
+def _best(reactants: list[_Mol], products: list[_Mol], mode: str) -> tuple[list[list[int]], list[list[int]], int]:
+ ind = _indigo()
+ best = None
+ tried = 0
+ started = time.monotonic()
+ for lo, ro in _orders(len(reactants), len(products), mode == "discard"):
+ if tried and time.monotonic() - started > BUDGET_SECONDS:
+ break
+ tried += 1
+ left_p, right_p = _run(ind, [reactants[i] for i in lo], [products[i] for i in ro], mode)
+ left = [left_p[lo.index(i)] for i in range(len(reactants))]
+ right = [right_p[ro.index(i)] for i in range(len(products))]
+ score = _score(reactants, products, left, right)
+ if best is None or score < best[0]:
+ best = (score, left, right)
+ right = _polish(reactants, products, best[1], best[2], best[0]) if mode == "discard" else best[2]
+ return best[1], right, tried
+
+
+def _polish(reactants: list[_Mol], products: list[_Mol], left: list[list[int]], right: list[list[int]], score: tuple) -> list[list[int]]:
+ slots = [(mi, ai) for mi, nums in enumerate(right) for ai in range(len(nums))]
+ if len(slots) > POLISH_ATOMS:
+ return right
+ right = [list(nums) for nums in right]
+ element = {(mi, ai): products[mi].conv.mol.GetAtomWithIdx(ai).GetAtomicNum() for mi, ai in slots}
+ for _ in range(POLISH_ROUNDS):
+ better = False
+ for (m1, a1), (m2, a2) in itertools.combinations(slots, 2):
+ if element[(m1, a1)] != element[(m2, a2)] or right[m1][a1] == right[m2][a2]:
+ continue
+ right[m1][a1], right[m2][a2] = right[m2][a2], right[m1][a1]
+ found = _score(reactants, products, left, right)
+ if found < score:
+ score, better = found, True
+ else:
+ right[m1][a1], right[m2][a2] = right[m2][a2], right[m1][a1]
+ if not better:
+ break
+ return right
+
+
+def _compact(left: list[list[int]], right: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
+ renumber: dict[int, int] = {}
+ for nums in left + right:
+ for n in nums:
+ if n and n not in renumber:
+ renumber[n] = len(renumber) + 1
+ return [[renumber.get(n, 0) for n in nums] for nums in left], [[renumber.get(n, 0) for n in nums] for nums in right]
+
+
+def _centres(reactants: list[_Mol], products: list[_Mol], left: list[list[int]], right: list[list[int]]) -> dict[tuple[str, str], str]:
+ a, b = _side_bonds(reactants, left), _side_bonds(products, right)
+ marks: dict[tuple[str, str], str] = {}
+ for mols, maps, mine, other, gone in ((reactants, left, a, b, "broken"), (products, right, b, a, "formed")):
+ for m, nums in zip(mols, maps):
+ for i, j, _order, bid in m.bonds():
+ if bid is None or not (nums[i] and nums[j]):
+ continue
+ key = frozenset((nums[i], nums[j]))
+ if key not in other:
+ marks[(m.frag["id"], bid)] = gone
+ elif other[key] != mine[key]:
+ marks[(m.frag["id"], bid)] = "order"
+ return marks
+
+
+def _molecules(doc: dict, step: dict, keep: bool) -> tuple[list[_Mol], list[_Mol]]:
+ expansions = doc.get("expansions")
+ seen: set[str] = set()
+ sides: dict[str, list[_Mol]] = {"reactants": [], "products": []}
+ for key in sides:
+ for oid in step.get(key) or []:
+ for frag in fragments_in(doc, oid):
+ if frag["id"] not in seen:
+ seen.add(frag["id"])
+ sides[key].append(_Mol(frag, key, expansions, keep))
+ return sides["reactants"], sides["products"]
+
+
+def _set(path: list, old: object, new: object) -> dict | None:
+ if new == old:
+ return None
+ op: dict = {"op": "set", "path": path}
+ if new is not None:
+ op["value"] = new
+ return op
+
+
+def map_ops(doc: dict, step: dict, mode: str = "discard", centres: bool = True) -> tuple[list[dict], dict]:
+ if mode not in MODES:
+ raise ReactionError(f"mode must be one of {', '.join(MODES)}")
+ if mode == "clear":
+ return clear_ops(doc, step, centres)
+ reactants, products = _molecules(doc, step, mode != "discard")
+ if not reactants or not products:
+ raise ReactionError("Mapping needs at least one reactant and one product structure.")
+ try:
+ left, right, tried = _best(reactants, products, mode)
+ except ImportError as exc:
+ raise ReactionError(f"Indigo is not available, so atoms cannot be mapped ({exc}).") from exc
+ except Exception as exc:
+ raise ReactionError(f"The mapper could not map this step: {exc}") from exc
+ left, right = _compact(left, right)
+ marks = _centres(reactants, products, left, right) if centres else {}
+ ops: list[dict] = []
+ unmapped = 0
+ mapped: set[int] = set()
+ for m, nums in zip(reactants + products, left + right):
+ fid, atoms = m.frag["id"], m.frag.get("atoms") or {}
+ for idx, n in enumerate(nums):
+ if not m.conv.drawn[idx]:
+ continue
+ aid = m.conv.owner[idx]
+ if n:
+ mapped.add(n)
+ else:
+ unmapped += 1
+ op = _set(["objects", fid, "atoms", aid, "map"], atoms[aid].get("map"), n or None)
+ if op:
+ ops.append(op)
+ if centres:
+ for bid, bond in (m.frag.get("bonds") or {}).items():
+ op = _set(["objects", fid, "bonds", bid, "reacting"], bond.get("reacting"), marks.get((fid, bid)))
+ if op:
+ ops.append(op)
+ counts = {k: sum(1 for v in marks.values() if v == k) for k in ("broken", "formed", "order")}
+ info = {"mode": mode, "mapped": len(mapped), "unmapped": unmapped, "orders_tried": tried,
+ "quality": "complete" if not unmapped else f"partial: {unmapped} unmapped atom{'s' if unmapped != 1 else ''}",
+ "centres": counts if centres else None, "warnings": []}
+ if any(not all(m.conv.drawn) for m in reactants + products):
+ info["warnings"].append(warning("abbreviations_unmapped", "Atoms inside abbreviations take part in the mapping but carry no map number on the drawing."))
+ return ops, info
+
+
+def clear_ops(doc: dict, step: dict, centres: bool = True) -> tuple[list[dict], dict]:
+ ops: list[dict] = []
+ seen: set[str] = set()
+ cleared = 0
+ for key in ("reactants", "agents", "products"):
+ for oid in step.get(key) or []:
+ for frag in fragments_in(doc, oid):
+ if frag["id"] in seen:
+ continue
+ seen.add(frag["id"])
+ for aid, atom in (frag.get("atoms") or {}).items():
+ if "map" in atom:
+ ops.append({"op": "set", "path": ["objects", frag["id"], "atoms", aid, "map"]})
+ cleared += 1
+ if centres:
+ for bid, bond in (frag.get("bonds") or {}).items():
+ if "reacting" in bond:
+ ops.append({"op": "set", "path": ["objects", frag["id"], "bonds", bid, "reacting"]})
+ return ops, {"mode": "clear", "cleared": cleared}
diff --git a/backend/app/services/chem/markush.py b/backend/app/services/chem/markush.py
new file mode 100644
index 00000000..590221e6
--- /dev/null
+++ b/backend/app/services/chem/markush.py
@@ -0,0 +1,217 @@
+import itertools
+import math
+import re
+
+from rdkit import Chem
+
+from app.services.chem import ids, perceive, warning
+
+LIMIT = 1000
+HARD_LIMIT = 100_000
+
+
+def occurrence_counts(text: str | None, sites: int) -> list[int]:
+ spec = (text or ">0").replace(" ", "")
+ allowed: set[int] = set()
+ for part in spec.split(","):
+ if not part:
+ continue
+ m = re.fullmatch(r"(\d+)-(\d+)", part)
+ if m:
+ allowed.update(range(int(m.group(1)), int(m.group(2)) + 1))
+ continue
+ m = re.fullmatch(r"([<>])(\d+)", part)
+ if m:
+ n = int(m.group(2))
+ allowed.update(range(n + 1, sites + 1) if m.group(1) == ">" else range(0, n))
+ continue
+ if part.isdigit():
+ allowed.add(int(part))
+ continue
+ raise ValueError(f"occurrence {text} is not understood (use forms like 1, >0, 1-3 or 1,3)")
+ return sorted(c for c in allowed if 0 <= c <= sites)
+
+
+def _stub_link(a: dict, bonds: dict) -> str | None:
+ if a.get("element") != "*" or a.get("label") not in (None, "", "*") or a.get("generic"):
+ return None
+ links = [b for b in bonds.values() if a["id"] in (b["a"], b["b"])]
+ return (links[0]["b"] if links[0]["a"] == a["id"] else links[0]["a"]) if len(links) == 1 else None
+
+
+def member_attachments(member: dict, declared: list | None = None) -> tuple[list[str], set[str]]:
+ atoms = member.get("atoms") or {}
+ bonds = member.get("bonds") or {}
+ chosen = [a for a in declared if isinstance(a, str) and a in atoms] if isinstance(declared, list) else []
+ if chosen:
+ attach, stubs = [], set()
+ for aid in chosen:
+ nb = _stub_link(atoms[aid], bonds)
+ attach.append(nb or aid)
+ if nb:
+ stubs.add(aid)
+ return attach, stubs
+ marked = sorted((a for a in atoms.values() if isinstance(a.get("data"), dict) and a["data"].get("attach") in (1, 2)),
+ key=lambda a: a["data"]["attach"])
+ if marked:
+ return [a["id"] for a in marked], set()
+ stubs = []
+ for a in sorted(atoms.values(), key=lambda a: a["id"]):
+ nb = _stub_link(a, bonds)
+ if nb:
+ stubs.append((a["id"], nb))
+ if stubs:
+ return [n for _, n in stubs], {s for s, _ in stubs}
+ first = min(atoms) if atoms else None
+ return ([first] if first else []), set()
+
+
+def describe(frag: dict, members: dict[str, dict]) -> dict:
+ atoms = frag.get("atoms") or {}
+ bonds = frag.get("bonds") or {}
+ notes: list[dict] = []
+ sites: dict[int, list[str]] = {}
+ for aid in sorted(atoms):
+ a = atoms[aid]
+ if a.get("element") == "R#" and isinstance(a.get("rgroup"), int):
+ sites.setdefault(a["rgroup"], []).append(aid)
+ degree = sum(1 for b in bonds.values() if aid in (b["a"], b["b"]))
+ if degree != 1:
+ notes.append(warning("rgroup_bonds", f"R{a['rgroup']} has {degree} bonds; only single-bonded R-group atoms are enumerated.", [aid]))
+ defs = frag.get("rgroups") or {}
+ groups = []
+ for key in sorted(set(defs) | {str(n) for n in sites}, key=lambda k: int(k) if k.isdigit() else 999):
+ d = defs.get(key) if isinstance(defs.get(key), dict) else {}
+ n = int(key) if key.isdigit() else 0
+ rows = []
+ for mid in d.get("members") or []:
+ member = members.get(mid)
+ if not member or not member.get("atoms"):
+ notes.append(warning("rgroup_member_missing", f"R{key} names {mid}, which is not a fragment of this document."))
+ continue
+ declared = (d.get("attach") or {}).get(mid) if isinstance(d.get("attach"), dict) else None
+ attach, stubs = member_attachments(member, declared)
+ if not declared and not any(isinstance(a.get("data"), dict) and a["data"].get("attach") for a in member["atoms"].values()) and not stubs:
+ notes.append(warning("rgroup_attachment_guessed", f"Member {mid} of R{key} marks no attachment point; its first atom is used."))
+ rows.append({"object": mid, "attach": attach, "stubs": sorted(stubs)})
+ if n in sites and not rows:
+ notes.append(warning("rgroup_undefined", f"R{key} has no members.", sites[n]))
+ if key in defs and n not in sites:
+ notes.append(warning("rgroup_unused", f"R{key} is defined but no atom of the scaffold carries it."))
+ groups.append({"n": n, "sites": sites.get(n, []), "members": rows, "occurrence": d.get("occurrence") or ">0",
+ "rest_h": bool(d.get("rest_h")), "if_then": d.get("if_then") if isinstance(d.get("if_then"), int) else None})
+ return {"groups": groups, "warnings": notes}
+
+
+def _choices(group: dict) -> list[tuple]:
+ k = len(group["sites"])
+ m = len(group["members"])
+ counts = occurrence_counts(group["occurrence"], k)
+ if not group["rest_h"]:
+ counts = [k] if k in counts or not counts else []
+ out = []
+ for c in counts:
+ for chosen in itertools.combinations(range(k), c):
+ for picks in itertools.product(range(m), repeat=c):
+ row = [None] * k
+ for site, pick in zip(chosen, picks):
+ row[site] = pick
+ out.append(tuple(row))
+ return out
+
+
+def count(desc: dict) -> int:
+ total = 1
+ for g in desc["groups"]:
+ if not g["sites"]:
+ continue
+ k, m = len(g["sites"]), len(g["members"])
+ counts = occurrence_counts(g["occurrence"], k)
+ if not g["rest_h"]:
+ counts = [k] if k in counts or not counts else []
+ total *= sum(math.comb(k, c) * m ** c for c in counts)
+ return total
+
+
+def _member_mol(member: dict, row: dict, label: int, expansions: dict | None) -> Chem.Mol:
+ conv = perceive.prepare(member, expansions)
+ mol = Chem.RWMol(conv.mol)
+ attach = conv.index[row["attach"][0]]
+ for sid in row["stubs"]:
+ mol.GetAtomWithIdx(conv.index[sid]).SetAtomMapNum(0)
+ if row["stubs"]:
+ stub = conv.index[row["stubs"][0]]
+ mol.GetAtomWithIdx(stub).SetAtomMapNum(label)
+ for extra in sorted((conv.index[s] for s in row["stubs"][1:]), reverse=True):
+ mol.RemoveAtom(extra)
+ else:
+ d = Chem.Atom(0)
+ d.SetAtomMapNum(label)
+ j = mol.AddAtom(d)
+ mol.AddBond(attach, j, Chem.BondType.SINGLE)
+ for a in mol.GetAtoms():
+ if a.GetAtomicNum() and a.GetAtomMapNum():
+ a.SetAtomMapNum(0)
+ return mol.GetMol()
+
+
+def enumerate_structures(frag: dict, members: dict[str, dict], expansions: dict | None = None, limit: int = LIMIT, force: bool = False) -> dict:
+ desc = describe(frag, members)
+ notes = list(desc["warnings"])
+ groups = [g for g in desc["groups"] if g["sites"]]
+ if not groups:
+ raise ValueError("the fragment has no R-group atoms")
+ total = count(desc)
+ if total > HARD_LIMIT and not force:
+ raise ValueError(f"{total} structures: more than {HARD_LIMIT}; pass force to enumerate anyway")
+ conv = perceive.prepare(frag, expansions)
+ base = Chem.RWMol(conv.mol)
+ for a in base.GetAtoms():
+ a.SetAtomMapNum(0)
+ site_label = {}
+ for g in groups:
+ for aid in g["sites"]:
+ site_label[aid] = len(site_label) + 1
+ base.GetAtomWithIdx(conv.index[aid]).SetAtomMapNum(site_label[aid])
+ by_n = {g["n"]: g for g in groups}
+ out: list[dict] = []
+ seen: set[str] = set()
+ truncated = False
+ params = Chem.MolzipParams()
+ params.label = Chem.MolzipLabel.AtomMapNumber
+ for combo in itertools.product(*(_choices(g) for g in groups)):
+ if len(out) >= limit:
+ truncated = True
+ notes.append(warning("enumeration_truncated", f"Only the first {limit} of {total} structures are listed."))
+ break
+ filled = {g["n"]: any(c is not None for c in row) for g, row in zip(groups, combo)}
+ if any(filled[g["n"]] and g["if_then"] in by_n and not filled[g["if_then"]] for g in groups):
+ continue
+ mol = Chem.RWMol(base)
+ parts = Chem.Mol()
+ choice: dict[str, list] = {}
+ for g, row in zip(groups, combo):
+ choice[str(g["n"])] = []
+ for aid, pick in zip(g["sites"], row):
+ if pick is None:
+ mol.GetAtomWithIdx(conv.index[aid]).SetAtomicNum(1)
+ mol.GetAtomWithIdx(conv.index[aid]).SetAtomMapNum(0)
+ mol.GetAtomWithIdx(conv.index[aid]).SetIsotope(0)
+ choice[str(g["n"])].append("H")
+ continue
+ member = g["members"][pick]
+ parts = Chem.CombineMols(parts, _member_mol(members[member["object"]], member, site_label[aid], expansions))
+ choice[str(g["n"])].append(member["object"])
+ try:
+ joined = Chem.molzip(Chem.CombineMols(mol, parts), params) if parts.GetNumAtoms() else mol.GetMol()
+ joined = Chem.RemoveHs(joined, sanitize=False)
+ Chem.SanitizeMol(joined, catchErrors=True)
+ smiles = ids.smiles(ids.identifier_mol(joined))
+ except Exception as exc:
+ notes.append(warning("enumeration_failed", f"One combination could not be built: {exc}"))
+ continue
+ if smiles in seen:
+ continue
+ seen.add(smiles)
+ out.append({"smiles": smiles, "formula": ids.formula(joined), "choice": choice})
+ return {"count": total, "structures": out, "truncated": truncated, "warnings": notes}
diff --git a/backend/app/services/chem/perceive.py b/backend/app/services/chem/perceive.py
index abd1317b..b509c15c 100644
--- a/backend/app/services/chem/perceive.py
+++ b/backend/app/services/chem/perceive.py
@@ -106,7 +106,7 @@ def _valence(p: Perception, ignored: set[str]) -> None:
violated = a.HasValenceViolation()
except Exception:
violated = False
- if not violated and valence <= max(allowed):
+ if valence <= max(allowed) and not (violated and a.GetFormalCharge() == 0):
continue
aid = conv.owner[a.GetIdx()]
if aid in ignored:
@@ -131,6 +131,34 @@ def _rings(p: Perception) -> None:
p.warnings.append(warning("aromatic_outside_ring", "Aromatic bond outside a ring.", bonds=[conv.bond_id(b.GetIdx())]))
+def _cumulene(mol: Chem.Mol, start: Chem.Bond) -> list[int]:
+ def walk(bond: Chem.Bond, atom: int) -> list[int]:
+ out = []
+ while True:
+ a = mol.GetAtomWithIdx(atom)
+ nxt = [x for x in a.GetBonds() if x.GetIdx() != bond.GetIdx() and x.GetBondType() == Chem.BondType.DOUBLE]
+ if len(nxt) != 1 or a.GetDegree() != 2 or nxt[0].GetIdx() in out:
+ return out
+ bond = nxt[0]
+ out.append(bond.GetIdx())
+ atom = bond.GetOtherAtomIdx(atom)
+ return walk(start, start.GetBeginAtomIdx())[::-1] + [start.GetIdx()] + walk(start, start.GetEndAtomIdx())
+
+
+def not_ez_bonds(mol: Chem.Mol) -> set[int]:
+ skip: set[int] = set()
+ seen: set[int] = set()
+ for b in mol.GetBonds():
+ if b.GetIdx() in seen or b.GetBondType() != Chem.BondType.DOUBLE:
+ continue
+ chain = _cumulene(mol, b)
+ seen.update(chain)
+ if len(chain) > 1:
+ keep = chain[len(chain) // 2] if len(chain) % 2 else None
+ skip.update(i for i in chain if i != keep)
+ return skip
+
+
def _cip(p: Perception) -> None:
conv = p.conv
mol = conv.mol
@@ -147,13 +175,22 @@ def _cip(p: Perception) -> None:
if bid and b.HasProp("_CIPCode"):
p.cip[bid] = b.GetProp("_CIPCode")
try:
- undefined = [conv.owner[si.centeredOn] for si in Chem.FindPotentialStereo(mol)
- if si.type == Chem.StereoType.Atom_Tetrahedral and si.specified == Chem.StereoSpecified.Unspecified
- and conv.drawn[si.centeredOn]]
+ found = list(Chem.FindPotentialStereo(mol))
except Exception:
- undefined = []
+ found = []
+ centres = [si for si in found if si.type == Chem.StereoType.Atom_Tetrahedral and conv.drawn[si.centeredOn]]
+ undefined = [conv.owner[si.centeredOn] for si in centres if si.specified == Chem.StereoSpecified.Unspecified]
+ unknown = [conv.owner[si.centeredOn] for si in centres if si.specified == Chem.StereoSpecified.Unknown]
+ marked = {b for w in conv.warnings if w.get("code") == "unknown_ez" for b in w.get("bonds", [])}
+ cumulated = not_ez_bonds(mol)
+ loose = [conv.bond_id(si.centeredOn) for si in found if si.type == Chem.StereoType.Bond_Double and si.centeredOn not in cumulated
+ and si.specified != Chem.StereoSpecified.Specified and conv.bond_id(si.centeredOn) and conv.bond_id(si.centeredOn) not in marked]
if undefined:
p.warnings.append(warning("undefined_stereocentre", f"{len(undefined)} stereocentre(s) without a configuration.", undefined))
+ if unknown:
+ p.warnings.append(warning("stereo_unknown", f"{len(unknown)} stereocentre(s) marked unknown with a wavy bond.", unknown))
+ if loose:
+ p.warnings.append(warning("undefined_double_bond", "Stereogenic double bond drawn without a clear E or Z geometry (a substituent lies on the bond's line).", bonds=loose))
def _geometry(p: Perception, frag: dict) -> None:
diff --git a/backend/app/services/chem/props.py b/backend/app/services/chem/props.py
new file mode 100644
index 00000000..d1ca05b8
--- /dev/null
+++ b/backend/app/services/chem/props.py
@@ -0,0 +1,99 @@
+from rdkit import Chem
+from rdkit.Chem import Crippen, rdMolDescriptors
+
+from app.services.chem import ENGINE, ids, mass, perceive, warning
+
+ROWS = (
+ ("formula", "Formula", "", "ids.formula (Hill order)", "Hill order with charge"),
+ ("mw", "Molecular weight", "g/mol", "mass.average_mass (RDKit periodic table)", "standard atomic weights"),
+ ("exact_mass", "Exact mass", "Da", "mass.exact_mass (most abundant isotopes)", "monoisotopic, electron mass removed per charge"),
+ ("clogp", "cLogP", "", "Crippen.MolLogP", "Wildman and Crippen 1999 atom contributions; typical error 0.5 to 0.7 log units"),
+ ("mr", "Molar refractivity", "cm3/mol", "Crippen.MolMR", "Wildman and Crippen 1999 atom contributions"),
+ ("tpsa", "TPSA", "A2", "rdMolDescriptors.CalcTPSA", "Ertl 2000 fragment contributions, N and O only"),
+ ("tpsa_sp", "TPSA with S and P", "A2", "rdMolDescriptors.CalcTPSA(includeSandP=True)", "Ertl 2000 with S and P contributions"),
+ ("hbd", "H-bond donors", "", "rdMolDescriptors.CalcNumLipinskiHBD", "Lipinski: N-H and O-H"),
+ ("hba", "H-bond acceptors", "", "rdMolDescriptors.CalcNumLipinskiHBA", "Lipinski: every N and O"),
+ ("hbd_refined", "H-bond donors (refined)", "", "rdMolDescriptors.CalcNumHBD", "pattern rules"),
+ ("hba_refined", "H-bond acceptors (refined)", "", "rdMolDescriptors.CalcNumHBA", "pattern rules, no amide N or nitro O"),
+ ("rotatable_bonds", "Rotatable bonds", "", "rdMolDescriptors.CalcNumRotatableBonds", "strict: no amide C-N, no bonds to triple-bonded atoms"),
+ ("heavy_atoms", "Heavy atoms", "", "Mol.GetNumHeavyAtoms", "atoms other than hydrogen"),
+ ("rings", "Rings", "", "rdMolDescriptors.CalcNumRings", "smallest set of smallest rings"),
+ ("aromatic_rings", "Aromatic rings", "", "rdMolDescriptors.CalcNumAromaticRings", "RDKit aromaticity model"),
+ ("fraction_csp3", "Fraction Csp3", "", "rdMolDescriptors.CalcFractionCSP3", "sp3 carbons over all carbons"),
+ ("formal_charge", "Formal charge", "", "Chem.GetFormalCharge", "sum of formal charges"),
+ ("stereocentres", "Stereocentres", "", "Chem.FindPotentialStereo", "tetrahedral centres, defined and undefined"),
+ ("undefined_stereocentres", "Undefined stereocentres", "", "Chem.FindPotentialStereo", "centres without a configuration"),
+ ("pieces", "Pieces", "", "Chem.GetMolFrags", "disconnected components"),
+)
+LIPINSKI = (("mw", 500.0), ("clogp", 5.0), ("hbd", 5), ("hba", 10))
+VEBER = (("rotatable_bonds", 10), ("tpsa", 140.0))
+ROUND = {"mw": 2, "exact_mass": 4, "clogp": 2, "mr": 2, "tpsa": 2, "tpsa_sp": 2, "fraction_csp3": 3}
+
+
+def _rule(values: dict, rules: tuple, name: str, method: str) -> dict:
+ rows = [{"key": k, "value": values.get(k), "limit": limit, "ok": values.get(k) is not None and values[k] <= limit} for k, limit in rules]
+ bad = sum(1 for r in rows if not r["ok"])
+ return {"name": name, "method": method, "rules": rows, "violations": bad, "pass": bad <= (1 if name == "Lipinski" else 0)}
+
+
+def _stereo_counts(mol: Chem.Mol, conv) -> tuple[int, int]:
+ try:
+ found = [si for si in Chem.FindPotentialStereo(mol) if si.type == Chem.StereoType.Atom_Tetrahedral]
+ except Exception:
+ return 0, 0
+ return len(found), sum(1 for si in found if si.specified != Chem.StereoSpecified.Specified)
+
+
+def compute(frag: dict, expansions: dict | None = None) -> dict:
+ conv = perceive.prepare(frag, expansions)
+ mol = ids.identifier_mol(conv.mol)
+ Chem.SanitizeMol(mol, Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_PROPERTIES, catchErrors=True)
+ mol.UpdatePropertyCache(strict=False)
+ Chem.GetSymmSSSR(mol)
+ notes = [w for w in conv.warnings if w.get("code") in ("unknown_label", "abbreviation_bonds", "bad_expansion")]
+ excluded = sorted({conv.owner[a.GetIdx()] for a in conv.mol.GetAtoms() if a.GetAtomicNum() == 0})
+ if excluded:
+ notes.append(warning("incomplete", f"{len(excluded)} label(s) or R-group(s) are not counted; descriptors treat them as dummy atoms.", excluded))
+ values: dict = {
+ "formula": ids.formula(conv.mol),
+ "mw": mass.average_mass(conv.mol),
+ "exact_mass": mass.exact_mass(conv.mol),
+ "formal_charge": Chem.GetFormalCharge(mol),
+ "heavy_atoms": mol.GetNumHeavyAtoms(),
+ "pieces": len(Chem.GetMolFrags(mol, sanitizeFrags=False)),
+ }
+ calls = {
+ "clogp": lambda: Crippen.MolLogP(mol),
+ "mr": lambda: Crippen.MolMR(mol),
+ "tpsa": lambda: rdMolDescriptors.CalcTPSA(mol),
+ "tpsa_sp": lambda: rdMolDescriptors.CalcTPSA(mol, includeSandP=True),
+ "hbd": lambda: rdMolDescriptors.CalcNumLipinskiHBD(mol),
+ "hba": lambda: rdMolDescriptors.CalcNumLipinskiHBA(mol),
+ "hbd_refined": lambda: rdMolDescriptors.CalcNumHBD(mol),
+ "hba_refined": lambda: rdMolDescriptors.CalcNumHBA(mol),
+ "rotatable_bonds": lambda: rdMolDescriptors.CalcNumRotatableBonds(mol, rdMolDescriptors.NumRotatableBondsOptions.Strict),
+ "rings": lambda: rdMolDescriptors.CalcNumRings(mol),
+ "aromatic_rings": lambda: rdMolDescriptors.CalcNumAromaticRings(mol),
+ "fraction_csp3": lambda: rdMolDescriptors.CalcFractionCSP3(mol),
+ }
+ for key, fn in calls.items():
+ try:
+ values[key] = fn()
+ except Exception as exc:
+ values[key] = None
+ notes.append(warning("property_failed", f"{key} could not be computed: {exc}"))
+ values["stereocentres"], values["undefined_stereocentres"] = _stereo_counts(conv.mol, conv)
+ for key, digits in ROUND.items():
+ if isinstance(values.get(key), float):
+ values[key] = round(values[key], digits)
+ rows = [{"key": k, "label": label, "value": values.get(k), "unit": unit, "method": method, "note": note} for k, label, unit, method, note in ROWS]
+ return {
+ "rows": rows,
+ "values": values,
+ "lipinski": _rule(values, LIPINSKI, "Lipinski", "Lipinski rule of five: MW <= 500, cLogP <= 5, HBD <= 5, HBA <= 10; one violation allowed"),
+ "veber": _rule(values, VEBER, "Veber", "Veber: rotatable bonds <= 10, TPSA <= 140"),
+ "elemental_analysis": mass.elemental_analysis(conv.mol),
+ "excluded": excluded,
+ "engine": ENGINE,
+ "warnings": notes,
+ }
diff --git a/backend/app/services/chem/query.py b/backend/app/services/chem/query.py
new file mode 100644
index 00000000..e863d2ac
--- /dev/null
+++ b/backend/app/services/chem/query.py
@@ -0,0 +1,340 @@
+import re
+
+from rdkit import Chem
+from rdkit.Chem import rdDepictor
+
+from app.services.chem import DEFAULT_BOND_LENGTH, convert, perceive, warning
+from app.services.model import ELEMENTS, new_id
+
+BT = Chem.BondType
+NONMETALS = frozenset({1, 2, 5, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18, 32, 33, 34, 35, 36, 51, 52, 53, 54, 85, 86, 117, 118})
+METALS = ",".join(f"#{z}" for z in range(1, 119) if z not in NONMETALS)
+HALOGENS = "#9,#17,#35,#53,#85"
+GENERIC_SMARTS = {
+ "A": "!#1", "AH": "*", "Q": "!#6&!#1", "QH": "!#6", "X": HALOGENS, "XH": f"{HALOGENS},#1", "M": METALS, "MH": f"{METALS},#1",
+}
+LABEL_SMARTS = {"Hal": HALOGENS, "X": HALOGENS, "Ar": "a", "Alk": "C", "Het": "!#6&!#1", "M": METALS, "R": "*", "G": "*"}
+BOND_QUERY_SMARTS = {"any": "~", "single_or_double": "-,=", "single_or_aromatic": "-,:", "double_or_aromatic": "=,:"}
+BOND_SMARTS = {BT.SINGLE: "-", BT.DOUBLE: "=", BT.TRIPLE: "#", BT.AROMATIC: ":", BT.QUADRUPLE: "$"}
+UNSATURATED = "$(*=,#,:*)"
+QUERY_KEYS = ("list", "not", "generic", "ring_bonds", "subst", "unsat", "h_min", "aromatic", "smarts")
+
+
+def is_query_atom(a: dict) -> bool:
+ q = a.get("query")
+ return isinstance(q, dict) and any(k in q for k in QUERY_KEYS)
+
+
+def is_query_bond(b: dict) -> bool:
+ return bool(b.get("query") or b.get("topology"))
+
+
+def has_query(frag: dict) -> bool:
+ return any(is_query_atom(a) for a in (frag.get("atoms") or {}).values()) or any(is_query_bond(b) for b in (frag.get("bonds") or {}).values())
+
+
+def _number(symbol: str) -> str | None:
+ return f"#{ELEMENTS.index(symbol) + 1}" if symbol in ELEMENTS else None
+
+
+def _or(terms: list[str]) -> str:
+ return ",".join(terms)
+
+
+def _ring_bonds(frag: dict, aid: str, ring_bonds: set[str]) -> int:
+ return sum(1 for k, b in (frag.get("bonds") or {}).items() if k in ring_bonds and aid in (b["a"], b["b"]))
+
+
+def _degree(frag: dict, aid: str) -> int:
+ atoms = frag.get("atoms") or {}
+ return sum(1 for b in (frag.get("bonds") or {}).values() if aid in (b["a"], b["b"])
+ and atoms.get(b["b"] if b["a"] == aid else b["a"], {}).get("element") != "H")
+
+
+def atom_smarts(a: dict, frag: dict, ring_bonds: set[str], notes: list[dict]) -> str:
+ q = a.get("query") if isinstance(a.get("query"), dict) else {}
+ el = a.get("element", "C")
+ if isinstance(q.get("smarts"), str) and q["smarts"].strip():
+ raw = q["smarts"].strip()
+ return raw[1:-1] if raw.startswith("[") and raw.endswith("]") else raw
+ terms: list[str] = []
+ listed = [n for n in (_number(s) for s in q.get("list") or []) if n]
+ if listed:
+ terms.append("&".join(f"!{n}" for n in listed) if q.get("not") else _or(listed))
+ elif q.get("generic") in GENERIC_SMARTS:
+ terms.append(GENERIC_SMARTS[q["generic"]])
+ elif el == "R#":
+ terms.append("*")
+ elif el == "*":
+ label = a.get("generic") or a.get("label") or ""
+ terms.append(LABEL_SMARTS.get(label, "*"))
+ if label and label not in LABEL_SMARTS:
+ notes.append(warning("smarts_any_atom", f"The label {label} is written as any atom.", [a["id"]]))
+ else:
+ iso = a.get("isotope")
+ terms.append(f"{iso}{_number(el)}" if iso else _number(el) or "*")
+ if q.get("aromatic") is True:
+ terms.append("a")
+ elif q.get("aromatic") is False:
+ terms.append("A")
+ charge = a.get("charge") or 0
+ if charge:
+ terms.append(f"{'+' if charge > 0 else '-'}{abs(charge)}")
+ rb = q.get("ring_bonds")
+ if isinstance(rb, int) and not isinstance(rb, bool):
+ n = _ring_bonds(frag, a["id"], ring_bonds) if rb == -2 else rb
+ terms.append(f"x{n}" if n < 4 else "x4,x5,x6")
+ sub = q.get("subst")
+ if isinstance(sub, int) and not isinstance(sub, bool):
+ n = _degree(frag, a["id"]) if sub == -2 else sub
+ terms.append(f"D{n}" if n < 6 else "D6,D7,D8")
+ if q.get("unsat"):
+ terms.append(UNSATURATED)
+ h = q.get("h_min")
+ if isinstance(h, int) and not isinstance(h, bool) and h > 0:
+ terms.extend(f"!H{i}" for i in range(h))
+ return ";".join(t for t in terms if t) if len(terms) > 1 else terms[0]
+
+
+def bond_smarts(b: dict | None, rb: Chem.Bond) -> str:
+ q = (b or {}).get("query")
+ base = BOND_QUERY_SMARTS.get(q) or BOND_SMARTS.get(rb.GetBondType(), "~")
+ if rb.GetIsAromatic() and not q:
+ base = ":"
+ topo = (b or {}).get("topology")
+ if topo == "ring":
+ return "@" if base == "~" else f"{base};@"
+ if topo == "chain":
+ return "!@" if base == "~" else f"{base};!@"
+ return base
+
+
+def query_mol(frag: dict, expansions: dict | None = None) -> tuple[Chem.Mol, convert.Conversion, list[dict]]:
+ conv = perceive.prepare(frag, expansions)
+ notes: list[dict] = []
+ mol = conv.mol
+ atoms = frag.get("atoms") or {}
+ bonds = frag.get("bonds") or {}
+ ring_bonds = {conv.bond_id(b.GetIdx()) for b in mol.GetBonds() if conv.bond_id(b.GetIdx()) and mol.GetRingInfo().NumBondRings(b.GetIdx())}
+ qm = Chem.RWMol()
+ for a in mol.GetAtoms():
+ i = a.GetIdx()
+ if conv.drawn[i]:
+ text = atom_smarts(atoms[conv.owner[i]], frag, ring_bonds, notes)
+ else:
+ text = f"#{a.GetAtomicNum()}" + (";a" if a.GetIsAromatic() else "")
+ qa = Chem.AtomFromSmarts(f"[{text}]")
+ if qa is None:
+ notes.append(warning("bad_smarts", f"The query on this atom ({text}) is not valid SMARTS; it matches any atom.", [conv.owner[i]]))
+ qa = Chem.AtomFromSmarts("[*]")
+ qa.SetChiralTag(a.GetChiralTag())
+ qa.SetProp(convert.OWNER_PROP, conv.owner[i])
+ qm.AddAtom(qa)
+ for b in mol.GetBonds():
+ bid = conv.bond_id(b.GetIdx())
+ qm.AddBond(b.GetBeginAtomIdx(), b.GetEndAtomIdx(), BT.UNSPECIFIED)
+ qb = Chem.BondFromSmarts(bond_smarts(bonds.get(bid) if bid else None, b))
+ qm.ReplaceBond(qm.GetNumBonds() - 1, qb)
+ if any(a.GetAtomicNum() == 1 for a in mol.GetAtoms()):
+ try:
+ qm = Chem.RWMol(Chem.MergeQueryHs(qm))
+ except Exception:
+ notes.append(warning("explicit_h", "Explicit hydrogens in the query could not be folded into hydrogen counts."))
+ return qm.GetMol(), conv, notes
+
+
+def to_smarts(frag: dict, expansions: dict | None = None, atoms: list[str] | None = None) -> tuple[str, list[dict]]:
+ if atoms is not None:
+ keep = {a for a in atoms if a in (frag.get("atoms") or {})}
+ if not keep:
+ raise ValueError("none of the chosen atoms is in the fragment")
+ frag = {**frag, "atoms": {k: v for k, v in frag["atoms"].items() if k in keep},
+ "bonds": {k: b for k, b in (frag.get("bonds") or {}).items() if b["a"] in keep and b["b"] in keep}}
+ qm, conv, notes = query_mol(frag, expansions)
+ if conv.expanded:
+ notes.append(warning("abbreviations_expanded", "Abbreviations are written as their full structures."))
+ if frag.get("rgroups"):
+ notes.append(warning("smarts_rgroups", "SMARTS cannot hold R-group definitions or their logic; R-groups are written as any atom."))
+ if frag.get("stereo_groups"):
+ notes.append(warning("smarts_stereo_groups", "SMARTS cannot hold enhanced stereo groups."))
+ return Chem.MolToSmarts(qm), notes
+
+
+PRIMITIVE_LETTERS = {"A", "D", "H", "R", "X"}
+AROMATIC_SYMBOLS = {"c": "C", "n": "N", "o": "O", "s": "S", "p": "P", "b": "B", "se": "Se", "as": "As", "te": "Te"}
+GENERIC_BY_SMARTS = {v: k for k, v in GENERIC_SMARTS.items()}
+BOND_FROM_SMARTS = {"-": (1, None), "=": (2, None), "#": (3, None), ":": (1.5, None), "$": (4, None), "~": (1, "any"), "": (1, "single_or_aromatic"),
+ "-,=": (1, "single_or_double"), "=,-": (1, "single_or_double"), "-,:": (1, "single_or_aromatic"), ":,-": (1, "single_or_aromatic"),
+ "=,:": (2, "double_or_aromatic"), ":,=": (2, "double_or_aromatic")}
+_ISOTOPE = re.compile(r"^(\d+)(.*)$")
+_CHARGE = re.compile(r"^([+-])(\d*)$|^(\+\++|--+)$")
+
+
+def _element(prim: str) -> tuple[str, bool | None] | None:
+ m = re.fullmatch(r"#(\d+)", prim)
+ if m:
+ z = int(m.group(1))
+ return (ELEMENTS[z - 1], None) if 1 <= z <= len(ELEMENTS) else None
+ if prim in AROMATIC_SYMBOLS:
+ return AROMATIC_SYMBOLS[prim], True
+ if prim in ELEMENTS and prim not in PRIMITIVE_LETTERS:
+ return prim, False
+ return None
+
+
+def parse_atom_smarts(text: str) -> dict | None:
+ body = text[1:-1] if text.startswith("[") and text.endswith("]") else text
+ out: dict = {"query": {}}
+ m = re.fullmatch(r"(.*):(\d+)", body)
+ if m:
+ body, out["map"] = m.group(1), int(m.group(2))
+ if body in GENERIC_BY_SMARTS:
+ out["element"] = "*"
+ out["query"]["generic"] = GENERIC_BY_SMARTS[body]
+ return out
+ if body == "*":
+ out["element"] = "*"
+ out["query"]["generic"] = "AH"
+ return out
+ h_not: list[int] = []
+ nots: list[str] = []
+ for term in re.split(r"[&;]", body):
+ if not term:
+ return None
+ if term == "$(*=,#,:*)":
+ out["query"]["unsat"] = True
+ continue
+ if "," in term:
+ alts = term.split(",")
+ els = [_element(a) for a in alts]
+ if all(els) and "element" not in out and "list" not in out["query"]:
+ out["query"]["list"] = [e[0] for e in els]
+ out["element"] = "*"
+ continue
+ if alts in (["x4", "x5", "x6"],):
+ out["query"]["ring_bonds"] = 4
+ continue
+ if alts == ["D6", "D7", "D8"]:
+ out["query"]["subst"] = 6
+ continue
+ return None
+ iso = _ISOTOPE.match(term)
+ if iso and iso.group(2) in ("*", "") or iso and _element(iso.group(2)):
+ out["isotope"] = int(iso.group(1))
+ term = iso.group(2)
+ if term in ("*", ""):
+ continue
+ el = _element(term)
+ if el and "element" not in out:
+ out["element"] = el[0]
+ if el[1] is not None:
+ out["query"]["aromatic"] = el[1]
+ continue
+ neg = re.fullmatch(r"!(#\d+|[A-Z][a-z]?)", term)
+ if neg and _element(neg.group(1)):
+ nots.append(_element(neg.group(1))[0])
+ continue
+ hm = re.fullmatch(r"!H(\d)", term)
+ if hm:
+ h_not.append(int(hm.group(1)))
+ continue
+ ch = _CHARGE.fullmatch(term)
+ if ch:
+ if ch.group(3):
+ out["charge"] = len(ch.group(3)) * (1 if ch.group(3)[0] == "+" else -1)
+ else:
+ out["charge"] = int(ch.group(2) or 1) * (1 if ch.group(1) == "+" else -1)
+ continue
+ for pattern, key in ((r"x(\d)", "ring_bonds"), (r"D(\d)", "subst")):
+ pm = re.fullmatch(pattern, term)
+ if pm:
+ out["query"][key] = int(pm.group(1))
+ break
+ else:
+ if term == "R0":
+ out["query"]["ring_bonds"] = 0
+ elif term in ("a", "A") and "aromatic" not in out["query"]:
+ out["query"]["aromatic"] = term == "a"
+ else:
+ return None
+ if nots:
+ if "element" in out or "list" in out["query"]:
+ return None
+ out["element"] = "*"
+ out["query"]["list"] = nots
+ out["query"]["not"] = True
+ if h_not:
+ if sorted(h_not) != list(range(len(h_not))):
+ return None
+ out["query"]["h_min"] = len(h_not)
+ out.setdefault("element", "*")
+ return out
+
+
+def from_smarts(text: str, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0)) -> tuple[dict, list[dict]]:
+ mol = Chem.MolFromSmarts(text.strip())
+ if mol is None:
+ raise ValueError("not valid SMARTS")
+ notes: list[dict] = []
+ try:
+ mol.UpdatePropertyCache(strict=False)
+ Chem.FastFindRings(mol)
+ except Exception:
+ pass
+ rdDepictor.Compute2DCoords(mol)
+ pts = convert._page_coords(mol, bond_length)
+ if pts:
+ dx, dy = origin[0] - min(p[0] for p in pts), origin[1] - min(p[1] for p in pts)
+ pts = [(round(x + dx, 3), round(y + dy, 3)) for x, y in pts]
+ used: set[str] = set()
+
+ def fresh(prefix: str) -> str:
+ while True:
+ i = new_id(prefix)
+ if i not in used:
+ used.add(i)
+ return i
+
+ frag: dict = {"id": fresh("f"), "kind": "fragment", "atoms": {}, "bonds": {}}
+ ids: list[str] = []
+ opaque: list[str] = []
+ for a in mol.GetAtoms():
+ aid = fresh("a")
+ ids.append(aid)
+ x, y = pts[a.GetIdx()]
+ found = parse_atom_smarts(a.GetSmarts())
+ if found is None:
+ z = a.GetAtomicNum()
+ rec = {"id": aid, "element": ELEMENTS[z - 1] if 0 < z <= len(ELEMENTS) else "*", "x": x, "y": y, "query": {"smarts": a.GetSmarts()}}
+ opaque.append(aid)
+ else:
+ rec = {"id": aid, "x": x, "y": y, **found}
+ if not rec["query"]:
+ del rec["query"]
+ if a.GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED:
+ notes.append(warning("smarts_chirality", "Chirality in the SMARTS is not drawn; set it with wedges.", [aid]))
+ frag["atoms"][aid] = rec
+ if opaque:
+ notes.append(warning("smarts_opaque", "These atoms keep their SMARTS text as an opaque query.", opaque))
+ for b in mol.GetBonds():
+ bid = fresh("b")
+ text_b = b.GetSmarts()
+ topo = None
+ base = text_b
+ for suffix, kind in ((";!@", "chain"), ("&!@", "chain"), (";@", "ring"), ("&@", "ring")):
+ if text_b.endswith(suffix):
+ base, topo = text_b[: -len(suffix)], kind
+ break
+ else:
+ if text_b in ("@", "!@"):
+ base, topo = "~", "ring" if text_b == "@" else "chain"
+ order, q = BOND_FROM_SMARTS.get(base, (1, None))
+ if base not in BOND_FROM_SMARTS:
+ notes.append(warning("smarts_bond_simplified", f"The bond query {text_b} is read as a single bond.", bonds=[bid]))
+ rec = {"id": bid, "a": ids[b.GetBeginAtomIdx()], "b": ids[b.GetEndAtomIdx()], "order": order}
+ if q:
+ rec["query"] = q
+ if topo:
+ rec["topology"] = topo
+ frag["bonds"][bid] = rec
+ return frag, notes
diff --git a/backend/app/services/chem/reactions.py b/backend/app/services/chem/reactions.py
new file mode 100644
index 00000000..4f21a197
--- /dev/null
+++ b/backend/app/services/chem/reactions.py
@@ -0,0 +1,356 @@
+import copy
+
+from app.services import model
+from app.services.chem import geometry
+
+REACTION_ARROWS = ("forward", "equilibrium", "equilibrium_unbalanced", "reversible", "retro", "nogo_cross", "nogo_slash", "dashed")
+ROLE_KEYS = ("reactants", "products", "agents", "conditions")
+BAND_BONDS = 1.5
+ROW_BONDS = 2.5
+JOIN_BONDS = 1.0
+END_BONDS = 0.5
+
+
+class ReactionError(ValueError):
+ status = 422
+
+
+class NotFound(ReactionError):
+ status = 404
+
+
+def bond_length(doc: dict) -> float:
+ return float(model.resolve_style(doc).get("bond_length") or 14.4)
+
+
+def page_of(doc: dict, page_id: str | None = None) -> dict:
+ pages = [p for p in doc.get("pages") or [] if isinstance(p, dict)]
+ if not pages:
+ raise NotFound("The drawing has no pages.")
+ if page_id is None:
+ return pages[0]
+ for p in pages:
+ if p.get("id") == page_id:
+ return p
+ raise NotFound(f"The drawing has no page {page_id}.")
+
+
+def used_ids(doc: dict) -> set[str]:
+ out: set[str] = set()
+ stack: list = [doc]
+ while stack:
+ node = stack.pop()
+ if isinstance(node, dict):
+ if isinstance(node.get("id"), str):
+ out.add(node["id"])
+ stack.extend(node.values())
+ elif isinstance(node, list):
+ stack.extend(node)
+ return out
+
+
+def fresh_id(used: set[str], prefix: str) -> str:
+ while True:
+ found = model.new_id(prefix)
+ if found not in used:
+ used.add(found)
+ return found
+
+
+def is_reaction_arrow(obj: object) -> bool:
+ return isinstance(obj, dict) and obj.get("kind") == "arrow" and (obj.get("type") or "forward") in REACTION_ARROWS and geometry.arrow_points(obj) is not None
+
+
+def direction(obj: dict) -> tuple[tuple[float, float], tuple[float, float]]:
+ tail, head = geometry.arrow_points(obj)
+ if obj.get("head") == "none" and obj.get("tail") not in (None, "none"):
+ return head, tail
+ return tail, head
+
+
+def _role_kind(doc: dict, oid: str) -> str | None:
+ obj = (doc.get("objects") or {}).get(oid)
+ if not isinstance(obj, dict):
+ return None
+ kind = obj.get("kind")
+ if kind == "fragment" and obj.get("atoms"):
+ return "structure"
+ if kind == "group" and geometry.has_fragment(doc, oid):
+ return "structure"
+ if kind == "text":
+ return "formula" if obj.get("formula") else "text"
+ return None
+
+
+class _Item:
+ def __init__(self, oid: str, role: str | None, plus: bool, span: tuple[float, float, float, float]):
+ self.oid = oid
+ self.role = role
+ self.plus = plus
+ self.s0, self.s1, self.t0, self.t1 = span
+
+ @property
+ def s(self) -> float:
+ return (self.s0 + self.s1) / 2
+
+ def gap(self) -> float:
+ return 0.0 if self.t0 <= 0 <= self.t1 else min(abs(self.t0), abs(self.t1))
+
+
+def _items(doc: dict, page: dict, arrow_id: str, frame: geometry.Frame, style: dict) -> list[_Item]:
+ out = []
+ for oid in page.get("order") or []:
+ if oid == arrow_id or not isinstance(oid, str):
+ continue
+ obj = (doc.get("objects") or {}).get(oid)
+ if not isinstance(obj, dict) or obj.get("hidden"):
+ continue
+ box = geometry.object_box(doc, oid, style)
+ if box is None:
+ continue
+ out.append(_Item(oid, _role_kind(doc, oid), obj.get("kind") == "plus", frame.project(box)))
+ return out
+
+
+def _walk(items: list[_Item], forward: bool, bl: float) -> list[str]:
+ pluses = [i for i in items if i.plus]
+ chosen: list[_Item] = []
+ candidates = sorted((i for i in items if i.role in ("structure", "formula")), key=lambda i: i.s0 if forward else -i.s1)
+ for item in candidates:
+ if not chosen:
+ chosen.append(item)
+ continue
+ last = chosen[-1]
+ lo, hi = (last.s1, item.s0) if forward else (item.s1, last.s0)
+ joined = hi - lo <= JOIN_BONDS * bl or any(lo - END_BONDS * bl <= p.s <= hi + END_BONDS * bl for p in pluses)
+ if not joined:
+ break
+ chosen.append(item)
+ if not forward:
+ chosen.reverse()
+ return [i.oid for i in chosen]
+
+
+def infer_step(doc: dict, page: dict, arrow_id: str, used: set[str] | None = None) -> dict | None:
+ arrow = (doc.get("objects") or {}).get(arrow_id)
+ if not is_reaction_arrow(arrow):
+ return None
+ style = model.resolve_style(doc)
+ bl = bond_length(doc)
+ tail, head = direction(arrow)
+ frame = geometry.Frame(tail, head)
+ if frame.length <= 0:
+ return None
+ items = _items(doc, page, arrow_id, frame, style)
+ agents, conditions = [], []
+ for i in items:
+ if i.role is None or not 0 <= i.s <= frame.length or i.gap() > BAND_BONDS * bl:
+ continue
+ (conditions if i.role == "text" else agents).append(i)
+ taken = {i.oid for i in agents + conditions}
+ row = [i for i in items if i.oid not in taken and i.t1 >= -ROW_BONDS * bl and i.t0 <= ROW_BONDS * bl]
+ tol = END_BONDS * bl
+ before = _walk([i for i in row if i.s1 <= tol or i.plus], False, bl)
+ after = _walk([i for i in row if i.s0 >= frame.length - tol or i.plus], True, bl)
+ if not before and not after:
+ return None
+ if arrow.get("type") == "retro":
+ before, after = after, before
+ order = lambda i: (i.t0, i.s0)
+ return {
+ "id": fresh_id(used if used is not None else used_ids(doc), "r"),
+ "arrow": arrow_id,
+ "reactants": before,
+ "products": after,
+ "agents": [i.oid for i in sorted(agents, key=order)],
+ "conditions": [i.oid for i in sorted(conditions, key=order)],
+ "explicit": False,
+ }
+
+
+def role_ids(step: dict) -> set[str]:
+ return {i for key in ("reactants", "products", "agents") for i in step.get(key) or [] if isinstance(i, str)}
+
+
+def _keep_extras(step: dict, old: dict) -> dict:
+ roles = role_ids(step)
+ out = dict(step, id=old["id"])
+ for key, value in old.items():
+ if key in ("id", "arrow", "explicit") or key in ROLE_KEYS:
+ continue
+ if key == "coefficients" and isinstance(value, dict):
+ kept = {k: v for k, v in value.items() if k in roles}
+ if kept:
+ out[key] = kept
+ elif key == "stoich" and isinstance(value, dict):
+ st = copy.deepcopy(value)
+ comps = st.get("components") if isinstance(st.get("components"), dict) else {}
+ st["components"] = {k: v for k, v in comps.items() if k in roles}
+ for ref in ("limiting", "product"):
+ if ref in st and st[ref] not in roles:
+ st.pop(ref)
+ out[key] = st
+ else:
+ out[key] = copy.deepcopy(value)
+ return out
+
+
+def _arrow_key(doc: dict, step: dict) -> tuple[float, float]:
+ arrow = (doc.get("objects") or {}).get(step.get("arrow"))
+ ends = geometry.arrow_points(arrow) if isinstance(arrow, dict) else None
+ if ends is None:
+ return (float("inf"), float("inf"))
+ (x1, y1), (x2, y2) = ends
+ return (round(min(y1, y2), 1), min(x1, x2))
+
+
+def _chains(doc: dict, steps: list[dict]) -> list[list[dict]]:
+ n = len(steps)
+ parent = list(range(n))
+
+ def find(i: int) -> int:
+ while parent[i] != i:
+ parent[i] = parent[parent[i]]
+ i = parent[i]
+ return i
+
+ feeds = [[j for j in range(n) if j != i and set(steps[i].get("products") or []) & set(steps[j].get("reactants") or [])] for i in range(n)]
+ for i in range(n):
+ for j in feeds[i]:
+ parent[find(i)] = find(j)
+ depth = [0] * n
+ for _ in range(n):
+ moved = False
+ for i in range(n):
+ for j in feeds[i]:
+ if depth[j] < depth[i] + 1 and depth[i] < n:
+ depth[j] = depth[i] + 1
+ moved = True
+ if not moved:
+ break
+ groups: dict[int, list[int]] = {}
+ for i in range(n):
+ groups.setdefault(find(i), []).append(i)
+ ordered = [sorted(g, key=lambda i: (depth[i], _arrow_key(doc, steps[i]))) for g in groups.values()]
+ ordered.sort(key=lambda g: _arrow_key(doc, steps[g[0]]))
+ return [[steps[i] for i in g] for g in ordered]
+
+
+def perceive_page(doc: dict, page: dict, used: set[str] | None = None) -> tuple[list[dict], dict]:
+ used = used if used is not None else used_ids(doc)
+ objects = doc.get("objects") or {}
+ old = [r for r in page.get("reactions") or [] if isinstance(r, dict) and isinstance(r.get("id"), str)]
+ owner: dict[str, dict] = {}
+ previous: dict[str, dict] = {}
+ explicit: list[dict] = []
+ for r in old:
+ for s in r.get("steps") or []:
+ if not isinstance(s, dict) or not isinstance(s.get("id"), str):
+ continue
+ owner[s["id"]] = r
+ if s.get("explicit"):
+ explicit.append(copy.deepcopy(s))
+ elif isinstance(s.get("arrow"), str):
+ previous.setdefault(s["arrow"], s)
+ covered = {s.get("arrow") for s in explicit}
+ steps = list(explicit)
+ for oid in page.get("order") or []:
+ if oid in covered:
+ continue
+ step = infer_step(doc, page, oid, used)
+ if step is not None:
+ steps.append(_keep_extras(step, previous[oid]) if oid in previous else step)
+ found: list[dict] = []
+ claimed: set[str] = set()
+ for group in _chains(doc, steps):
+ rec = None
+ for s in group:
+ r = owner.get(s["id"])
+ if r is not None and r["id"] not in claimed:
+ rec = {k: copy.deepcopy(v) for k, v in r.items() if k != "steps"}
+ break
+ if rec is None:
+ rec = {"id": fresh_id(used, "r")}
+ claimed.add(rec["id"])
+ rec["steps"] = group
+ found.append(rec)
+ summary = {
+ "page": page.get("id"),
+ "reactions": len(found),
+ "steps": sum(len(r["steps"]) for r in found),
+ "explicit": len(explicit),
+ "stale": [s["id"] for s in explicit if s.get("arrow") not in objects],
+ "changed": found != (page.get("reactions") or []),
+ }
+ return found, summary
+
+
+def _pages(doc: dict, page_ids: list[str] | None) -> list[dict]:
+ if page_ids:
+ return [page_of(doc, p) for p in page_ids]
+ return [p for p in doc.get("pages") or [] if isinstance(p, dict)]
+
+
+def preview(doc: dict, page_ids: list[str] | None = None) -> list[dict]:
+ used = used_ids(doc)
+ out = []
+ for page in _pages(doc, page_ids):
+ found, summary = perceive_page(doc, page, used)
+ out.append({**summary, "list": found})
+ return out
+
+
+def perceive_ops(doc: dict, page_ids: list[str] | None = None) -> tuple[list[dict], list[dict]]:
+ used = used_ids(doc)
+ ops: list[dict] = []
+ summaries: list[dict] = []
+ for page in _pages(doc, page_ids):
+ found, summary = perceive_page(doc, page, used)
+ summaries.append(summary)
+ if not summary["changed"]:
+ continue
+ op: dict = {"op": "set", "path": ["pages", {"id": page["id"]}, "reactions"]}
+ if found:
+ op["value"] = found
+ elif "reactions" not in page:
+ continue
+ ops.append(op)
+ return ops, summaries
+
+
+def step_path(page_id: str, reaction_id: str, step_id: str) -> list:
+ return ["pages", {"id": page_id}, "reactions", {"id": reaction_id}, "steps", {"id": step_id}]
+
+
+def find_step(doc: dict, reaction_id: str | None = None, step_id: str | None = None, page_id: str | None = None) -> tuple[dict, dict, dict]:
+ pages = [page_of(doc, page_id)] if page_id else [p for p in doc.get("pages") or [] if isinstance(p, dict)]
+ any_steps = False
+ for page in pages:
+ for r in page.get("reactions") or []:
+ if not isinstance(r, dict):
+ continue
+ for s in r.get("steps") or []:
+ if not isinstance(s, dict):
+ continue
+ any_steps = True
+ if (reaction_id is None or r.get("id") == reaction_id) and (step_id is None or s.get("id") == step_id):
+ return page, r, s
+ if not any_steps:
+ raise NotFound("The drawing has no reaction steps yet: draw an arrow between structures and perceive reactions first.")
+ if step_id is not None:
+ raise NotFound(f"No reaction step {step_id}" + (f" in reaction {reaction_id}." if reaction_id else "."))
+ raise NotFound(f"No reaction {reaction_id}.")
+
+
+def roles_of(step: dict) -> list[tuple[str, str]]:
+ out = []
+ for key, role in (("reactants", "reactant"), ("agents", "agent"), ("products", "product")):
+ for oid in step.get(key) or []:
+ if isinstance(oid, str):
+ out.append((oid, role))
+ return out
+
+
+def coefficient(step: dict, oid: str) -> float:
+ found = (step.get("coefficients") or {}).get(oid)
+ return float(found) if isinstance(found, (int, float)) and not isinstance(found, bool) and found > 0 else 1.0
diff --git a/backend/app/services/chem/rxnio.py b/backend/app/services/chem/rxnio.py
new file mode 100644
index 00000000..b7ecbe08
--- /dev/null
+++ b/backend/app/services/chem/rxnio.py
@@ -0,0 +1,90 @@
+from rdkit import Chem
+from rdkit.Chem import rdChemReactions
+
+from app.services.chem import convert, io, warning
+from app.services.chem.reactions import ReactionError, coefficient, roles_of
+
+FORMATS = ("smiles", "rxn", "rxnv3000")
+REACT_STATUS = {"broken": 4, "formed": 4, "order": 8, "unchanged": 2, "centre": 1, "stereo": 1}
+LINE = 80
+
+
+def fragments_in(doc: dict, oid: str, depth: int = 0) -> list[dict]:
+ obj = (doc.get("objects") or {}).get(oid)
+ if not isinstance(obj, dict) or depth > 32:
+ return []
+ if obj.get("kind") == "fragment":
+ return [obj] if obj.get("atoms") else []
+ if obj.get("kind") == "group":
+ return [f for c in obj.get("children") or [] if isinstance(c, str) for f in fragments_in(doc, c, depth + 1)]
+ return []
+
+
+def plain_text(obj: dict | None) -> str:
+ if not isinstance(obj, dict):
+ return ""
+ return " ".join("".join(str(r.get("t") or "") for r in obj.get("runs") or [] if isinstance(r, dict)).split())
+
+
+def molecule(doc: dict, frag: dict, kekulize: bool = False) -> tuple[Chem.Mol, list[dict]]:
+ mol, notes = io._writable(frag, doc.get("expansions"))
+ bonds = frag.get("bonds") or {}
+ for b in mol.GetBonds():
+ if not b.HasProp(convert.ID_PROP):
+ continue
+ status = REACT_STATUS.get((bonds.get(b.GetProp(convert.ID_PROP)) or {}).get("reacting"))
+ if status:
+ b.SetIntProp("molReactStatus", status)
+ b.ClearProp(convert.ID_PROP)
+ if kekulize:
+ try:
+ Chem.Kekulize(mol, clearAromaticFlags=True)
+ except Exception:
+ notes.append(warning("cannot_kekulise", "Aromatic bonds were written as type 4 because the system cannot be kekulised."))
+ return mol.GetMol(), notes
+
+
+def build(doc: dict, step: dict, kekulize: bool = False) -> tuple[rdChemReactions.ChemicalReaction, list[dict]]:
+ rxn = rdChemReactions.ChemicalReaction()
+ notes: list[dict] = []
+ add = {"reactant": rxn.AddReactantTemplate, "product": rxn.AddProductTemplate, "agent": rxn.AddAgentTemplate}
+ for oid, role in roles_of(step):
+ frags = fragments_in(doc, oid)
+ if not frags:
+ obj = (doc.get("objects") or {}).get(oid)
+ what = f"the text {plain_text(obj)!r}" if isinstance(obj, dict) and obj.get("kind") == "text" else oid
+ notes.append(warning("not_a_structure", f"The {role} {what} is not a structure and is left out."))
+ continue
+ n = coefficient(step, oid)
+ if n != 1:
+ notes.append(warning("coefficient_dropped", f"The coefficient {n:g} of {oid} has no place in the format and is not written."))
+ for frag in frags:
+ mol, more = molecule(doc, frag, kekulize)
+ notes.extend(more)
+ add[role](mol)
+ if not rxn.GetNumReactantTemplates() and not rxn.GetNumProductTemplates():
+ raise ReactionError("This step has no reactant or product structures to write.")
+ return rxn, notes
+
+
+def _header(block: str, title: str, comment: str) -> str:
+ lines = block.split("\n")
+ if len(lines) > 3:
+ lines[1] = title[:LINE]
+ lines[3] = comment[:LINE]
+ return "\n".join(lines)
+
+
+def export_step(doc: dict, step: dict, fmt: str, title: str | None = None) -> tuple[str, list[dict]]:
+ if fmt not in FORMATS:
+ raise ReactionError(f"format must be one of {', '.join(FORMATS)}")
+ rxn, notes = build(doc, step, fmt != "smiles")
+ conditions = "; ".join(t for t in (plain_text((doc.get("objects") or {}).get(c)) for c in step.get("conditions") or []) if t)
+ if fmt == "smiles":
+ if conditions:
+ notes.append(warning("conditions_dropped", "Reaction SMILES has no place for the conditions text."))
+ return rdChemReactions.ReactionToSmiles(rxn), notes
+ block = rdChemReactions.ReactionToRxnBlock(rxn, separateAgents=True, forceV3000=fmt == "rxnv3000")
+ if conditions:
+ notes.append(warning("conditions_comment", "The conditions text is written on the comment line, which most readers ignore."))
+ return _header(block, title or "", conditions), notes
diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py
new file mode 100644
index 00000000..9b2b400a
--- /dev/null
+++ b/backend/app/services/chem/scheme.py
@@ -0,0 +1,177 @@
+import math
+
+from app.services import model
+from app.services.chem import DEFAULT_BOND_LENGTH, geometry, io, warning
+from app.services.chem.reactions import ReactionError, fresh_id, used_ids
+
+GAP_BONDS = 1.0
+END_BONDS = 0.5
+ARROW_BONDS = 4.0
+ROW_GAP_BONDS = 2.0
+PLUS_BONDS = 0.6
+CONDITION_PAD = 7.2
+ALIASES = {"smiles": "rsmiles", "rsmiles": "rsmiles", "rxn": "rxn", "rxnv3000": "rxn", "cml": "cml", "cdxml": "cdxml"}
+
+
+def _claim(frag: dict, used: set[str]) -> dict:
+ if frag["id"] in used:
+ frag["id"] = fresh_id(used, "f")
+ else:
+ used.add(frag["id"])
+ renamed: dict[str, str] = {}
+ atoms: dict = {}
+ for aid, atom in frag["atoms"].items():
+ new = fresh_id(used, "a") if aid in used else aid
+ used.add(new)
+ renamed[aid] = new
+ atoms[new] = {**atom, "id": new}
+ bonds: dict = {}
+ for bid, bond in frag["bonds"].items():
+ new = fresh_id(used, "b") if bid in used else bid
+ used.add(new)
+ bonds[new] = {**bond, "id": new, "a": renamed[bond["a"]], "b": renamed[bond["b"]]}
+ frag["atoms"], frag["bonds"] = atoms, bonds
+ return frag
+
+
+def _repair(frag: dict, bond_length: float) -> bool:
+ atoms = list(frag["atoms"].values())
+ if all(math.isfinite(a["x"]) and math.isfinite(a["y"]) for a in atoms):
+ return False
+ for n, a in enumerate(atoms):
+ a["x"], a["y"] = round(n * bond_length, 3), 0.0
+ return True
+
+
+def _move(frag: dict, dx: float, dy: float) -> None:
+ for a in frag["atoms"].values():
+ a["x"] = round(a["x"] + dx, 3)
+ a["y"] = round(a["y"] + dy, 3)
+
+
+class _Placer:
+ def __init__(self, bond_length: float):
+ self.bl = bond_length
+ self.style = {"bond_length": bond_length, "label_font": {"size": 10}}
+
+ def box(self, frag: dict) -> geometry.Box:
+ return geometry.fragment_box(frag, self.style) or (0.0, 0.0, 0.0, 0.0)
+
+ def put(self, frag: dict, left: float, cy: float) -> float:
+ b = self.box(frag)
+ _move(frag, left - b[0], cy - (b[1] + b[3]) / 2)
+ return left + b[2] - b[0]
+
+
+def rxn_comment(text: str) -> str:
+ lines = text.replace("\r\n", "\n").lstrip("").split("\n")
+ return lines[3].strip() if len(lines) > 3 and lines[0].startswith("$RXN") else ""
+
+
+def layout(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0),
+ used: set[str] | None = None, conditions: str = "") -> dict:
+ used = used if used is not None else set()
+ roles = parsed.reaction or {}
+ frags = {f["id"]: f for f in parsed.fragments}
+ repaired = [f["id"] for f in parsed.fragments if _repair(f, bond_length)]
+ pick = lambda key: [frags[i] for i in roles.get(key) or [] if i in frags]
+ reactants, products, agents = pick("reactants"), pick("products"), pick("agents")
+ if not reactants and not products:
+ raise ReactionError("The text holds no reactants or products.")
+ placed = {id(f) for f in reactants + products + agents}
+ others = [f for f in parsed.fragments if id(f) not in placed]
+ p = _Placer(bond_length)
+ bl = bond_length
+ height = max((p.box(f)[3] - p.box(f)[1] for f in reactants + products), default=bl)
+ agent_h = max((p.box(f)[3] - p.box(f)[1] for f in agents), default=0.0)
+ x0, y0 = origin
+ cy = y0 + max(height / 2, agent_h + END_BONDS * bl if agents else 0.0)
+ plus_size = PLUS_BONDS * bl
+ objects: list[dict] = []
+ x = x0
+
+ def side(items: list[dict], x: float) -> float:
+ for n, f in enumerate(items):
+ if n:
+ x += GAP_BONDS * bl
+ objects.append({"id": fresh_id(used, "o"), "kind": "plus", "x": round(x + plus_size / 2, 3), "y": round(cy, 3), "symbol": "plus"})
+ x += plus_size + GAP_BONDS * bl
+ x = p.put(f, x, cy)
+ objects.append(f)
+ return x
+
+ x = side(reactants, x)
+ tail = x + END_BONDS * bl if reactants else x
+ widths = [p.box(f)[2] - p.box(f)[0] for f in agents]
+ span = sum(widths) + GAP_BONDS * bl * max(0, len(agents) - 1)
+ note = {"id": fresh_id(used, "o"), "kind": "text", "x": 0.0, "y": round(cy + END_BONDS * bl, 3), "align": "c", "runs": [{"t": conditions}]} if conditions else None
+ note_w = geometry.text_box(note, p.style)[2] - geometry.text_box(note, p.style)[0] if note else 0.0
+ length = max(ARROW_BONDS * bl, span + 2 * CONDITION_PAD, note_w + 2 * CONDITION_PAD)
+ ax = tail + (length - span) / 2
+ for f, w in zip(agents, widths):
+ b = p.box(f)
+ _move(f, ax - b[0], cy - END_BONDS * bl - b[3])
+ objects.append(f)
+ ax += w + GAP_BONDS * bl
+ head = tail + length
+ arrow = {"id": fresh_id(used, "o"), "kind": "arrow", "type": "forward", "x1": round(tail, 3), "y1": round(cy, 3),
+ "x2": round(head, 3), "y2": round(cy, 3), "head": "full", "tail": "none"}
+ objects.append(arrow)
+ if note:
+ note["x"] = round((tail + head) / 2, 3)
+ objects.append(note)
+ side(products, head + END_BONDS * bl)
+ bottom = max((p.box(f)[3] for f in reactants + products), default=cy) + ROW_GAP_BONDS * bl
+ x = x0
+ for f in others:
+ b = p.box(f)
+ _move(f, x - b[0], bottom - b[1])
+ x += b[2] - b[0] + ROW_GAP_BONDS * bl
+ objects.append(f)
+ for f in parsed.fragments:
+ _claim(f, used)
+ step = {"id": fresh_id(used, "r"), "arrow": arrow["id"], "reactants": [f["id"] for f in reactants], "products": [f["id"] for f in products],
+ "agents": [f["id"] for f in agents], "conditions": [note["id"]] if note else [], "explicit": True}
+ notes = [w for w in parsed.warnings if w.get("code") != "reaction_arrow"]
+ if repaired:
+ notes.append(warning("no_coordinates", f"{len(repaired)} structure{'s' if len(repaired) != 1 else ''} got no 2D layout and {'were' if len(repaired) != 1 else 'was'} drawn as a row of atoms; clean them up."))
+ return {"objects": objects, "reaction": {"id": fresh_id(used, "r"), "steps": [step]}, "warnings": notes}
+
+
+def parse(text: str, fmt: str | None = None, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0),
+ used: set[str] | None = None) -> dict:
+ kind = ALIASES.get(fmt) if fmt else None
+ if fmt and kind is None:
+ raise ReactionError(f"format must be one of {', '.join(ALIASES)}")
+ try:
+ parsed = io.read_text(text, kind, bond_length, origin)
+ except ValueError as exc:
+ raise ReactionError(str(exc)) from exc
+ if parsed.reaction is None:
+ raise ReactionError(f"The text reads as {parsed.format}, not as a reaction.")
+ comment = rxn_comment(text) if parsed.format == "rxn" else ""
+ return {"format": parsed.format, **layout(parsed, bond_length, origin, used, comment)}
+
+
+def free_origin(doc: dict, page: dict) -> tuple[float, float]:
+ style = model.resolve_style(doc)
+ margin = float(page.get("margins", 36))
+ box = geometry.union([geometry.object_box(doc, oid, style) for oid in page.get("order") or [] if isinstance(oid, str)])
+ if box is None:
+ return (margin, margin)
+ return (margin, round(box[3] + ROW_GAP_BONDS * float(style.get("bond_length") or DEFAULT_BOND_LENGTH), 3))
+
+
+def insert_ops(doc: dict, page: dict, text: str, fmt: str | None = None, origin: tuple[float, float] | None = None) -> tuple[list[dict], dict]:
+ bl = float(model.resolve_style(doc).get("bond_length") or DEFAULT_BOND_LENGTH)
+ found = parse(text, fmt, bl, origin or free_origin(doc, page), used_ids(doc))
+ ops: list[dict] = []
+ order = ["pages", {"id": page["id"]}, "order"]
+ for obj in found["objects"]:
+ ops.append({"op": "set", "path": ["objects", obj["id"]], "value": obj})
+ ops.append({"op": "ins", "path": order, "value": obj["id"]})
+ if isinstance(page.get("reactions"), list):
+ ops.append({"op": "ins", "path": ["pages", {"id": page["id"]}, "reactions"], "value": found["reaction"]})
+ else:
+ ops.append({"op": "set", "path": ["pages", {"id": page["id"]}, "reactions"], "value": [found["reaction"]]})
+ return ops, found
diff --git a/backend/app/services/chem/search.py b/backend/app/services/chem/search.py
new file mode 100644
index 00000000..e9538208
--- /dev/null
+++ b/backend/app/services/chem/search.py
@@ -0,0 +1,61 @@
+from rdkit import Chem
+
+from app.services.chem import perceive, query, warning
+
+MAX_HITS = 1000
+
+
+def query_from(fragment: dict | None, smarts: str | None, expansions: dict | None = None) -> tuple[Chem.Mol, list[str] | None, list[dict]]:
+ if smarts is not None:
+ qm = Chem.MolFromSmarts(smarts.strip())
+ if qm is None:
+ raise ValueError("not valid SMARTS")
+ return qm, None, []
+ if not fragment or not fragment.get("atoms"):
+ raise ValueError("give a query fragment with atoms, or smarts")
+ qm, conv, notes = query.query_mol(fragment, expansions)
+ return qm, conv.owner, notes
+
+
+def substructure(targets: dict[str, dict], fragment: dict | None = None, smarts: str | None = None, expansions: dict | None = None,
+ max_hits: int = MAX_HITS, chirality: bool = False) -> dict:
+ qm, owners, notes = query_from(fragment, smarts, expansions)
+ hits: list[dict] = []
+ by_object: dict[str, int] = {}
+ truncated = False
+ for fid in sorted(targets):
+ frag = targets[fid]
+ if not frag.get("atoms"):
+ continue
+ left = max_hits - len(hits)
+ if left <= 0:
+ truncated = True
+ break
+ try:
+ conv = perceive.prepare(frag, expansions)
+ params = Chem.SubstructMatchParameters()
+ params.useChirality = chirality
+ params.maxMatches = left + 1
+ params.uniquify = True
+ found = conv.mol.GetSubstructMatches(qm, params)
+ except Exception as exc:
+ notes.append(warning("search_failed", f"{fid} could not be searched: {exc}"))
+ continue
+ if len(found) > left:
+ found, truncated = found[:left], True
+ for match in found:
+ atoms = list(dict.fromkeys(conv.owner[i] for i in match))
+ bonds = []
+ for qb in qm.GetBonds():
+ tb = conv.mol.GetBondBetweenAtoms(match[qb.GetBeginAtomIdx()], match[qb.GetEndAtomIdx()])
+ bid = conv.bond_id(tb.GetIdx()) if tb is not None else None
+ if bid and bid not in bonds:
+ bonds.append(bid)
+ mapping: dict[str, str] = {}
+ for qi, ti in enumerate(match):
+ key = owners[qi] if owners else str(qi)
+ mapping.setdefault(key, conv.owner[ti])
+ hits.append({"object": fid, "atoms": atoms, "bonds": bonds, "map": mapping})
+ if found:
+ by_object[fid] = len(found)
+ return {"hits": hits, "count": len(hits), "by_object": by_object, "truncated": truncated, "smarts": Chem.MolToSmarts(qm), "warnings": notes}
diff --git a/backend/app/services/chem/stereo.py b/backend/app/services/chem/stereo.py
new file mode 100644
index 00000000..7c734aff
--- /dev/null
+++ b/backend/app/services/chem/stereo.py
@@ -0,0 +1,253 @@
+from rdkit import Chem
+from rdkit.Chem import rdCIPLabeler
+from rdkit.Geometry import Point3D
+
+from app.services.chem import convert, ids, perceive, warning
+from app.services.ops import bond_path, object_path
+
+ST = Chem.StereoType
+SPEC = Chem.StereoSpecified
+STEREO_CODES = {"undefined_stereocentre", "stereo_unknown", "undefined_double_bond", "unknown_ez", "misplaced_wedge", "ambiguous_wedge",
+ "conflicting_wedges", "wedge_between_centres", "ring_double_bond_stereo", "stereo_ignored", "cip_failed", "bad_stereo_group",
+ "stereo_group_overlap", "stereo_group_not_centre"}
+SPECIFIED = {SPEC.Specified: "defined", SPEC.Unspecified: "undefined", SPEC.Unknown: "unknown"}
+KINDS = ("abs", "and", "or")
+
+
+def group_labels(conv: convert.Conversion) -> dict[int, str]:
+ out: dict[int, str] = {}
+ counters = {"and": 0, "or": 0}
+ for g in conv.mol.GetStereoGroups():
+ kind = convert.GROUP_KINDS.get(g.GetGroupType())
+ if kind is None:
+ continue
+ if kind == "abs":
+ label = "abs"
+ else:
+ counters[kind] += 1
+ label = f"{kind}{g.GetReadId() or counters[kind]}"
+ for a in g.GetAtoms():
+ out[a.GetIdx()] = label
+ return out
+
+
+def report(frag: dict, expansions: dict | None = None) -> dict:
+ conv = perceive.prepare(frag, expansions)
+ p = perceive.perceive(frag, expansions, conv)
+ mol = conv.mol
+ groups = group_labels(conv)
+ try:
+ found = list(Chem.FindPotentialStereo(mol))
+ except Exception:
+ found = []
+ centres, double_bonds, axes = [], [], []
+ cumulated = perceive.not_ez_bonds(mol)
+ for si in found:
+ if si.type == ST.Bond_Double and si.centeredOn in cumulated:
+ continue
+ if si.type == ST.Atom_Tetrahedral:
+ i = si.centeredOn
+ if not conv.drawn[i]:
+ continue
+ aid = conv.owner[i]
+ row = {"atom": aid, "label": p.cip.get(aid), "state": SPECIFIED.get(si.specified, "undefined")}
+ if row["state"] == "defined":
+ row["group"] = groups.get(i, "abs")
+ centres.append(row)
+ elif si.type in (ST.Bond_Double, ST.Bond_Atropisomer, ST.Bond_Cumulene_Even):
+ bid = conv.bond_id(si.centeredOn)
+ if not bid:
+ continue
+ row = {"bond": bid, "label": p.cip.get(bid), "state": SPECIFIED.get(si.specified, "undefined")}
+ (axes if si.type == ST.Bond_Atropisomer else double_bonds).append(row)
+ atoms = {k: v for k, v in p.cip.items() if k in (frag.get("atoms") or {})}
+ bonds = {k: v for k, v in p.cip.items() if k in (frag.get("bonds") or {})}
+ id_mol = ids.identifier_mol(mol)
+ return {
+ "atoms": atoms,
+ "bonds": bonds,
+ "centres": centres,
+ "double_bonds": double_bonds,
+ "axes": axes,
+ "chiral": frag.get("chiral"),
+ "stereo_groups": convert.groups_from_mol(mol, conv.owner),
+ "smiles": ids.smiles(id_mol),
+ "cxsmiles": ids.cxsmiles(id_mol),
+ "warnings": [w for w in p.warnings if w.get("code") in STEREO_CODES],
+ }
+
+
+def _clean_groups(groups: list) -> list[dict]:
+ out = []
+ for g in groups or []:
+ if isinstance(g, dict) and g.get("kind") in KINDS:
+ out.append({k: v for k, v in g.items() if k != "atoms"} | {"atoms": [a for a in g.get("atoms") or [] if isinstance(a, str)]})
+ return out
+
+
+def regroup(frag: dict, kind: str, atoms: list[str], n: int | None = None) -> list[dict]:
+ if kind not in KINDS:
+ raise ValueError("kind must be abs, and or or")
+ moving = [a for a in dict.fromkeys(atoms) if a in (frag.get("atoms") or {})]
+ groups = _clean_groups(frag.get("stereo_groups") or [])
+ for g in groups:
+ g["atoms"] = [a for a in g["atoms"] if a not in moving]
+ groups = [g for g in groups if g["atoms"]]
+ if not moving:
+ return groups
+ if kind == "abs":
+ target = next((g for g in groups if g["kind"] == "abs"), None)
+ else:
+ taken = {g.get("n") for g in groups if g["kind"] == kind}
+ if n is None:
+ n = next(i for i in range(1, len(taken) + 2) if i not in taken)
+ target = next((g for g in groups if g["kind"] == kind and g.get("n") == n), None)
+ if target is None:
+ target = {"kind": kind, **({"n": n} if kind != "abs" else {}), "atoms": []}
+ groups.append(target)
+ target["atoms"].extend(moving)
+ return groups
+
+
+def groups_tx(frag: dict, groups: list[dict] | None, chiral: str | None, set_chiral: bool) -> dict:
+ fid = frag["id"]
+ ops = []
+ old = frag.get("stereo_groups")
+ if groups is not None and groups != old:
+ ops.append({"op": "set", "path": object_path(fid, "stereo_groups"), **({"value": groups} if groups else {})})
+ if set_chiral and chiral != frag.get("chiral"):
+ ops.append({"op": "set", "path": object_path(fid, "chiral"), **({"value": chiral} if chiral else {})})
+ label = "Set stereo group" if groups is not None else "Set chiral flag"
+ return {"label": label, "ops": ops}
+
+
+def preview(frag: dict, groups: list[dict] | None, chiral: str | None, set_chiral: bool, expansions: dict | None = None) -> dict:
+ trial = dict(frag)
+ if groups is not None:
+ trial["stereo_groups"] = groups
+ if set_chiral:
+ trial["chiral"] = chiral
+ conv = perceive.prepare(trial, expansions)
+ id_mol = ids.identifier_mol(conv.mol)
+ return {
+ "groups": convert.groups_from_mol(conv.mol, conv.owner),
+ "chiral": trial.get("chiral"),
+ "cxsmiles": ids.cxsmiles(id_mol),
+ "warnings": [w for w in conv.warnings if w.get("code") in STEREO_CODES],
+ }
+
+
+CT = Chem.ChiralType
+TETRA = (CT.CHI_TETRAHEDRAL_CW, CT.CHI_TETRAHEDRAL_CCW)
+BD = Chem.BondDir
+WEDGES = ("wedge", "hash", "hollow")
+
+
+def _cip_labels(mol: Chem.Mol) -> dict[int, str]:
+ probe = Chem.Mol(mol)
+ try:
+ rdCIPLabeler.AssignCIPLabels(probe, maxRecursiveIterations=perceive.CIP_MAX_ITERATIONS)
+ except Exception:
+ return {}
+ return {a.GetIdx(): a.GetProp("_CIPCode") for a in probe.GetAtoms() if a.HasProp("_CIPCode")}
+
+
+def _from_3d(conv: convert.Conversion, mol: Chem.RWMol, coords3d: dict) -> None:
+ if conv.expanded:
+ raise ValueError("expand the abbreviations before reading 3D coordinates")
+ missing = [a for a in conv.index if a not in coords3d]
+ if missing:
+ raise ValueError(f"coords3d has no position for {len(missing)} atom(s), such as {missing[0]}")
+ conf = Chem.Conformer(mol.GetNumAtoms())
+ for aid, i in conv.index.items():
+ x, y, z = (float(v) for v in coords3d[aid])
+ conf.SetAtomPosition(i, Point3D(x, y, z))
+ conf.Set3D(True)
+ cid = mol.AddConformer(conf, assignId=True)
+ for a in mol.GetAtoms():
+ a.SetChiralTag(CT.CHI_UNSPECIFIED)
+ Chem.AssignStereochemistryFrom3D(mol, confId=cid, replaceExistingTags=True)
+ mol.RemoveConformer(cid)
+
+
+def _aim(conv: convert.Conversion, mol: Chem.RWMol, wanted: dict[str, str], notes: list[dict]) -> None:
+ targets = {conv.index[a]: v for a, v in wanted.items() if a in conv.index and conv.drawn[conv.index[a]]}
+ for _ in range(4):
+ labels = _cip_labels(mol)
+ wrong = [i for i, v in targets.items() if labels.get(i) != v]
+ if not wrong:
+ return
+ for i in wrong:
+ atom = mol.GetAtomWithIdx(i)
+ atom.SetChiralTag(CT.CHI_TETRAHEDRAL_CCW if atom.GetChiralTag() == CT.CHI_TETRAHEDRAL_CW else CT.CHI_TETRAHEDRAL_CW)
+ labels = _cip_labels(mol)
+ left = [conv.owner[i] for i, v in targets.items() if labels.get(i) != v]
+ for i in [i for i, v in targets.items() if labels.get(i) != v]:
+ mol.GetAtomWithIdx(i).SetChiralTag(conv.mol.GetAtomWithIdx(i).GetChiralTag())
+ if left:
+ notes.append(warning("cip_unreachable", "These atoms cannot take the asked label (not a stereocentre, or the label depends on another centre).", left))
+
+
+def rewedge(frag: dict, expansions: dict | None = None, centres: list[str] | None = None, cip: dict[str, str] | None = None,
+ coords3d: dict | None = None) -> dict:
+ conv = perceive.prepare(frag, expansions)
+ mol = Chem.RWMol(conv.mol)
+ notes: list[dict] = []
+ if coords3d:
+ _from_3d(conv, mol, coords3d)
+ if cip:
+ _aim(conv, mol, {k: v for k, v in cip.items() if v in ("R", "S")}, notes)
+ chiral = {i for i in range(mol.GetNumAtoms()) if conv.drawn[i] and mol.GetAtomWithIdx(i).GetChiralTag() in TETRA}
+ chosen = {conv.owner[i] for i in chiral} if centres is None else {a for a in centres if a in conv.index} & {conv.owner[i] for i in chiral}
+ for b in mol.GetBonds():
+ if b.GetBondDir() in (BD.BEGINWEDGE, BD.BEGINDASH):
+ b.SetBondDir(BD.NONE)
+ try:
+ Chem.WedgeMolBonds(mol, mol.GetConformer())
+ except Exception as exc:
+ raise ValueError(f"wedges could not be placed: {exc}") from exc
+ bonds = frag.get("bonds") or {}
+ fid = frag["id"]
+ ops: list[dict] = []
+ changed: list[str] = []
+ after = {k: dict(v) for k, v in bonds.items()}
+ for b in mol.GetBonds():
+ bid = conv.bond_id(b.GetIdx())
+ if not bid or bid not in bonds:
+ continue
+ rec = bonds[bid]
+ old = rec.get("stereo") or "none"
+ if old in ("wavy", "either"):
+ continue
+ d = b.GetBondDir()
+ new = "wedge" if d == BD.BEGINWEDGE else "hash" if d == BD.BEGINDASH else "none"
+ begin = conv.owner[b.GetBeginAtomIdx()]
+ if new != "none" and begin not in chosen:
+ continue
+ if new == "none" and not (old in WEDGES and rec["a"] in chosen):
+ continue
+ if new != "none" and old in WEDGES and rec["a"] not in chosen:
+ continue
+ if new == "wedge" and old == "hollow":
+ new = "hollow"
+ flip = new != "none" and rec["a"] != begin
+ if new == old and not flip:
+ continue
+ if flip:
+ ops.append({"op": "set", "path": bond_path(fid, bid, "a"), "value": rec["b"]})
+ ops.append({"op": "set", "path": bond_path(fid, bid, "b"), "value": rec["a"]})
+ after[bid]["a"], after[bid]["b"] = rec["b"], rec["a"]
+ ops.append({"op": "set", "path": bond_path(fid, bid, "stereo"), **({"value": new} if new != "none" else {})})
+ after[bid]["stereo"] = new
+ changed.append(bid)
+ check = perceive.prepare({**frag, "bonds": after}, expansions)
+ off = [conv.owner[i] for i in chiral if conv.owner[i] in chosen and check.mol.GetAtomWithIdx(i).GetChiralTag() != mol.GetAtomWithIdx(i).GetChiralTag()]
+ if off:
+ notes.append(warning("wedge_mismatch", "The new wedges do not express the wanted configuration at these centres.", off))
+ labels = _cip_labels(check.mol)
+ return {
+ "tx": {"label": "Assign wedges", "ops": ops},
+ "changed": changed,
+ "cip": {conv.owner[i]: v for i, v in labels.items() if conv.drawn[i]},
+ "warnings": notes,
+ }
diff --git a/backend/app/services/chem/stoich.py b/backend/app/services/chem/stoich.py
new file mode 100644
index 00000000..89e9b0a8
--- /dev/null
+++ b/backend/app/services/chem/stoich.py
@@ -0,0 +1,250 @@
+import math
+
+from app.services import model
+from app.services.chem import geometry, warning
+from app.services.chem.reactions import bond_length, coefficient, find_step, fresh_id, roles_of
+from app.services.chem.rxnio import fragments_in, plain_text
+
+FIELDS = ("equiv", "mass_mg", "volume_ml", "density_g_ml", "conc_m", "purity_pct", "mw")
+MISMATCH = 0.01
+
+
+def _pos(v: object) -> float | None:
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v > 0:
+ return float(v)
+ return None
+
+
+def _r(v: float | None, places: int = 4) -> float | None:
+ return None if v is None else round(v, places)
+
+
+def derived_mass(doc: dict, oid: str, derived: dict | None) -> tuple[float | None, str]:
+ found = (derived or {}).get("fragments") or {}
+ frags = fragments_in(doc, oid)
+ if not frags:
+ return None, ""
+ total, formulas = 0.0, []
+ for f in frags:
+ d = found.get(f["id"])
+ mw = _pos((d or {}).get("mw"))
+ if mw is None:
+ return None, ""
+ total += mw
+ if d.get("formula"):
+ formulas.append(d["formula"])
+ return total, ".".join(formulas)
+
+
+def _label(doc: dict, oid: str, comp: dict, formula: str) -> str:
+ obj = (doc.get("objects") or {}).get(oid) or {}
+ if isinstance(comp.get("label"), str) and comp["label"].strip():
+ return comp["label"].strip()
+ if isinstance(obj.get("name"), str) and obj["name"].strip():
+ return obj["name"].strip()
+ return formula or plain_text(obj) or oid
+
+
+def _fixed(comp: dict, mw: float | None, purity: float) -> tuple[float | None, float | None, str | None]:
+ mass, volume = _pos(comp.get("mass_mg")), _pos(comp.get("volume_ml"))
+ density, conc = _pos(comp.get("density_g_ml")), _pos(comp.get("conc_m"))
+ if mass is not None:
+ return (mass * purity / 100 / mw if mw else None), mass, "mass"
+ if volume is not None and conc is not None:
+ mmol = conc * volume
+ return mmol, (mmol * mw / (purity / 100) if mw else None), "solution"
+ if volume is not None and density is not None:
+ mass = volume * density * 1000
+ return (mass * purity / 100 / mw if mw else None), mass, "volume"
+ return None, None, None
+
+
+def compute(doc: dict, reaction: dict, step: dict, derived: dict | None) -> dict:
+ st = step.get("stoich") if isinstance(step.get("stoich"), dict) else {}
+ comps = st.get("components") if isinstance(st.get("components"), dict) else {}
+ notes: list[dict] = []
+ rows: list[dict] = []
+ for oid, role in roles_of(step):
+ comp = comps.get(oid) if isinstance(comps.get(oid), dict) else {}
+ found_mw, formula = derived_mass(doc, oid, derived)
+ entered = _pos(comp.get("mw"))
+ mw = entered or found_mw
+ purity = _pos(comp.get("purity_pct")) or 100.0
+ mmol, mass, source = _fixed(comp, mw, purity)
+ if mw is None:
+ notes.append(warning("no_mw", f"{_label(doc, oid, comp, formula)} has no molecular weight yet; enter one to compute its amounts."))
+ rows.append({"id": oid, "role": role, "label": _label(doc, oid, comp, formula), "formula": formula or None, "mw": _r(mw),
+ "mw_source": "entered" if entered else "derived" if found_mw else None, "coefficient": coefficient(step, oid),
+ "purity_pct": purity, "density_g_ml": _pos(comp.get("density_g_ml")), "conc_m": _pos(comp.get("conc_m")),
+ "equiv_entered": _pos(comp.get("equiv")), "mmol": mmol, "mass_mg": mass, "source": source if role != "product" else None,
+ "actual_mg": mass if role == "product" else None})
+ by_id = {r["id"]: r for r in rows}
+ users = [r for r in rows if r["role"] != "product"]
+ reactants = [r for r in rows if r["role"] == "reactant"]
+ scale = _pos(st.get("scale_mmol"))
+ limiting_set = st.get("limiting") if (by_id.get(st.get("limiting")) or {}).get("role") == "reactant" else None
+ if st.get("limiting") and not limiting_set:
+ notes.append(warning("bad_limiting", "The chosen limiting reagent is not a reactant of this step."))
+ reference = None
+ if scale:
+ reference = scale
+ else:
+ pick = [by_id[limiting_set]] if limiting_set else []
+ for r in pick + users:
+ if r["source"] and r["mmol"]:
+ reference = r["mmol"] / (r["equiv_entered"] or 1.0)
+ break
+ for r in users:
+ if r["source"] is None and r["equiv_entered"] and reference:
+ r["mmol"], r["source"] = r["equiv_entered"] * reference, "equiv"
+ if r["mmol"] and r["mass_mg"] is None and r["mw"]:
+ r["mass_mg"] = r["mmol"] * r["mw"] / (r["purity_pct"] / 100)
+ r["equiv"] = r["mmol"] / reference if r["mmol"] and reference else r["equiv_entered"]
+ if r["source"] in ("mass", "volume", "solution") and r["equiv_entered"] and r["equiv"] and abs(r["equiv"] - r["equiv_entered"]) > MISMATCH * r["equiv_entered"]:
+ notes.append(warning("equiv_mismatch", f"{r['label']}: the amount entered gives {r['equiv']:.3g} equivalents, not the {r['equiv_entered']:g} entered."))
+ if r["mmol"] is None:
+ notes.append(warning("no_amount", f"{r['label']} has no amount yet."))
+ for r in rows:
+ r["volume_ml"] = None
+ if r["role"] != "product" and r["mass_mg"]:
+ if r["conc_m"] and r["mmol"]:
+ r["volume_ml"] = r["mmol"] / r["conc_m"]
+ elif r["density_g_ml"]:
+ r["volume_ml"] = r["mass_mg"] / r["density_g_ml"] / 1000
+ limiting = by_id.get(limiting_set) if limiting_set else None
+ if limiting is None:
+ ranked = [r for r in reactants if r["mmol"]]
+ limiting = min(ranked, key=lambda r: r["mmol"] / r["coefficient"]) if ranked else None
+ for r in rows:
+ r["limiting"] = limiting is not None and r is limiting
+ target = st.get("product") if (by_id.get(st.get("product")) or {}).get("role") == "product" else next((r["id"] for r in rows if r["role"] == "product"), None)
+ summary = None
+ for r in rows:
+ if r["role"] != "product":
+ continue
+ r["mmol"] = r["mass_mg"] = None
+ if limiting is not None and limiting["mmol"]:
+ r["mmol"] = limiting["mmol"] / limiting["coefficient"] * r["coefficient"]
+ r["mass_mg"] = r["mmol"] * r["mw"] if r["mw"] else None
+ actual = r["actual_mg"]
+ if r["id"] == target and _pos(st.get("isolated_mg")):
+ actual = r["actual_mg"] = _pos(st.get("isolated_mg"))
+ r["yield_pct"] = round(actual / r["mass_mg"] * 100, 1) if actual and r["mass_mg"] else None
+ if r["id"] == target:
+ summary = {"product": r["id"], "theoretical_mmol": _r(r["mmol"]), "theoretical_mg": _r(r["mass_mg"]), "isolated_mg": actual, "percent": r["yield_pct"]}
+ for r in rows:
+ for key in ("mmol", "mass_mg", "volume_ml", "equiv"):
+ r[key] = _r(r.get(key))
+ r.setdefault("yield_pct", None)
+ return {"reaction": reaction.get("id"), "step": step.get("id"), "scale_mmol": scale, "reference_mmol": _r(reference),
+ "limiting": limiting["id"] if limiting else None, "limiting_source": "entered" if limiting_set else "computed" if limiting else None,
+ "rows": rows, "yield": summary, "warnings": notes}
+
+
+HEADERS = ("Compound", "Formula", "Role", "MW", "Equiv", "Amount", "Mass", "Volume", "Isolated", "Yield")
+ROLE_NAMES = {"reactant": "reactant", "agent": "reagent", "product": "product"}
+PADDING = 3.0
+GRID_GAP_BONDS = 1.5
+
+
+def sig3(v: float) -> str:
+ if v == 0:
+ return "0"
+ exponent = int(math.floor(math.log10(abs(v))))
+ if abs(round(v, 2 - exponent)) >= 10 ** (exponent + 1):
+ exponent += 1
+ places = max(0, 2 - exponent)
+ return f"{round(v, places):.{places}f}"
+
+
+def _scaled(v: float | None, steps: tuple[tuple[float, str], ...], least: float) -> str:
+ if v is None:
+ return ""
+ for factor, unit in reversed(steps):
+ if abs(v) * factor >= least or unit == steps[0][1]:
+ return f"{sig3(v * factor)} {unit}"
+ return ""
+
+
+def amount_text(mmol: float | None) -> str:
+ return _scaled(mmol, ((1000.0, "µmol"), (1.0, "mmol"), (0.001, "mol")), 1.0)
+
+
+def mass_text(mg: float | None) -> str:
+ return _scaled(mg, ((1000.0, "µg"), (1.0, "mg"), (0.001, "g"), (0.000001, "kg")), 1.0)
+
+
+def volume_text(ml: float | None) -> str:
+ return _scaled(ml, ((1000.0, "µL"), (1.0, "mL"), (0.001, "L")), 0.1)
+
+
+def _formula_runs(text: str) -> list[dict]:
+ runs: list[dict] = []
+ for ch in text:
+ sub = ch.isdigit() and bool(runs) and (runs[-1].get("sub") or not runs[-1]["t"][-1:].isspace())
+ if runs and bool(runs[-1].get("sub")) == sub:
+ runs[-1]["t"] += ch
+ else:
+ runs.append({"t": ch, "sub": True} if sub else {"t": ch})
+ return runs or [{"t": ""}]
+
+
+def _cells(row: dict) -> list[list[dict]]:
+ texts = [
+ row["label"],
+ None,
+ ROLE_NAMES.get(row["role"], row["role"]) + (", limiting" if row.get("limiting") else ""),
+ f"{row['mw']:.2f}" if row["mw"] else "",
+ sig3(row["equiv"]) if row.get("equiv") else "",
+ amount_text(row["mmol"]),
+ mass_text(row["mass_mg"]),
+ volume_text(row.get("volume_ml")),
+ mass_text(row.get("actual_mg")) if row["role"] == "product" else "",
+ f"{row['yield_pct']:.1f}%" if row.get("yield_pct") is not None else "",
+ ]
+ out = []
+ for n, t in enumerate(texts):
+ formula = n == 1 or (n == 0 and row["formula"] and row["label"] == row["formula"])
+ out.append(_formula_runs(row["formula"] or "") if formula else [{"t": t or ""}])
+ return out
+
+
+def _width(runs: list[dict], size: float) -> float:
+ return sum(len(r["t"]) * size * (0.75 if r.get("sub") else 1.0) for r in runs) * 0.55
+
+
+def grid(view: dict, size: float = 10.0) -> tuple[list[float], list[list[list[dict]]]]:
+ body = [[[{"t": h}] for h in HEADERS]] + [_cells(r) for r in view["rows"]]
+ cols = [round(max(_width(row[c], size) for row in body) + 2 * PADDING + 2, 1) for c in range(len(HEADERS))]
+ return cols, body
+
+
+def table_ops(doc: dict, page: dict, view: dict, used: set[str], at: tuple[float, float] | None = None) -> tuple[list[dict], dict]:
+ style = model.resolve_style(doc)
+ size = float((style.get("caption_font") or {}).get("size") or 10)
+ cols, body = grid(view, size)
+ height = round(size * 1.2 + 2 * PADDING, 1)
+ link = {"reaction": view["reaction"], "step": view["step"]}
+ objects = doc.get("objects") or {}
+ existing = next((objects[o] for o in page.get("order") or [] if isinstance(objects.get(o), dict)
+ and objects[o].get("kind") == "table" and objects[o].get("stoich") == link), None)
+ old_rows = existing.get("rows") if existing and isinstance(existing.get("rows"), list) else []
+ rows = []
+ for n, cells in enumerate(body):
+ rid = old_rows[n].get("id") if n < len(old_rows) and isinstance(old_rows[n], dict) and old_rows[n].get("id") else fresh_id(used, "l")
+ rows.append({"id": rid, "h": height, "cells": [{"runs": runs} for runs in cells]})
+ if existing is not None:
+ ops = []
+ for key, value in (("cols", cols), ("rows", rows)):
+ if existing.get(key) != value:
+ ops.append({"op": "set", "path": ["objects", existing["id"], key], "value": value})
+ return ops, {**existing, "cols": cols, "rows": rows}
+ if at is None:
+ _, _, step = find_step(doc, view["reaction"], view["step"], page.get("id"))
+ ids = [step.get("arrow")] + [o for k in ("reactants", "products", "agents", "conditions") for o in step.get(k) or []]
+ box = geometry.union([geometry.object_box(doc, o, style) for o in ids if isinstance(o, str)])
+ at = (box[0], box[3] + GRID_GAP_BONDS * bond_length(doc)) if box else (float(page.get("margins", 36)),) * 2
+ table = {"id": fresh_id(used, "o"), "kind": "table", "x": round(at[0], 3), "y": round(at[1], 3), "cols": cols, "rows": rows,
+ "padding": PADDING, "header": True, "borders": "all", "stoich": link}
+ return [{"op": "set", "path": ["objects", table["id"]], "value": table},
+ {"op": "ins", "path": ["pages", {"id": page["id"]}, "order"], "value": table["id"]}], table
diff --git a/backend/app/services/chem/superatom.py b/backend/app/services/chem/superatom.py
new file mode 100644
index 00000000..26e1da3e
--- /dev/null
+++ b/backend/app/services/chem/superatom.py
@@ -0,0 +1,239 @@
+import math
+
+from rdkit import Chem
+
+from app.services.chem import abbrev, convert, ids, perceive, warning
+from app.services.model import new_id
+from app.services.ops import atom_path, bond_path, object_path
+
+Point = tuple[float, float]
+
+
+def _fresh(prefix: str, used: set[str]) -> str:
+ while True:
+ i = new_id(prefix)
+ if i not in used:
+ used.add(i)
+ return i
+
+
+def _bond_key(b: dict) -> tuple:
+ return (b.get("z") or 0, b["id"])
+
+
+def _rotate(dx: float, dy: float, c: float, s: float) -> Point:
+ return dx * c - dy * s, dx * s + dy * c
+
+
+def _components(atoms: set[str], bonds: dict) -> int:
+ adj: dict[str, set[str]] = {a: set() for a in atoms}
+ for b in bonds.values():
+ if b["a"] in atoms and b["b"] in atoms:
+ adj[b["a"]].add(b["b"])
+ adj[b["b"]].add(b["a"])
+ seen: set[str] = set()
+ count = 0
+ for start in atoms:
+ if start in seen:
+ continue
+ count += 1
+ stack = [start]
+ seen.add(start)
+ while stack:
+ for n in adj[stack.pop()] - seen:
+ seen.add(n)
+ stack.append(n)
+ return count
+
+
+def substituent_smiles(frag: dict, sel: set[str], crossing: list[dict], expansions: dict | None = None) -> str:
+ atoms = frag["atoms"]
+ sub_atoms = {a: atoms[a] for a in sel}
+ sub_bonds = {k: b for k, b in frag["bonds"].items() if b["a"] in sel and b["b"] in sel}
+ for i, b in enumerate(crossing):
+ inner, outer = (b["a"], b["b"]) if b["a"] in sel else (b["b"], b["a"])
+ sid = f"__star{i}"
+ sub_atoms[sid] = {"id": sid, "element": "*", "x": atoms[outer]["x"], "y": atoms[outer]["y"]}
+ sub_bonds[f"__bond{i}"] = {"id": f"__bond{i}", "a": inner, "b": sid, "order": b.get("order", 1)}
+ conv = perceive.prepare({"atoms": sub_atoms, "bonds": sub_bonds}, expansions)
+ mol = ids.identifier_mol(conv.mol)
+ Chem.RemoveStereochemistry(mol)
+ return ids.smiles(mol)
+
+
+def contract(frag: dict, atoms: list[str], label: str | None = None, expansions: dict | None = None,
+ has_map: bool = True, used: set[str] | None = None) -> dict:
+ fid = frag["id"]
+ frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {}
+ sel = {a for a in atoms if a in frag_atoms}
+ if not sel:
+ raise ValueError("select the atoms of the substituent to contract")
+ if len(sel) == len(frag_atoms):
+ raise ValueError("the selection is the whole fragment; leave at least the atom it is attached to")
+ if _components(sel, frag_bonds) > 1:
+ raise ValueError("the selection must be one connected piece")
+ crossing = sorted((b for b in frag_bonds.values() if (b["a"] in sel) != (b["b"] in sel)), key=_bond_key)
+ if not crossing:
+ raise ValueError("the selection is not bonded to the rest of the fragment")
+ notes: list[dict] = []
+ drawn = substituent_smiles(frag, sel, crossing[:1], expansions) if len(crossing) == 1 else ""
+ found = abbrev.match(drawn) if drawn else None
+ if label is None:
+ if found is None:
+ raise ValueError("no abbreviation in the library matches this selection; give a label")
+ label = found
+ elif drawn and abbrev.entry(label) and found != label:
+ notes.append(warning("label_mismatch", f"{label} in the library is a different group; the drawn atoms are kept as its expansion."))
+ used = set(used or ()) | set(frag_atoms) | set(frag_bonds)
+ eid = _fresh("e", used | set(expansions or {}))
+ nid = _fresh("a", used)
+ attach = []
+ for b in crossing:
+ inner = b["a"] if b["a"] in sel else b["b"]
+ if inner not in attach:
+ attach.append(inner)
+ first = crossing[0]
+ origin, outer = (first["a"], first["b"]) if first["a"] in sel else (first["b"], first["a"])
+ ox, oy = frag_atoms[origin]["x"], frag_atoms[origin]["y"]
+ t = math.atan2(frag_atoms[outer]["y"] - oy, frag_atoms[outer]["x"] - ox)
+ c, s = math.cos(-t), math.sin(-t)
+ rec_atoms = {}
+ for aid in sorted(sel):
+ a = dict(frag_atoms[aid])
+ a["x"], a["y"] = (round(v, 4) for v in _rotate(a["x"] - ox, a["y"] - oy, c, s))
+ rec_atoms[aid] = a
+ rec = {"id": eid, "label": label, "reversed": abbrev.reversed_label(label) if abbrev.entry(label) else label, "atoms": rec_atoms,
+ "bonds": {k: dict(b) for k, b in frag_bonds.items() if b["a"] in sel and b["b"] in sel}, "attach": attach,
+ "source": "user" if label in abbrev.user_entries() or not abbrev.entry(label) else "builtin"}
+ ops: list[dict] = [{"op": "set", "path": ["expansions", eid], "value": rec} if has_map else {"op": "set", "path": ["expansions"], "value": {eid: rec}}]
+ ops.append({"op": "set", "path": atom_path(fid, nid), "value": {"id": nid, "element": "*", "x": ox, "y": oy, "label": label, "expansion": eid}})
+ for b in crossing:
+ end = "a" if b["a"] in sel else "b"
+ ops.append({"op": "set", "path": bond_path(fid, b["id"], end), "value": nid})
+ if end == "a" and (b.get("stereo") or "none") in ("wedge", "hash", "hollow", "wavy"):
+ ops.append({"op": "set", "path": bond_path(fid, b["id"], "stereo")})
+ notes.append(warning("stereo_dropped", "A wedge that started inside the contracted atoms was removed.", bonds=[b["id"]]))
+ ops.extend({"op": "set", "path": bond_path(fid, k)} for k, b in sorted(frag_bonds.items()) if b["a"] in sel and b["b"] in sel)
+ ops.extend({"op": "set", "path": atom_path(fid, a)} for a in sorted(sel))
+ groups = frag.get("stereo_groups")
+ if groups and any(a in sel for g in groups if isinstance(g, dict) for a in g.get("atoms") or []):
+ kept = [{**g, "atoms": [a for a in g.get("atoms") or [] if a not in sel]} for g in groups if isinstance(g, dict)]
+ kept = [g for g in kept if g["atoms"]]
+ ops.append({"op": "set", "path": object_path(fid, "stereo_groups"), **({"value": kept} if kept else {})})
+ return {"tx": {"label": f"Contract to {label}", "ops": ops}, "atom": nid, "expansion": eid, "label": label, "warnings": notes}
+
+
+def template_record(label: str, smiles: str, bond_length: float) -> dict | None:
+ mol = Chem.MolFromSmiles(smiles)
+ if mol is None:
+ return None
+ frag = convert.from_mol(mol, bond_length)
+ star = next((a for a in frag["atoms"].values() if a["element"] == "*"), None)
+ link = next((b for b in frag["bonds"].values() if star and star["id"] in (b["a"], b["b"])), None)
+ if star is None or link is None:
+ return None
+ origin = frag["atoms"][link["b"] if link["a"] == star["id"] else link["a"]]
+ t = math.atan2(star["y"] - origin["y"], star["x"] - origin["x"])
+ c, s = math.cos(-t), math.sin(-t)
+ atoms = {}
+ for aid, a in frag["atoms"].items():
+ if aid == star["id"]:
+ continue
+ x, y = _rotate(a["x"] - origin["x"], a["y"] - origin["y"], c, s)
+ atoms[aid] = {**a, "x": x, "y": y}
+ bonds = {k: b for k, b in frag["bonds"].items() if k != link["id"]}
+ return {"label": label, "atoms": atoms, "bonds": bonds, "attach": [origin["id"]]}
+
+
+def _clashes(pts: dict[str, Point], others: list[Point], limit: float) -> float:
+ score = 0.0
+ for x, y in pts.values():
+ for ox, oy in others:
+ d = math.hypot(x - ox, y - oy)
+ if d < limit:
+ score += (limit - d) / limit
+ return score
+
+
+def abbreviation_atoms(frag: dict, expansions: dict | None = None) -> list[str]:
+ out = []
+ for aid, a in sorted((frag.get("atoms") or {}).items()):
+ if a.get("expansion") and a["expansion"] in (expansions or {}):
+ out.append(aid)
+ elif a.get("label"):
+ nbrs = [frag["atoms"][b["b"] if b["a"] == aid else b["a"]].get("element", "C") for b in (frag.get("bonds") or {}).values() if aid in (b["a"], b["b"])]
+ if abbrev.resolve(a["label"], a.get("element", "C"), nbrs):
+ out.append(aid)
+ return out
+
+
+def expand(frag: dict, atoms: list[str] | None = None, expansions: dict | None = None, bond_length: float | None = None,
+ used: set[str] | None = None, elsewhere: set[str] | None = None, drop: bool = False) -> dict:
+ fid = frag["id"]
+ frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {}
+ expansions = expansions or {}
+ length = bond_length or convert.median_bond_length(frag)
+ candidates = abbreviation_atoms(frag, expansions)
+ targets = candidates if atoms is None else [a for a in atoms if a in candidates]
+ if not targets:
+ raise ValueError("none of the chosen atoms is an abbreviation")
+ used = set(used or ()) | set(frag_atoms) | set(frag_bonds)
+ placed: list[Point] = [(a["x"], a["y"]) for k, a in frag_atoms.items() if k not in targets]
+ ops: list[dict] = []
+ notes: list[dict] = []
+ expanded: dict[str, list[str]] = {}
+ for sid in targets:
+ s_atom = frag_atoms[sid]
+ rec = expansions.get(s_atom.get("expansion")) if s_atom.get("expansion") else None
+ if rec is None:
+ nbrs = [frag_atoms[b["b"] if b["a"] == sid else b["a"]].get("element", "C") for b in frag_bonds.values() if sid in (b["a"], b["b"])]
+ smiles = abbrev.resolve(s_atom.get("label"), s_atom.get("element", "C"), nbrs)
+ rec = template_record(s_atom["label"], smiles, length) if smiles else None
+ attach = [a for a in (rec or {}).get("attach") or [] if a in (rec or {}).get("atoms", {})]
+ if not attach:
+ notes.append(warning("bad_expansion", "This abbreviation has no attachment atom and was left as is.", [sid]))
+ continue
+ links = sorted((b for b in frag_bonds.values() if sid in (b["a"], b["b"])), key=_bond_key)
+ px, py = s_atom["x"], s_atom["y"]
+ if links:
+ other = frag_atoms[links[0]["b"] if links[0]["a"] == sid else links[0]["a"]]
+ t = math.atan2(other["y"] - py, other["x"] - px)
+ else:
+ t = 0.0
+ c, s = math.cos(t), math.sin(t)
+ ax0, ay0 = rec["atoms"][attach[0]]["x"], rec["atoms"][attach[0]]["y"]
+ best = None
+ for mirror in (1.0, -1.0):
+ pts = {}
+ for aid, a in rec["atoms"].items():
+ dx, dy = _rotate(a["x"] - ax0, (a["y"] - ay0) * mirror, c, s)
+ pts[aid] = (round(px + dx, 3), round(py + dy, 3))
+ score = _clashes({k: p for k, p in pts.items() if k != attach[0]}, placed, 0.6 * length)
+ if best is None or score < best[0] - 1e-9:
+ best = (score, pts)
+ pts = best[1]
+ idmap = {aid: (aid if aid not in used else _fresh("a", used)) for aid in rec["atoms"]}
+ used.update(idmap.values())
+ for aid, a in rec["atoms"].items():
+ nid = idmap[aid]
+ ops.append({"op": "set", "path": atom_path(fid, nid), "value": {**a, "id": nid, "x": pts[aid][0], "y": pts[aid][1]}})
+ for bid, b in rec.get("bonds", {}).items():
+ if b.get("a") not in idmap or b.get("b") not in idmap:
+ continue
+ nb = bid if bid not in used else _fresh("b", used)
+ used.add(nb)
+ ops.append({"op": "set", "path": bond_path(fid, nb), "value": {**b, "id": nb, "a": idmap[b["a"]], "b": idmap[b["b"]]}})
+ if len(links) > len(attach):
+ notes.append(warning("abbreviation_bonds", f"{rec.get('label') or sid} has {len(attach)} attachment point(s) but {len(links)} bonds; the extra bonds join the last one.", [sid]))
+ for k, b in enumerate(links):
+ end = "a" if b["a"] == sid else "b"
+ ops.append({"op": "set", "path": bond_path(fid, b["id"], end), "value": idmap[attach[min(k, len(attach) - 1)]]})
+ ops.append({"op": "set", "path": atom_path(fid, sid)})
+ placed.extend(pts.values())
+ expanded[sid] = [idmap[a] for a in sorted(rec["atoms"])]
+ if drop:
+ gone = {frag_atoms[s].get("expansion") for s in expanded if frag_atoms[s].get("expansion")}
+ still = {a.get("expansion") for k, a in frag_atoms.items() if k not in expanded} | set(elsewhere or ())
+ ops.extend({"op": "set", "path": ["expansions", e]} for e in sorted(gone - still))
+ label = "Expand abbreviation" if len(expanded) == 1 else "Expand abbreviations"
+ return {"tx": {"label": label, "ops": ops}, "expanded": expanded, "warnings": notes}
diff --git a/backend/app/services/chem/v3000.py b/backend/app/services/chem/v3000.py
new file mode 100644
index 00000000..c2a56e21
--- /dev/null
+++ b/backend/app/services/chem/v3000.py
@@ -0,0 +1,292 @@
+from rdkit import Chem
+
+from app.services.chem import DEFAULT_BOND_LENGTH, convert, io, markush, perceive, query, warning
+
+PREFIX = "M V30 "
+WIDTH = 78
+BOND_TYPES = {"any": "8", "single_or_double": "5", "single_or_aromatic": "6", "double_or_aromatic": "7"}
+TOPOLOGY = {"ring": "1", "chain": "2"}
+
+
+def _unwrap(block: str) -> list[str]:
+ out: list[str] = []
+ carry = ""
+ for line in block.splitlines():
+ if carry:
+ line = carry + line[len(PREFIX):] if line.startswith(PREFIX) else carry + line
+ carry = ""
+ if line.startswith(PREFIX) and line.endswith("-"):
+ carry = line[:-1]
+ continue
+ out.append(line)
+ return out
+
+
+def _wrap(line: str) -> list[str]:
+ if not line.startswith(PREFIX) or len(line) <= WIDTH:
+ return [line]
+ out, rest = [], line
+ while len(rest) > WIDTH:
+ out.append(rest[: WIDTH - 1] + "-")
+ rest = PREFIX + rest[WIDTH - 1:]
+ out.append(rest)
+ return out
+
+
+def atom_type(a: dict) -> str | None:
+ q = a.get("query") if isinstance(a.get("query"), dict) else {}
+ if q.get("list"):
+ body = "[" + ",".join(q["list"]) + "]"
+ return f"NOT{body}" if q.get("not") else body
+ if q.get("generic") in query.GENERIC_SMARTS:
+ return q["generic"]
+ return None
+
+
+def atom_keywords(a: dict, frag: dict, ring_bonds: set[str], notes: list[dict]) -> list[str]:
+ q = a.get("query") if isinstance(a.get("query"), dict) else {}
+ out = []
+ rb = q.get("ring_bonds")
+ if isinstance(rb, int) and not isinstance(rb, bool):
+ out.append(f"RBCNT={-1 if rb == 0 else -2 if rb == -2 else min(rb, 4)}")
+ sub = q.get("subst")
+ if isinstance(sub, int) and not isinstance(sub, bool):
+ out.append(f"SUBST={-1 if sub == 0 else -2 if sub == -2 else min(sub, 6)}")
+ if q.get("unsat"):
+ out.append("UNSAT=1")
+ h = q.get("h_min")
+ if isinstance(h, int) and not isinstance(h, bool) and h > 0:
+ out.append(f"HCOUNT={h}")
+ if "aromatic" in q or q.get("smarts"):
+ lossy = next((w for w in notes if w["code"] == "v3000_query_lossy"), None)
+ if lossy is None:
+ notes.append(warning("v3000_query_lossy", "Aromaticity and SMARTS atom queries have no V3000 field; they are left out.", [a["id"]]))
+ else:
+ lossy["atoms"] = sorted({*lossy.get("atoms", []), a["id"]})
+ return out
+
+
+def _decorate(block: str, frag: dict, conv, notes: list[dict], attach: dict[str, int] | None = None) -> list[str]:
+ atoms = frag.get("atoms") or {}
+ bonds = frag.get("bonds") or {}
+ mol = conv.mol
+ ring_bonds = {conv.bond_id(b.GetIdx()) for b in mol.GetBonds() if conv.bond_id(b.GetIdx()) and mol.GetRingInfo().NumBondRings(b.GetIdx())}
+ lines = _unwrap(block)
+ section = None
+ out: list[str] = []
+ for line in lines:
+ body = line[len(PREFIX):] if line.startswith(PREFIX) else None
+ if body in ("BEGIN ATOM", "BEGIN BOND"):
+ section = body[6:]
+ elif body in ("END ATOM", "END BOND"):
+ section = None
+ elif section and body:
+ parts = body.split()
+ i = int(parts[0]) - 1
+ if section == "ATOM" and i < len(conv.owner) and conv.drawn[i]:
+ a = atoms[conv.owner[i]]
+ kind = atom_type(a)
+ if kind:
+ parts[1] = kind
+ parts.extend(atom_keywords(a, frag, ring_bonds, notes))
+ if attach and conv.owner[i] in attach:
+ parts.append(f"ATTCHPT={attach[conv.owner[i]]}")
+ elif section == "BOND":
+ bid = conv.bond_id(i)
+ b = bonds.get(bid) if bid else None
+ if b and b.get("query") in BOND_TYPES:
+ parts[1] = BOND_TYPES[b["query"]]
+ if b and b.get("topology") in TOPOLOGY:
+ parts.append(f"TOPO={TOPOLOGY[b['topology']]}")
+ line = PREFIX + " ".join(parts)
+ out.append(line)
+ return out
+
+
+def _ctab(frag: dict, expansions: dict | None, notes: list[dict], attach: dict[str, int] | None = None) -> list[str]:
+ mol, extra = io._writable(frag, expansions)
+ asked = {k for k, a in (frag.get("atoms") or {}).items() if query.is_query_atom(a)}
+ notes.extend(w for w in extra if w["code"] != "query_ignored" and not (w["code"] == "unknown_label" and set(w.get("atoms", [])) <= asked))
+ conv = perceive.prepare(frag, expansions)
+ try:
+ block = Chem.MolToV3KMolBlock(mol, includeStereo=True, kekulize=True)
+ except Exception:
+ block = Chem.MolToV3KMolBlock(mol, includeStereo=True, kekulize=False)
+ return _decorate(block, frag, conv, notes, attach)
+
+
+def _member(frag: dict, row: dict) -> dict:
+ stubs = set(row["stubs"])
+ return {**frag, "atoms": {k: a for k, a in frag["atoms"].items() if k not in stubs},
+ "bonds": {k: b for k, b in (frag.get("bonds") or {}).items() if b["a"] not in stubs and b["b"] not in stubs}}
+
+
+def write(frag: dict, expansions: dict | None = None, members: dict[str, dict] | None = None) -> tuple[str, list[dict]]:
+ notes: list[dict] = []
+ lines = _ctab(frag, expansions, notes)
+ blocks: list[str] = []
+ if frag.get("rgroups"):
+ desc = markush.describe(frag, members or {})
+ notes.extend(desc["warnings"])
+ for g in desc["groups"]:
+ if not g["members"]:
+ continue
+ blocks.append(f"{PREFIX}BEGIN RGROUP {g['n']}")
+ blocks.append(f"{PREFIX}RLOGIC {g['if_then'] or 0} {1 if g['rest_h'] else 0} {g['occurrence']}")
+ for row in g["members"]:
+ member = _member(members[row["object"]], row)
+ ctab = _ctab(member, expansions, notes, {a: 1 for a in row["attach"][:1]})
+ start = next(i for i, l in enumerate(ctab) if l == f"{PREFIX}BEGIN CTAB")
+ end = next(i for i, l in enumerate(ctab) if l == f"{PREFIX}END CTAB")
+ blocks.extend(ctab[start:end + 1])
+ blocks.append(f"{PREFIX}END RGROUP")
+ end = len(lines) - 1 - next(i for i, l in enumerate(reversed(lines)) if l.startswith("M END"))
+ lines = lines[:end] + blocks + lines[end:]
+ seen: set[tuple] = set()
+ unique = []
+ for w in notes:
+ key = (w["code"], tuple(w.get("atoms", ())), tuple(w.get("bonds", ())))
+ if key not in seen:
+ seen.add(key)
+ unique.append(w)
+ return "\n".join(x for line in lines for x in _wrap(line)) + "\n", unique
+
+
+GENERIC_TYPES = set(query.GENERIC_SMARTS)
+QUERY_BONDS = {v: k for k, v in BOND_TYPES.items()}
+TOPOLOGY_BY_CODE = {v: k for k, v in TOPOLOGY.items()}
+HEADER = ["", " FormChem", "", " 0 0 0 0 0 999 V3000"]
+
+
+def _keywords(parts: list[str]) -> dict[str, str]:
+ return {p.split("=", 1)[0].upper(): p.split("=", 1)[1] for p in parts if "=" in p}
+
+
+def _read_ctab(lines: list[str], bond_length: float, origin: tuple[float, float], used: set[str]) -> tuple[dict, list[dict]]:
+ notes: list[dict] = []
+ atom_q: list[dict] = []
+ bond_q: list[dict] = []
+ clean: list[str] = []
+ section = None
+ for line in lines:
+ body = line[len(PREFIX):] if line.startswith(PREFIX) else None
+ if body in ("BEGIN ATOM", "BEGIN BOND"):
+ section = body[6:]
+ elif body in ("END ATOM", "END BOND"):
+ section = None
+ elif section and body:
+ parts = body.split()
+ kw = _keywords(parts[6:] if section == "ATOM" else parts[4:])
+ if section == "ATOM":
+ q: dict = {}
+ kind = parts[1].strip('"')
+ listed = kind.upper().startswith("NOT")
+ inner = kind[3:].strip() if listed else kind
+ if inner.startswith("[") and inner.endswith("]"):
+ q["list"] = [s.strip() for s in inner[1:-1].split(",") if s.strip()]
+ if listed:
+ q["not"] = True
+ parts[1] = "C"
+ elif kind in GENERIC_TYPES:
+ q["generic"] = kind
+ parts[1] = "C"
+ for key, field, zero, cap in (("RBCNT", "ring_bonds", 0, 4), ("SUBST", "subst", 0, 6)):
+ if key in kw and kw[key].lstrip("-").isdigit() and int(kw[key]) != 0:
+ v = int(kw[key])
+ q[field] = zero if v == -1 else -2 if v == -2 else min(v, cap)
+ if kw.get("UNSAT") == "1":
+ q["unsat"] = True
+ if kw.get("HCOUNT", "").isdigit() and int(kw["HCOUNT"]) > 0:
+ q["h_min"] = int(kw["HCOUNT"])
+ atom_q.append({"query": q, "attach": int(kw["ATTCHPT"]) if kw.get("ATTCHPT", "").lstrip("-").isdigit() else 0})
+ parts = parts[:6] + [p for p in parts[6:] if p.split("=", 1)[0].upper() not in ("RBCNT", "SUBST", "UNSAT", "HCOUNT", "ATTCHPT")]
+ else:
+ bond_q.append({"query": QUERY_BONDS.get(parts[1]), "topology": TOPOLOGY_BY_CODE.get(kw.get("TOPO", ""))})
+ if parts[1] in QUERY_BONDS:
+ parts[1] = "2" if parts[1] == "7" else "1"
+ parts = parts[:4] + [p for p in parts[4:] if not p.upper().startswith("TOPO=")]
+ line = PREFIX + " ".join(parts)
+ clean.append(line)
+ mol = Chem.MolFromMolBlock("\n".join(HEADER + clean + ["M END"]), sanitize=False, removeHs=False, strictParsing=False)
+ if mol is None:
+ raise ValueError("a CTAB in this molfile cannot be read")
+ try:
+ Chem.SanitizeMol(mol, Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_PROPERTIES, catchErrors=True)
+ mol.UpdatePropertyCache(strict=False)
+ except Exception:
+ pass
+ frag = convert.from_mol(mol, bond_length, origin, used=used)
+ atom_ids, bond_ids = list(frag["atoms"]), list(frag["bonds"])
+ for aid, extra in zip(atom_ids, atom_q):
+ a = frag["atoms"][aid]
+ if extra["query"]:
+ a["query"] = extra["query"]
+ if "list" in extra["query"] or "generic" in extra["query"]:
+ a["element"] = "*"
+ a.pop("hydrogens", None)
+ if extra["attach"]:
+ a["data"] = {**(a.get("data") or {}), "attach": 1 if extra["attach"] in (1, -1) else 2}
+ for bid, extra in zip(bond_ids, bond_q):
+ b = frag["bonds"][bid]
+ if extra["query"]:
+ b["query"] = extra["query"]
+ if extra["topology"]:
+ b["topology"] = extra["topology"]
+ return frag, notes
+
+
+def read(text: str, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0)) -> tuple[list[dict], list[dict]]:
+ lines = _unwrap(text.replace("\r\n", "\n"))
+ if not any(line.startswith(f"{PREFIX}BEGIN CTAB") for line in lines):
+ raise ValueError("not a V3000 molfile")
+ used: set[str] = set()
+ root: list[str] = []
+ groups: list[dict] = []
+ current: dict | None = None
+ ctab: list[str] | None = None
+ for line in lines:
+ body = line[len(PREFIX):] if line.startswith(PREFIX) else None
+ if body is None:
+ continue
+ if body.startswith("BEGIN RGROUP"):
+ current = {"n": int(body.split()[2]), "logic": [], "ctabs": []}
+ groups.append(current)
+ elif body == "END RGROUP":
+ current = None
+ elif current is not None and body.startswith("RLOGIC"):
+ current["logic"] = body.split()[1:]
+ elif body == "BEGIN CTAB":
+ ctab = [line]
+ elif body == "END CTAB" and ctab is not None:
+ ctab.append(line)
+ if current is not None:
+ current["ctabs"].append(ctab)
+ else:
+ root.extend(ctab)
+ ctab = None
+ elif ctab is not None:
+ ctab.append(line)
+ notes: list[dict] = []
+ scaffold, found = _read_ctab(root, bond_length, origin, used)
+ notes.extend(found)
+ out = [scaffold]
+ bottom = max((a["y"] for a in scaffold["atoms"].values()), default=origin[1]) + 3 * bond_length
+ rgroups: dict[str, dict] = {}
+ for g in groups:
+ x = origin[0]
+ members = []
+ for lines_m in g["ctabs"]:
+ member, found = _read_ctab(lines_m, bond_length, (x, bottom), used)
+ notes.extend(found)
+ members.append(member["id"])
+ out.append(member)
+ x = max((a["x"] for a in member["atoms"].values()), default=x) + 3 * bond_length
+ bottom += 4 * bond_length
+ logic = g["logic"]
+ rec: dict = {"members": members, "occurrence": logic[2].strip('"') if len(logic) > 2 else ">0", "rest_h": len(logic) > 1 and logic[1] == "1"}
+ if logic and logic[0].isdigit() and int(logic[0]) > 0:
+ rec["if_then"] = int(logic[0])
+ rgroups[str(g["n"])] = rec
+ if rgroups:
+ scaffold["rgroups"] = rgroups
+ return out, notes
diff --git a/backend/app/services/importers.py b/backend/app/services/importers.py
index e4613ee4..f40d0335 100644
--- a/backend/app/services/importers.py
+++ b/backend/app/services/importers.py
@@ -170,6 +170,23 @@ def place(frags: list[dict], page: dict, bond_length: float) -> None:
top += height + gap
+def _reaction(doc: dict, page: dict, result: object, bond_length: float, ids: _Ids, warnings: list[str], source: Path) -> bool:
+ margin = float(page.get("margins", 36))
+ try:
+ from app.services.chem import scheme
+ comment = scheme.rxn_comment(source.read_text(encoding="utf-8", errors="replace")) if source.suffix.lower() == ".rxn" else ""
+ found = scheme.layout(result, bond_length, (margin, margin), ids.used, comment)
+ except Exception as exc:
+ warnings.append(f"the reaction could not be laid out, so its structures are placed in rows ({exc})")
+ return False
+ for obj in found["objects"]:
+ doc["objects"][obj["id"]] = obj
+ page["order"].append(obj["id"])
+ page["reactions"] = [found["reaction"]]
+ warnings[:] = [t for t in (_warning_text(w) for w in found["warnings"]) if t]
+ return True
+
+
def import_file(path: str | Path) -> tuple[dict, list[str]]:
p = Path(path).expanduser()
if not can_import(p):
@@ -189,13 +206,14 @@ def import_file(path: str | Path) -> tuple[dict, list[str]]:
page = doc["pages"][0]
ids = _Ids({doc["id"], page["id"]})
warnings: list[str] = [t for t in (_warning_text(w) for w in getattr(result, "warnings", None) or []) if t]
- frags = [f for f in (normalise_fragment(raw, ids, warnings) for raw in parsed if isinstance(raw, dict)) if f is not None]
- if not frags:
- raise ImportFailed(f"{p.name} holds no structures FormChem can draw.")
- place(frags, page, bond_length)
- for f in frags:
- doc["objects"][f["id"]] = f
- page["order"].append(f["id"])
+ if not (getattr(result, "reaction", None) and _reaction(doc, page, result, bond_length, ids, warnings, p)):
+ frags = [f for f in (normalise_fragment(raw, ids, warnings) for raw in parsed if isinstance(raw, dict)) if f is not None]
+ if not frags:
+ raise ImportFailed(f"{p.name} holds no structures FormChem can draw.")
+ place(frags, page, bond_length)
+ for f in frags:
+ doc["objects"][f["id"]] = f
+ page["order"].append(f["id"])
doc["meta"]["imported"] = {"name": p.name, "format": FORMATS[p.suffix.lower()]}
errors = model.validate(doc)
if errors:
diff --git a/backend/app/services/model.py b/backend/app/services/model.py
index b80dab0d..71aa9551 100644
--- a/backend/app/services/model.py
+++ b/backend/app/services/model.py
@@ -92,6 +92,14 @@ class Bond(TypedDict):
data: NotRequired[dict[str, Any]]
+class RGroupDef(TypedDict):
+ members: list[str]
+ occurrence: NotRequired[str]
+ rest_h: NotRequired[bool]
+ if_then: NotRequired[int]
+ attach: NotRequired[dict[str, list[str]]]
+
+
class Fragment(TypedDict):
id: str
kind: Literal["fragment"]
@@ -105,7 +113,7 @@ class Fragment(TypedDict):
data: NotRequired[dict[str, Any]]
chiral: NotRequired[Literal["absolute", "relative", "racemic"]]
stereo_groups: NotRequired[list[dict[str, Any]]]
- rgroups: NotRequired[dict[str, dict[str, Any]]]
+ rgroups: NotRequired[dict[str, RGroupDef]]
class Page(TypedDict):
diff --git a/backend/app/services/package.py b/backend/app/services/package.py
index b04d3a01..109d793c 100644
--- a/backend/app/services/package.py
+++ b/backend/app/services/package.py
@@ -36,6 +36,59 @@ def media_ext(mime: str | None) -> str:
return EXT_BY_MIME.get(mime) or mimetypes.guess_extension(mime) or ".bin"
+def _jpeg_size(data: bytes) -> tuple[int, int] | None:
+ i = 2
+ while i + 9 < len(data):
+ if data[i] != 0xFF:
+ i += 1
+ continue
+ marker = data[i + 1]
+ if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7 or marker == 0xFF:
+ i += 1 if marker == 0xFF else 2
+ continue
+ length = int.from_bytes(data[i + 2:i + 4], "big")
+ if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
+ return int.from_bytes(data[i + 7:i + 9], "big"), int.from_bytes(data[i + 5:i + 7], "big")
+ i += 2 + length
+ return None
+
+
+def _webp_size(data: bytes) -> tuple[int, int] | None:
+ chunk = data[12:16]
+ if chunk == b"VP8 " and len(data) >= 30:
+ return int.from_bytes(data[26:28], "little") & 0x3FFF, int.from_bytes(data[28:30], "little") & 0x3FFF
+ if chunk == b"VP8L" and len(data) >= 25:
+ bits = int.from_bytes(data[21:25], "little")
+ return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
+ if chunk == b"VP8X" and len(data) >= 30:
+ return int.from_bytes(data[24:27], "little") + 1, int.from_bytes(data[27:30], "little") + 1
+ return None
+
+
+def _is_svg(head: bytes) -> bool:
+ return head.startswith((b"