formlab-mcp 0.6.96 → 0.6.98

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
@@ -28,24 +28,24 @@ Ask Claude (or another MCP client) things like:
28
28
 
29
29
  | Tool | Purpose |
30
30
  |---|---|
31
- | `list_formulations` | Filtered list of recipes, each with exact `batchCount` / `sampleCount` / `testReportCount`; `sort` (`batches`, `samples`, `test_reports`, `name`, `updated`) ranks every match before the limit — "which formulas have the most batch runs?" in one call |
31
+ | `list_formulations` | Filtered list of recipes, each with exact `batchCount` / `sampleCount` / `testReportCount`; `sort` (`batches`, `samples`, `test_reports`, `name`, `updated`) ranks every match before the limit — "which formulas have the most batch runs?" in one call; `review` (`sent` = waiting for a reviewer, `returned`, `approved`, `none`) |
32
32
  | `get_formulation` | Full record (incl. `versionLabel`, the label the user types, e.g. 1.0) + **version history** (`versionHistory`: one snapshot per save, v1, v2…, newest first, with the label each save had and its note) + flattened wt-% composition (sub-formulas expanded), the ordered **step procedure**, user **custom fields**, any **process-factor values** (DOE inputs — cure temp, mix time, RPM, pH…), the declared **finishedDensity** (g/mL of the mixed product; volume-targeted batches scale by it), and its **theoretical parameters computed** the way the app's Params tab does (Energy kcal/100g, NV %, Cost/kg…: value, unit, formula, spec pass/fail, and a `warning` when ingredients lack a value or carry mixed units) — the app's own engine, vendored in `mcp/vendor/` and run in an isolated `node:vm` context |
33
33
  | `get_nutrition_label` | The formula's **Label** tab (Pro, live workspace only): US Nutrition Facts lines per serving with FDA rounding and % Daily Value, the per-container column, whether the simplified format applies, the EU declaration (kJ / kcal, salt) and EU ingredient list with allergens in capitals, the ingredient statement with its Contains line, and which ingredients are missing nutrition data. |
34
34
  | `get_fragrance_compliance` | The formula's **Fragrance** tab (Pro, live workspace only): each fragrance material's % in the finished product against its IFRA limit for the product category, the highest dosage that passes and the material that limits it, and the EU fragrance allergens to name on the label. Optional what-if `category`, `use`, `dosage` ("can this oil go into a body lotion at 2%?"). Limits come only from the certificates the lab has on file; anything missing makes the state `incomplete`. Not a certification. `get_formulation` carries the same summary as `fragranceCompliance`. |
35
35
  | `find_similar_formulations` | Find formulas using a given ingredient ≥ threshold % |
36
36
  | `compare_formulations` | Pairwise side-by-side composition diff |
37
- | `list_ingredients` | Filtered list of raw materials. Filters: `family`, `supplier`, `name_contains`, `lot_number` (the ingredient a lot belongs to), `in_stock_only`, `ingredient_class` (small-molecule / surfactant / polymer / extract / fragrance / pigment / sequence / mixture), `sequence_contains` (e.g. `KTTKS` → Matrixyl), `taxon_contains` (e.g. `Centella`) |
37
+ | `list_ingredients` | Filtered list of raw materials. Filters: `family`, `supplier`, `name_contains`, `lot_number` (the ingredient a lot belongs to), `in_stock_only`, `ingredient_class` (small-molecule / surfactant / polymer / extract / fragrance / pigment / sequence / mixture), `sequence_contains` (e.g. `KTTKS` → Matrixyl), `taxon_contains` (e.g. `Centella`), `docs_expiring`, `reg_stale`, `trial_sources` (the app's Needs Attention rows) |
38
38
  | `get_ingredient` | Full record + supplier / **cost ($/kg)** / stock / chemical name / molecular weight / storage / formulations using it, plus **GHS safety** (pictograms, H/P codes, signal word), **per-jurisdiction regulatory status**, **approved sources** (the suppliers / manufacturers qualified to supply this material — ASL/AML), and **inventory lots** (balances + expiry + the source each was received from). Returns every class-specific sub-object when present: `sequence` (peptide / oligo), `taxon` (NCBI ID + scientific name), `ingredientClass`, `extractDetails`, `sequenceDetails`, `polymerDetails`, `surfactantDetails`, `pigmentDetails`, `fragranceDetails`, and its **custom fields** with units (`customFields`: protein / carb / fat in g/100g, solids %… — what theoretical parameters read), and its **reactive groups** (EEW, AHEW, OH number, NCO %, acid / amine value: as entered, in the datasheet's terms and meq/g, with any row the app ignores and why) |
39
- | `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 `holdAt` — 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`, `lot_number`, `expiring_within_days`, `status` (e.g. `hold` to find lots held for a recall), `missing_coa` |
39
+ | `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 `holdAt` — 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`, `lot_number`, `expiring_within_days`, `status` (e.g. `hold` to find lots held for a recall), `missing_coa`, `disqualified_source` |
40
40
  | `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 |
41
41
  | `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) |
42
42
  | `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 |
43
43
  | `list_inventory` | Portfolio stock rollup — one row per ingredient with on-hand qty, summed lot balance, nearest expiry, a low-stock flag (on-hand ≤ `reorderThreshold`, or zero), and stock on hold (`heldQty` plus `lotsOnHold`: lot number, quantity, reason, since; a held lot with stock left). Filters: `low_stock_only`, `expiring_within_days`, `on_hold_only`, `family` |
44
44
  | `list_batches` | Filtered list of production / lab-prep events; each row has **`bestBy`**; filter by `best_by_before` (past best-by = today) or `lots_expire_first`, `on_hold`, `made_with_lot`, `released_with_lot` (batches released together with a lot) (batches that drew from a recalled lot), `held_lot` (drew from any lot now on hold) |
45
45
  | `get_batch` | Full record + **`lotsUsed`** (raw lots drawn, with each lot's status and hold reason now) + **`holdHistory`** (each hold with its release: when, by whom, "Released with lot X") + 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 **`bestBy`** (the adjusted date with its change, reason, note and retest report, else prepared date + shelf life; `lotsExpiringFirst` = lots it drew from that expire sooner), its storage **`location`** + finished-goods **`stockLedger`** (shipments out + adjustments; `shippedQty` total), and its **theoretical parameters computed on the batch as made** (actual composition when logged — `basis: "actual"` — else the recipe; the batch's own parameter list when it overrides the formula's) |
46
- | `list_samples` | Filtered list of physical specimens |
46
+ | `list_samples` | Filtered list of physical specimens; `overdue` = In Testing with no report in 30+ days (Needs Attention) |
47
47
  | `get_sample` | Full record + canonical variant + test reports + blend lineage + its stability pulls (next pull, or pulled at) |
48
- | `list_test_results` | Filtered list of test reports (by sample, parameter, **measured-value range** (`value_min`/`value_max` — a curve at its final point, a distribution at its spec's statistic or D50), **grade** (`min_grade`/`max_grade` on a ranked scale), **text value** (`value_equals`), **run condition** (`condition`), date, or lab) |
48
+ | `list_test_results` | Filtered list of test reports (by sample, parameter, **measured-value range** (`value_min`/`value_max` — a curve at its final point, a distribution at its spec's statistic or D50), **grade** (`min_grade`/`max_grade` on a ranked scale), **text value** (`value_equals`), **run condition** (`condition`), date, or lab; `in_doubt` (a reading's instrument failed calibration in its window or was Out of service; each row carries `readingsInDoubt`) and `review` state) |
49
49
  | `get_test_result` | Full report: every measurement's value, spec, any per-measurement run **conditions**, and the **resolved instrument** (`instrumentSource`: row / method / run). Complex types carry a `representative` (time-series → final, distribution → D50; a distribution also its `bins` and, when its spec names a statistic, `judged` at it); a ranked grade carries its `scale` and `rank`; a time series adds `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (repeat readings at one `t`). Report-level `seriesReplicates` lists parameters measured 2+ times as separate rows — point vs series replicates are distinct. Each measurement also gives its **effective spec** (`effectiveSpec`, `specSource`: override / template / parameter / none) and `passFail` — panel and Test Method specs apply exactly as in the app, and every pass/fail count across the tools uses the same rule |
50
50
  | `get_doe_matrix` | Pivot matrix (CSV by default) — rows × ingredients × parameters. A parameter measured under two or more **run conditions** (storage 25 °C vs 40 °C) is one column per condition (`pH`, `pH · 40 °C`; the bare name is the base arm), never averaged together — same columns, in the same order (grouped by measurement type, the test panel's order within a group), as the app's DOE Matrix |
51
51
  | `find_failures` | Parameters ranked by failure **rate** (failing ÷ all readings; replicates in one report count once), `lowN` flag under 5 readings, plus formulations ranked by share of failing reports — same numbers as the app's Test Analytics → Failures |
package/attention.js ADDED
@@ -0,0 +1,55 @@
1
+ // =====================================================================
2
+ // Needs Attention states for the MCP list filters (0.6.98), each a copy of the app's own rule, so an MCP client
3
+ // finds what the app's Dashboard and its AI assistant find (Jun, 30 Nov: "make sure AI search is consistent").
4
+ // reviewState js/review.js flReviewState none | sent | approved | returned
5
+ // sampleOverdue js/views/dashboard.js stale samples In Testing, no report (or creation) for 30+ days
6
+ // docExpiring js/documents.js docExpiryStatus expired, or expiring within 30 days
7
+ // regStale js/regulatory.js regIsStale checked 12+ months ago (30.4375-day months)
8
+ // trialSources js/inventory-sources.js approved-source entries with status "trial"
9
+ // lotSource js/inventory-sources.js resolveLotSource by sourceId, else supplier / manufacturer name
10
+ // test/mcp-attention-30nov.test.js runs the app's functions beside these on the same records.
11
+ // =====================================================================
12
+ const REVIEW_STATES = new Set(['sent', 'approved', 'returned']);
13
+ export function reviewState(rec) { const s = rec && rec.review && rec.review.state; return REVIEW_STATES.has(s) ? s : 'none'; }
14
+
15
+ const DAY = 86400000;
16
+ export function sampleOverdue(s, tests, nowMs = Date.now()) {
17
+ if (!s || s.status !== 'In Testing') return false;
18
+ const dates = (tests || []).filter(t => t && t.sampleId === s.id).map(t => {
19
+ const d = t.testDate ? Date.parse(t.testDate) : (t.createdAt ? Date.parse(t.createdAt) : 0);
20
+ return Number.isFinite(d) ? d : 0;
21
+ }).filter(Boolean);
22
+ const last = dates.length ? Math.max(...dates) : (s.createdAt ? Date.parse(s.createdAt) : 0);
23
+ if (!last || last > nowMs) return false;
24
+ return Math.round((nowMs - last) / DAY) >= 30;
25
+ }
26
+
27
+ export function docExpiry(doc, now = new Date()) {
28
+ if (!doc || !doc.expiryDate) return 'none';
29
+ const exp = new Date(doc.expiryDate + 'T00:00:00');
30
+ if (isNaN(exp.getTime())) return 'none';
31
+ const today = new Date(now); today.setHours(0, 0, 0, 0);
32
+ const days = Math.round((exp - today) / DAY);
33
+ return days < 0 ? 'expired' : days <= 30 ? 'soon' : 'current';
34
+ }
35
+ export function docsExpiring(ing, now) { return (ing && ing.documents || []).filter(d => { const s = docExpiry(d, now); return s === 'expired' || s === 'soon'; }).length; }
36
+
37
+ export function regStale(ing, nowMs = Date.now()) {
38
+ return (ing && ing.regulatory || []).some(r => {
39
+ if (!r || !r.status || !r.checkedDate) return false;
40
+ const t = Date.parse(r.checkedDate);
41
+ if (!isFinite(t)) return false;
42
+ return Math.max(0, Math.floor(((nowMs - t) / DAY) / 30.4375)) >= 12;
43
+ });
44
+ }
45
+
46
+ const _srcT = (v) => String(v == null ? '' : v).trim();
47
+ export function ingSources(ing) { return (ing && Array.isArray(ing.sources)) ? ing.sources : []; }
48
+ export function trialSources(ing) { return ingSources(ing).filter(s => s && s.status === 'trial').length; }
49
+ export function lotSource(lot, ing) {
50
+ if (!lot || !ing) return null;
51
+ if (lot.sourceId) { const s = ingSources(ing).find(x => x && x.id === lot.sourceId); if (s) return s; }
52
+ const name = _srcT(lot.supplier).toLowerCase();
53
+ if (!name) return null;
54
+ return ingSources(ing).find(s => _srcT(s.supplier).toLowerCase() === name || _srcT(s.manufacturer).toLowerCase() === name) || null;
55
+ }
package/calibration.js CHANGED
@@ -17,7 +17,13 @@ function ctx() {
17
17
  vm.createContext(sandbox);
18
18
  vm.runInContext(src + `
19
19
  ;function __calStatus(json, today) { return JSON.stringify(eqCalStatus(JSON.parse(json), today)); }
20
- ;function __calHistory(json) { return JSON.stringify(eqCalHistory(JSON.parse(json))); }`, sandbox, { timeout: 1000 });
20
+ ;function __calHistory(json) { return JSON.stringify(eqCalHistory(JSON.parse(json))); }
21
+ ;function __doubt(json, today) {
22
+ const p = JSON.parse(json), insOf = (m) => ({ name: m.instrument || '', equipmentId: m.equipmentId || '' });
23
+ const idx = eqCalDoubtIndex(p.equipment, p.tests, insOf, today), out = {};
24
+ p.tests.forEach(t => t.measurements.forEach((m, i) => { const d = eqCalReadingDoubt(m, t, idx, insOf); if (d) { out[t.id] = out[t.id] || {}; out[t.id][i] = d.why; } }));
25
+ return JSON.stringify(out);
26
+ }`, sandbox, { timeout: 1000 });
21
27
  _ctx = sandbox;
22
28
  return _ctx;
23
29
  }
@@ -28,3 +34,22 @@ const _slim = (e) => JSON.stringify({ status: e.status || '', calIntervalMonths:
28
34
  export function calibrationStatus(e, today) { return JSON.parse(ctx().__calStatus(_slim(e), today || _today())); }
29
35
  // Newest first.
30
36
  export function calibrationHistory(e) { return JSON.parse(ctx().__calHistory(_slim(e))); }
37
+
38
+ // Readings in doubt, the app's own rule (eqCalDoubtIndex / eqCalReadingDoubt in the vendored file): a reading taken on an
39
+ // instrument after its last good calibration and up to a failed or out-of-tolerance one, or saved while the instrument
40
+ // was Out of service. resolveIns(m, t) gives { instrument, equipmentId } (analytics.js _resolveInstrument).
41
+ // Returns { [testId]: { [measurementIndex]: why } }. Memoized per loaded store for a few seconds.
42
+ let _doubtMemo = null;
43
+ export function readingDoubts(db, resolveIns, today) {
44
+ if (!db) return {};
45
+ const now = Date.now();
46
+ if (_doubtMemo && _doubtMemo.db === db && now - _doubtMemo.at < 5000) return _doubtMemo.out;
47
+ const equipment = (db.equipment || []).filter(Boolean).map(e => ({ id: e.id, uid: e.uid || '', name: e.name || '', status: e.status || '',
48
+ _trashed: !!e._trashed, calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [] }));
49
+ const tests = (db.testResults || []).filter(t => t && t.id).map(t => ({ id: t.id, testDate: t.testDate || '',
50
+ measurements: (t.measurements || []).map(m => { const r = resolveIns(m, t, db) || {}; return { instrument: r.instrument || '', equipmentId: r.equipmentId || '', ...(m && m.instrumentOos ? { instrumentOos: m.instrumentOos } : {}) }; }) }));
51
+ let out = {};
52
+ try { out = JSON.parse(ctx().__doubt(JSON.stringify({ equipment, tests }), today || _today())); } catch (_) { out = {}; }
53
+ _doubtMemo = { db, at: now, out };
54
+ return out;
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.96",
3
+ "version": "0.6.98",
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",
@@ -14,6 +14,7 @@
14
14
  "data.js",
15
15
  "cloud.js",
16
16
  "calibration.js",
17
+ "attention.js",
17
18
  "peptide.js",
18
19
  "theoretical.js",
19
20
  "tools/",
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.96",
5
+ "version": "0.6.98",
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.96",
11
+ "version": "0.6.98",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -11,6 +11,8 @@
11
11
  // ============================================================
12
12
 
13
13
  import { getStore, resolveById, flattenComposition, localDay, localToday } from '../data.js';
14
+ import { readingDoubts } from '../calibration.js';
15
+ import { reviewState } from '../attention.js';
14
16
 
15
17
  // Which instrument produced a measurement. Mirrors the app's _trMeasInstrument:
16
18
  // a measurement's raw `instrument` is usually EMPTY because blank means inherit,
@@ -139,7 +141,7 @@ function _trimMeasurement(m, t, db) {
139
141
  const list_test_results = {
140
142
  definition: {
141
143
  name: 'list_test_results',
142
- description: 'List test result reports, optionally filtered by sample, parameter, measured-value range, grade, text value, run condition, date range, or lab. Combine parameter + value_min/value_max to find reports whose measurement is in range (the "find by results" query, e.g. parameter="Viscosity", value_min=800, value_max=3000). The number a range filter reads: a scalar as recorded, a curve at its final point, a distribution at the statistic its spec names (D90) or else D50; a ranked scale or text result has no number — use min_grade / max_grade (positions on the reading\'s own scale, e.g. parameter="Pencil hardness", min_grade="HB") or value_equals (a text result, case-insensitive). condition narrows to readings under a run condition (substring of e.g. "Storage 40 °C"; "none" = readings with no condition). Returns metadata (incl. the run-level instrument and controlSample flag) + parameters tested; use get_test_result for per-measurement values and their resolved instruments.',
144
+ description: 'List test result reports, optionally filtered by sample, parameter, measured-value range, grade, text value, run condition, date range, or lab. Combine parameter + value_min/value_max to find reports whose measurement is in range (the "find by results" query, e.g. parameter="Viscosity", value_min=800, value_max=3000). The number a range filter reads: a scalar as recorded, a curve at its final point, a distribution at the statistic its spec names (D90) or else D50; a ranked scale or text result has no number — use min_grade / max_grade (positions on the reading\'s own scale, e.g. parameter="Pencil hardness", min_grade="HB") or value_equals (a text result, case-insensitive). condition narrows to readings under a run condition (substring of e.g. "Storage 40 °C"; "none" = readings with no condition). Returns metadata (incl. the run-level instrument and controlSample flag) + parameters tested, and readingsInDoubt (count) when some readings are in doubt; use get_test_result for per-measurement values, their resolved instruments and inDoubt reasons.',
143
145
  inputSchema: {
144
146
  type: 'object',
145
147
  properties: {
@@ -154,6 +156,8 @@ const list_test_results = {
154
156
  since_date: { type: 'string', description: 'ISO date — only reports on/after this date.' },
155
157
  until_date: { type: 'string', description: 'ISO date — only reports on/before this date.' },
156
158
  lab: { type: 'string', description: 'Filter by lab name (case-insensitive substring).' },
159
+ in_doubt: { type: 'boolean', description: 'true = only reports with a reading in doubt (its instrument failed or was found out of tolerance at a calibration after its last good one, in that window, or was Out of service when the report was saved): the app\'s amber "In doubt". get_test_result gives each reading\'s reason.' },
160
+ review: { type: 'string', enum: ['none', 'sent', 'approved', 'returned'], description: 'Review state (FormLab Team): sent = waiting for a reviewer, returned = sent back with a note, approved, none.' },
157
161
  limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
158
162
  },
159
163
  },
@@ -174,6 +178,8 @@ const list_test_results = {
174
178
  if (args.since_date && (t.testDate || '') < args.since_date) return false;
175
179
  if (args.until_date && (t.testDate || '') > args.until_date) return false;
176
180
  if (args.lab && !norm(t.lab).includes(norm(args.lab))) return false;
181
+ if (args.review && reviewState(t) !== args.review) return false;
182
+ if (args.in_doubt === true && !readingDoubts(db, _resolveInstrument)[t.id]) return false;
177
183
  const hasRange = args.value_min != null || args.value_max != null;
178
184
  const hasGrade = !!(args.min_grade || args.max_grade);
179
185
  if (args.parameter || hasRange || hasGrade || args.value_equals || args.condition) {
@@ -210,7 +216,7 @@ const list_test_results = {
210
216
  return {
211
217
  totalMatching: filtered.length,
212
218
  returned: Math.min(filtered.length, limit),
213
- testResults: filtered.slice(0, limit).map(t => _trimTest(t, indexes.samplesById)),
219
+ testResults: filtered.slice(0, limit).map(t => { const dz = readingDoubts(getStore().db, _resolveInstrument)[t.id]; const n = dz ? Object.keys(dz).length : 0; return { ..._trimTest(t, indexes.samplesById), review: reviewState(t), ...(n ? { readingsInDoubt: n } : {}) }; }),
214
220
  };
215
221
  },
216
222
  };
@@ -218,7 +224,7 @@ const list_test_results = {
218
224
  const get_test_result = {
219
225
  definition: {
220
226
  name: 'get_test_result',
221
- description: 'Get full details for a single test result report: every measurement\'s value, unit, type, acceptance criteria, captured run CONDITIONS (e.g. {Storage:"40 °C / 75% RH"} — the storage/temp/RPM the reading was measured under, so it is self-describing and comparable across runs; present only when captured), and the INSTRUMENT that produced it. instrument is RESOLVED (measurement override → the parameter\'s Test Method equipment → the report default) with instrumentSource telling you which — treat source "run" as an inherited assumption, not evidence. For complex measurements a `representative` value is included (time_series → final point, distribution → D50); a time_series also carries `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (true when a timestamp has repeat readings — POINT replicates, averaged per t). The report-level `seriesReplicates` lists parameters measured 2+ times as SEPARATE rows (SERIES replicates). These two notions are different: point replicates are within one run, series replicates are repeated runs. Accepts internal id or UID.',
227
+ description: 'Get full details for a single test result report: every measurement\'s value, unit, type, acceptance criteria, captured run CONDITIONS (e.g. {Storage:"40 °C / 75% RH"} — the storage/temp/RPM the reading was measured under, so it is self-describing and comparable across runs; present only when captured), and the INSTRUMENT that produced it. instrument is RESOLVED (measurement override → the parameter\'s Test Method equipment → the report default) with instrumentSource telling you which — treat source "run" as an inherited assumption, not evidence. For complex measurements a `representative` value is included (time_series → final point, distribution → D50); a time_series also carries `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (true when a timestamp has repeat readings — POINT replicates, averaged per t). The report-level `seriesReplicates` lists parameters measured 2+ times as SEPARATE rows (SERIES replicates). These two notions are different: point replicates are within one run, series replicates are repeated runs. A measurement carries `inDoubt` (the reason) when its instrument failed (or was found out of tolerance at) a calibration after its last good one and the reading falls in that window, or the instrument was Out of service when the report was saved; the value and passFail are unchanged, but say so and recommend a retest before relying on it. Accepts internal id or UID.',
222
228
  inputSchema: {
223
229
  type: 'object',
224
230
  properties: {
@@ -250,7 +256,9 @@ const get_test_result = {
250
256
  // Parameters measured 2+ times as separate rows (series replicates). Empty
251
257
  // when none. Point replicates live on each measurement (`pointReplicates`).
252
258
  seriesReplicates,
253
- measurements: (t.measurements || []).map(m => _trimMeasurement(m, t, getStore().db)),
259
+ // inDoubt (the app's amber "In doubt"): why this reading is suspect: its instrument failed calibration in its
260
+ // window, or was Out of service when the report was saved. Value and passFail are unchanged.
261
+ measurements: (t.measurements || []).map((m, i) => { const dz = readingDoubts(getStore().db, _resolveInstrument)[t.id]; return { ..._trimMeasurement(m, t, getStore().db), ...(dz && dz[i] ? { inDoubt: dz[i] } : {}) }; }),
254
262
  };
255
263
  },
256
264
  };
@@ -6,6 +6,7 @@
6
6
  // - compare_formulations: pairwise composition diff
7
7
  // ============================================================
8
8
 
9
+ import { reviewState } from '../attention.js';
9
10
  import { getStore, resolveById, flattenComposition } from '../data.js';
10
11
  import { theoreticalParams, nutritionLabel, fragranceCompliance } from '../theoretical.js';
11
12
 
@@ -69,6 +70,7 @@ const list_formulations = {
69
70
  family: { type: 'string', description: 'Filter by formula family (e.g. "Acrylic Coating", "Skin Serum"). Case-insensitive substring.' },
70
71
  tag: { type: 'string', description: 'Filter to formulas containing this tag.' },
71
72
  name_contains: { type: 'string', description: 'Case-insensitive substring match on formula name.' },
73
+ review: { type: 'string', enum: ['none', 'sent', 'approved', 'returned'], description: 'Review state (FormLab Team): sent = waiting for a reviewer, returned = sent back to its maker with a note, approved, none = never sent (or changed since). Needs Attention "waiting for review" / "returned".' },
72
74
  sort: { type: 'string', enum: ['batches', 'samples', 'test_reports', 'name', 'updated'], description: 'Order before the limit: batches / samples / test_reports = most first; name = A–Z; updated = most recently updated first. Default: database order.' },
73
75
  limit: { type: 'number', description: 'Max rows to return (default 50, max 500).' },
74
76
  },
@@ -89,6 +91,7 @@ const list_formulations = {
89
91
  if (args.family && !norm(f.family).includes(norm(args.family))) return false;
90
92
  if (args.tag && !(f.tags || []).some(t => norm(t) === norm(args.tag))) return false;
91
93
  if (args.name_contains && !norm(f.name).includes(norm(args.name_contains))) return false;
94
+ if (args.review && reviewState(f) !== args.review) return false;
92
95
  return true;
93
96
  });
94
97
  if (args.sort && Object.hasOwn(_SORTS, args.sort)) {
@@ -107,7 +110,7 @@ const list_formulations = {
107
110
  totalMatching: filtered.length,
108
111
  returned: Math.min(filtered.length, limit),
109
112
  ...(args.sort ? { sortedBy: args.sort } : {}),
110
- formulations: filtered.slice(0, limit).map(_trimFormulation),
113
+ formulations: filtered.slice(0, limit).map(f => ({ ..._trimFormulation(f), review: reviewState(f) })),
111
114
  };
112
115
  },
113
116
  };
@@ -4,6 +4,7 @@
4
4
  // - get_ingredient: full record incl. supplier, density, stock, cost
5
5
  // ============================================================
6
6
 
7
+ import { docsExpiring, regStale, trialSources, lotSource } from '../attention.js';
7
8
  import { getStore, resolveById } from '../data.js';
8
9
  import { ingredientSmiles } from '../peptide.js';
9
10
  import { reactiveGroups } from '../theoretical.js';
@@ -134,6 +135,9 @@ const list_ingredients = {
134
135
  sequence_contains: { type: 'string', description: 'Case-insensitive substring match on peptide / oligo sequence (e.g. "KTTKS" matches Matrixyl).' },
135
136
  taxon_contains: { type: 'string', description: 'Case-insensitive substring match on botanical scientific name (e.g. "Centella").' },
136
137
  inchikey: { type: 'string', description: 'Exact match on the InChIKey identity hash. The first 14 characters are the connectivity hash; pass either the full 27-char key or just the first 14 to dedup-search across tautomers/salts.' },
138
+ docs_expiring: { type: 'boolean', description: 'true = only ingredients with a document (SDS, CoA, TDS…) expired or expiring within 30 days: the app\'s Needs Attention "documents expiring".' },
139
+ reg_stale: { type: 'boolean', description: 'true = only ingredients with a regulatory status last checked 12+ months ago: Needs Attention "regulatory re-check overdue".' },
140
+ trial_sources: { type: 'boolean', description: 'true = only ingredients with an approved-source entry still on trial: Needs Attention "trial source awaiting qualification".' },
137
141
  limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
138
142
  },
139
143
  },
@@ -161,12 +165,15 @@ const list_ingredients = {
161
165
  if (!have) return false;
162
166
  if (want.length === 14 ? !have.startsWith(want) : have !== want) return false;
163
167
  }
168
+ if (args.docs_expiring === true && !docsExpiring(i)) return false;
169
+ if (args.reg_stale === true && !regStale(i)) return false;
170
+ if (args.trial_sources === true && !trialSources(i)) return false;
164
171
  return true;
165
172
  });
166
173
  return {
167
174
  totalMatching: filtered.length,
168
175
  returned: Math.min(filtered.length, limit),
169
- ingredients: filtered.slice(0, limit).map(_trimIngredient),
176
+ ingredients: filtered.slice(0, limit).map(i => ({ ..._trimIngredient(i), ...(docsExpiring(i) ? { docsExpiring: docsExpiring(i) } : {}), ...(regStale(i) ? { regStale: true } : {}), ...(trialSources(i) ? { trialSources: trialSources(i) } : {}) })),
170
177
  };
171
178
  },
172
179
  };
@@ -360,6 +367,7 @@ const list_lots = {
360
367
  expiring_within_days: { type: 'number', description: 'Only lots whose expiryDate is within this many days from now (negative days = already expired are always included).' },
361
368
  status: { type: 'string', description: 'Filter by lot status: "active", "hold", "quarantine", or "rejected". Held/quarantined/rejected lots are blocked from auto-consumption (use "hold" to find lots put on hold for a QC / recall).' },
362
369
  missing_coa: { type: 'boolean', description: 'true = only lots still in stock (not rejected) that have no Certificate of Analysis — neither linked nor a CoA on the ingredient with the same lot number. Same list as the app\'s Documents → "Lots in stock without CoA".' },
370
+ disqualified_source: { type: 'boolean', description: 'true = only lots whose approved source is disqualified (by the lot\'s source, else its supplier / manufacturer name). With stock left this is the app\'s Needs Attention "lot on hand from a disqualified source".' },
363
371
  limit: { type: 'number', description: 'Max rows (default 200, max 1000).' },
364
372
  },
365
373
  },
@@ -381,6 +389,7 @@ const list_lots = {
381
389
  if (args.lot_number) { const w = String(args.lot_number).toLowerCase(); if (!String(l.lotNumber || '').toLowerCase().includes(w) && !String(l.uid || '').toLowerCase().includes(w)) return false; }
382
390
  if (args.missing_coa === true && !_lotCoaInfo(l, ingById.get(l.ingredientId)).coaMissing) return false;
383
391
  if (args.status && String(l.status || 'active').toLowerCase() !== String(args.status).toLowerCase()) return false;
392
+ if (args.disqualified_source === true) { const src = lotSource(l, ingById.get(l.ingredientId)); if (!(src && src.status === 'disqualified')) return false; }
384
393
  if (args.expiring_within_days != null) {
385
394
  if (!l.expiryDate) return false;
386
395
  const days = Math.floor((Date.parse(l.expiryDate) - nowMs) / 86400000);
package/tools/lab.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // - get_sample
7
7
  // ============================================================
8
8
 
9
+ import { sampleOverdue } from '../attention.js';
9
10
  import { getStore, resolveById } from '../data.js';
10
11
  import { theoreticalParams } from '../theoretical.js';
11
12
  import { _mcpSamplePulls } from './analytics.js';
@@ -464,6 +465,7 @@ const list_samples = {
464
465
  formulation_id: { type: 'string', description: 'Filter to samples of this formulation (id or UID).' },
465
466
  status: { type: 'string', description: 'Filter by status (case-insensitive substring).' },
466
467
  is_blend_only: { type: 'boolean', description: 'When true, return only samples with sourceBlend lineage.' },
468
+ overdue: { type: 'boolean', description: 'true = only samples In Testing with no test report (or, with none, no creation) in 30+ days: the app\'s Needs Attention "samples overdue for testing".' },
467
469
  limit: { type: 'number', description: 'Max rows (default 100, max 1000).' },
468
470
  },
469
471
  },
@@ -489,6 +491,7 @@ const list_samples = {
489
491
  if (formId && s.formulationId !== formId) return false;
490
492
  if (args.status && !norm(s.status).includes(norm(args.status))) return false;
491
493
  if (args.is_blend_only && !(Array.isArray(s.sourceBlend) && s.sourceBlend.length)) return false;
494
+ if (args.overdue === true && !sampleOverdue(s, db.testResults)) return false;
492
495
  return true;
493
496
  });
494
497
  return {
@@ -112,8 +112,15 @@ function eqCalStatusText(st) {
112
112
  if (st.state === 'soon') return d === 0 ? `Due today` : `Due in ${d} d · ${st.due}`;
113
113
  return st.due ? `OK · due ${st.due}` : 'OK';
114
114
  }
115
- function eqCalChipHtml(st) {
115
+ // short: the state alone, for the Calibration card, whose row goes on to say Next due (30 Nov: "OK · due 2027-11-30"
116
+ // sat right before "Next due 2027-11-30"). The Equipment list keeps the date in its chip.
117
+ function eqCalChipHtml(st, short) {
116
118
  if (!st || st.state === 'none') return '<span style="color:var(--dk-dim, #cbd5e1)">—</span>';
119
+ if (short) {
120
+ const d = st.daysToDue;
121
+ const t = { ok: 'OK', never: 'Never calibrated', failed: 'Failed calibration', overdue: `Overdue ${-d} d`, soon: d === 0 ? 'Due today' : `Due in ${d} d` }[st.state] || eqCalStatusText(st);
122
+ return `<span class="badge eq-cal-chip" style="${_EQ_CAL_TONE[st.state] || ''};font-size:11px">${esc(t)}</span>`;
123
+ }
117
124
  return `<span class="badge eq-cal-chip" style="${_EQ_CAL_TONE[st.state] || ''};font-size:11px" title="${esc(st.last ? `Last calibrated ${st.last}${st.lastResult ? ' (' + (_EQ_CAL_RESULT_LABEL[st.lastResult] || st.lastResult) + ')' : ''}` : 'No calibration logged yet')}">${esc(eqCalStatusText(st))}</span>`;
118
125
  }
119
126
  // Sort key for the list column: most urgent first when ascending.
@@ -127,12 +134,18 @@ function eqCalSortKey(e) {
127
134
  // said which of its 8 reports came after its last pass). The latest entry must be a Fail or an Adjusted (out of
128
135
  // tolerance as found). Suspect = reports dated after the last good calibration before it: up to today for a Fail
129
136
  // (it may still be in use), up to the adjustment for Adjusted. `tests` = the reports that used this unit.
137
+ // A pass logged after the repair does not clear them (30 Nov, Jun: "Yes, keep it"; the banner vanished while the 28 Aug -
138
+ // 30 Nov readings were still in doubt): the bad entry may be the latest, or the one just before the repair's pass. The
139
+ // window for a Fail then ends at that pass. The next routine calibration after that (two entries on) closes it.
130
140
  function eqCalSuspect(e, tests, todayIso) {
131
- const hist = eqCalHistory(e), bad = hist[0];
141
+ const hist = eqCalHistory(e);
132
142
  const res = (c) => String((c && c.result) || '').trim().toLowerCase();
133
- if (!bad || !['fail', 'adjusted'].includes(res(bad))) return null;
134
- const good = hist.slice(1).find(c => ['pass', 'adjusted'].includes(res(c)));
135
- const since = (good && good.date) || '', until = res(bad) === 'adjusted' ? (bad.date || '') : (todayIso || _eqCalToday());
143
+ const i = hist.findIndex(c => ['fail', 'adjusted'].includes(res(c)));
144
+ if (i < 0 || i > 1) return null;
145
+ const bad = hist[i], fixed = i === 1 ? hist[0] : null;
146
+ if (fixed && !['pass', 'adjusted'].includes(res(fixed))) return null;
147
+ const good = hist.slice(i + 1).find(c => ['pass', 'adjusted'].includes(res(c)));
148
+ const since = (good && good.date) || '', until = res(bad) === 'adjusted' ? (bad.date || '') : ((fixed && fixed.date) || todayIso || _eqCalToday());
136
149
  const day = (t) => String((t && t.testDate) || '').split('T')[0];
137
150
  const hit = (tests || []).filter(t => { const d = day(t); return d && (!since || d > since) && (!until || d <= until); })
138
151
  .sort((a, b) => day(a).localeCompare(day(b)));
@@ -142,7 +155,47 @@ function eqCalSuspect(e, tests, todayIso) {
142
155
  const b = sm && sm.batchId ? (db.batches || []).find(x => x && x.id === sm.batchId && !x._trashed) : null;
143
156
  if (b && !batches.includes(b)) batches.push(b);
144
157
  });
145
- return { kind: res(bad), at: bad.date || '', since, until, tests: hit, batches };
158
+ return { kind: res(bad), at: bad.date || '', since, until, fixedAt: fixed ? (fixed.date || '') : '', tests: hit, batches };
159
+ }
160
+
161
+ // ---- Readings in doubt (Jun, 30 Nov: "Flag doubtful readings"; shared with the MCP server) ----
162
+ // A reading is in doubt when it was saved while its instrument was Out of service (m.instrumentOos, stamped by the app's
163
+ // test save) or it falls in a failed / out-of-tolerance calibration's window (eqCalSuspect). insOf(m, t) resolves a
164
+ // reading's instrument to { name, equipmentId } (the app's _trMeasInstrument; the MCP server passes it resolved).
165
+ // eqCalDoubtIndex: Map testId → [{ eqId, lname, why }]; eqCalReadingDoubt: { why } or null.
166
+ function eqCalDoubtIndex(equipment, tests, insOf, todayIso) {
167
+ const map = new Map();
168
+ const res = (c) => String((c && c.result) || '').trim().toLowerCase();
169
+ (equipment || []).forEach(e => {
170
+ if (!e || e._trashed) return;
171
+ if (!eqCalHistory(e).slice(0, 2).some(c => res(c) === 'fail' || res(c) === 'adjusted')) return; // nothing to doubt
172
+ const lname = String(e.name || '').trim().toLowerCase();
173
+ const match = (m, t) => { const r = (insOf && insOf(m, t)) || {}; return r.equipmentId ? r.equipmentId === e.id : (!!lname && String(r.name || '').trim().toLowerCase() === lname); };
174
+ const used = (tests || []).filter(t => t && (t.measurements || []).some(m => match(m, t)));
175
+ const sus = eqCalSuspect(e, used, todayIso);
176
+ if (!sus || !sus.tests.length) return;
177
+ const name = e.name || e.uid || 'its instrument';
178
+ const from = sus.since ? `after its last good calibration (${sus.since})` : 'before any good calibration on record';
179
+ const why = sus.kind === 'adjusted' ? `Taken on ${name} ${from}; it was found out of tolerance on ${sus.at}.`
180
+ : sus.fixedAt ? `Taken on ${name} ${from} and before the repair passed on ${sus.fixedAt}; it failed calibration on ${sus.at}.`
181
+ : `Taken on ${name} ${from}; it failed calibration on ${sus.at} and has not passed since.`;
182
+ // short: the same in a few words, for compact uses (the AI context).
183
+ const short = `${name} ${sus.kind === 'adjusted' ? 'out of tolerance' : 'failed calibration'} ${sus.at}`;
184
+ const d = { eqId: e.id, lname, why, short };
185
+ sus.tests.forEach(t => { if (!map.has(t.id)) map.set(t.id, []); map.get(t.id).push(d); });
186
+ });
187
+ return map;
188
+ }
189
+ function eqCalReadingDoubt(m, t, index, insOf) {
190
+ if (!m) return null;
191
+ if (m.instrumentOos) return { why: `Measured while ${m.instrumentOos.name || 'its instrument'} was Out of service${m.instrumentOos.at ? ' (' + m.instrumentOos.at + ')' : ''}.`,
192
+ short: `${m.instrumentOos.name || 'instrument'} Out of service${m.instrumentOos.at ? ' ' + m.instrumentOos.at : ''}` };
193
+ const list = t && index ? index.get(t.id) : null;
194
+ if (!list) return null;
195
+ const r = (insOf && insOf(m, t)) || {};
196
+ const nm = String(r.name || '').trim().toLowerCase();
197
+ const hit = list.find(d => r.equipmentId ? r.equipmentId === d.eqId : (!!nm && nm === d.lname));
198
+ return hit ? { why: hit.why, short: hit.short } : null;
146
199
  }
147
200
 
148
201
  // ---- The Calibration card on the equipment page ----
@@ -169,10 +222,9 @@ function eqCalCardHtml(e) {
169
222
  const summary = st.state === 'none'
170
223
  ? `<div style="color:var(--text-muted);font-size:13px">Not tracked yet. Set how often it is calibrated, or log its last calibration.</div>`
171
224
  : `<div style="display:flex;flex-wrap:wrap;gap:10px 22px;align-items:center;font-size:13px">
172
- ${eqCalChipHtml(st)}
225
+ ${eqCalChipHtml(st, true)}
173
226
  <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>
174
227
  <span><span style="color:var(--text-muted)">Next due</span> <strong>${esc(st.due || '—')}</strong></span>
175
- <span><span style="color:var(--text-muted)">Interval</span> <strong>${interval ? interval + ' month' + (interval === 1 ? '' : 's') : '—'}</strong></span>
176
228
  </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>` : ''}${
177
229
  // Dogfooding, 22 Nov (pH meter back in service): the card read "OK · due 2027-11-22" under an Out of service
178
230
  // badge and said nothing, where a failed calibration says to take the unit out. The way back is said too.
@@ -180,16 +232,26 @@ function eqCalCardHtml(e) {
180
232
  const sus = typeof _eqUsageTests === 'function' ? eqCalSuspect(e, _eqUsageTests(e)) : null;
181
233
  const susHtml = sus && sus.tests.length ? (() => {
182
234
  const uids = sus.tests.map(t => t.uid).filter(Boolean);
183
- const bl = sus.batches.slice(0, 8).map(b => `<a style="cursor:pointer;color:inherit;text-decoration:underline" onclick="navigate('batch-detail','${_eqCalJs(b.id)}')">${esc(b.uid || '')}</a>`).join(', ') + (sus.batches.length > 8 ? ` +${sus.batches.length - 8}` : '');
235
+ // Counts, not a run of eight batch links and "+79" (30 Nov layout check): the Equipment report and Test Reports list them.
184
236
  const when = sus.since ? `since its last good calibration (${esc(sus.since)})` : 'before any good calibration on record';
185
- const head = sus.kind === 'adjusted' ? `Found out of tolerance on ${esc(sus.at)}: <strong>${sus.tests.length} test report${sus.tests.length === 1 ? '' : 's'}</strong> used it ${when}.` : `<strong>${sus.tests.length} test report${sus.tests.length === 1 ? '' : 's'}</strong> used it ${when}.`;
186
- return `<div class="eq-cal-suspect" style="margin-top:10px;padding:8px 10px;border-radius:8px;font-size:12.5px;background:var(--dk-amber-bg2, #fef3c7);color:var(--dk-amber-fg, #92400e)">${head}${sus.batches.length ? ` Batches: ${bl}.` : ''} Check whether to retest. <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline" onclick="openRecordsInList('test','${_eqCalJs(uids.join(','))}')">Open ${uids.length === 1 ? 'it' : 'them'} in Test Reports</a></div>`;
237
+ const n = `<strong>${sus.tests.length} test report${sus.tests.length === 1 ? '' : 's'}</strong>${sus.batches.length ? ` and <strong>${sus.batches.length} batch${sus.batches.length === 1 ? '' : 'es'}</strong>` : ''}`;
238
+ const head = sus.kind === 'adjusted' ? `Found out of tolerance on ${esc(sus.at)}: ${n} used it ${when}.`
239
+ : sus.fixedAt ? `Failed on ${esc(sus.at)}, passed again on ${esc(sus.fixedAt)}: ${n} used it ${when} until then.`
240
+ : `${n} used it ${when}.`;
241
+ return `<div class="eq-cal-suspect" style="margin-top:10px;padding:8px 10px;border-radius:8px;font-size:12.5px;background:var(--dk-amber-bg2, #fef3c7);color:var(--dk-amber-fg, #92400e)">${head} Check whether to retest. <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="openRecordsInList('test','${_eqCalJs(uids.join(','))}')">Open ${uids.length === 1 ? 'it' : 'them'} in Test Reports</a>${(() => { const open = sus.batches.filter(b => !(b.fgHold && b.fgHold.at && !b.fgHold.releasedAt) && !['Planned', 'Cancelled', 'Failed'].includes(b.status)).length;
242
+ // One step to hold what these readings went into (30 Nov, Jun: "Yes, add it"; 81 batches had to be held one by one).
243
+ // A link like "Open them in Test Reports" beside it (Jun: the button "looks ugly").
244
+ // How many already are, once some are (dogfooding 30 Nov: after the hold the link just went away).
245
+ const onHold = sus.batches.filter(b => b.fgHold && b.fgHold.at && !b.fgHold.releasedAt).length;
246
+ const heldTxt = onHold ? ` · <span style="white-space:nowrap">${onHold} on hold</span>` : '';
247
+ return (open && typeof flEqHoldSuspectUI === 'function' ? ` · <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="flEqHoldSuspectUI('${_eqCalJs(e.id)}')">Put ${open} batch${open === 1 ? '' : 'es'} on hold</a>` : '') + heldTxt; })()}</div>`;
187
248
  })() : '';
249
+ // Dates never wrap ("2026-11-/30" in a narrow window, 30 Nov Definition tab check).
188
250
  const rows = hist.map(c => `<tr>
189
- <td style="font-variant-numeric:tabular-nums">${esc(c.date || '—')}</td>
251
+ <td style="font-variant-numeric:tabular-nums;white-space:nowrap">${esc(c.date || '—')}</td>
190
252
  <td>${esc(c.by || '—')}</td>
191
253
  <td>${c.result ? `<span class="badge" style="${_EQ_CAL_TONE[c.result === 'fail' ? 'failed' : c.result === 'adjusted' ? 'soon' : 'ok']};font-size:11px">${esc(_EQ_CAL_RESULT_LABEL[c.result] || c.result)}</span>` : '—'}</td>
192
- <td style="font-variant-numeric:tabular-nums">${esc((String(c.result || '').toLowerCase() === 'fail' ? '' : c.nextDue) || '—')}</td>
254
+ <td style="font-variant-numeric:tabular-nums;white-space:nowrap">${esc((String(c.result || '').toLowerCase() === 'fail' ? '' : c.nextDue) || '—')}</td>
193
255
  <td>${c.certificateId && certName(c.certificateId) ? `<a style="color:var(--primary);cursor:pointer" onclick="attachOpenInTab('${_eqCalJs(c.certificateId)}')">${esc(certName(c.certificateId))}</a>` : (c.certificateRef ? esc(c.certificateRef) : '<span style="color:var(--dk-dim, #cbd5e1)">—</span>')}</td>
194
256
  <td style="color:var(--text-muted);max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(c.notes || '')}">${esc(c.notes || '')}</td>
195
257
  <td style="text-align:right;white-space:nowrap">${on ? `<button class="btn btn-secondary btn-sm" onclick="openEqCalLogModal('${_eqCalJs(e.id)}','${_eqCalJs(c.id)}')" title="Edit this calibration">${typeof ICON !== 'undefined' && ICON.edit ? ICON.edit : 'Edit'}</button>` : ''}</td>
@@ -232,6 +294,13 @@ function _eqCalResultDue(sel, interval) {
232
294
  const d = document.getElementById('eq-cal-due'); if (!d || !sel) return;
233
295
  const fail = sel.value === 'fail';
234
296
  d.disabled = fail;
297
+ // The +6 mo / +1 yr / +2 yr shortcuts sit in the label, on the box's top-right corner like every other date field (30
298
+ // Nov, Jun: "+xx month should be on top of the date box like everywhere else"; the label line is the box's width in styles.css),
299
+ // and go with it when a Fail leaves nothing to set.
300
+ const q = document.getElementById('eq-cal-due-quick'); if (q) q.style.display = fail ? 'none' : '';
301
+ // The hint says why the box is empty (dogfooding 30 Nov: "No interval set: enter it here" stayed under a locked box).
302
+ const h = document.getElementById('eq-cal-due-hint');
303
+ if (h) { if (!h.dataset.base) h.dataset.base = h.textContent; h.textContent = fail ? 'None while it fails: log a passing calibration after the repair.' : h.dataset.base; }
235
304
  if (fail) { d.dataset.was = d.value; d.value = ''; d.placeholder = 'After it passes'; }
236
305
  else if (!d.value) d.value = d.dataset.was || _eqCalAddMonths((document.getElementById('eq-cal-date') || {}).value || _eqCalToday(), interval) || '';
237
306
  }
@@ -248,8 +317,6 @@ function openEqCalLogModal(eqId, calId) {
248
317
  }
249
318
  const interval = eqCalInterval(e);
250
319
  const date = c ? (c.date || '') : _eqCalToday();
251
- const files = Array.isArray(e.fileAttachments) ? e.fileAttachments : [];
252
- const certOpts = `<option value="">— None —</option>` + files.map(a => `<option value="${esc(a.id)}"${c && c.certificateId === a.id ? ' selected' : ''}>${esc(a.name || a.title || a.url || a.id)}</option>`).join('');
253
320
  const hint = (t) => `<div style="font-size:11.5px;color:var(--text-muted);margin-top:4px;line-height:1.4">${t}</div>`;
254
321
  const body = `<div class="form-grid">
255
322
  <div class="form-group"><label>Date calibrated *</label><input id="eq-cal-date" type="date" value="${esc(date)}" max="${_eqCalToday()}" onchange="_eqCalAutoDue(${interval})"></div>
@@ -257,14 +324,11 @@ function openEqCalLogModal(eqId, calId) {
257
324
  <div class="form-group span-2"><label>Result *</label>
258
325
  <select id="eq-cal-result" onchange="_eqCalResultDue(this, ${interval})">${EQ_CAL_RESULTS.map(r => `<option value="${r.value}"${(c ? c.result : 'pass') === r.value ? ' selected' : ''}>${esc(r.label)} — ${esc(r.hint)}</option>`).join('')}</select>
259
326
  </div>
260
- <div class="form-group"><label>Next due ${typeof flDateQuickHtml === 'function' ? flDateQuickHtml('eq-cal-due', { from: 'eq-cal-date', fromLabel: 'calibration date', add: [[6, 'm'], [1, 'y'], [2, 'y']] }) : ''}</label>
327
+ <div class="form-group"><label>Next due<span id="eq-cal-due-quick"${c && c.result === 'fail' ? ' style="display:none"' : ''}>${typeof flDateQuickHtml === 'function' ? flDateQuickHtml('eq-cal-due', { from: 'eq-cal-date', fromLabel: 'calibration date', add: [[6, 'm'], [1, 'y'], [2, 'y']] }) : ''}</span></label>
261
328
  <input id="eq-cal-due" type="date" value="${esc(c ? (c.nextDue || '') : _eqCalAddMonths(date, interval))}" data-auto="${c && c.nextDue ? '0' : '1'}" oninput="this.dataset.auto='0'"${c && c.result === 'fail' ? ' disabled placeholder="After it passes"' : ''}>
262
- ${hint(interval ? `From the interval (every ${interval} month${interval === 1 ? '' : 's'}); change it for this one if needed.` : 'No interval set: enter it here, or set one on the Calibration card.')}
263
- </div>
264
- <div class="form-group"><label>Certificate</label>
265
- ${files.length ? `<select id="eq-cal-cert">${certOpts}</select>` : `<input id="eq-cal-certref" value="${esc(c ? (c.certificateRef || '') : '')}" placeholder="Certificate no.">`}
266
- ${hint(files.length ? 'One of this instrument\'s files. Upload more on its Attachments card.' : 'Or upload the certificate on this instrument\'s Attachments card to pick it here.')}
329
+ <div id="eq-cal-due-hint" style="font-size:11.5px;color:var(--text-muted);margin-top:4px;line-height:1.4">${c && c.result === 'fail' ? 'None while it fails: log a passing calibration after the repair.' : interval ? `From the interval (every ${interval} month${interval === 1 ? '' : 's'}); change it for this one if needed.` : 'No interval set: enter it here, or set one on the Calibration card.'}</div>
267
330
  </div>
331
+ <div class="form-group" id="eq-cal-cert-wrap">${_eqCalCertFieldHtml(e, c)}</div>
268
332
  <div class="form-group span-2"><label>Notes</label><textarea id="eq-cal-notes" style="min-height:56px" placeholder="As-found / as-left readings, standards used, provider…">${esc(c ? (c.notes || '') : '')}</textarea></div>
269
333
  </div>`;
270
334
  showModal(c ? 'Edit calibration' : 'Log calibration', body, () => {
@@ -289,12 +353,17 @@ function openEqCalLogModal(eqId, calId) {
289
353
  const list = (cur.calibrations || []).filter(x => x && x.id !== rec.id);
290
354
  list.push(rec);
291
355
  const patch = { calibrations: list };
356
+ // A new Fail takes an In-service instrument out of service in the same save (dogfooding 30 Nov: the result reads
357
+ // "Fail — out of tolerance; take it out of service", yet Tara had to open the status dialog as a second step). A
358
+ // calibrator may set In service / Out of service (0186); Retired is left alone.
359
+ const outNow = !c && rec.result === 'fail' && (cur.status || 'In service') === 'In service';
360
+ if (outNow) patch.status = 'Out of service';
292
361
  updateEquipment(eqId, patch);
293
362
  if (typeof renderEquipmentDetail === 'function' && typeof currentView !== 'undefined' && currentView === 'equipment-detail') renderEquipmentDetail(eqId);
294
- toast(c ? 'Calibration updated.' : (rec.result === 'fail' ? 'Calibration logged as failed. Set the instrument Out of service until it passes.'
363
+ toast(c ? 'Calibration updated.' : (rec.result === 'fail' ? (outNow ? 'Calibration logged as failed. The instrument is now Out of service until it passes.' : 'Calibration logged as failed. Keep the instrument out of use until it passes.')
295
364
  : (cur.status === 'Out of service' ? 'Calibration logged. The instrument is still Out of service.' : 'Calibration logged.')));
296
365
  return true;
297
- }, true, null, c ? 'Save' : 'Log calibration');
366
+ }, false, null, c ? 'Save' : 'Log calibration'); // the standard width (30 Nov: "this modal view is too wide")
298
367
  if (c) {
299
368
  // Delete sits in the dialog's footer, left of the buttons.
300
369
  setTimeout(() => {
@@ -303,6 +372,42 @@ function openEqCalLogModal(eqId, calId) {
303
372
  }, 0);
304
373
  }
305
374
  }
375
+ // The Certificate field of Log calibration, with Upload on its label line (30 Nov, Jun: "should we add a button to
376
+ // upload certificate or failure report?" → "Yes, add it"). The file lands on the instrument's Attachments, as one
377
+ // uploaded there would, and is picked here. Adding a file here asks equipment.calibrate, as logging does (0266, Jun
378
+ // 30 Nov: a Technician attaches the certificate too; the server lets a calibrator add files, never change or remove one).
379
+ function _eqCalCertFieldHtml(e, c, pickId) {
380
+ const files = Array.isArray(e.fileAttachments) ? e.fileAttachments : [];
381
+ const sel = pickId || (c && c.certificateId) || '';
382
+ const hint = (t) => `<div style="font-size:11.5px;color:var(--text-muted);margin-top:4px;line-height:1.4">${t}</div>`;
383
+ const may = !(typeof flFileCapMissing === 'function' && flFileCapMissing('equipment', 'equipment.calibrate'));
384
+ // A quiet link on the label line, like the date shortcuts (30 Nov, Jun: the documents' button above the field "is
385
+ // ugly, maybe go back and make it subtle"; and no "…"). A span, not a button: a <label> adopts a button inside it.
386
+ const up = may && typeof attachAdd === 'function' ? `<span class="fl-dq"><span class="fl-dq-link" role="button" tabindex="0" onclick="_eqCalUploadCert('${_eqCalJs(e.id)}')" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();this.click();}">Upload</span></span>` : '';
387
+ const opts = `<option value="">— None —</option>` + files.map(a => `<option value="${esc(a.id)}"${sel === a.id ? ' selected' : ''}>${esc(a.name || a.title || a.url || a.id)}</option>`).join('');
388
+ return `<label>Certificate${up}</label>
389
+ ${files.length ? `<select id="eq-cal-cert">${opts}</select>` : `<input id="eq-cal-certref" value="${esc(c ? (c.certificateRef || '') : '')}" placeholder="Certificate no.">`}
390
+ ${hint(may ? 'Upload the certificate or the failure report: it is kept on this instrument\'s Attachments.' : 'A lab manager or a formulator can attach the certificate to this instrument; then pick it here.')}`;
391
+ }
392
+ function _eqCalUploadCert(eqId) {
393
+ const inp = document.createElement('input');
394
+ inp.type = 'file'; inp.accept = '.pdf,image/*,.doc,.docx,.xlsx,.csv,.txt';
395
+ inp.onchange = async () => {
396
+ const file = inp.files && inp.files[0]; if (!file) return;
397
+ const v = typeof attachValidateFile === 'function' ? attachValidateFile(file) : { ok: true };
398
+ if (!v.ok) { toast(v.reason); return; }
399
+ const wrap = document.getElementById('eq-cal-cert-wrap');
400
+ if (wrap) wrap.style.opacity = '.6';
401
+ try {
402
+ const id = await attachAdd('equipment', eqId, 'upload', { name: file.name, mime: file.type, size: file.size, blob: file, cap: 'equipment.calibrate' });
403
+ const e = (typeof getEquipment === 'function' ? getEquipment(eqId) : null) || (db.equipment || []).find(x => x.id === eqId);
404
+ if (wrap && e) wrap.innerHTML = _eqCalCertFieldHtml(e, null, id);
405
+ toast(`Attached "${file.name}" to this instrument.`);
406
+ } catch (err) { toast(err && err.message ? err.message : 'Could not attach the file.'); }
407
+ finally { if (wrap) wrap.style.opacity = ''; }
408
+ };
409
+ inp.click();
410
+ }
306
411
  // Keep "Next due" following the date while it hasn't been typed over.
307
412
  function _eqCalAutoDue(interval) {
308
413
  const due = document.getElementById('eq-cal-due'), d = document.getElementById('eq-cal-date');
@@ -1575,16 +1575,19 @@ function _tpFieldPaletteHtml(evalRows, params, currentParamId) {
1575
1575
  const numNote = `<span style="font-size:11px;color:var(--dk-amber-fg, #b45309)">No numeric fields on these ingredients yet — add values like density, or a custom field such as “solids”, on the Ingredients page to use them here.</span>`;
1576
1576
 
1577
1577
  return `
1578
+ <details class="tp-palette-fold" style="margin-top:6px">
1579
+ <summary style="cursor:pointer;font-size:12px;color:var(--primary);list-style:none;width:fit-content">Show fields</summary>
1578
1580
  <div style="margin-top:6px;padding:9px 11px;background:var(--dk-subtle, #f8fafc);border:1px solid var(--border);border-radius:6px">
1579
1581
  <div style="font-size:11.5px;color:var(--text-muted);margin-bottom:7px;line-height:1.55">
1580
- <strong style="color:var(--text)">Click to build.</strong> A formula runs across every ingredient row, so wrap fields in an aggregation like <code>SUM()</code> or <code>AVG()</code>. Try: click <code>AVG()</code>, then (cursor inside the brackets) click <code>ing.density</code>.
1582
+ Wrap fields in an aggregation: click <code>AVG()</code>, then <code>ing.density</code>.
1581
1583
  </div>
1582
1584
  ${group('Aggregations', aggs)}
1583
1585
  ${group('Row fields', rowChips)}
1584
1586
  ${group('Ingredient numbers', numChips || numNote)}
1585
1587
  ${group('Ingredient text', txtChips)}
1586
1588
  ${group('Other parameters', paramChips)}
1587
- </div>`;
1589
+ </div>
1590
+ </details>`;
1588
1591
  }
1589
1592
 
1590
1593
  function openTheoreticalParamModal(entityType, entityId, paramId) {
@@ -1614,7 +1617,7 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1614
1617
  <div class="form-group span-2">
1615
1618
  <label>Formula *</label>
1616
1619
  <textarea id="tp-formula" style="min-height:60px;font-family:ui-monospace,monospace;font-size:13px"
1617
- placeholder="AVG(ing.density) — or click the chips below to build one"
1620
+ placeholder="e.g. AVG(ing.density)"
1618
1621
  oninput="_tpRefreshPreview('${entityType}','${entityId}')">${esc(initialFormula)}</textarea>
1619
1622
  ${_tpFieldPaletteHtml(evalRows, params, p?.id)}
1620
1623
  </div>
@@ -1627,11 +1630,11 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1627
1630
  <input id="tp-unit" value="${esc(initialUnit)}" placeholder="%, mg KOH/g, g/L, kcal/100g, …" />
1628
1631
  </div>
1629
1632
  <div class="form-group">
1630
- <label>Spec min <span style="font-weight:400;color:var(--text-muted);text-transform:none;letter-spacing:0">(optional)</span></label>
1633
+ <label>Spec min</label>
1631
1634
  <input id="tp-spec-min" type="number" step="any" value="${esc(initialSpecMin)}" oninput="_tpRefreshPreview('${entityType}','${entityId}')" />
1632
1635
  </div>
1633
1636
  <div class="form-group">
1634
- <label>Spec max <span style="font-weight:400;color:var(--text-muted);text-transform:none;letter-spacing:0">(optional)</span></label>
1637
+ <label>Spec max</label>
1635
1638
  <input id="tp-spec-max" type="number" step="any" value="${esc(initialSpecMax)}" oninput="_tpRefreshPreview('${entityType}','${entityId}')" />
1636
1639
  </div>
1637
1640
  <div class="form-group span-2">
@@ -1641,7 +1644,7 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1641
1644
  <div class="form-group span-2">
1642
1645
  <label style="display:flex;align-items:flex-start;gap:8px;cursor:pointer;text-transform:none;letter-spacing:0;font-weight:500">
1643
1646
  <input id="tp-pinned" type="checkbox" ${initialPinned ? 'checked' : ''} style="width:auto;margin:0" />
1644
- Pin to summary<br><span style="font-weight:400;color:var(--text-muted)">Shows this value as a chip on the formula &amp; batch summary, not just the parameters tab</span>
1647
+ <span>Pin to summary<span style="display:block;font-weight:400;font-size:12px;color:var(--text-muted)">Shows this value as a chip on the formula and batch summary</span></span>
1645
1648
  </label>
1646
1649
  </div>
1647
1650
  </div>
@@ -1681,9 +1684,8 @@ function openTheoreticalParamModal(entityType, entityId, paramId) {
1681
1684
  else renderFormulationDetail(entityId);
1682
1685
  });
1683
1686
 
1684
- // A touch wider than the default modal — the formula, click-to-build palette
1685
- // and the result card breathe better with the extra room (chips wrap less).
1686
- document.querySelector('#modal-backdrop > .modal')?.classList.add('tp-modal-wide');
1687
+ // Standard 640 (Jun, 30 Nov: Add dialogs review): the chip palette folds
1688
+ // behind "Show fields", so the 780 "tp-modal-wide" is gone.
1687
1689
  // Fire an initial preview render
1688
1690
  setTimeout(() => _tpRefreshPreview(entityType, entityId), 0);
1689
1691
  }