dsh-molbio-tools 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -6,8 +6,9 @@
6
6
  * package — so the toolset travels with an agent preset and can be referenced
7
7
  * by a package-name row (see README.md and rules.md rule 1).
8
8
  *
9
- * Every tool is pure computation: deterministic, no network, no filesystem.
10
- * The plugin publishes no service, so the preset row needs no isolate realm.
9
+ * Every tool is deterministic. File-reading/writing tools go through ctx.fs with
10
+ * the session sandboxPolicy; PubMed search is the only network path. The plugin
11
+ * publishes no service, so the preset row needs no isolate realm.
11
12
  */
12
13
 
13
14
  import {
@@ -72,6 +73,9 @@ import { addExperiment, addProtocol, loadRecords, recordPath, saveRecords, updat
72
73
  import { toBibtex } from './papers.mjs';
73
74
  import { parseXml } from './snapgene.mjs';
74
75
  import { analyzeDuplex } from './thermo.mjs';
76
+ import { antigenicityProfile, renderSignalPeptideProfile, scanProteinFeatures, signalPeptideAnalysis } from './protein-annotate.mjs';
77
+ import { editSequence, exportFeatures } from './sequence-ops.mjs';
78
+ import { assembleReads, callEditingOutcomes } from './sequencing.mjs';
75
79
  import { smithWaterman } from './align.mjs';
76
80
  import { conservationAnalysis, normalizeAlignedRow, normalizeMsaSequence, pairwiseIdentities, progressiveAlign } from './msa.mjs';
77
81
  import { ALIGN_POST_LIMITS, CONSENSUS_MODES, alignmentPostprocess } from './align-post.mjs';
@@ -8192,6 +8196,627 @@ const paperRemoveTool = (ctx) => define({
8192
8196
 
8193
8197
  // ── plugin apply ────────────────────────────────────────────────────────────
8194
8198
 
8199
+ // ── v0.28.0: protein annotation (#13/#14/#21) ───────────────────────────────
8200
+
8201
+ const PTM_SITE_SCHEMA = {
8202
+ type: 'object',
8203
+ additionalProperties: false,
8204
+ required: ['type', 'motif', 'position', 'context'],
8205
+ properties: {
8206
+ type: { type: 'string' },
8207
+ motif: { type: 'string' },
8208
+ position: { type: 'integer' },
8209
+ context: { type: 'string' },
8210
+ },
8211
+ };
8212
+
8213
+ const proteinFeaturesTool = define({
8214
+ name: 'molbio_protein_features',
8215
+ description: 'Scan a protein for post-translational-modification motifs (N-glycosylation N-{P}-[S/T], C-mannosylation W-x-x-W, N-terminal N-myristoylation, SUMOylation [LIVFM]-K-x-E, PKA R-R-x-[S/T], CK2 [S/T]-x-x-[D/E], proline-directed [S/T]-P), SEG-style low-complexity regions from an entropy window, and composition flags (aromaticity, instability index with its stable/unstable call). Motifs are linear consensus patterns and low complexity is an entropy approximation — a match is a candidate, not evidence that the site is modified.',
8216
+ parameters: {
8217
+ type: 'object',
8218
+ required: ['sequence'],
8219
+ properties: {
8220
+ sequence: requiredString('Protein sequence (one-letter amino acid codes).'),
8221
+ window: { type: 'integer', description: 'Low-complexity entropy window in residues (4-50, default 12).' },
8222
+ entropy_threshold: { type: 'number', description: 'Entropy threshold in bits (0-4.5, default 2.2); windows below it are low complexity.' },
8223
+ max_sites: { type: 'integer', description: 'Maximum reported PTM sites (1-2000, default 200).' },
8224
+ },
8225
+ },
8226
+ outputSchema: {
8227
+ type: 'object',
8228
+ additionalProperties: false,
8229
+ required: ['length', 'ptm_sites', 'low_complexity_regions', 'composition', 'window', 'entropy_threshold', 'truncated', 'notes'],
8230
+ properties: {
8231
+ length: { type: 'integer' },
8232
+ ptm_sites: { type: 'array', items: PTM_SITE_SCHEMA },
8233
+ low_complexity_regions: {
8234
+ type: 'array',
8235
+ items: {
8236
+ type: 'object',
8237
+ additionalProperties: false,
8238
+ required: ['start', 'end', 'length', 'entropy', 'min_window_entropy'],
8239
+ properties: {
8240
+ start: { type: 'integer' },
8241
+ end: { type: 'integer' },
8242
+ length: { type: 'integer' },
8243
+ entropy: { type: 'number' },
8244
+ min_window_entropy: { type: 'number' },
8245
+ },
8246
+ },
8247
+ },
8248
+ composition: {
8249
+ type: 'object',
8250
+ additionalProperties: false,
8251
+ required: ['aromaticity', 'instability_index', 'instability_class'],
8252
+ properties: {
8253
+ aromaticity: { type: 'number' },
8254
+ instability_index: { type: 'number' },
8255
+ instability_class: { type: 'string', enum: ['stable', 'unstable'] },
8256
+ },
8257
+ },
8258
+ window: { type: 'integer' },
8259
+ entropy_threshold: { type: 'number' },
8260
+ truncated: { type: 'boolean' },
8261
+ notes: { type: 'array', items: { type: 'string' } },
8262
+ },
8263
+ },
8264
+ render(value) {
8265
+ const lines = [`${value.length} aa · ${value.ptm_sites.length} PTM site(s) · ${value.low_complexity_regions.length} low-complexity region(s)`];
8266
+ if (value.ptm_sites.length === 0) lines.push('PTM sites: none matched the built-in motifs');
8267
+ else {
8268
+ lines.push('PTM sites:');
8269
+ for (const site of value.ptm_sites.slice(0, 20)) lines.push(` ${site.position}: ${site.type} (${site.motif}) ${site.context}`);
8270
+ if (value.ptm_sites.length > 20) lines.push(` ... ${value.ptm_sites.length - 20} more`);
8271
+ }
8272
+ if (value.low_complexity_regions.length > 0) {
8273
+ lines.push(`low-complexity regions (entropy < ${value.entropy_threshold} bits, window ${value.window}):`);
8274
+ for (const region of value.low_complexity_regions.slice(0, 10)) lines.push(` ${region.start}-${region.end} (${region.length} aa, entropy ${region.entropy} bits)`);
8275
+ }
8276
+ lines.push(`aromaticity ${value.composition.aromaticity} · instability index ${value.composition.instability_index} (${value.composition.instability_class}; >40 is conventionally unstable)`);
8277
+ lines.push('Heuristics: linear motif matches and an entropy-window low-complexity approximation (SEG-style, not SEG); not a modification predictor.');
8278
+ return lines.join('\n');
8279
+ },
8280
+ execute(args) {
8281
+ return scanProteinFeatures(args.sequence, {
8282
+ window: args.window,
8283
+ entropyThreshold: args.entropy_threshold,
8284
+ maxSites: args.max_sites,
8285
+ });
8286
+ },
8287
+ });
8288
+
8289
+ const SIGNAL_CANDIDATE_SCHEMA = {
8290
+ type: 'object',
8291
+ additionalProperties: false,
8292
+ required: ['cleavage_after', 'score'],
8293
+ properties: {
8294
+ cleavage_after: { type: 'integer' },
8295
+ score: { type: 'number' },
8296
+ },
8297
+ };
8298
+
8299
+ const TM_SEGMENT_SCHEMA = {
8300
+ type: 'object',
8301
+ additionalProperties: false,
8302
+ required: ['start', 'end', 'length', 'mean_hydropathy', 'peak_position'],
8303
+ properties: {
8304
+ start: { type: 'integer' },
8305
+ end: { type: 'integer' },
8306
+ length: { type: 'integer' },
8307
+ mean_hydropathy: { type: 'number' },
8308
+ peak_position: { type: 'integer' },
8309
+ },
8310
+ };
8311
+
8312
+ const signalPeptideTool = (ctx) => define({
8313
+ safe: false,
8314
+ name: 'molbio_signal_peptide',
8315
+ description: 'Score N-terminal signal-peptide cleavage with the von Heijne 1986 position weights (the EMBOSS sigcleave table, eukaryote or gram-negative) and list candidate transmembrane segments with the same Kyte-Doolittle window molbio_hydropathy_plot uses. Returns the best cleavage position (residues in the signal peptide), the signal peptide itself, candidate cleavage sites above the threshold, and a score-profile SVG written to the workspace. A score above the threshold is a candidate, NOT a SignalP prediction; topology/orientation is not predicted.',
8316
+ parameters: {
8317
+ type: 'object',
8318
+ required: ['sequence'],
8319
+ properties: {
8320
+ sequence: requiredString('Protein sequence (one-letter amino acid codes).'),
8321
+ organism: { type: 'string', enum: ['eukaryote', 'gram_negative'], description: 'Which von Heijne table to use (default eukaryote).' },
8322
+ threshold: { type: 'number', description: 'Minimum score to report a cleavage site (-20 to 20, default 3.5 = EMBOSS sigcleave minweight).' },
8323
+ max_cleavage: { type: 'integer', description: 'Only score cleavage positions up to this residue (15-200, default 50; signal peptides are N-terminal).' },
8324
+ tm_window: { type: 'integer', description: 'Kyte-Doolittle window for transmembrane segments (3-51, default 19).' },
8325
+ tm_threshold: { type: 'number', description: 'Kyte-Doolittle threshold for transmembrane segments (-4.5 to 4.5, default 1.6).' },
8326
+ title: { type: 'string', description: 'Title drawn on the SVG (default "Signal-peptide score profile").' },
8327
+ output_path: { type: 'string', description: 'Optional SVG file path; default signal-peptide.svg in the session workspace.' },
8328
+ auto_view: { type: 'boolean', description: 'Open the SVG automatically with the OS default application (default true).' },
8329
+ ...ATTACH_IMAGE_PARAM,
8330
+ },
8331
+ },
8332
+ outputSchema: {
8333
+ type: 'object',
8334
+ additionalProperties: false,
8335
+ required: ['length', 'organism', 'threshold', 'cleavable', 'best_score', 'cleavage_after', 'scanned_to', 'window_start', 'window_end', 'signal_peptide', 'mature_sequence', 'candidates', 'transmembrane_segments', 'tm_window', 'tm_threshold', 'svg_path', 'auto_viewed', 'notes'],
8336
+ properties: {
8337
+ length: { type: 'integer' },
8338
+ organism: { type: 'string', enum: ['eukaryote', 'gram_negative'] },
8339
+ threshold: { type: 'number' },
8340
+ cleavable: { type: 'boolean' },
8341
+ best_score: { type: 'number' },
8342
+ cleavage_after: { type: 'integer' },
8343
+ scanned_to: { type: 'integer' },
8344
+ window_start: { type: 'integer' },
8345
+ window_end: { type: 'integer' },
8346
+ signal_peptide: { type: 'string' },
8347
+ mature_sequence: { type: 'string' },
8348
+ candidates: { type: 'array', items: SIGNAL_CANDIDATE_SCHEMA },
8349
+ transmembrane_segments: { type: 'array', items: TM_SEGMENT_SCHEMA },
8350
+ tm_window: { type: 'integer' },
8351
+ tm_threshold: { type: 'number' },
8352
+ svg_path: { type: 'string' },
8353
+ auto_viewed: { type: 'boolean' },
8354
+ image: ATTACHED_IMAGE_SCHEMA,
8355
+ image_note: { type: 'string' },
8356
+ notes: { type: 'array', items: { type: 'string' } },
8357
+ },
8358
+ },
8359
+ render(value) {
8360
+ const lines = [`${value.length} aa · ${value.organism} weights · threshold ${value.threshold}`];
8361
+ if (value.cleavable) {
8362
+ lines.push(`candidate signal peptide: cleavage after residue ${value.cleavage_after} (score ${value.best_score}, window ${value.window_start}-${value.window_end})`);
8363
+ lines.push(`signal peptide (${value.signal_peptide.length} aa): ${value.signal_peptide}`);
8364
+ lines.push(`mature protein starts at residue ${value.cleavage_after + 1} (${value.mature_sequence.length} aa)`);
8365
+ } else lines.push(`no cleavage site above ${value.threshold} (best score ${value.best_score} over the first ${value.scanned_to} residues)`);
8366
+ if (value.candidates.length > 1) lines.push(`other candidates: ${value.candidates.slice(1, 6).map((c) => `${c.cleavage_after} (${c.score})`).join(', ')}`);
8367
+ if (value.transmembrane_segments.length === 0) lines.push(`no candidate transmembrane segment above ${value.tm_threshold} (window ${value.tm_window})`);
8368
+ else lines.push(`candidate transmembrane segments: ${value.transmembrane_segments.map((s) => `${s.start}-${s.end} (${s.length} aa)`).join(', ')}`);
8369
+ lines.push('Heuristics: von Heijne 1986 weights and Kyte-Doolittle runs — candidates, not SignalP/TMHMM predictions; topology is not predicted.');
8370
+ lines.push(`score profile: ${value.svg_path}${value.auto_viewed ? ' (opened in the default viewer)' : ''}`);
8371
+ return lines.join('\n');
8372
+ },
8373
+ async execute(args, exec) {
8374
+ const analysis = signalPeptideAnalysis(args.sequence, {
8375
+ organism: args.organism,
8376
+ threshold: args.threshold,
8377
+ maxCleavage: args.max_cleavage,
8378
+ tmWindow: args.tm_window,
8379
+ tmThreshold: args.tm_threshold,
8380
+ });
8381
+ const { profile, ...value } = analysis;
8382
+ const svg = renderSignalPeptideProfile(analysis, { title: args.title });
8383
+ const { file, viewed, attached } = await writeSvgFile(ctx, exec, args, svg, 'signal-peptide');
8384
+ return mergeAttachedImage({ ...value, svg_path: file, auto_viewed: viewed }, attached);
8385
+ },
8386
+ });
8387
+
8388
+ const ANTIGENIC_REGION_SCHEMA = {
8389
+ type: 'object',
8390
+ additionalProperties: false,
8391
+ required: ['start', 'end', 'length', 'peak_position', 'peak_propensity', 'parker_mean', 'emini_mean', 'flexibility_mean'],
8392
+ properties: {
8393
+ start: { type: 'integer' },
8394
+ end: { type: 'integer' },
8395
+ length: { type: 'integer' },
8396
+ peak_position: { type: 'integer' },
8397
+ peak_propensity: { type: 'number' },
8398
+ parker_mean: { type: 'number' },
8399
+ emini_mean: { type: 'number' },
8400
+ flexibility_mean: { type: 'number' },
8401
+ },
8402
+ };
8403
+
8404
+ const antigenicityTool = define({
8405
+ name: 'molbio_antigenicity',
8406
+ description: 'Rank candidate surface-exposed (antigenic) regions with the Kolaskar & Tongaonkar 1990 7-mer antigenic propensity, and report Parker hydrophilicity, Emini accessibility and Vihinen flexibility as region means. A residue is selected when its 7-mer <A(p)> reaches the protein mean (or 1.0 when that mean is at least 1.0); a region needs at least min_region_length consecutive selected residues. This is a documented propensity ranking, NOT an epitope predictor (BepiPred/NetMHC are trained models with different semantics).',
8407
+ parameters: {
8408
+ type: 'object',
8409
+ required: ['sequence'],
8410
+ properties: {
8411
+ sequence: requiredString('Protein sequence (one-letter amino acid codes).'),
8412
+ min_region_length: { type: 'integer', description: 'Minimum consecutive selected residues for a region (1-100, default 6).' },
8413
+ max_regions: { type: 'integer', description: 'Maximum reported regions (1-200, default 20).' },
8414
+ },
8415
+ },
8416
+ outputSchema: {
8417
+ type: 'object',
8418
+ additionalProperties: false,
8419
+ required: ['length', 'window', 'mean_propensity', 'threshold', 'regions', 'parker_mean', 'emini_mean', 'flexibility_mean', 'truncated', 'notes'],
8420
+ properties: {
8421
+ length: { type: 'integer' },
8422
+ window: { type: 'integer' },
8423
+ mean_propensity: { type: 'number' },
8424
+ threshold: { type: 'number' },
8425
+ regions: { type: 'array', items: ANTIGENIC_REGION_SCHEMA },
8426
+ parker_mean: { type: 'number' },
8427
+ emini_mean: { type: 'number' },
8428
+ flexibility_mean: { type: 'number' },
8429
+ truncated: { type: 'boolean' },
8430
+ notes: { type: 'array', items: { type: 'string' } },
8431
+ },
8432
+ },
8433
+ render(value) {
8434
+ const lines = [`${value.length} aa · mean A(p) ${value.mean_propensity} · selection threshold ${value.threshold} · ${value.regions.length} candidate region(s)`];
8435
+ for (const region of value.regions.slice(0, 10)) {
8436
+ lines.push(` ${region.start}-${region.end} (${region.length} aa, peak ${region.peak_propensity} at ${region.peak_position}; Parker ${region.parker_mean}, Emini ${region.emini_mean}, flexibility ${region.flexibility_mean})`);
8437
+ }
8438
+ if (value.regions.length > 10) lines.push(` ... ${value.regions.length - 10} more`);
8439
+ lines.push('Heuristic ranking (Kolaskar-Tongaonkar 1990 propensity), not an epitope predictor; the three scales are reported separately, not combined into one score.');
8440
+ return lines.join('\n');
8441
+ },
8442
+ execute(args) {
8443
+ return antigenicityProfile(args.sequence, {
8444
+ minRegionLength: args.min_region_length,
8445
+ maxRegions: args.max_regions,
8446
+ });
8447
+ },
8448
+ });
8449
+ // ── v0.28.0: format interchange and sequence surgery (#10) ──────────────────
8450
+
8451
+ const EXPORT_FEATURE_IN_SCHEMA = {
8452
+ type: 'object',
8453
+ additionalProperties: false,
8454
+ required: ['start', 'end'],
8455
+ properties: {
8456
+ type: { type: 'string', description: 'Feature type written to the type column (default misc_feature).' },
8457
+ start: { type: 'integer', description: '1-based inclusive start.' },
8458
+ end: { type: 'integer', description: '1-based inclusive end.' },
8459
+ strand: { type: 'integer', enum: [1, -1], description: '1 = forward (default), -1 = reverse.' },
8460
+ label: { type: 'string', description: 'Feature name; defaults to the type.' },
8461
+ gene: { type: 'string' },
8462
+ product: { type: 'string' },
8463
+ note: { type: 'string' },
8464
+ location: { type: 'string', description: 'Raw location string (e.g. join(1..10,50..60)); kept in the export.' },
8465
+ multi_part: { type: 'boolean', description: 'True when start-end is only the outer bound of a multi-part location.' },
8466
+ },
8467
+ };
8468
+
8469
+ async function writeTextOutput(ctx, exec, path, content) {
8470
+ const fs = fsService(ctx);
8471
+ const sandboxPolicyService = ctx.get('sandboxPolicy');
8472
+ const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
8473
+ const file = workspaceFilePath(path, exec, policy?.workspaceRoot);
8474
+ await writeWorkspaceFile(fs, file, content, policy);
8475
+ return file;
8476
+ }
8477
+
8478
+ const featureExportTool = (ctx) => define({
8479
+ safe: (args) => args.output_path === undefined || args.output_path === '',
8480
+ name: 'molbio_feature_export',
8481
+ description: 'Export a plasmid/genome annotation as GFF3, BED or CSV, with each format\'s coordinate convention kept explicit: GFF3 and CSV are 1-based inclusive, BED is 0-based half-open (start-1 .. end). Features come from a .dna/.gb file (source_path) or from an inline sequence plus a features array. Multi-part features are written as their OUTER span with the raw location preserved; CDS phase is NOT computed (the transcript frame is not modelled), so that column is \'.\'. Writes the file when output_path is given and returns the text either way.',
8482
+ parameters: {
8483
+ type: 'object',
8484
+ properties: {
8485
+ source_path: { type: 'string', description: 'Path to a .dna/.gb/.gbk file whose features are exported (alternative to sequence + features).' },
8486
+ sequence: { type: 'string', description: 'Inline sequence (used with features when no source_path is given).' },
8487
+ features: { type: 'array', items: EXPORT_FEATURE_IN_SCHEMA, description: 'Features to export (1-based inclusive); required with an inline sequence.' },
8488
+ format: { type: 'string', enum: ['gff3', 'bed', 'csv'], description: 'Output format (required).' },
8489
+ output_path: { type: 'string', description: 'Optional file path; when omitted the content is returned inline only.' },
8490
+ },
8491
+ required: ['format'],
8492
+ },
8493
+ outputSchema: {
8494
+ type: 'object',
8495
+ additionalProperties: false,
8496
+ required: ['format', 'coordinate_system', 'count', 'content', 'saved_to', 'notes'],
8497
+ properties: {
8498
+ format: { type: 'string', enum: ['gff3', 'bed', 'csv'] },
8499
+ coordinate_system: { type: 'string' },
8500
+ count: { type: 'integer' },
8501
+ content: { type: 'string' },
8502
+ saved_to: { type: 'string' },
8503
+ notes: { type: 'array', items: { type: 'string' } },
8504
+ },
8505
+ },
8506
+ render(value) {
8507
+ const lines = [`exported ${value.count} feature(s) as ${value.format} (${value.coordinate_system})`];
8508
+ for (const line of value.content.split('\n').filter((line) => line !== '').slice(0, 4)) lines.push(` ${line.length > 160 ? line.slice(0, 160) + '…' : line}`);
8509
+ if (value.saved_to !== '') lines.push(`written to ${value.saved_to}`);
8510
+ else lines.push('content returned inline (no output_path given)');
8511
+ for (const note of value.notes) lines.push(`note: ${note}`);
8512
+ return lines.join('\n');
8513
+ },
8514
+ async execute(args, exec) {
8515
+ const vector = await resolveVector(ctx, exec, args, 'source_path');
8516
+ const features = args.features ?? vector.features;
8517
+ if (features.length === 0) throw new MolbioInputError('no features to export; pass a file with annotations or a features array');
8518
+ const result = exportFeatures({ name: vector.name, sequence: vector.sequence, features, format: args.format });
8519
+ const savedTo = args.output_path === undefined || args.output_path === '' ? '' : await writeTextOutput(ctx, exec, args.output_path, result.content);
8520
+ return { ...result, saved_to: savedTo };
8521
+ },
8522
+ });
8523
+
8524
+ const sequenceEditTool = (ctx) => define({
8525
+ safe: (args) => args.output_path === undefined || args.output_path === '',
8526
+ name: 'molbio_sequence_edit',
8527
+ description: 'Edit a DNA sequence: rotate (circular), insert, delete, replace, split or join (with an optional exact overlap). All coordinates are 1-based inclusive; insert.position and split.position count the bases kept before the cut (0 = prepend, length = append). Optionally write the result(s) as FASTA. Features are NOT remapped — re-export annotations against the new coordinates if an edit moves them.',
8528
+ parameters: {
8529
+ type: 'object',
8530
+ properties: {
8531
+ source_path: { type: 'string', description: 'Path to a .dna/.gb/.fa file (alternative to sequence).' },
8532
+ sequence: { type: 'string', description: 'Inline DNA sequence (alternative to source_path).' },
8533
+ operation: { type: 'string', enum: ['rotate', 'insert', 'delete', 'replace', 'split', 'join'], description: 'Which edit to perform (required).' },
8534
+ position: { type: 'integer', description: 'rotate: the 1-based base that becomes base 1. insert: bases kept before the insertion (0..length). split: split after this base.' },
8535
+ start: { type: 'integer', description: 'delete/replace: 1-based inclusive start.' },
8536
+ end: { type: 'integer', description: 'delete/replace: 1-based inclusive end.' },
8537
+ inserted: { type: 'string', description: 'insert: the sequence to insert.' },
8538
+ replacement: { type: 'string', description: 'replace: the replacement sequence.' },
8539
+ join_with: { type: 'string', description: 'join: the second sequence.' },
8540
+ overlap: { type: 'integer', description: 'join: exact suffix/prefix overlap to merge (0-…, default 0).' },
8541
+ name: { type: 'string', description: 'FASTA record name (default edited).' },
8542
+ output_path: { type: 'string', description: 'Optional FASTA output path; split writes one record per part.' },
8543
+ },
8544
+ required: ['operation'],
8545
+ },
8546
+ outputSchema: {
8547
+ type: 'object',
8548
+ additionalProperties: false,
8549
+ required: ['operation', 'input_length', 'output_length', 'sequences', 'saved_to', 'notes'],
8550
+ properties: {
8551
+ operation: { type: 'string', enum: ['rotate', 'insert', 'delete', 'replace', 'split', 'join'] },
8552
+ input_length: { type: 'integer' },
8553
+ output_length: { type: 'integer' },
8554
+ sequences: { type: 'array', items: { type: 'string' } },
8555
+ saved_to: { type: 'string' },
8556
+ notes: { type: 'array', items: { type: 'string' } },
8557
+ },
8558
+ },
8559
+ render(value) {
8560
+ const lines = [`${value.operation}: ${value.input_length} bp → ${value.sequences.length === 1 ? value.output_length + ' bp' : value.sequences.length + ' parts'}`];
8561
+ value.sequences.forEach((sequence, index) => {
8562
+ lines.push(value.sequences.length === 1 ? sequence : `part ${index + 1} (${sequence.length} bp): ${sequence}`);
8563
+ });
8564
+ if (value.saved_to !== '') lines.push(`written to ${value.saved_to}`);
8565
+ for (const note of value.notes) lines.push(`note: ${note}`);
8566
+ return lines.join('\n');
8567
+ },
8568
+ async execute(args, exec) {
8569
+ const vector = await resolveVector(ctx, exec, args, 'source_path');
8570
+ const result = editSequence({
8571
+ sequence: vector.sequence,
8572
+ operation: args.operation,
8573
+ position: args.position,
8574
+ start: args.start,
8575
+ end: args.end,
8576
+ inserted: args.inserted,
8577
+ replacement: args.replacement,
8578
+ joinWith: args.join_with,
8579
+ overlap: args.overlap,
8580
+ });
8581
+ let savedTo = '';
8582
+ if (args.output_path !== undefined && args.output_path !== '') {
8583
+ const stem = sanitizeFastaName(args.name ?? 'edited');
8584
+ const records = result.sequences.map((sequence, index) => `>${stem}${result.sequences.length > 1 ? `_part${index + 1}` : ''} (${args.operation})\n${wrapFasta(sequence)}`).join('');
8585
+ savedTo = await writeTextOutput(ctx, exec, args.output_path, records);
8586
+ }
8587
+ return { ...result, saved_to: savedTo };
8588
+ },
8589
+ });
8590
+
8591
+ function sanitizeFastaName(value) {
8592
+ return String(value).trim().replace(/[\s]+/g, '_') || 'edited';
8593
+ }
8594
+
8595
+ function wrapFasta(sequence) {
8596
+ const lines = [];
8597
+ for (let i = 0; i < sequence.length; i += 70) lines.push(sequence.slice(i, i + 70));
8598
+ return lines.join('\n') + '\n';
8599
+ }
8600
+
8601
+ // ── v0.28.0: sequencing read sets (#27/#31) ─────────────────────────────────
8602
+
8603
+ const READ_IN_SCHEMA = {
8604
+ type: 'object',
8605
+ additionalProperties: false,
8606
+ required: ['sequence'],
8607
+ properties: {
8608
+ name: { type: 'string', description: 'Read name (default readN).' },
8609
+ sequence: { type: 'string', description: 'Read bases (IUPAC DNA).' },
8610
+ qualities: { type: 'array', items: { type: 'number' }, description: 'Optional per-base Phred qualities (0-100).' },
8611
+ },
8612
+ };
8613
+
8614
+ async function readSequencingInputs(ctx, exec, args) {
8615
+ const reads = [];
8616
+ for (const path of args.paths ?? []) {
8617
+ const bytes = await readFileBytes(ctx, exec, path);
8618
+ const trace = readTraceFromBytes(bytes, path);
8619
+ const name = String(path).split(/[\\/]/).pop().replace(/\.[^.]*$/, '') || 'read';
8620
+ reads.push({ name, sequence: trace.bases, qualities: trace.qualities });
8621
+ }
8622
+ for (const read of args.reads ?? []) reads.push(read);
8623
+ if (reads.length === 0) throw new MolbioInputError('provide paths (sequencing files) and/or an inline reads array');
8624
+ return reads;
8625
+ }
8626
+
8627
+ const ASSEMBLED_READ_SCHEMA = {
8628
+ type: 'object',
8629
+ additionalProperties: false,
8630
+ required: ['name', 'orientation', 'start', 'end', 'length', 'trimmed_bases', 'overlap_left', 'overlap_right', 'mismatches'],
8631
+ properties: {
8632
+ name: { type: 'string' },
8633
+ orientation: { type: 'string', enum: ['forward', 'reverse'] },
8634
+ start: { type: 'integer' },
8635
+ end: { type: 'integer' },
8636
+ length: { type: 'integer' },
8637
+ trimmed_bases: { type: 'integer' },
8638
+ overlap_left: { type: 'integer' },
8639
+ overlap_right: { type: 'integer' },
8640
+ mismatches: { type: 'integer' },
8641
+ },
8642
+ };
8643
+
8644
+ const UNPLACED_READ_SCHEMA = {
8645
+ type: 'object',
8646
+ additionalProperties: false,
8647
+ required: ['name', 'reason'],
8648
+ properties: {
8649
+ name: { type: 'string' },
8650
+ reason: { type: 'string' },
8651
+ },
8652
+ };
8653
+
8654
+ const sangerAssembleTool = (ctx) => define({
8655
+ safe: (args) => args.output_path === undefined || args.output_path === '',
8656
+ name: 'molbio_sanger_assemble',
8657
+ description: 'Assemble a handful of Sanger reads (1-24 .ab1/.seq/.fasta files, or inline reads) into one quality-weighted consensus contig by greedy overlap-layout. Each read is tried in both orientations; quality trimming (default Phred 20 at the ends), overlap length/mismatch limits and exact-overlap circular closure (opt-in) are configurable. Reports every read\'s placement, coverage, conflicts and any unplaced read, and can write the contig as FASTA. This is not a genome assembler and does not merge paired-end reads.',
8658
+ parameters: {
8659
+ type: 'object',
8660
+ properties: {
8661
+ paths: { type: 'array', items: { type: 'string' }, description: 'Sequencing files: .ab1 (with qualities), .seq/.txt/.fasta (plain bases).' },
8662
+ reads: { type: 'array', items: READ_IN_SCHEMA, description: 'Inline reads (alternative or in addition to paths).' },
8663
+ name: { type: 'string', description: 'Contig name (default contig).' },
8664
+ min_overlap: { type: 'integer', description: 'Minimum acceptable overlap in bases (5-500, default 20).' },
8665
+ max_overlap: { type: 'integer', description: 'Longest overlap tested (min_overlap-2000, default 250).' },
8666
+ max_mismatch_fraction: { type: 'number', description: 'Mismatch fraction allowed inside an overlap (0-0.5, default 0.1).' },
8667
+ trim_quality: { type: 'number', description: 'Trim read ends below this Phred value (0-60, default 20; 0 disables).' },
8668
+ circular: { type: 'boolean', description: 'Try exact-overlap circular closure of the finished contig (default false).' },
8669
+ output_path: { type: 'string', description: 'Optional FASTA output path for the contig.' },
8670
+ },
8671
+ },
8672
+ outputSchema: {
8673
+ type: 'object',
8674
+ additionalProperties: false,
8675
+ required: ['name', 'sequence', 'length', 'read_count', 'placed_count', 'coverage_mean', 'coverage_min', 'conflicts', 'conflict_positions', 'circular_requested', 'circularized', 'circular_overlap', 'reads', 'unplaced', 'saved_to', 'notes'],
8676
+ properties: {
8677
+ name: { type: 'string' },
8678
+ sequence: { type: 'string' },
8679
+ length: { type: 'integer' },
8680
+ read_count: { type: 'integer' },
8681
+ placed_count: { type: 'integer' },
8682
+ coverage_mean: { type: 'number' },
8683
+ coverage_min: { type: 'integer' },
8684
+ conflicts: { type: 'integer' },
8685
+ conflict_positions: { type: 'array', items: { type: 'integer' } },
8686
+ circular_requested: { type: 'boolean' },
8687
+ circularized: { type: 'boolean' },
8688
+ circular_overlap: { type: 'integer' },
8689
+ reads: { type: 'array', items: ASSEMBLED_READ_SCHEMA },
8690
+ unplaced: { type: 'array', items: UNPLACED_READ_SCHEMA },
8691
+ saved_to: { type: 'string' },
8692
+ notes: { type: 'array', items: { type: 'string' } },
8693
+ },
8694
+ },
8695
+ render(value) {
8696
+ const lines = [`${value.name}: ${value.length} bp from ${value.placed_count}/${value.read_count} read(s) · coverage ${value.coverage_mean}× (min ${value.coverage_min}×) · ${value.conflicts} conflict(s)`];
8697
+ for (const read of value.reads) lines.push(` ${read.name} ${read.orientation} ${read.start}-${read.end} (${read.length} bp, overlaps ${read.overlap_left}/${read.overlap_right}, ${read.mismatches} mismatch(es), ${read.trimmed_bases} trimmed)`);
8698
+ if (value.unplaced.length > 0) lines.push(`unplaced: ${value.unplaced.map((read) => `${read.name} (${read.reason})`).join('; ')}`);
8699
+ if (value.circular_requested) lines.push(value.circularized ? `circularized by removing a ${value.circular_overlap} bp exact end overlap` : 'circular closure requested but no acceptable end overlap was found');
8700
+ if (value.saved_to !== '') lines.push(`contig written to ${value.saved_to}`);
8701
+ for (const note of value.notes) lines.push(`note: ${note}`);
8702
+ return lines.join('\n');
8703
+ },
8704
+ async execute(args, exec) {
8705
+ const reads = await readSequencingInputs(ctx, exec, args);
8706
+ const result = assembleReads(reads, {
8707
+ name: args.name,
8708
+ minOverlap: args.min_overlap,
8709
+ maxOverlap: args.max_overlap,
8710
+ maxMismatchFraction: args.max_mismatch_fraction,
8711
+ trimQuality: args.trim_quality,
8712
+ circular: args.circular,
8713
+ });
8714
+ const savedTo = args.output_path === undefined || args.output_path === ''
8715
+ ? ''
8716
+ : await writeTextOutput(ctx, exec, args.output_path, `>${sanitizeFastaName(result.name)}\n${wrapFasta(result.sequence)}`);
8717
+ return { ...result, saved_to: savedTo };
8718
+ },
8719
+ });
8720
+
8721
+ const VARIANT_SCHEMA = {
8722
+ type: 'object',
8723
+ additionalProperties: false,
8724
+ required: ['kind', 'position', 'ref', 'alt', 'length'],
8725
+ properties: {
8726
+ kind: { type: 'string', enum: ['mismatch', 'deletion', 'insertion'] },
8727
+ position: { type: 'integer' },
8728
+ end: { type: 'integer' },
8729
+ ref: { type: 'string' },
8730
+ alt: { type: 'string' },
8731
+ length: { type: 'integer' },
8732
+ },
8733
+ };
8734
+
8735
+ const ALLELE_SCHEMA = {
8736
+ type: 'object',
8737
+ additionalProperties: false,
8738
+ required: ['signature', 'label', 'count', 'frequency', 'variants', 'variant_count', 'edited_from', 'edited_to', 'effect', 'protein_change', 'representative', 'mean_identity'],
8739
+ properties: {
8740
+ signature: { type: 'string' },
8741
+ label: { type: 'string' },
8742
+ count: { type: 'integer' },
8743
+ frequency: { type: 'number' },
8744
+ variants: { type: 'array', items: VARIANT_SCHEMA },
8745
+ variant_count: { type: 'integer' },
8746
+ edited_from: { type: 'integer' },
8747
+ edited_to: { type: 'integer' },
8748
+ effect: { type: 'string', enum: ['wild_type', 'silent', 'missense', 'nonsense', 'frameshift', 'in_frame_indel', 'outside_cds', 'not_evaluated'] },
8749
+ protein_change: { type: 'string' },
8750
+ representative: { type: 'string' },
8751
+ mean_identity: { type: 'number' },
8752
+ },
8753
+ };
8754
+
8755
+ const editingOutcomeTool = (ctx) => define({
8756
+ name: 'molbio_editing_outcome',
8757
+ description: 'Cluster ALL reads against the reference in ONE call and report each allele\'s frequency and (inside an optional CDS) its protein effect — do not call this once per read and do not re-derive the effect with molbio_translate, a script, or a shell command; the result already carries frameshift/missense/nonsense/silent/in_frame_indel. Pass every read in `reads` as [{name, sequence}] with sequences copied exactly (or pass `paths` for .ab1/.seq/.fasta files instead of retyping them), and pass the COMPLETE reference molecule in `reference` — not the CDS and not one of the reads; `cds_start`/`cds_end` are 1-based inclusive coordinates ON that reference. Reads align in both orientations; reads below the identity/span thresholds are reported as unaligned rather than forced into an allele. Frequencies are fractions of the ALIGNED reads (read-fraction clustering, NOT TIDE peak decomposition). A `wild_type` allele means a read identical to the reference; if you expected wild-type reads and none appear, check that `reference` is the full molecule.',
8758
+ parameters: {
8759
+ type: 'object',
8760
+ properties: {
8761
+ paths: { type: 'array', items: { type: 'string' }, description: 'Sequencing files (.ab1/.seq/.fasta); prefer this over retyping inline sequences when the reads are files.' },
8762
+ reads: { type: 'array', items: READ_IN_SCHEMA, description: 'Inline reads; each item needs sequence (IUPAC DNA, copied exactly) and accepts name/qualities. Pass all reads in one call.' },
8763
+ reference: { type: 'string', description: 'The COMPLETE reference molecule (alternative to reference_path), not the CDS; cds_start/cds_end index into it.' },
8764
+ reference_path: { type: 'string', description: 'Path to the reference .dna/.gb/.fa file.' },
8765
+ circular: { type: 'boolean', description: 'Treat the reference as circular (default true); pass false for a linear amplicon, because the wrong topology misplaces reads that span the ends.' },
8766
+ min_frequency: { type: 'number', description: 'Omit alleles below this aligned-read fraction (0-1, default 0.01).' },
8767
+ identity_threshold: { type: 'number', description: 'Minimum alignment identity for a read to count (0-1, default 0.6).' },
8768
+ cds_start: { type: 'integer', description: 'Optional CDS start (1-based inclusive) ON the reference; give both cds_start and cds_end or neither.' },
8769
+ cds_end: { type: 'integer', description: 'Optional CDS end (1-based inclusive) ON the reference.' },
8770
+ },
8771
+ },
8772
+ outputSchema: {
8773
+ type: 'object',
8774
+ additionalProperties: false,
8775
+ required: ['reference_length', 'circular', 'total_reads', 'aligned_reads', 'unaligned_reads', 'unaligned', 'alleles', 'allele_count', 'cds_start', 'cds_end', 'notes'],
8776
+ properties: {
8777
+ reference_length: { type: 'integer' },
8778
+ circular: { type: 'boolean' },
8779
+ total_reads: { type: 'integer' },
8780
+ aligned_reads: { type: 'integer' },
8781
+ unaligned_reads: { type: 'integer' },
8782
+ unaligned: { type: 'array', items: { type: 'object', additionalProperties: false, required: ['name', 'identity'], properties: { name: { type: 'string' }, identity: { type: 'number' } } } },
8783
+ alleles: { type: 'array', items: ALLELE_SCHEMA },
8784
+ allele_count: { type: 'integer' },
8785
+ cds_start: { type: 'integer' },
8786
+ cds_end: { type: 'integer' },
8787
+ notes: { type: 'array', items: { type: 'string' } },
8788
+ },
8789
+ },
8790
+ render(value) {
8791
+ const lines = [`${value.aligned_reads}/${value.total_reads} read(s) aligned to a ${value.reference_length} bp ${value.circular ? 'circular' : 'linear'} reference · ${value.allele_count} allele(s)`];
8792
+ for (const allele of value.alleles) {
8793
+ const span = allele.edited_from === 0 ? '' : ` @${allele.edited_from}-${allele.edited_to}`;
8794
+ lines.push(` ${(allele.frequency * 100).toFixed(1)}% (${allele.count}) ${allele.label}${span}${allele.effect === 'not_evaluated' ? '' : ` → ${allele.effect}${allele.protein_change === '' ? '' : ' ' + allele.protein_change}`}`);
8795
+ }
8796
+ if (value.unaligned_reads > 0) lines.push(`${value.unaligned_reads} read(s) did not align (${value.unaligned.map((read) => `${read.name} ${read.identity}%`).join(', ')})`);
8797
+ lines.push('Read-fraction clustering, not TIDE: mixed Sanger peaks are not decomposed; frequencies are fractions of the aligned reads.');
8798
+ return lines.join('\n');
8799
+ },
8800
+ async execute(args, exec) {
8801
+ const vector = await resolveVector(ctx, exec, args, 'reference_path');
8802
+ const reads = await readSequencingInputs(ctx, exec, args);
8803
+ return callEditingOutcomes(reads, vector.sequence, {
8804
+ circular: args.circular,
8805
+ minFrequency: args.min_frequency,
8806
+ identityThreshold: args.identity_threshold,
8807
+ cdsStart: args.cds_start,
8808
+ cdsEnd: args.cds_end,
8809
+ });
8810
+ },
8811
+ });
8812
+
8813
+ // ── prompt guidance for the v0.28.0 tools ──────────────────────────────────
8814
+
8815
+ const NEW_PROMPT_LINES = [
8816
+ '- Protein annotation (v0.28): molbio_protein_features (PTM motifs, SEG-style low-complexity regions, aromaticity, instability index), molbio_signal_peptide (von Heijne 1986 cleavage score + candidate transmembrane segments + a score SVG) and molbio_antigenicity (Kolaskar-Tongaonkar 7-mer propensity with Parker/Emini/Vihinen region means). All three are heuristics from published tables: never call them SignalP/TMHMM/NetNGlyc/BepiPred predictions.',
8817
+ '- Formats and sequence surgery (v0.28): molbio_feature_export writes features as GFF3 (1-based inclusive), BED (0-based half-open) or CSV and states which convention it used; molbio_sequence_edit rotates/inserts/deletes/replaces/splits/joins and does NOT remap features — re-export annotations when an edit moves them.',
8818
+ '- Sequencing read sets (v0.28): molbio_sanger_assemble builds a quality-weighted consensus contig from a few reads (both orientations, opt-in circular closure); molbio_editing_outcome clusters reads into alleles and classifies the CDS effect. Its frequencies are fractions of aligned reads, not TIDE peak decomposition.',
8819
+ ].join('\n');
8195
8820
  const PROMPT_SECTION = `Molecular-biology tools (dsh-molbio-tools) are available with the molbio_* prefix:
8196
8821
  - Sequence math: molbio_reverse_complement, molbio_gc_content, molbio_translate, molbio_restriction_sites, molbio_methylation_check (which enzymes a Dam/Dcm-methylated template blocks, plus the enzymes that survive), molbio_double_digest (two enzymes: per-enzyme and combined fragments + whether they share a buffer).
8197
8822
  - Primer work: molbio_design_primers (automatic pair design), molbio_design_intron_primers (qPCR primers spanning an exon-exon junction against a genomic sequence + exon list, so gDNA does not amplify), molbio_primer_tm, molbio_primer_check, molbio_duplex_thermo (ΔH/ΔS/ΔG°37/Tm for one exact duplex plus hairpin and dimer checks; a mismatched partner is refused, not estimated), molbio_design_taqman (hydrolysis-probe assay: primer pair + probe with the no-5'-G / probe-Tm-margin rules; probe_chemistry='mgb' for shorter MGB probes with an explicitly unmodified NN Tm, and save_path for an ordering CSV of F/R/P with modifications/scale/purification), molbio_multiplex_check (whether several primer pairs can share one tube: cross-dimers, cross-template annealing, gel-resolvable amplicon sizes, plus an annealing-temperature recommendation and a size-balanced starting primer-concentration plan).
@@ -8209,6 +8834,8 @@ const PROMPT_SECTION = `Molecular-biology tools (dsh-molbio-tools) are available
8209
8834
  - Bench analysis (v19): molbio_fastq_qc (read-level QC for a FASTQ file: per-base quality with quartiles, per-read quality, base content, GC distribution, length, exact duplication, over-represented sequences, adapter screen, plus a report SVG — use it for "is this run good"), molbio_codon_usage (CAI/RSCU/Nc/GC3, rare-codon list and CDS CpG against E. coli/yeast/human — use it for "will this gene express"; it explains, molbio_codon_optimize rewrites), molbio_phylogenetic_tree (distance method: p-distance/JC/K2P/Tamura-Nei, UPGMA or neighbour-joining, bootstrap support, consensus, Newick file and an SVG tree — it is NOT a maximum-likelihood or Bayesian analysis, and bootstrap percentages are not p-values), molbio_pcr_simulate (where a primer pair amplifies: product sizes and coordinates on both strands, mismatch detail, the 3'-end exact-match requirement, circular templates, screening other templates, and an expected gel — use it for "what band will I see"), molbio_gc_composition (sliding-window GC, CpG islands under the Gardiner-Garden or Takai criteria, GC/AT skew with the cumulative-skew origin/terminus indication, dinucleotide obs/exp, entropy, complexity, N50/L50, plus a figure — use it for "is this a promoter or an origin"), molbio_fastq_trim (trim low-quality 3' tails, exact adapters/primers, poly-G/poly-A, then filter by length/N and write FASTQ/FASTA — not a paired-end merger).
8210
8835
  - Literature: molbio_pubmed_search — with an NCBI API key (api_key argument, the credential store under NCBI_API_KEY / MOLBIO_NCBI_API_KEY, or the environment) it uses the official PubMed E-utilities API and returns PMIDs, titles, journal/year, authors and DOI; without a key it falls back to the harness web search. The reading library is molbio_paper_add / molbio_paper_list / molbio_paper_update / molbio_paper_remove (papers.json in the workspace).
8211
8836
 
8837
+ ${NEW_PROMPT_LINES}
8838
+
8212
8839
  Cloning workflow rules (follow them to avoid slow re-derivation):
8213
8840
  - To clone a sequence into a plasmid, call molbio_clone_simulate FIRST — pass the BARE insert with add_flanks: true and the tool adds the enzyme recognition sites itself. The tool also validates single cutting, insert orientation, and internal sites itself: never pre-verify enzymes, cutting counts, or flank construction by thinking. Its output already contains final_sequence AND the remapped feature coordinates (features field). NEVER recompute feature coordinates or insert positions by reasoning — always take them from the tool output.
8214
8841
  - To draw the new plasmid, either pass map_path to molbio_clone_simulate (one call writes the SVG with remapped features and verification enzymes marked) or feed its features + final_sequence to molbio_plasmid_map. Never rebuild the feature list by hand.
@@ -8288,6 +8915,13 @@ export function apply(ctx) {
8288
8915
  paperListTool(ctx),
8289
8916
  paperUpdateTool(ctx),
8290
8917
  paperRemoveTool(ctx),
8918
+ proteinFeaturesTool,
8919
+ signalPeptideTool(ctx),
8920
+ antigenicityTool,
8921
+ featureExportTool(ctx),
8922
+ sequenceEditTool(ctx),
8923
+ sangerAssembleTool(ctx),
8924
+ editingOutcomeTool(ctx),
8291
8925
  ];
8292
8926
  for (const tool of tools) ctx.tools.register(tool);
8293
8927
  }