formlab-mcp 0.6.35 → 0.6.37

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/README.md CHANGED
@@ -37,7 +37,7 @@ Ask Claude (or another MCP client) things like:
37
37
  | `list_lots` | Inventory lots across ingredients (each a received batch with its own remaining balance, supplier, expiry, **unit cost**, **status** — `active` / `hold` / `quarantine` / `rejected`; held lots are blocked from consumption, with a `holdReason` — and the **approved source** it was received from: `source.supplier` + `source.manufacturer`, where recalls hinge on the manufacturer). Each lot also reports its **Certificate of Analysis** (`coa`: linked, or matched by lot number) and `coaMissing` for an in-stock lot without one. Filters: `ingredient_id`, `expiring_within_days`, `status` (e.g. `hold` to find lots held for a recall), `missing_coa` |
38
38
  | `list_suppliers` | Supplier / manufacturer records with roll-ups — ingredients approved, lots received / on hand (+ value at paid cost), qualified / trial / disqualified source counts, last receipt; lots count by supplier **and** by manufacturer |
39
39
  | `get_supplier` | One supplier in full: record, every ingredient it's an approved source for, every lot from it, and the **recall trace** (batches that consumed those lots → products, shipments, samples, sub-batches; lots on hold flagged) |
40
- | `list_documents` | The document register (same as the app's Documents page): ingredient SDS / PDS / CoA / other with lot, version, source and expiry; test and notebook attachments; per-record uploads and links (formulas, batches, samples, suppliers, equipment…). File **metadata** only, never the text inside a file. Filters: `type`, `record`, `linked`, `query`, `lot`, `format`, `expiry`, `expiring_within_days`, `without_expiry`, `uploaded_within_days`. A `summary` block carries the page's tile counts: expired, expiring in 30 days, SDS/CoA without expiry, ingredients missing an SDS (+ coverage %), lots in stock without a CoA, added last 7 days |
40
+ | `list_documents` | The document register (same as the app's Documents page): ingredient SDS / PDS / CoA / other with lot, version, source and expiry; test and notebook attachments; per-record uploads and links (formulas, batches, samples, suppliers, equipment…). File **metadata** only, never the text inside a file, with who added each file (`addedBy`) and when. Filters: `type`, `record`, `linked`, `query`, `lot`, `format`, `expiry`, `expiring_within_days`, `without_expiry`, `uploaded_within_days`, `added_by`. A `summary` block carries the page's tile counts: expired, expiring in 30 days, SDS/CoA without expiry, ingredients missing an SDS (+ coverage %), lots in stock without a CoA, added last 7 days |
41
41
  | `list_inventory` | Portfolio stock rollup — one row per ingredient with on-hand qty, summed lot balance, nearest expiry, and a low-stock flag (on-hand ≤ `reorderThreshold`, or zero). Filters: `low_stock_only`, `expiring_within_days`, `family` |
42
42
  | `list_batches` | Filtered list of production / lab-prep events |
43
43
  | `get_batch` | Full record + actual composition, measured/derived **actual volume** (mass ÷ density, never a sum of per-ingredient volumes) and **actual mass** (yield, else summed as-prepared inputs — mL rows through that ingredient's density — else measured volume × density), **estimatedVolume** (mass ÷ the formula's finished density when no actual exists, flagged `estimate: true`), **plannedMass** for volume-target batches (target × finished density) and **formulaFinishedDensity**, the **process** method + any **process-factor values** (DOE inputs), samples + blend lineage, and — as a finished-goods lot — its storage **`location`** + finished-goods **`stockLedger`** (shipments out + adjustments; `shippedQty` total) |
@@ -52,7 +52,7 @@ Ask Claude (or another MCP client) things like:
52
52
  | `get_batch_pivot` | Production analytics — aggregate batches by `group_by` (formula / status / month / prepared_by / project) × `metric` (count, avg_yield_pct, total_produced_kg, avg_cost_per_batch, total_samples, total_tests), with share + total for additive metrics. Optional `batch_uids` scope + `status` filter |
53
53
  | `get_project_pivot` | Portfolio analytics — aggregate projects by `group_by` (status / phase / priority / business_unit / site / customer / lead, or `cf:<custom field>`) × `metric` (count, total_formulas / batches / samples, total_cost, avg_formulas / batches / cost_per_batch), rolling child activity + cost up by any project attribute. Optional `project_uids` scope |
54
54
  | `get_stability` | Grounded stability / shelf-life analysis for a formulation, sample or batch × parameter (auto-detected): time-series, drift (per-month slope + R²), an I-chart (mean ±3σ + out-of-control points), spec status, and an ICH-Q1E-flavored projected shelf life (point + 95%-CI crossing), all on **one point per test date per run condition** (replicates averaged, never separate time points), split by storage condition |
55
- | `get_design_space` | COMPOSITION design space for one project: which ingredients vary and over what observed wt-% ranges (ranked), an occupied-region summary ("where you've been"), the biggest untested **interior gap** as ready-to-seed DOE ranges (a combination you could have made but skipped), and an optional standardised **2-component PCA** of all varying ingredients — loadings, variance-explained, scree, and a full-dimensional gap. Matches the in-app Design Space Viewer exactly. Answers *"where haven't I explored?"* / *"what should I formulate next?"* |
55
+ | `get_design_space` | COMPOSITION design space for one project, several (`projects`) or any formula list (`formulas`, across projects — like the app's Scope → DOE Matrix): which ingredients vary and over what observed wt-% ranges (ranked), an occupied-region summary ("where you've been"), the biggest untested **interior gap** as ready-to-seed DOE ranges (a combination you could have made but skipped), and an optional standardised **2-component PCA** of all varying ingredients — loadings, variance-explained, scree, and a full-dimensional gap. Optional `axes` (choose the 2–3 axes), `by_role` (map ingredients summed by primary Function, e.g. Pigment / Solvent / Film Former — no gap, roles aren't DOE factors) and `property` (highest / lowest formula plus the ingredients whose level tracks it, Spearman ρ). Reports formulas that aren't on the map and the spread on it. Matches the in-app Design Space Viewer exactly. Answers *"where haven't I explored?"* / *"what should I formulate next?"* |
56
56
  | `list_doe_designs` | Saved DOE designs — the *recipe* behind each batch of runs: design type, factors + ranges, constraints, run count, D-efficiency. Filters: `project`, `design_type`, `constrained_only`, `name_contains` |
57
57
  | `get_doe_design` | One design in full: constraints in plain language, the model it was optimised for, generation settings (run budget, replicates, centre points, seed) and the complete run matrix with the formulation each run became |
58
58
  | `find_by_smarts` | SMARTS-pattern substructure search across every ingredient with a SMILES; peptides that only store a sequence are searched with the structure derived from it, as the app draws them (`smilesDerived: true`). Requires `@rdkit/rdkit` (optional dependency — install with `npm install @rdkit/rdkit` in `mcp/` if you get a "not installed" error). Examples: `c1ccccc1` (any aromatic 6-ring), `[OX2H1]` (any hydroxyl), `C(=O)O` (carboxylic acid), `[F,Cl,Br,I]` (any halogen). |
@@ -66,8 +66,8 @@ Ask Claude (or another MCP client) things like:
66
66
  | `get_test_panel` | One Test Panel: ordered parameters with resolved method UIDs + specs, plus `usage` (reports created from it) and `performanceByParameter` |
67
67
  | `list_projects` | Filtered list of projects (the buckets formulations are filed under) + per-project formulation count. Filters: `status`, `name_contains` |
68
68
  | `get_project` | Full project record + the formulations filed under it |
69
- | `list_notebook_entries` | ELN feed — dated authored notes attached to records. Filters: `entity_type`, `entity_id`, `author`, `text_contains`, `since`, `until` |
70
- | `get_notebook_entry` | One notebook entry — full body, author, attachment metadata, resolved linked record |
69
+ | `list_notebook_entries` | ELN feed — dated authored notes attached to records. Append-only: a withdrawn note is kept with `retracted` = {at, by, reason}. Filters: `entity_type`, `entity_id`, `author`, `text_contains`, `since`, `until`, `retracted` |
70
+ | `get_notebook_entry` | One notebook entry — full body, author, attachment metadata, resolved linked record, and `retracted` when withdrawn |
71
71
 
72
72
  ## Install
73
73
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.35",
3
+ "version": "0.6.37",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab \u2014 lets Claude (and other MCP clients) read and analyze your FormLab data, from a local export file OR your live cloud workspace.",
6
6
  "type": "module",
package/server.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.juliu1980/formlab-mcp",
4
4
  "description": "Read-only MCP for FormLab — let Claude query your formulation lab. Free reads a local export; Pro connects to your live cloud workspace with a dedicated read-only token.",
5
- "version": "0.6.35",
5
+ "version": "0.6.37",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "repository": {
8
8
  "url": "https://github.com/juliu1980/FormLab",
@@ -13,7 +13,7 @@
13
13
  {
14
14
  "registryType": "npm",
15
15
  "identifier": "formlab-mcp",
16
- "version": "0.6.35",
16
+ "version": "0.6.37",
17
17
  "runtimeHint": "npx",
18
18
  "transport": {
19
19
  "type": "stdio"
@@ -292,14 +292,87 @@ function _eligibleProjects(db) {
292
292
  return out;
293
293
  }
294
294
 
295
+ // ---- scope, roles, property insights (ports of the app's build 26p–26s) -----
296
+
297
+ // Resolve a list of formula ids / UIDs / names (exact name first, then substring).
298
+ function _resolveFormulas(list, db) {
299
+ const norm = (s) => String(s || '').toLowerCase();
300
+ const out = [], missing = [];
301
+ (list || []).forEach(q => {
302
+ const f = resolveById('formulations', q)
303
+ || (db.formulations || []).find(x => x && norm(x.name) === norm(q))
304
+ || (db.formulations || []).find(x => x && norm(x.name).includes(norm(q)));
305
+ if (f && !f._trashed) { if (!out.includes(f)) out.push(f); } else missing.push(q);
306
+ });
307
+ return { forms: out, missing };
308
+ }
309
+ function _resolveProject(q, db) {
310
+ const norm = (s) => String(s || '').toLowerCase();
311
+ return resolveById('projects', q)
312
+ || (db.projects || []).find(p => norm(p.name) === norm(q))
313
+ || (db.projects || []).find(p => norm(p.name).includes(norm(q)));
314
+ }
315
+ // Primary Function role per ingredient ("Pigment|Opacifier" → "Pigment").
316
+ function _roleMap(db) {
317
+ const m = new Map();
318
+ (db.ingredients || []).forEach(i => { const r = i && i.function ? String(i.function).split('|')[0].trim() : ''; if (r) m.set(i.id, r); });
319
+ return m;
320
+ }
321
+ // Per-formula role totals (wt% summed by role), as a map shaped like the
322
+ // ingredient maps so the same geometry helpers work on it (keys 'role:<name>').
323
+ function _roleMaps(forms, mapsByForm, db) {
324
+ const rm = _roleMap(db), out = new Map();
325
+ forms.forEach(f => {
326
+ const m = mapsByForm.get(f.id) || new Map(), t = new Map();
327
+ m.forEach((v, id) => { const r = rm.get(id); if (r && Number.isFinite(v)) t.set('role:' + r, (t.get('role:' + r) || 0) + v); });
328
+ out.set(f.id, t);
329
+ });
330
+ return out;
331
+ }
332
+ // Roles that vary, ranked by ABSOLUTE spread (the app's _asmDsRoleCands) — the
333
+ // big building blocks first, not a small role that swings a lot relatively.
334
+ function _roleCandidates(forms, roleMaps) {
335
+ const by = new Map();
336
+ forms.forEach(f => (roleMaps.get(f.id) || new Map()).forEach((v, id) => { if (!by.has(id)) by.set(id, []); by.get(id).push(v); }));
337
+ const out = [];
338
+ by.forEach((a, id) => {
339
+ if (a.length < 2) return;
340
+ const min = Math.min(...a), max = Math.max(...a), spread = max - min;
341
+ if (spread <= 0.01) return;
342
+ const mean = a.reduce((x, y) => x + y, 0) / a.length;
343
+ out.push({ id, name: id.slice(5), role: true, obs: { min, max, mean, n: a.length }, spread, rel: mean > 0 ? spread / mean : 0, score: spread });
344
+ });
345
+ return out.sort((a, b) => b.score - a.score);
346
+ }
347
+ // A formula's value for a measured parameter: the mean of every numeric
348
+ // reading of it across the formula's samples (the app's _asmFormulaValueForCol).
349
+ function _paramValue(f, param, db) {
350
+ const sids = new Set((db.samples || []).filter(s => s.formulationId === f.id).map(s => s.id));
351
+ const vals = [];
352
+ (db.testResults || []).forEach(t => { if (!sids.has(t.sampleId)) return; (t.measurements || []).forEach(m => { if (m.parameter === param) { const v = parseFloat(m.value); if (!isNaN(v)) vals.push(v); } }); });
353
+ return vals.length ? vals.reduce((a, b) => a + b, 0) / vals.length : null;
354
+ }
355
+ function _spearman(xs, ys) {
356
+ const rank = (a) => { const idx = a.map((v, i) => [v, i]).sort((p, q) => p[0] - q[0]); const r = new Array(a.length); let i = 0; while (i < idx.length) { let j = i; while (j + 1 < idx.length && idx[j + 1][0] === idx[i][0]) j++; const avg = (i + j) / 2 + 1; for (let k = i; k <= j; k++) r[idx[k][1]] = avg; i = j + 1; } return r; };
357
+ const rx = rank(xs), ry = rank(ys), n = xs.length;
358
+ const mx = rx.reduce((a, b) => a + b, 0) / n, my = ry.reduce((a, b) => a + b, 0) / n;
359
+ let sxx = 0, syy = 0, sxy = 0; for (let i = 0; i < n; i++) { const dx = rx[i] - mx, dy = ry[i] - my; sxx += dx * dx; syy += dy * dy; sxy += dx * dy; }
360
+ return (sxx && syy) ? sxy / Math.sqrt(sxx * syy) : null;
361
+ }
362
+
295
363
  const get_design_space = {
296
364
  definition: {
297
365
  name: 'get_design_space',
298
- description: 'Map a project\'s COMPOSITION design space (the descriptive mirror of the DOE designer, and the composition-space counterpart to get_coverage_matrix\'s TEST coverage). For one project it returns: the ingredients that actually VARY across its formulas + their observed wt-% ranges (ranked by proportional swing); an occupied-region summary ("where you\'ve been"); the biggest untested INTERIOR gap — a combination you could have made but skipped, kept inside the occupied cloud — expressed as ready-to-seed DOE ingredient ranges (low/high %); and, when the project has ≥3 varying ingredients, a standardised 2-component PCA of ALL of them: per-axis ingredient loadings, variance-explained, a scree list, and a full-dimensional gap. Numbers match FormLab\'s in-app Design Space Viewer exactly. Use it to answer "where haven\'t I explored?" / "what should I formulate next?" and to hand a chemist an experiment target. Read-only.',
366
+ description: 'Map a project\'s COMPOSITION design space (the descriptive mirror of the DOE designer, and the composition-space counterpart to get_coverage_matrix\'s TEST coverage). For one project it returns: the ingredients that actually VARY across its formulas + their observed wt-% ranges (ranked by proportional swing); an occupied-region summary ("where you\'ve been"); the biggest untested INTERIOR gap — a combination you could have made but skipped, kept inside the occupied cloud — expressed as ready-to-seed DOE ingredient ranges (low/high %); and, when the project has ≥3 varying ingredients, a standardised 2-component PCA of ALL of them: per-axis ingredient loadings, variance-explained, a scree list, and a full-dimensional gap. Numbers match FormLab\'s in-app Design Space Viewer exactly. Scope can be one project, several (projects), or any formula list (formulas); axes can be chosen (axes) or mapped by ingredient role (by_role); property adds best/worst formula and the ingredient that tracks it. Use it to answer "where haven\'t I explored?" / "what should I formulate next?" and to hand a chemist an experiment target. Read-only.',
299
367
  inputSchema: {
300
368
  type: 'object',
301
369
  properties: {
302
- project: { type: 'string', description: 'Project id, UID, or name (case-insensitive; substring allowed). Omit to auto-pick the most-populated eligible project (≥3 formulas).' },
370
+ project: { type: 'string', description: 'Project id, UID, or name (case-insensitive; substring allowed). Omit (and omit projects/formulas) to auto-pick the most-populated eligible project (≥3 formulas).' },
371
+ projects: { type: 'array', items: { type: 'string' }, description: 'Map several projects together (ids, UIDs or names) — the app\'s cross-project scope. Ingredients most of the formulas share are ranked first.' },
372
+ formulas: { type: 'array', items: { type: 'string' }, description: 'Map exactly these formulas (ids, UIDs or names), from any projects — like the app\'s "Scope → DOE Matrix". Overrides project/projects.' },
373
+ axes: { type: 'array', items: { type: 'string' }, description: 'Choose the 2 or 3 axes yourself (ingredient names/ids, or role names with by_role) instead of the most-varying ones. Each must vary in the scope.' },
374
+ by_role: { type: 'boolean', description: 'Map ROLES instead of single ingredients: each formula\'s ingredients summed by their primary Function (e.g. Pigment / Solvent / Film Former), ranked by absolute spread. No gap is reported (roles are not DOE factors).' },
375
+ property: { type: 'string', description: 'A measured parameter name (e.g. "Gloss @60°"). Adds insights over the formulas on the map: highest and lowest formula, and the varying ingredient whose level tracks it most (Spearman ρ; a correlation, not a cause).' },
303
376
  include_pca: { type: 'boolean', description: 'Include the "map everything" PCA of all varying ingredients (loadings + variance + full-dimensional gap). Default true. Needs ≥3 varying ingredients and ≥3 formulas.' },
304
377
  loadings_per_component: { type: 'number', description: 'How many top ingredient loadings to list per principal component. Default 5, max 20.' },
305
378
  },
@@ -309,34 +382,54 @@ const get_design_space = {
309
382
  const { db } = getStore();
310
383
  const norm = (s) => String(s || '').toLowerCase();
311
384
 
312
- // Resolve the project (explicit pick, else the most-populated eligible one).
313
- let proj = null;
314
- if (args.project) {
315
- proj = resolveById('projects', args.project)
316
- || (db.projects || []).find(p => norm(p.name) === norm(args.project))
317
- || (db.projects || []).find(p => norm(p.name).includes(norm(args.project)));
318
- if (!proj) return { error: `No project matched "${args.project}".` };
385
+ // Resolve the scope: explicit formulas > several projects > one project >
386
+ // the most-populated eligible project.
387
+ let proj = null, forms, scope;
388
+ const notes = [];
389
+ if (Array.isArray(args.formulas) && args.formulas.length) {
390
+ const r = _resolveFormulas(args.formulas, db);
391
+ if (r.missing.length) notes.push(`No formula matched: ${r.missing.join(', ')}.`);
392
+ forms = r.forms;
393
+ scope = { kind: 'formulas' };
394
+ } else if (Array.isArray(args.projects) && args.projects.length) {
395
+ const ps = [];
396
+ for (const q of args.projects) { const p = _resolveProject(q, db); if (!p) return { error: `No project matched "${q}".` }; if (!ps.includes(p)) ps.push(p); }
397
+ const ids = new Set(ps.map(p => p.id));
398
+ forms = (db.formulations || []).filter(f => f && !f._trashed && ids.has(f.projectId));
399
+ scope = { kind: 'projects' };
400
+ if (ps.length === 1) proj = ps[0];
319
401
  } else {
320
- const elig = _eligibleProjects(db);
321
- if (!elig.length) return { error: 'No project has ≥3 formulas to map. Assign at least 3 formulas to a project first.' };
322
- proj = (db.projects || []).find(p => p.id === elig[0].id);
402
+ if (args.project) {
403
+ proj = _resolveProject(args.project, db);
404
+ if (!proj) return { error: `No project matched "${args.project}".` };
405
+ } else {
406
+ const elig = _eligibleProjects(db);
407
+ if (!elig.length) return { error: 'No project has ≥3 formulas to map. Assign at least 3 formulas to a project first.' };
408
+ proj = (db.projects || []).find(p => p.id === elig[0].id);
409
+ }
410
+ forms = (db.formulations || []).filter(f => f && !f._trashed && f.projectId === proj.id);
411
+ scope = { kind: 'project' };
323
412
  }
324
- const pid = proj.id;
325
- const forms = (db.formulations || []).filter(f => f && !f._trashed && f.projectId === pid);
413
+ const projIds = [...new Set(forms.map(f => f.projectId || ''))];
414
+ scope.formulaCount = forms.length;
415
+ scope.projects = projIds.map(id => (((db.projects || []).find(p => p.id === id) || {}).name) || (id ? id : '(no project)'));
326
416
 
327
417
  // Precompute ingredient maps once (reused by ranking, gap, PCA, observed range).
328
418
  const mapsByForm = new Map(forms.map(f => [f.id, _ingredientPctMap(f)]));
329
419
 
330
- const out = {
331
- project: { id: pid, uid: proj.uid || null, name: proj.name || pid, formulaCount: forms.length },
332
- notes: [],
333
- };
420
+ const out = { scope, notes };
421
+ if (proj) out.project = { id: proj.id, uid: proj.uid || null, name: proj.name || proj.id, formulaCount: forms.length };
334
422
  if (forms.length < 3) {
335
- out.notes.push('This project has fewer than 3 formulas — a design space is only coherent with at least 3 points. Results below are provisional.');
423
+ out.notes.push('The scope has fewer than 3 formulas — a design space is only coherent with at least 3 points. Results below are provisional.');
336
424
  }
337
425
 
338
- // Varying ingredients + observed ranges (ranked).
339
- const cand = _factorCandidates(forms, mapsByForm, db);
426
+ // Varying ingredients + observed ranges (ranked). A scope spanning projects
427
+ // ranks ingredients at least half its formulas SHARE first (the app's rule).
428
+ let cand = _factorCandidates(forms, mapsByForm, db);
429
+ if (projIds.length > 1) {
430
+ const half = forms.length / 2;
431
+ cand = cand.filter(c => c.obs.n >= half).concat(cand.filter(c => c.obs.n < half));
432
+ }
340
433
  out.varyingIngredientCount = cand.length;
341
434
  out.varyingIngredients = cand.map(c => ({
342
435
  ingredient: c.name,
@@ -354,31 +447,73 @@ const get_design_space = {
354
447
  return out;
355
448
  }
356
449
 
357
- // Axes: top-3 ternary (relative proportions) or top-2 scatter (absolute %).
358
- const mode = cand.length >= 3 ? 'ternary' : 'scatter';
359
- const comps = cand.slice(0, mode === 'ternary' ? 3 : 2);
450
+ // Axes: by role (pseudo-components) or ingredients; auto (most varying) or
451
+ // chosen. Values for the geometry come from `vmaps` (ingredient or role maps).
452
+ const byRole = !!args.by_role;
453
+ let vmaps = mapsByForm, axCand = cand;
454
+ if (byRole) {
455
+ vmaps = _roleMaps(forms, mapsByForm, db);
456
+ axCand = _roleCandidates(forms, vmaps);
457
+ out.roles = axCand.map(c => ({ role: c.name, observedRange: { min: +c.obs.min.toFixed(4), max: +c.obs.max.toFixed(4), unit: '%' }, usedInFormulas: c.obs.n }));
458
+ if (axCand.length < 2) { out.notes.push('Fewer than 2 ingredient roles vary (set ingredient Functions to use by_role).'); out.axes = null; return out; }
459
+ }
460
+ let comps = null, chosen = false;
461
+ if (Array.isArray(args.axes) && args.axes.length) {
462
+ const find = (q) => axCand.find(c => norm(c.id) === norm(q) || norm(c.name) === norm(q)) || axCand.find(c => norm(c.name).includes(norm(q)));
463
+ const picked = [];
464
+ args.axes.forEach(q => { const c = find(q); if (c && !picked.includes(c)) picked.push(c); });
465
+ if ((picked.length === 3 || picked.length === 2) && picked.length === args.axes.length) { comps = picked; chosen = true; }
466
+ else out.notes.push(`Could not use axes [${args.axes.join(', ')}] — each must be a distinct ${byRole ? 'role' : 'ingredient'} that varies in this scope (2 or 3). Using the most-varying instead.`);
467
+ }
468
+ if (!comps) comps = axCand.slice(0, axCand.length >= 3 ? 3 : 2);
469
+ const mode = comps.length === 3 ? 'ternary' : 'scatter';
470
+ const kind = byRole ? 'roles (ingredients summed by primary Function)' : 'ingredients';
360
471
  out.axes = {
361
472
  mode,
362
- basis: mode === 'ternary'
363
- ? 'Top 3 most-varying ingredients, as relative proportions (a ternary).'
364
- : 'Top 2 most-varying ingredients, as absolute wt-%.',
365
- ingredients: comps.map(c => c.name),
473
+ basis: `${chosen ? 'Chosen' : (mode === 'ternary' ? 'Top 3 most-varying' : 'Top 2 most-varying')} ${kind}, ${mode === 'ternary' ? 'as relative proportions (a ternary: each axis is its share of the three shown, not wt% of the recipe).' : 'as absolute wt-%.'}`,
474
+ [byRole ? 'roles' : 'ingredients']: comps.map(c => c.name),
366
475
  };
367
476
 
368
477
  // Occupied-region summary: the bounding envelope of the plotted axes + how
369
478
  // many formulas actually sit in the space. The app draws the convex hull of
370
479
  // these points; the per-axis min/max here is that hull's bounding box.
371
- let inSpace = 0;
372
- forms.forEach(f => { if (comps.some(c => _ingVal(mapsByForm, f, c.id) != null)) inSpace++; });
480
+ const onMap = forms.filter(f => comps.some(c => (_ingVal(vmaps, f, c.id) || 0) > 0));
481
+ const inSpace = onMap.length;
482
+ if (inSpace < forms.length) out.notes.push(`${forms.length - inSpace} of ${forms.length} formulas contain none of the axes and are not on the map.`);
483
+ const share = onMap.map(f => { const v = comps.map(c => _ingVal(vmaps, f, c.id) || 0); const t = v.reduce((a, b) => a + b, 0) || 1; return mode === 'ternary' ? v.map(x => 100 * x / t) : v; });
373
484
  out.occupiedRegion = {
374
485
  formulaPoints: inSpace,
486
+ spreadOnMap: comps.map((c, i) => { const vs = share.map(r => r[i]); return { axis: c.name, min: +Math.min(...vs).toFixed(2), max: +Math.max(...vs).toFixed(2), unit: mode === 'ternary' ? '% of the three' : '%' }; }),
375
487
  axisRanges: comps.map(c => ({ ingredient: c.name, id: c.id, min: +c.obs.min.toFixed(4), max: +c.obs.max.toFixed(4), unit: '%' })),
376
488
  note: 'Bounding envelope of the observed compositions on the mapped axes. In the app this is the shaded convex hull ("where you\'ve been"); the untested gap below was found INSIDE that occupied cloud, not on its frontier.',
377
489
  };
378
490
 
379
- // The top untested interior gap, as ready-to-seed DOE ranges.
380
- const gap = _computeGap(mode, comps, forms, mapsByForm);
381
- if (!gap) {
491
+ // Property insights over the formulas on the map.
492
+ if (args.property) {
493
+ const vals = onMap.map(f => ({ f, v: _paramValue(f, args.property, db) })).filter(x => x.v != null);
494
+ if (vals.length < 2) out.notes.push(`"${args.property}" is measured on ${vals.length} of the formulas on the map — need at least 2 for insights (check the exact parameter name).`);
495
+ else {
496
+ const hi = vals.reduce((a, b) => b.v > a.v ? b : a), lo = vals.reduce((a, b) => b.v < a.v ? b : a);
497
+ const pi = { property: args.property, basis: 'mean of every reading per formula', formulasMeasured: vals.length,
498
+ highest: { formula: hi.f.name, uid: hi.f.uid || null, value: +hi.v.toFixed(4) },
499
+ lowest: { formula: lo.f.name, uid: lo.f.uid || null, value: +lo.v.toFixed(4) } };
500
+ if (vals.length >= 4) {
501
+ const ranked = [];
502
+ cand.forEach(c => { const xs = vals.map(x => _ingVal(mapsByForm, x.f, c.id) || 0); if (new Set(xs).size < 2) return; const r = _spearman(xs, vals.map(x => x.v)); if (r != null) ranked.push({ ingredient: c.name, rho: +r.toFixed(3) }); });
503
+ ranked.sort((a, b) => Math.abs(b.rho) - Math.abs(a.rho));
504
+ pi.tracksMost = ranked.slice(0, 5);
505
+ pi.note = 'Spearman rank correlation across these formulas — a lead for what to vary, not proof of cause' + (vals.length < 8 ? '; few formulas, so treat it cautiously.' : '.');
506
+ }
507
+ out.propertyInsights = pi;
508
+ }
509
+ }
510
+
511
+ // The top untested interior gap, as ready-to-seed DOE ranges (not for roles:
512
+ // they aren't DOE factors).
513
+ const gap = byRole ? null : _computeGap(mode, comps, forms, mapsByForm);
514
+ if (byRole) {
515
+ out.gap = null;
516
+ } else if (!gap) {
382
517
  out.gap = null;
383
518
  out.notes.push('Too few distinct formula points (need ≥4 with these axes) to locate a trustworthy gap.');
384
519
  } else {
@@ -60,7 +60,7 @@ function allDocuments(db) {
60
60
  lot: d.lotNumber || '', version: d.version != null ? String(d.version) : '', source: d.source || '',
61
61
  expiryDate: d.expiryDate || null, expiryStatus: ex.status, daysToExpiry: ex.daysToExpiry,
62
62
  sizeKb: Number.isFinite(+d.size) && d.size != null ? Math.round(+d.size / 102.4) / 10 : null,
63
- uploadedAt: d.uploadedAt || null,
63
+ uploadedAt: d.uploadedAt || null, addedBy: d.addedBy || null,
64
64
  });
65
65
  }));
66
66
  const testsById = new Map((db.testResults || []).map(t => [t.id, t]));
@@ -71,7 +71,7 @@ function allDocuments(db) {
71
71
  record: 'test', linked: (t ? (t.uid || t.id) : 'Test') + (a.measurementParameter ? ' · ' + a.measurementParameter : ''), linkedId: t ? (t.uid || t.id) : null,
72
72
  lot: '', version: '', source: '', expiryDate: null, expiryStatus: 'none', daysToExpiry: null,
73
73
  sizeKb: Number.isFinite(+a.fileSize) && a.fileSize != null ? Math.round(+a.fileSize / 102.4) / 10 : null,
74
- uploadedAt: a.uploadedAt || null,
74
+ uploadedAt: a.uploadedAt || null, addedBy: a.addedBy || null,
75
75
  });
76
76
  });
77
77
  (db.notebookEntries || []).filter(live).forEach(ne => (ne.attachments || []).forEach(att => {
@@ -83,7 +83,7 @@ function allDocuments(db) {
83
83
  record: 'notebook', linked: rec ? (rec.name || rec.uid || '') : (ne.entityType || 'note'), linkedId: rec ? (rec.uid || rec.id) : null,
84
84
  lot: '', version: '', source: '', expiryDate: null, expiryStatus: 'none', daysToExpiry: null,
85
85
  sizeKb: Number.isFinite(+att.size) && att.size != null ? Math.round(+att.size / 102.4) / 10 : null,
86
- uploadedAt: att.uploadedAt || null,
86
+ uploadedAt: att.uploadedAt || null, addedBy: att.addedBy || ne.author || null, // a note's file is its author's
87
87
  });
88
88
  }));
89
89
  Object.entries(ATTACH_COLL).forEach(([etype, coll]) => (db[coll] || []).filter(live).forEach(rec => (rec.fileAttachments || []).forEach(a => {
@@ -95,7 +95,7 @@ function allDocuments(db) {
95
95
  ...(isLink && a.url ? { url: a.url } : {}),
96
96
  lot: '', version: '', source: '', expiryDate: null, expiryStatus: 'none', daysToExpiry: null,
97
97
  sizeKb: (!isLink && Number.isFinite(+a.size) && a.size != null) ? Math.round(+a.size / 102.4) / 10 : null,
98
- uploadedAt: a.createdAt || null,
98
+ uploadedAt: a.createdAt || null, addedBy: a.addedBy || null,
99
99
  });
100
100
  })));
101
101
  return out;
@@ -121,7 +121,7 @@ function summary(db, docs) {
121
121
  const list_documents = {
122
122
  definition: {
123
123
  name: 'list_documents',
124
- description: 'The workspace document register — same list as the app\'s Documents page: ingredient SDS / PDS / CoA / other files (with lot, version, source, expiry), test-result and notebook attachments, and per-record uploads and links (formulas, batches, samples, suppliers, equipment…). Returns file METADATA only (never the text inside a file). Filters combine. The summary block matches the page\'s tiles: expired, expiring in 30 days, SDS/CoA without an expiry date, ingredients missing an SDS (+ coverage %), lots in stock without a CoA, files added in the last 7 days. For the lots themselves use list_lots with missing_coa: true.',
124
+ description: 'The workspace document register — same list as the app\'s Documents page: ingredient SDS / PDS / CoA / other files (with lot, version, source, expiry), test-result and notebook attachments, and per-record uploads and links (formulas, batches, samples, suppliers, equipment…). Returns file METADATA only (never the text inside a file), including addedBy (who added it — null for files added before that was recorded) and uploadedAt. Filters combine. The summary block matches the page\'s tiles: expired, expiring in 30 days, SDS/CoA without an expiry date, ingredients missing an SDS (+ coverage %), lots in stock without a CoA, files added in the last 7 days. For the lots themselves use list_lots with missing_coa: true.',
125
125
  inputSchema: {
126
126
  type: 'object',
127
127
  properties: {
@@ -135,6 +135,7 @@ const list_documents = {
135
135
  expiring_within_days: { type: 'number', description: 'Only documents whose expiry date is within this many days (already expired included).' },
136
136
  without_expiry: { type: 'boolean', description: 'true = only SDS / CoA files with no expiry date (the "SDS / CoA without expiry" tile).' },
137
137
  uploaded_within_days: { type: 'number', description: 'Only files uploaded within this many days.' },
138
+ added_by: { type: 'string', description: 'Who added the file: case-insensitive substring of their email / name. Files from before this was recorded have none and never match.' },
138
139
  limit: { type: 'number', description: 'Max rows (default 200, max 1000).' },
139
140
  },
140
141
  },
@@ -156,6 +157,7 @@ const list_documents = {
156
157
  if (args.expiring_within_days != null && !(d.daysToExpiry != null && d.daysToExpiry <= args.expiring_within_days)) return false;
157
158
  if (args.without_expiry === true && !(d.record === 'ingredient' && d.expiryStatus === 'none' && (d.type === 'SDS' || d.type === 'COA'))) return false;
158
159
  if (args.uploaded_within_days != null && !(d.ageDays != null && d.ageDays <= args.uploaded_within_days)) return false;
160
+ if (args.added_by && !norm(d.addedBy).includes(norm(args.added_by))) return false;
159
161
  return true;
160
162
  }).sort((a, b) => String(b.uploadedAt || '').localeCompare(String(a.uploadedAt || '')));
161
163
  return { summary: summary(db, all), totalMatching: rows.length, returned: Math.min(rows.length, limit), documents: rows.slice(0, limit) };
package/tools/notebook.js CHANGED
@@ -46,6 +46,10 @@ function _trimEntry(e, db, { full = false } = {}) {
46
46
  updatedAt: e.updatedAt || null,
47
47
  author: e.author || '',
48
48
  attachmentCount: atts.length,
49
+ // Withdrawn by its author or the workspace owner (append-only notebook):
50
+ // the note is kept, but it is not a finding. null when not retracted.
51
+ retracted: (e.retracted && typeof e.retracted === 'object')
52
+ ? { at: e.retracted.at || null, by: e.retracted.by || '', reason: e.retracted.reason || '' } : null,
49
53
  };
50
54
  if (!full) return { ...base, body: (e.body || '').slice(0, 240) };
51
55
  return {
@@ -58,7 +62,7 @@ function _trimEntry(e, db, { full = false } = {}) {
58
62
  const list_notebook_entries = {
59
63
  definition: {
60
64
  name: 'list_notebook_entries',
61
- description: 'List ELN notebook entries — dated, authored notes attached to records — optionally filtered by the record they hang off (entity_type + entity_id), author, text, or date range. Newest first. Use get_notebook_entry for the full body + attachments.',
65
+ description: 'List ELN notebook entries — dated, authored notes attached to records — optionally filtered by the record they hang off (entity_type + entity_id), author, text, or date range. Newest first. Entries are append-only: a withdrawn one is kept with retracted = {at, by, reason} — treat it as withdrawn, not as a finding. Use get_notebook_entry for the full body + attachments.',
62
66
  inputSchema: {
63
67
  type: 'object',
64
68
  properties: {
@@ -68,6 +72,7 @@ const list_notebook_entries = {
68
72
  text_contains: { type: 'string', description: 'Case-insensitive substring on the note body.' },
69
73
  since: { type: 'string', description: 'ISO date/time — only entries at or after this timestamp.' },
70
74
  until: { type: 'string', description: 'ISO date/time — only entries at or before this timestamp.' },
75
+ retracted: { type: 'boolean', description: 'false = only notes that stand (leave out retracted ones); true = only retracted notes. Omit for both.' },
71
76
  limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
72
77
  },
73
78
  },
@@ -91,6 +96,7 @@ const list_notebook_entries = {
91
96
  if (wantEntityId && e.entityId !== wantEntityId) return false;
92
97
  if (args.author && !_norm(e.author).includes(_norm(args.author))) return false;
93
98
  if (args.text_contains && !_norm(e.body).includes(_norm(args.text_contains))) return false;
99
+ if (typeof args.retracted === 'boolean' && (!!(e.retracted && typeof e.retracted === 'object')) !== args.retracted) return false;
94
100
  if (sinceMs != null || untilMs != null) {
95
101
  const t = Date.parse(_entryTs(e));
96
102
  if (!isFinite(t)) return false;
@@ -110,7 +116,7 @@ const list_notebook_entries = {
110
116
  const get_notebook_entry = {
111
117
  definition: {
112
118
  name: 'get_notebook_entry',
113
- description: 'Get one ELN notebook entry by id — full note body, author, timestamp, the record it is attached to (resolved to uid/name), and attachment metadata (filename / type). Attachment binaries are not returned.',
119
+ description: 'Get one ELN notebook entry by id — full note body, author, timestamp, the record it is attached to (resolved to uid/name), attachment metadata (filename / type), and retracted = {at, by, reason} when the note was withdrawn. Attachment binaries are not returned.',
114
120
  inputSchema: {
115
121
  type: 'object',
116
122
  properties: { id: { type: 'string', description: 'Internal id of the notebook entry.' } },