formlab-mcp 0.6.60 → 0.6.62

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
@@ -52,7 +52,7 @@ Ask Claude (or another MCP client) things like:
52
52
  | `compare_batches` | Reproducibility of 2+ runs (ideally of one formula): each run's **yield %**, actual produced mass, cost/kg; per-ingredient **drift** across the runs vs the formula's proposed wt-%; and the biggest **outlier** run. `basis`: `wt_percent` (default) or `amount` |
53
53
  | `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 |
54
54
  | `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 |
55
- | `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. A ranked-scale (ordinal) or text parameter returns its step / pass-fail series instead: per-condition points, firstFail, latest, scaleShift |
55
+ | `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. A ranked-scale (ordinal) or text parameter returns its step / pass-fail series instead: per-condition points, firstFail, latest, scaleShift. Also the app's **Time points** (per condition: tested time points, skipped pulls, the next pull with its due date and whether it's overdue, on the formula's own pull schedule or the standard one; `as_of`) and **Arrhenius** (rates at the storage temperatures → the rate, Ea, Q10 and shelf life at `predict_at_c`, zero or first `order`, with 95% CIs and a verdict against the target) |
56
56
  | `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?"* |
57
57
  | `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` |
58
58
  | `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 |
@@ -68,6 +68,8 @@ Ask Claude (or another MCP client) things like:
68
68
  | `list_projects` | Filtered list of projects (the buckets formulations are filed under) + per-project formulation count. Filters: `status`, `name_contains` |
69
69
  | `get_project` | Full project record + the formulations filed under it |
70
70
  | `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` |
71
+ | `list_discussions` | Discussions beside records and work requests (live workspace): threads with their comments, resolved or not; append-only, a retracted comment keeps `retracted` = {at, reason}; `tab` = the record tab it was written on. Filters: `entity_type`, `entity_id`, `author`, `text_contains`, `since`, `open_only`, `flat` |
72
+ | `list_requests` | Work requests REQ-0001 … (Team, live workspace): title, kind, status (blocked with a reason), assignee, asked by, due, late, the linked record. Filters: `status` (or `active`), `assignee`, `kind`, `entity_type`, `entity_id`, `late_only` |
71
73
  | `get_notebook_entry` | One notebook entry — full body, author, attachment metadata, resolved linked record, and `retracted` when withdrawn |
72
74
 
73
75
  ## Install
package/index.js CHANGED
@@ -37,6 +37,7 @@ import * as designspace from './tools/designspace.js';
37
37
  import * as library from './tools/library.js';
38
38
  import * as projects from './tools/projects.js';
39
39
  import * as notebook from './tools/notebook.js';
40
+ import * as discussions from './tools/discussions.js';
40
41
  import * as batchAnalyze from './tools/batch-analyze.js';
41
42
  import * as suppliers from './tools/suppliers.js';
42
43
  import * as documents from './tools/documents.js';
@@ -123,6 +124,7 @@ const TOOLS = [
123
124
  ...Object.values(library.tools),
124
125
  ...Object.values(projects.tools),
125
126
  ...Object.values(notebook.tools),
127
+ ...Object.values(discussions.tools),
126
128
  ...Object.values(suppliers.tools),
127
129
  ...Object.values(documents.tools),
128
130
  ...Object.values(batchAnalyze.tools),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.60",
3
+ "version": "0.6.62",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
6
6
  "homepage": "https://formvix.com/mcp",
package/server.json CHANGED
@@ -2,13 +2,13 @@
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 server for FormLab formulation data: a local export file or your live cloud workspace.",
5
- "version": "0.6.60",
5
+ "version": "0.6.62",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "formlab-mcp",
11
- "version": "0.6.60",
11
+ "version": "0.6.62",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
package/theoretical.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // =====================================================================
2
2
  // Theoretical parameters for the MCP server — the app's own engine, not a
3
- // port. mcp/vendor/ holds exact copies of js/cost.js, js/nesting.js and
4
- // js/views/theoretical-params.js (test/mcp-theoretical.test.js keeps them
3
+ // port. mcp/vendor/ holds exact copies of js/cost.js, js/nesting.js,
4
+ // js/views/theoretical-params.js and js/reactive.js (test/mcp-theoretical.test.js keeps them
5
5
  // identical), so get_formulation reports the same Energy / NV / Cost per kg
6
6
  // the Params tab shows, with the same ⚠ notes.
7
7
  //
@@ -16,7 +16,7 @@ import { readFileSync } from 'node:fs';
16
16
  import vm from 'node:vm';
17
17
 
18
18
  const VENDOR = new URL('./vendor/', import.meta.url);
19
- const FILES = ['cost.js', 'nesting.js', 'theoretical-params.js'];
19
+ const FILES = ['cost.js', 'nesting.js', 'theoretical-params.js', 'reactive.js']; // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
20
20
  let _source = null;
21
21
  function source() {
22
22
  if (!_source) _source = FILES.map(f => readFileSync(new URL(f, VENDOR), 'utf8')).join('\n;\n');
@@ -1350,16 +1350,213 @@ function _shelfLifeAssess(sl, targetMonths, now) {
1350
1350
  return { verdict: null, level: (overdue || sl.remainingMonths < 3) ? 'medium' : 'info', pointTotal, ciTotal, overdue, crossDate };
1351
1351
  }
1352
1352
 
1353
+ // ---- Time points and Arrhenius: the app's Stability plots as numbers (FormLab 46a–46i) ----
1354
+ // Copies of js/views/stability.js (_stabTpBucket, _stabTpLadder, _stabTpRows, _stabCondTempC, _stabArrRows);
1355
+ // test/mcp-stability-arrhenius-timepoints.test.js holds them to the app's.
1356
+ const _MS_PER_DAY = 86400000;
1357
+ const _PULLS_ACCEL = [1, 2, 3, 6];
1358
+ const _PULLS_LONG = [1, 2, 3, 6, 9, 12, 18, 24, 36];
1359
+ // A time point from days since T₀: T₀ (≤ 3 days), weeks under 3 weeks, else whole months. key = days, for sorting.
1360
+ function _tpBucket(days) {
1361
+ if (days <= 3) return { key: 0, label: 'T₀' };
1362
+ if (days < 21) { const w = Math.max(1, Math.round(days / 7)); return { key: w * 7, label: `${w} wk` }; }
1363
+ const m = Math.max(1, Math.round(days / 30.4375));
1364
+ return { key: Math.round(m * 30.4375), label: `${m} mo` };
1365
+ }
1366
+ // A formula's own pull months (Stability → Time points → Pull schedule): { long, accel }, accel = 35 °C and up.
1367
+ function _tpPlanOf(formula) {
1368
+ const p = formula && formula.stabilityPulls;
1369
+ const ok = a => Array.isArray(a) ? [...new Set(a.map(Number).filter(m => m > 0))].sort((x, y) => x - y) : [];
1370
+ return { long: p ? ok(p.long) : [], accel: p ? ok(p.accel) : [] };
1371
+ }
1372
+ function _tpOwnPulls(plan, tC) {
1373
+ const own = plan && plan[tC != null && tC >= 35 ? 'accel' : 'long'];
1374
+ return own && own.length ? own : null;
1375
+ }
1376
+ // The months a condition is pulled at: the formula's own, else accelerated (35 °C and up) to 6 months and the rest
1377
+ // to the target shelf life.
1378
+ function _tpLadder(tC, targetMonths, plan) {
1379
+ const own = _tpOwnPulls(plan, tC);
1380
+ if (own) return own;
1381
+ if (tC != null && tC >= 35) return _PULLS_ACCEL;
1382
+ const end = targetMonths || 36;
1383
+ const l = _PULLS_LONG.filter(m => m <= end);
1384
+ if (targetMonths && !l.includes(targetMonths)) l.push(targetMonths);
1385
+ return l;
1386
+ }
1387
+ // A storage temperature in °C from a condition's name: "40 °C / 75% RH" → 40, "2–8 °C" → 5, "104F" → 40, else null.
1388
+ // A bare number with no C or F (a humidity, a cycle count) is never a temperature.
1389
+ function _condTempC(label) {
1390
+ const s = String(label || '');
1391
+ const toC = (v, u) => /f/i.test(u) ? (v - 32) * 5 / 9 : v;
1392
+ const range = s.match(/(\d+(?:\.\d+)?)\s*(?:–|-|to)\s*(\d+(?:\.\d+)?)\s*(?:°|º|deg(?:rees)?\.?)?\s*([CF])\b/i);
1393
+ if (range) return toC((parseFloat(range[1]) + parseFloat(range[2])) / 2, range[3]);
1394
+ const one = s.match(/(^|[^\d.\-–])(-?\d+(?:\.\d+)?)\s*(?:°|º|deg(?:rees)?\.?)?\s*([CF])\b/i);
1395
+ return one ? toC(parseFloat(one[2]), one[3]) : null;
1396
+ }
1397
+ // The study at a glance, one row per storage condition (the app's Time points plot): what was tested at each time
1398
+ // point from the entity's T₀ (its first test under any condition), the time points skipped, and the next pull with
1399
+ // its due date. points: [{ date, cond, pf }].
1400
+ function _mcpTimePoints(points, formula, targetMonths, now) {
1401
+ if (!points.length) return null;
1402
+ const day = d => new Date(d).toISOString().slice(0, 10);
1403
+ const t0 = Math.min(...points.map(p => p.date.getTime()));
1404
+ const plan = _tpPlanOf(formula);
1405
+ const byCond = new Map();
1406
+ points.forEach(p => { const c = (p.cond || '').trim(); if (!byCond.has(c)) byCond.set(c, []); byCond.get(c).push(p); });
1407
+ const rows = [...byCond.entries()].map(([cond, ps]) => ({ cond, ps, tC: cond ? _condTempC(cond) : null }))
1408
+ .sort((a, b) => (a.tC == null ? -Infinity : a.tC) - (b.tC == null ? -Infinity : b.tC) || a.cond.localeCompare(b.cond))
1409
+ .map(({ cond, ps, tC }) => {
1410
+ const cells = new Map();
1411
+ ps.forEach(p => {
1412
+ const b = _tpBucket((p.date.getTime() - t0) / _MS_PER_DAY);
1413
+ if (!cells.has(b.key)) cells.set(b.key, { ...b, dates: new Set(), pfs: [] });
1414
+ const c = cells.get(b.key); c.dates.add(day(p.date)); c.pfs.push(p.pf);
1415
+ });
1416
+ const lastKey = Math.max(...cells.keys());
1417
+ const ladder = _tpLadder(tC, targetMonths, plan);
1418
+ const nextM = ladder.find(m => Math.round(m * 30.4375) > lastKey);
1419
+ const due = nextM == null ? null : t0 + nextM * _MS_PER_MONTH;
1420
+ return { cond, tC, cells, lastKey, ladder, ladderKeys: ladder.map(m => Math.round(m * 30.4375)), own: !!_tpOwnPulls(plan, tC),
1421
+ next: nextM == null ? null : { timePoint: `${nextM} mo`, due: day(due), daysUntil: Math.floor((due - now) / _MS_PER_DAY) } };
1422
+ });
1423
+ // Skipped: a time point before this row's last test that its schedule, or (on the standard one) another row at its
1424
+ // temperature, has.
1425
+ rows.forEach(r => {
1426
+ const peers = r.own ? [] : rows.filter(o => o !== r && (o.tC != null ? o.tC === r.tC : o.cond === r.cond));
1427
+ const keys = new Set([...r.ladderKeys, ...peers.flatMap(o => [...o.cells.keys()])]);
1428
+ r.skipped = [...keys].filter(k => k > 0 && k < r.lastKey && !r.cells.has(k)).sort((a, b) => a - b);
1429
+ });
1430
+ return {
1431
+ t0: day(t0),
1432
+ rows: rows.map(r => ({
1433
+ condition: r.cond || null,
1434
+ temperatureC: r.tC != null ? _round(r.tC, 1) : null,
1435
+ schedule: r.own ? 'formula' : 'standard',
1436
+ pullMonths: r.ladder,
1437
+ tested: [...r.cells.values()].sort((a, b) => a.key - b.key).map(c => ({ timePoint: c.label, testDates: c.dates.size,
1438
+ pf: c.pfs.includes('fail') ? 'fail' : c.pfs.includes('pass') ? 'pass' : null })),
1439
+ skipped: r.skipped.map(k => _tpBucket(k).label),
1440
+ next: r.next ? { ...r.next, overdue: r.next.daysUntil < 0 } : null,
1441
+ })),
1442
+ };
1443
+ }
1444
+ // Two-sided 95% Student t (t 0.975), for a confidence interval: the Arrhenius CI. A copy of the app's _stabT975.
1445
+ const _T975_TABLE = [null, 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, 2.045, 2.042];
1446
+ function _t975(df) {
1447
+ df = Math.floor(df);
1448
+ if (!(df >= 1)) return Infinity;
1449
+ if (df < _T975_TABLE.length) return _T975_TABLE[df];
1450
+ const z = 1.959964;
1451
+ return z + (z ** 3 + z) / (4 * df) + (5 * z ** 5 + 16 * z ** 3 + 3 * z) / (96 * df * df);
1452
+ }
1453
+ // Standard error of an OLS slope; null with fewer than 3 points.
1454
+ function _slopeSE(xs, ys, fit) {
1455
+ const n = xs.length;
1456
+ if (!fit || n < 3) return null;
1457
+ const mx = xs.reduce((a, b) => a + b, 0) / n;
1458
+ const ssX = xs.reduce((a, x) => a + (x - mx) ** 2, 0);
1459
+ if (!(ssX > 0)) return null;
1460
+ let ssR = 0; xs.forEach((x, i) => { ssR += (ys[i] - (fit.intercept + fit.slope * x)) ** 2; });
1461
+ return Math.sqrt(ssR / (n - 2) / ssX);
1462
+ }
1463
+ // Arrhenius (the app's plot of that name): each storage condition with a temperature in its name and 3+ test dates
1464
+ // gives a rate (zero order: the slope per month; first order: of ln value, a steady % change). ln(rate) against 1/T
1465
+ // is fitted and read at atC for the rate, Ea, Q10 and the shelf life from the T₀ value to the spec limit, with 95%
1466
+ // CIs. null when no condition names a temperature. points: [{ date, value, cond }].
1467
+ function _mcpArrhenius(points, spec, atC, order, targetMonths) {
1468
+ const firstOrder = order === 'first';
1469
+ const skipped = [];
1470
+ const byT = new Map();
1471
+ points.forEach(p => {
1472
+ const cond = (p.cond || '').trim();
1473
+ const t = cond ? _condTempC(cond) : null;
1474
+ if (t == null) { const k = cond || '(no condition)'; if (!skipped.some(x => x.condition === k)) skipped.push({ condition: k, why: cond ? 'no temperature in the name' : 'no storage condition' }); return; }
1475
+ const key = Number(t.toFixed(1));
1476
+ if (!byT.has(key)) byT.set(key, { tC: key, conds: new Set(), points: [] });
1477
+ byT.get(key).conds.add(cond); byT.get(key).points.push(p);
1478
+ });
1479
+ if (!byT.size) return null;
1480
+ const temps = [...byT.values()].sort((a, b) => a.tC - b.tC).map(g => {
1481
+ const pts = g.points.slice().sort((a, b) => a.date - b.date);
1482
+ const t0 = pts[0].date.getTime();
1483
+ const days = new Set(pts.map(p => p.date.toISOString().slice(0, 10))).size;
1484
+ const mx = pts.map(p => (p.date.getTime() - t0) / _MS_PER_MONTH), my = pts.map(p => p.value);
1485
+ const fitOf = (ys) => { const f = days >= 3 ? _ols(mx, ys) : null; if (f) { f.se = _slopeSE(mx, ys, f) || 0; f.df = pts.length - 2; } return f; };
1486
+ const pos = my.every(v => v > 0);
1487
+ const fitZ = fitOf(my), fitF = pos ? fitOf(my.map(Math.log)) : null;
1488
+ const firstDay = pts[0].date.toISOString().slice(0, 10);
1489
+ const t0Vals = pts.filter(p => p.date.toISOString().slice(0, 10) === firstDay).map(p => p.value);
1490
+ return { tC: g.tC, label: [...g.conds].join(' / '), points: pts, days, fit: firstOrder ? fitF : fitZ, fitZ, fitF, pos,
1491
+ y0: t0Vals.reduce((a, b) => a + b, 0) / t0Vals.length };
1492
+ });
1493
+ // The direction is the hottest fitted temperature's; a temperature moving the other way, or not at all, has no rate.
1494
+ const fitted = temps.filter(t => t.fit && Math.abs(t.fit.slope) > 1e-12);
1495
+ temps.filter(t => !t.fit).forEach(t => skipped.push({ condition: t.label, why: t.days < 3 ? `${t.days} test date${t.days === 1 ? '' : 's'}` : firstOrder && !t.pos ? 'a value ≤ 0' : 'no change' }));
1496
+ const dir = fitted.length ? Math.sign(fitted[fitted.length - 1].fit.slope) : 0;
1497
+ const used = fitted.filter(t => Math.sign(t.fit.slope) === dir);
1498
+ fitted.filter(t => Math.sign(t.fit.slope) !== dir).forEach(t => skipped.push({ condition: t.label, why: 'changes the other way' }));
1499
+ const rate = (k) => firstOrder ? _round(k * 100, 4) : _round(k, 6); // first order: % per month
1500
+ const mo = (m) => m == null ? null : (!Number.isFinite(m) || m > 120) ? '> 120' : _round(m, 1);
1501
+ const out = {
1502
+ predictAtC: atC, order, rateUnit: firstOrder ? '% per month' : 'per month',
1503
+ temperatures: used.map(t => ({ temperatureC: t.tC, conditions: t.label, testDates: t.days, rate: rate(Math.abs(t.fit.slope)), r2: _round(t.fit.r2, 3) })),
1504
+ skipped,
1505
+ };
1506
+ const both = used.filter(t => t.fitZ && t.fitF);
1507
+ if (both.length) out.meanR2ByOrder = { zero: _round(both.reduce((a, t) => a + t.fitZ.r2, 0) / both.length, 3), first: _round(both.reduce((a, t) => a + t.fitF.r2, 0) / both.length, 3) };
1508
+ if (used.length < 2) { out.why = !points.length ? 'no readings' : used.length ? 'one temperature with a rate' : 'no temperature with a rate'; return out; }
1509
+ const xs = used.map(t => 1 / (t.tC + 273.15)), ys = used.map(t => Math.log(Math.abs(t.fit.slope)));
1510
+ const arr = _ols(xs, ys);
1511
+ if (!arr || !(arr.slope < 0)) { out.why = 'the rate doesn’t rise with temperature'; return out; }
1512
+ const kAt = (c) => Math.exp(arr.intercept + arr.slope / (c + 273.15));
1513
+ // 95% CI on ln k: each rate's own scatter carried through the fit (SE(ln k) = SE(k) / k), or, with 3+
1514
+ // temperatures, the rates' scatter about the line when that is wider.
1515
+ const m = used.length, mx = xs.reduce((a, b) => a + b, 0) / m, sxx = xs.reduce((a, x) => a + (x - mx) ** 2, 0);
1516
+ const v = used.map(t => Math.max(1e-18, (t.fit.se / Math.abs(t.fit.slope)) ** 2));
1517
+ const tW = _t975(used.reduce((a, t) => a + t.fit.df, 0));
1518
+ const ssB = xs.reduce((a, x, i) => a + (ys[i] - (arr.intercept + arr.slope * x)) ** 2, 0);
1519
+ const tsB = m > 2 ? _t975(m - 2) * Math.sqrt(ssB / (m - 2)) : 0;
1520
+ const d = 1 / (atC + 273.15) - mx;
1521
+ const lam = xs.map(x => 1 / m + d * (x - mx) / sxx);
1522
+ const h = Math.max(tW * Math.sqrt(lam.reduce((a, l, i) => a + l * l * v[i], 0)), tsB * Math.sqrt(1 / m + d * d / sxx));
1523
+ const k = kAt(atC), kLo = k * Math.exp(-h), kHi = k * Math.exp(h);
1524
+ out.fit = { activationEnergyKJmol: _round(-arr.slope * 8.314 / 1000, 1), q10: _round(kAt(atC + 10) / k, 2), r2: _round(arr.r2, 3), exactLine: m === 2 };
1525
+ out.rateAt = { rate: rate(k), ci95: [rate(kLo), rate(kHi)] };
1526
+ // Shelf life at atC: from the T₀ value (the first test date's mean, averaged over the temperatures used) to the
1527
+ // spec limit the change heads for, at the predicted rate; the CI from the rate's (a faster rate, a shorter life).
1528
+ const y0 = used.reduce((a, t) => a + t.y0, 0) / used.length;
1529
+ const limit = dir < 0 ? (spec && spec.min) : (spec && spec.max);
1530
+ let shelf = null, lo = null, hi = null, why = null;
1531
+ if (limit == null) why = spec && (spec.min != null || spec.max != null) ? `no ${dir < 0 ? 'lower' : 'upper'} limit` : 'no spec';
1532
+ else if ((limit - y0) * dir <= 0) why = 'starts outside spec';
1533
+ else if (firstOrder && !(limit > 0)) shelf = lo = hi = Infinity;
1534
+ else {
1535
+ const gap = firstOrder ? Math.abs(Math.log(limit / y0)) : Math.abs(limit - y0);
1536
+ shelf = gap / k; lo = gap / kHi; hi = gap / kLo;
1537
+ }
1538
+ const verdict = shelf != null && targetMonths ? (shelf < targetMonths ? 'short' : lo < targetMonths ? 'marginal' : 'meets') : null;
1539
+ out.shelfLife = shelf == null ? { months: null, why }
1540
+ : { months: mo(shelf), ci95Months: [mo(lo), mo(hi)], fromValue: _round(y0, 6), toLimit: limit, verdict };
1541
+ // Real time, when atC was itself tested: its own projection, for comparison.
1542
+ const rt = temps.find(t => Math.abs(t.tC - atC) <= 1);
1543
+ if (rt) { const a = _shelfLifeAssess(_shelfLife(rt.points, spec || {}), null); out.realTimeShelfLifeMonths = a ? _round(a.pointTotal, 1) : null; }
1544
+ return out;
1545
+ }
1546
+
1353
1547
  const get_stability = {
1354
1548
  definition: {
1355
1549
  name: 'get_stability',
1356
- description: 'Grounded stability / shelf-life analysis for one entity × parameter — the deterministic numbers behind the Stability & Trends view. Pass a formulation (pools all its samples), a sample (that sample over time), or a batch (pools its samples) by id or UID, plus a parameter name. Returns the time series, drift (per-month slope + R²), an individuals control chart (mean ± 3σ + out-of-control points), spec status, and an ICH-flavored projected shelf life (linear extrapolation to the spec crossing: point estimate + the conservative 95%-confidence-bound crossing). When measurements carry run conditions (e.g. Storage 25 °C vs 40 °C) it splits into one series per condition — a true accelerated-vs-ambient comparison. A point is one TEST DATE: every reading taken that day under that condition is averaged (points = test dates, readings = the raw count), so replicates never count as separate time points in the drift, control chart or shelf-life fit — the same points as the app. A ranked-scale (ordinal, e.g. pencil hardness) or text (e.g. appearance) parameter returns kind "ordinal" / "categorical" instead: per-condition points with the label (median rank for an ordinal), pass/fail, firstFail, latest and scaleShift — the app\'s step / pass-fail-strip trend, with no regression. Use these figures directly; do not re-derive the regression.',
1550
+ description: 'Grounded stability / shelf-life analysis for one entity × parameter — the deterministic numbers behind the Stability & Trends view. Pass a formulation (pools all its samples), a sample (that sample over time), or a batch (pools its samples) by id or UID, plus a parameter name. Returns the time series, drift (per-month slope + R²), an individuals control chart (mean ± 3σ + out-of-control points), spec status, and an ICH-flavored projected shelf life (linear extrapolation to the spec crossing: point estimate + the conservative 95%-confidence-bound crossing). When measurements carry run conditions (e.g. Storage 25 °C vs 40 °C) it splits into one series per condition — a true accelerated-vs-ambient comparison. A point is one TEST DATE: every reading taken that day under that condition is averaged (points = test dates, readings = the raw count), so replicates never count as separate time points in the drift, control chart or shelf-life fit — the same points as the app. A ranked-scale (ordinal, e.g. pencil hardness) or text (e.g. appearance) parameter returns kind "ordinal" / "categorical" instead: per-condition points with the label (median rank for an ordinal), pass/fail, firstFail, latest and scaleShift — the app\'s step / pass-fail-strip trend, with no regression. Also returns timePoints (the app\'s Time points plot: per condition, what was tested at each time point, skipped pulls, the next pull with its due date and whether it is overdue, on the formula\'s own pull schedule or the standard one) and arrhenius (the app\'s Arrhenius plot: rates at the storage temperatures fitted to predict the rate and shelf life at predict_at_c, with 95% CIs and a verdict against the target shelf life). Use these figures directly; do not re-derive the regression.',
1357
1551
  inputSchema: {
1358
1552
  type: 'object',
1359
1553
  properties: {
1360
1554
  entity_id: { type: 'string', description: 'A formulation, sample, or batch — id or UID (e.g. FRM-002, SMP-007, BTC-001). The type is auto-detected and sets the pooling level.' },
1361
1555
  parameter: { type: 'string', description: 'The measured parameter to analyze (case-insensitive, e.g. "Niacinamide assay").' },
1362
1556
  by_condition: { type: 'boolean', description: 'Split the series by captured storage condition (default true). Set false to pool all conditions into one trend.' },
1557
+ predict_at_c: { type: 'number', description: 'Arrhenius: the storage temperature (°C) to predict the rate and shelf life at (default 25; the app offers 5, 25 and 30).' },
1558
+ order: { type: 'string', enum: ['zero', 'first'], description: 'Arrhenius kinetics: "zero" (a steady change per month, default) or "first" (a steady % change per month, e.g. an assay or viscosity falling by a share of what is left). meanR2ByOrder compares the two.' },
1559
+ as_of: { type: 'string', description: 'Date (YYYY-MM-DD) that time points\' next pulls are counted from (due in / overdue). Default today.' },
1363
1560
  },
1364
1561
  required: ['entity_id', 'parameter'],
1365
1562
  },
@@ -1423,7 +1620,8 @@ const get_stability = {
1423
1620
  }
1424
1621
  const cond = (m.conditions && Object.keys(m.conditions).length)
1425
1622
  ? Object.entries(m.conditions).map(([k, v]) => `${k} ${v}`).join(' · ') : '';
1426
- points.push({ date, day: dStr, value, cond, spec: sp });
1623
+ const pf0 = sp ? _evalPassFail(m, t.templateId) : null;
1624
+ points.push({ date, day: dStr, value, cond, spec: sp, pf: pf0 === 'pass' || pf0 === 'fail' ? pf0 : null });
1427
1625
  });
1428
1626
  });
1429
1627
  const specList = [...specByKey.values()].map(e => ({ min: e.min, max: e.max, readings: e.readings, sources: [...e.sources] }));
@@ -1446,21 +1644,27 @@ const get_stability = {
1446
1644
  points.length = 0;
1447
1645
  byDay.forEach(g => {
1448
1646
  const value = g.reduce((a, r) => a + r.value, 0) / g.length;
1449
- points.push({ date: new Date(g[0].day), value, cond: g[0].cond, spec: (g.find(r => r.spec) || {}).spec || null, readings: g.length });
1647
+ points.push({ date: new Date(g[0].day), value, cond: g[0].cond, spec: (g.find(r => r.spec) || {}).spec || null, readings: g.length,
1648
+ pf: g.some(r => r.pf === 'fail') ? 'fail' : g.some(r => r.pf === 'pass') ? 'pass' : null });
1450
1649
  });
1451
1650
  points.sort((a, b) => (a.date - b.date) || a.cond.localeCompare(b.cond));
1452
- if (!points.length && graded.length) return _mcpGradedStability(entity, entityType, args, graded);
1453
- if (!points.length) return { error: `No dated "${args.parameter}" measurements on ${entity.uid || entity.id}.` };
1454
-
1455
- const spec = { min: specMin, max: specMax };
1456
1651
  // Target shelf life: the formula's own Shelf life, else the workspace
1457
1652
  // default when this store carries it (the app's Settings → Stability).
1653
+ // A batch or sample reaches its formula through formulationId (a sample of a batch through the batch).
1458
1654
  const formula = entityType === 'formulation' ? entity
1459
- : (db.formulations || []).find(f => f.id === entity.formulationId) || null;
1655
+ : (db.formulations || []).find(f => f.id === (entity.formulationId || ((db.batches || []).find(b => b.id === entity.batchId) || {}).formulationId)) || null;
1460
1656
  const ownT = formula ? parseFloat(formula.shelfLifeMonths) : NaN;
1461
1657
  const defT = parseFloat(db.defaultShelfLifeMonths);
1462
1658
  const target = (Number.isFinite(ownT) && ownT > 0) ? { months: ownT, source: 'formula' }
1463
1659
  : (Number.isFinite(defT) && defT > 0) ? { months: defT, source: 'workspace default' } : null;
1660
+ const asOf = args.as_of && /^\d{4}-\d{2}-\d{2}$/.test(args.as_of) ? Date.parse(args.as_of) : Date.now();
1661
+ if (!points.length && graded.length) {
1662
+ const tp = _mcpTimePoints(graded.map(r => ({ date: new Date(r.day), cond: r.cond, pf: r.pf === 'pass' || r.pf === 'fail' ? r.pf : null })), formula, target && target.months, asOf);
1663
+ return { ..._mcpGradedStability(entity, entityType, args, graded), ...(tp ? { timePoints: tp } : {}) };
1664
+ }
1665
+ if (!points.length) return { error: `No dated "${args.parameter}" measurements on ${entity.uid || entity.id}.` };
1666
+
1667
+ const spec = { min: specMin, max: specMax };
1464
1668
  const analyze = (pts) => {
1465
1669
  const ys = pts.map(p => p.value);
1466
1670
  const n = ys.length;
@@ -1519,6 +1723,10 @@ const get_stability = {
1519
1723
  entity: { type: entityType, uid: entity.uid, name: entity.name || entity.uid },
1520
1724
  parameter: args.parameter, unit, spec, ...((skipped.ordinal || skipped.categorical) ? { skipped, skippedNote: 'Ordinal (ranked scale) and text readings have no number to trend and are left out, as in the app.' } : {}), ...(specVaries ? { specVaries, specNote: 'Readings were judged against different specs (different panels): no single band, no shelf-life projection; each reading keeps its own pass/fail.' } : {}), pointCount: points.length, byCondition: split, series,
1521
1725
  targetShelfLife: target ? { months: target.months, source: target.source } : null,
1726
+ timePoints: _mcpTimePoints(points, formula, target && target.months, asOf),
1727
+ arrhenius: specVaries ? null : _mcpArrhenius(points, spec, Number.isFinite(+args.predict_at_c) && args.predict_at_c !== null && args.predict_at_c !== '' ? +args.predict_at_c : 25, args.order === 'first' ? 'first' : 'zero', target && target.months),
1728
+ timePointsNote: 'timePoints: one row per storage condition, time points counted from t0 (the first test under any condition): tested (pf "fail" when any reading that time point failed), skipped (a time point before the last test that the schedule or another condition at that temperature has, but this one does not), next (the next pull not yet tested, its due date, daysUntil; overdue = past as_of; null = schedule complete). schedule "formula" = the formula\'s own pull months, else "standard": 1, 2, 3, 6 months at 35 °C and up; 1, 2, 3, 6, 9, 12, 18, 24, 36 months up to the target shelf life.',
1729
+ arrheniusNote: 'arrhenius (null when no condition names a temperature): rates per storage temperature (3+ test dates each), ln(rate) against 1/T fitted and read at predictAtC: activation energy, Q10, the rate there with its 95% CI, and the shelf life there from the T0 value to the spec limit (ci95Months: a faster rate gives the low end). "> 120" = beyond 10 years. verdict as shelfLife.verdict, against targetShelfLife. realTimeShelfLifeMonths = the trend projection at predictAtC itself when that temperature was tested. why = no prediction, and the reason.',
1522
1730
  note: 'shelfLife.fromT0Months / ci95FromT0Months are the projected shelf life counted from the first test (T0): point estimate and the conservative (ICH Q1E) 95%-bound crossing. remainingMonths / ci95Months are the same, counted from the last test. verdict compares against targetShelfLife: "short" = the trend crosses spec before the target, "marginal" = the trend clears it but the 95% bound does not, "meets" = both clear it; null = no target set (then concern is by time left: medium <3 mo or overdue, else info). A projection never reaches \"high\": high is reserved for a MEASURED out-of-spec value (spec.latestInSpec=false). short/overdue → medium, marginal/meets → info. overdue=true means projectedCrossDate is already past today (time left runs from the last test), so the sample is probably out of spec now — recommend a re-test. reportable=false means the app shows no projection (R² < 0.3, crossing already past, or beyond 5 years). Numbers are computed here — narrate them, do not recompute.',
1523
1731
  };
1524
1732
  },
@@ -0,0 +1,138 @@
1
+ // ============================================================
2
+ // DISCUSSION + REQUEST TOOLS (FormLab Team / Pro shared workspaces, migrations 0201-0203).
3
+ // - list_discussions: comments beside records (and on work requests), grouped by thread or flat
4
+ // - list_requests: work requests (REQ-0001 …): what was asked of whom, by when, and where it stands
5
+ // A discussion is part of the record's history, not a chat: comments are append-only (a retracted one is kept with
6
+ // retracted = {at, reason} — never cite it as a finding). Only in a live workspace (cloud mode); an export file has
7
+ // none. Read-only; the server applies project walls and the owner's switch for restricted projects.
8
+ // ============================================================
9
+
10
+ import { getStore } from '../data.js';
11
+
12
+ const _norm = (s) => String(s == null ? '' : s).toLowerCase();
13
+ const _clampLimit = (n) => Math.min(1000, Math.max(1, n || 100));
14
+
15
+ const _COLL = {
16
+ formulation: 'formulations', batch: 'batches', sample: 'samples', testResult: 'testResults', project: 'projects',
17
+ ingredient: 'ingredients', equipment: 'equipment', parameter: 'parameters', template: 'templates', lot: 'lots', doeDesign: 'doeDesigns',
18
+ };
19
+
20
+ function _record(type, id, db) {
21
+ if (type === 'request') {
22
+ const r = (db.requests || []).find(x => x && x.id === id);
23
+ return r ? { uid: r.uid, name: r.title } : null;
24
+ }
25
+ const rec = (db[_COLL[type]] || []).find(x => x && (x.id === id || x.uid === id));
26
+ return rec ? { uid: rec.uid || null, name: rec.name || rec.reportName || rec.title || '' } : null;
27
+ }
28
+
29
+ // A UID or id the caller passed, down to the id the comments carry.
30
+ function _resolveId(type, id, db) {
31
+ if (!id) return null;
32
+ if (type === 'request') { const r = (db.requests || []).find(x => x && (x.id === id || x.uid === id)); return r ? r.id : id; }
33
+ const rec = (db[_COLL[type]] || []).find(x => x && (x.id === id || x.uid === id));
34
+ return rec ? rec.id : id;
35
+ }
36
+
37
+ function _notLive(db) {
38
+ return !Array.isArray(db.discussions) && !Array.isArray(db.requests)
39
+ ? { error: 'Discussions and requests are read from a live FormLab workspace (cloud mode). This data source has none.' } : null;
40
+ }
41
+
42
+ const list_discussions = {
43
+ definition: {
44
+ name: 'list_discussions',
45
+ description: 'List discussion comments that sit beside records (formulas, batches, samples, test reports, projects, ingredients, equipment) or work requests — optionally filtered by the record (entity_type + entity_id, UID accepted), author, text, date, or only unresolved threads. Grouped by thread by default (each thread: the record, resolved or not, its comments oldest first); flat=true returns comments newest first. Comments are append-only: a retracted one keeps retracted = {at, reason} — treat it as withdrawn, not as a finding. "tab" says which tab of the record the comment was written on.',
46
+ inputSchema: {
47
+ type: 'object',
48
+ properties: {
49
+ entity_type: { type: 'string', description: 'formulation, batch, sample, testResult, project, ingredient, equipment, or request.' },
50
+ entity_id: { type: 'string', description: 'The record (internal id or UID, e.g. FORM-0012, REQ-0003).' },
51
+ author: { type: 'string', description: 'Case-insensitive substring of the author\'s name.' },
52
+ text_contains: { type: 'string', description: 'Case-insensitive substring of the comment text.' },
53
+ since: { type: 'string', description: 'ISO date/time: only comments at or after it.' },
54
+ open_only: { type: 'boolean', description: 'true = only threads not resolved.' },
55
+ flat: { type: 'boolean', description: 'true = a flat list of comments, newest first, instead of threads.' },
56
+ limit: { type: 'number', description: 'Max threads (or comments when flat), default 100, max 1000.' },
57
+ },
58
+ },
59
+ },
60
+ handler: async (args) => {
61
+ const { db } = getStore();
62
+ const none = _notLive(db); if (none) return none;
63
+ const limit = _clampLimit(args.limit);
64
+ const wantId = _resolveId(args.entity_type, args.entity_id, db);
65
+ const sinceMs = args.since ? Date.parse(args.since) : null;
66
+ const all = (db.discussions || []).filter(c => c && (!args.entity_type || c.entityType === args.entity_type) && (!wantId || c.entityId === wantId));
67
+ const threads = new Map();
68
+ all.forEach(c => { const k = `${c.entityType}:${c.entityId}`; if (!threads.has(k)) threads.set(k, []); threads.get(k).push(c); });
69
+ const resolvedOf = (list) => { const last = list.filter(c => c.kind !== 'comment').pop(); return !!(last && last.kind === 'resolve'); };
70
+ const keep = (c) => c.kind === 'comment'
71
+ && (!args.author || _norm(c.author).includes(_norm(args.author)))
72
+ && (!args.text_contains || _norm(c.body).includes(_norm(args.text_contains)))
73
+ && (sinceMs == null || Date.parse(c.at) >= sinceMs);
74
+ const row = (c) => ({ id: c.id, author: c.author, at: c.at, body: c.body, tab: c.tab || null, replyTo: c.replyTo || null,
75
+ retracted: c.retracted || null });
76
+ if (args.flat) {
77
+ const flat = [...threads.values()].filter(l => !args.open_only || !resolvedOf(l)).flat().filter(keep)
78
+ .sort((a, b) => Date.parse(b.at) - Date.parse(a.at));
79
+ return { totalMatching: flat.length, returned: Math.min(flat.length, limit),
80
+ comments: flat.slice(0, limit).map(c => { const rec = _record(c.entityType, c.entityId, db);
81
+ return { ...row(c), entityType: c.entityType, entityId: c.entityId, entityUid: rec ? rec.uid : null, entityName: rec ? rec.name : '' }; }) };
82
+ }
83
+ const out = [...threads.values()].map(list => {
84
+ const comments = list.filter(keep);
85
+ if (!comments.length) return null;
86
+ const c0 = list[0], rec = _record(c0.entityType, c0.entityId, db), resolved = resolvedOf(list);
87
+ if (args.open_only && resolved) return null;
88
+ return { entityType: c0.entityType, entityId: c0.entityId, entityUid: rec ? rec.uid : null, entityName: rec ? rec.name : '',
89
+ resolved, lastAt: list[list.length - 1].at, comments: comments.map(row) };
90
+ }).filter(Boolean).sort((a, b) => Date.parse(b.lastAt) - Date.parse(a.lastAt));
91
+ return { totalMatching: out.length, returned: Math.min(out.length, limit), threads: out.slice(0, limit) };
92
+ },
93
+ };
94
+
95
+ const list_requests = {
96
+ definition: {
97
+ name: 'list_requests',
98
+ description: 'List work requests (REQ-0001 …) in a FormLab Team workspace: what was asked of whom, by when, on which record, and where it stands (open, in_progress, blocked with a reason, done, cancelled). Filter by status, assignee (name substring), kind (batch, tests, samples, review, other), the linked record (UID accepted), or late only. Open ones first, then by due date.',
99
+ inputSchema: {
100
+ type: 'object',
101
+ properties: {
102
+ status: { type: 'string', description: 'open, in_progress, blocked, done, cancelled; or "active" for open + in_progress + blocked.' },
103
+ assignee: { type: 'string', description: 'Case-insensitive substring of the name of the person it is asked of.' },
104
+ kind: { type: 'string', description: 'batch, tests, samples, review, other.' },
105
+ entity_type: { type: 'string', description: 'The linked record\'s type (formulation, batch, sample, testResult, project).' },
106
+ entity_id: { type: 'string', description: 'The linked record (internal id or UID).' },
107
+ late_only: { type: 'boolean', description: 'true = only active requests past their due date.' },
108
+ limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
109
+ },
110
+ },
111
+ },
112
+ handler: async (args) => {
113
+ const { db } = getStore();
114
+ const none = _notLive(db); if (none) return none;
115
+ const limit = _clampLimit(args.limit);
116
+ const today = new Date().toISOString().slice(0, 10);
117
+ const active = new Set(['open', 'in_progress', 'blocked']);
118
+ const wantId = _resolveId(args.entity_type, args.entity_id, db);
119
+ const order = { blocked: 0, open: 1, in_progress: 2, done: 3, cancelled: 4 };
120
+ const rows = (db.requests || []).filter(r => r
121
+ && (!args.status || (args.status === 'active' ? active.has(r.status) : r.status === args.status))
122
+ && (!args.assignee || _norm(r.assignee).includes(_norm(args.assignee)))
123
+ && (!args.kind || r.kind === args.kind)
124
+ && (!args.entity_type || r.entityType === args.entity_type) && (!wantId || r.entityId === wantId)
125
+ && (!args.late_only || (active.has(r.status) && r.due && r.due < today)))
126
+ .sort((a, b) => (order[a.status] - order[b.status]) || String(a.due || '9999').localeCompare(String(b.due || '9999')));
127
+ return {
128
+ totalMatching: rows.length, returned: Math.min(rows.length, limit),
129
+ requests: rows.slice(0, limit).map(r => { const rec = r.entityType ? _record(r.entityType, r.entityId, db) : null;
130
+ return { uid: r.uid, title: r.title, kind: r.kind, status: r.status, blockedReason: r.blockedReason || null, assignee: r.assignee || null,
131
+ askedBy: r.askedBy || null, due: r.due || null, late: !!(active.has(r.status) && r.due && r.due < today),
132
+ on: rec ? { type: r.entityType, uid: rec.uid, name: rec.name } : null, note: r.note || null,
133
+ createdAt: r.createdAt, closedAt: r.closedAt || null }; }),
134
+ };
135
+ },
136
+ };
137
+
138
+ export const tools = { list_discussions, list_requests };
@@ -30,6 +30,9 @@ function _trimFormulation(f) {
30
30
  // Target shelf life (months): sets finished-goods expiry AND is what
31
31
  // get_stability judges the projected shelf life against.
32
32
  shelfLifeMonths: f.shelfLifeMonths ?? null,
33
+ // Its own stability pull months (Stability → Time points → Pull schedule): long = below 35 °C, accel = 35 °C and
34
+ // up; null = the standard schedule. get_stability's timePoints follow it.
35
+ stabilityPulls: f.stabilityPulls && (Array.isArray(f.stabilityPulls.long) || Array.isArray(f.stabilityPulls.accel)) ? { long: f.stabilityPulls.long || [], accel: f.stabilityPulls.accel || [] } : null,
33
36
  // Density of the MIXED product (g/mL), when declared — volume-targeted
34
37
  // batches scale by it instead of the ideal-mix estimate. null = not set.
35
38
  finishedDensity: (f.finishedDensity && isFinite(parseFloat(f.finishedDensity.value)))
@@ -151,7 +151,7 @@ function eqCalCardHtml(e) {
151
151
  <span><span style="color:var(--text-muted)">Last</span> <strong>${esc(st.last || '—')}</strong>${st.lastResult ? ` · ${esc(_EQ_CAL_RESULT_LABEL[st.lastResult] || st.lastResult)}` : ''}</span>
152
152
  <span><span style="color:var(--text-muted)">Next due</span> <strong>${esc(st.due || '—')}</strong></span>
153
153
  <span><span style="color:var(--text-muted)">Interval</span> <strong>${interval ? interval + ' month' + (interval === 1 ? '' : 's') : '—'}</strong></span>
154
- </div>${st.state === 'failed' && e.status !== 'Out of service' ? `<div style="margin-top:10px;font-size:12.5px;color:var(--dk-red-fg, #b91c1c)">The latest calibration failed. Set the instrument <strong>Out of service</strong> (Edit) until it passes again.</div>` : ''}`;
154
+ </div>${st.state === 'failed' && e.status !== 'Out of service' ? `<div style="margin-top:10px;font-size:12.5px;color:var(--dk-red-fg, #b91c1c)">The latest calibration failed. Set the instrument <strong>Out of service</strong> (the status beside its name) until it passes again.</div>` : ''}`;
155
155
  const rows = hist.map(c => `<tr>
156
156
  <td style="font-variant-numeric:tabular-nums">${esc(c.date || '—')}</td>
157
157
  <td>${esc(c.by || '—')}</td>
@@ -199,6 +199,12 @@ function openEqCalLogModal(eqId, calId) {
199
199
  const e = typeof getEquipment === 'function' ? getEquipment(eqId) : (db.equipment || []).find(x => x.id === eqId);
200
200
  if (!e) return;
201
201
  const c = calId ? (e.calibrations || []).find(x => x && x.id === calId) : null;
202
+ // EQ1 (0186): a Technician adds calibrations; changing or deleting a logged one stays with "Edit the shared libraries".
203
+ const caps = typeof window !== 'undefined' ? window.flMyCaps : null;
204
+ if (c && Array.isArray(caps) && !caps.includes('library.edit')) {
205
+ toast('Your role can log new calibrations, not change a logged one. Ask a lab manager or a formulator.');
206
+ return;
207
+ }
202
208
  const interval = eqCalInterval(e);
203
209
  const date = c ? (c.date || '') : _eqCalToday();
204
210
  const files = Array.isArray(e.fileAttachments) ? e.fileAttachments : [];