formlab-mcp 0.6.98 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/calibration.js CHANGED
@@ -18,6 +18,7 @@ function ctx() {
18
18
  vm.runInContext(src + `
19
19
  ;function __calStatus(json, today) { return JSON.stringify(eqCalStatus(JSON.parse(json), today)); }
20
20
  ;function __calHistory(json) { return JSON.stringify(eqCalHistory(JSON.parse(json))); }
21
+ ;function __calWindows(json, today) { return JSON.stringify(eqCalWindows(JSON.parse(json), today)); }
21
22
  ;function __doubt(json, today) {
22
23
  const p = JSON.parse(json), insOf = (m) => ({ name: m.instrument || '', equipmentId: m.equipmentId || '' });
23
24
  const idx = eqCalDoubtIndex(p.equipment, p.tests, insOf, today), out = {};
@@ -28,7 +29,7 @@ function ctx() {
28
29
  return _ctx;
29
30
  }
30
31
  const _today = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
31
- const _slim = (e) => JSON.stringify({ status: e.status || '', calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [] });
32
+ const _slim = (e) => JSON.stringify({ status: e.status || '', calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [], calReviews: Array.isArray(e.calReviews) ? e.calReviews : [] });
32
33
 
33
34
  // { state, due, last, lastResult, interval, daysToDue, count } — state: ok | soon | overdue | failed | never | none
34
35
  export function calibrationStatus(e, today) { return JSON.parse(ctx().__calStatus(_slim(e), today || _today())); }
@@ -45,7 +46,7 @@ export function readingDoubts(db, resolveIns, today) {
45
46
  const now = Date.now();
46
47
  if (_doubtMemo && _doubtMemo.db === db && now - _doubtMemo.at < 5000) return _doubtMemo.out;
47
48
  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
+ _trashed: !!e._trashed, calIntervalMonths: e.calIntervalMonths || null, calibrations: Array.isArray(e.calibrations) ? e.calibrations : [], calReviews: Array.isArray(e.calReviews) ? e.calReviews : [] }));
49
50
  const tests = (db.testResults || []).filter(t => t && t.id).map(t => ({ id: t.id, testDate: t.testDate || '',
50
51
  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
52
  let out = {};
@@ -53,3 +54,7 @@ export function readingDoubts(db, resolveIns, today) {
53
54
  _doubtMemo = { db, at: now, out };
54
55
  return out;
55
56
  }
57
+
58
+ // A failed / out-of-tolerance calibration's window of doubt, newest first (the app's eqCalWindows): open until its
59
+ // review is closed with a reason; later calibrations never close it.
60
+ export function calibrationWindows(e, today) { return JSON.parse(ctx().__calWindows(_slim(e), today || _today())); }
package/index.js CHANGED
@@ -146,7 +146,14 @@ const PKG_VERSION = (() => {
146
146
 
147
147
  // 0.6.95: the lab's time zone, so a stored UTC time ("…Z") is told as the local day and time (an evening time west of
148
148
  // Greenwich is already tomorrow in UTC). Plain dates are calendar days as entered.
149
- const INSTRUCTIONS = `Times ending in "Z" (createdAt, updatedAt, holdAt, releasedAt, issuedAt, shipment dates…) are UTC. This lab's time zone is ${LOCAL_TZ}: when you give a date or time from one, convert it to ${LOCAL_TZ} first (late evening there can already be the next day in UTC). Plain dates with no time (testDate, preparedDate, expiryDate, best-by) are calendar days as entered: give them as they are. Day fields the server works out (asOf, a report's day when it has no test date, a supplier's lastReceived) are already ${LOCAL_TZ} days.`;
149
+ const INSTRUCTIONS = `Times ending in "Z" (createdAt, updatedAt, holdAt, releasedAt, issuedAt, shipment dates…) are UTC. This lab's time zone is ${LOCAL_TZ}: when you give a date or time from one, convert it to ${LOCAL_TZ} first (late evening there can already be the next day in UTC). Plain dates with no time (testDate, preparedDate, expiryDate, best-by) are calendar days as entered: give them as they are. Day fields the server works out (asOf, a report's day when it has no test date, a supplier's lastReceived) are already ${LOCAL_TZ} days.
150
+
151
+ FormLab's QC definitions (answer by these; never infer them):
152
+ - In doubt (a reading): its instrument failed or was found out of tolerance at a calibration, and the reading falls between the last good calibration before it and the repair's pass (or today while it still fails), or it was saved while the instrument was Out of service. Later calibrations do not clear it; a retest replaces the reading, or someone closes the instrument's review with a reason. The value and pass/fail stand. Tools: list_test_results in_doubt, get_test_result inDoubt, get_equipment doubtWindows.
153
+ - Retest: repeats only a report's out-of-spec and in-doubt readings, linked (retestOf); it replaces them in rollups and on the CoA.
154
+ - Same-day readings: one point per test date; a day's readings average only under one spec; when two panels judged the same parameter that day, the later report stands.
155
+ - Holds: a held batch cannot ship until released (the Dashboard counts held batches with stock left); a lot on hold has status "hold" (quarantine and rejected are separate statuses).
156
+ - Certificate of Analysis: latest result per parameter against its spec; required results come from the formula's releasePanel when set, else every panel used. Hard blocks: on hold, not made, no results. Out of spec ("Does not conform") and missing required results ("Not tested") can be issued with an override and a reason; a reading in doubt is only a warning.`;
150
157
  const server = new Server(
151
158
  { name: 'formlab-mcp', version: PKG_VERSION },
152
159
  { capabilities: { tools: {} }, instructions: INSTRUCTIONS }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.98",
3
+ "version": "0.7.0",
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.98",
5
+ "version": "0.7.0",
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.98",
11
+ "version": "0.7.0",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -224,7 +224,7 @@ const list_test_results = {
224
224
  const get_test_result = {
225
225
  definition: {
226
226
  name: 'get_test_result',
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.',
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 (to the repair, or today while it still fails), or the instrument was Out of service when the report was saved. Later calibrations never clear it; a retest replaces the reading, or a closed review (get_equipment doubtWindows) ends it. The value and passFail are unchanged, but say so and recommend a retest before relying on it. Accepts internal id or UID.',
228
228
  inputSchema: {
229
229
  type: 'object',
230
230
  properties: {
@@ -681,6 +681,17 @@ function _mcpCellValue(r) {
681
681
  return r.value;
682
682
  }
683
683
 
684
+ // The app's flSameDayOneSpec (js/utils.js): a day's readings average only when they share a spec; when two reports
685
+ // judged the parameter on different specs (different panels), the later report of that day stands.
686
+ function _mcpSameDayOneSpec(entries, specOf, testOf) {
687
+ if (!Array.isArray(entries) || entries.length < 2) return entries;
688
+ if (new Set(entries.map(testOf)).size < 2) return entries;
689
+ const sk = e => { try { return JSON.stringify(specOf(e) || null); } catch (_) { return 'null'; } };
690
+ if (new Set(entries.map(sk)).size < 2) return entries;
691
+ const when = e => { const t = testOf(e); return String((t && (t.createdAt || t.testDate)) || ''); };
692
+ const last = testOf(entries.slice().sort((a, b) => when(a).localeCompare(when(b)))[entries.length - 1]);
693
+ return entries.filter(e => testOf(e) === last);
694
+ }
684
695
  function _mcpFlattenReadings(tests, indexes, paramFilter) {
685
696
  const norm = (s) => String(s || '').toLowerCase();
686
697
  const groups = new Map(); const order = [];
@@ -1097,7 +1108,9 @@ function _mcpCoverageRows(flat, grain, indexes) {
1097
1108
  }
1098
1109
  for (const row of rows.values()) {
1099
1110
  row.cells = new Map();
1100
- for (const [param, { date, list }] of row.latest) {
1111
+ for (const [param, { date, list: _all }] of row.latest) {
1112
+ // Same-day readings under different specs: the day's later report stands (the app's flSameDayOneSpec, 30 Nov).
1113
+ const list = _mcpSameDayOneSpec(_all, x => (_resolveSpec(x.m, x.test && x.test.templateId, getStore().db) || {}).spec || null, x => x.test);
1101
1114
  const nums = list.map(x => x.numeric).filter(v => v != null && isFinite(v));
1102
1115
  const mean = nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : null;
1103
1116
  const pf = list.some(x => x.pf === 'fail') ? 'fail' : list.some(x => x.pf === 'pass') ? 'pass' : list[0].pf;
@@ -31,6 +31,8 @@ function _trimFormulation(f) {
31
31
  // Target shelf life (months): sets finished-goods expiry AND is what
32
32
  // get_stability judges the projected shelf life against.
33
33
  shelfLifeMonths: f.shelfLifeMonths ?? null,
34
+ // The panel a batch is released on: its CoA requires that panel's required results only (else every panel used).
35
+ releasePanel: f.releasePanelId ? (() => { const t = (getStore().db.templates || []).find(x => x && x.id === f.releasePanelId); return { id: f.releasePanelId, name: t ? (t.name || t.uid || '') : null }; })() : null,
34
36
  // Its own stability pull schedule (Stability → Time points → Pull schedule, or its Edit): long = below 35 °C,
35
37
  // accel = 35 °C and up; a number is months, "2w" two weeks; null = the standard schedule. get_stability's timePoints
36
38
  // follow it.
package/tools/library.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // ============================================================
13
13
 
14
14
  import { getStore, resolveById, localDay } from '../data.js';
15
- import { calibrationStatus, calibrationHistory } from '../calibration.js';
15
+ import { calibrationStatus, calibrationHistory, calibrationWindows } from '../calibration.js';
16
16
  import { _evalPassFail, _mcpRepNumber, _mcpMeasType, _resolveSpec, _mcpCondSig, _mcpCondLabel, _mcpCondTags, _mcpParamGroupsOf } from './analytics.js';
17
17
 
18
18
  // ── Usage roll-ups (mirror the Usage tabs on the Panel / Method / Equipment
@@ -181,7 +181,7 @@ const list_equipment = {
181
181
  const get_equipment = {
182
182
  definition: {
183
183
  name: 'get_equipment',
184
- description: 'Get one equipment record by UID (e.g. EQP-001) or id, including `usedIn` (everywhere its DEFINITION is referenced: test panels, step presets, test methods, formula steps, batches, plus testReports = reports with a measurement resolved to it), `usage` (those reports: totals, last used, distinct formulas/batches/samples, pass rate, top formulas) and `measured` (per parameter: readings and mean on this unit vs readings/mean on all OTHER instruments, with biasPct — the calibration question). Instrument resolution follows the app: named on the measurement → the Test Method\'s equipment → the report\'s run default. `calibration` (state ok | soon (≤30 days) | overdue | failed | never, nextDue, lastCalibrated, intervalMonths) and `calibrationHistory` (newest first: date, by, result pass | adjusted | fail, nextDue, certificate, notes) when the instrument is tracked.',
184
+ description: 'Get one equipment record by UID (e.g. EQP-001) or id, including `usedIn` (everywhere its DEFINITION is referenced: test panels, step presets, test methods, formula steps, batches, plus testReports = reports with a measurement resolved to it), `usage` (those reports: totals, last used, distinct formulas/batches/samples, pass rate, top formulas) and `measured` (per parameter: readings and mean on this unit vs readings/mean on all OTHER instruments, with biasPct — the calibration question). Instrument resolution follows the app: named on the measurement → the Test Method\'s equipment → the report\'s run default. `calibration` (state ok | soon (≤30 days) | overdue | failed | never, nextDue, lastCalibrated, intervalMonths) and `calibrationHistory` (newest first: date, by, result pass | adjusted | fail, nextDue, certificate, notes) when the instrument is tracked. `doubtWindows`: each failed (or out-of-tolerance) calibration, the window of readings it puts in doubt (since the last good calibration, until the repair or today), and reviewOpen (true = those readings are In doubt; closed = by, at, reason). Later calibrations never close a window; only a closed review or a retest does.',
185
185
  inputSchema: {
186
186
  type: 'object',
187
187
  properties: { id: { type: 'string', description: 'Equipment UID or internal id.' } },
@@ -225,7 +225,11 @@ const get_equipment = {
225
225
  const usedIn = _equipUsage(e, db);
226
226
  usedIn.testReports = tests.length;
227
227
  const calHistory = calibrationHistory(e).map(c => ({ date: c.date || null, by: c.by || '', result: c.result || '', nextDue: c.nextDue || null, ...(c.certificateRef ? { certificate: c.certificateRef } : {}), ...(c.certificateId ? { certificateFile: ((e.fileAttachments || []).find(a => a && a.id === c.certificateId) || {}).name || c.certificateId } : {}), ...(c.notes ? { notes: c.notes } : {}) }));
228
- return { ...(_trimEquipment(e)), ...(calHistory.length ? { calibrationHistory: calHistory } : {}), usedIn, usage: _usageRollup(db, tests, mine), measured };
228
+ // Windows of doubt (0.7.0): each failure / out-of-tolerance finding, the readings window, and whether its review is
229
+ // still open (readings in it are In doubt) or was closed (by whom, when, why).
230
+ const windows = calibrationWindows(e).map(w => ({ failedOn: w.at, kind: w.kind === 'adjusted' ? 'out_of_tolerance' : 'fail', since: w.since || null, until: w.until || null,
231
+ repairedOn: w.fixedAt || null, reviewOpen: !w.review, ...(w.review ? { reviewClosed: { by: w.review.by || '', at: w.review.at || null, reason: w.review.reason || '' } } : {}) }));
232
+ return { ...(_trimEquipment(e)), ...(calHistory.length ? { calibrationHistory: calHistory } : {}), ...(windows.length ? { doubtWindows: windows } : {}), usedIn, usage: _usageRollup(db, tests, mine), measured };
229
233
  },
230
234
  };
231
235
 
@@ -131,31 +131,54 @@ function eqCalSortKey(e) {
131
131
  }
132
132
 
133
133
  // Readings to doubt after a calibration found the unit out of tolerance (dogfooding 28 Nov: RV-1 failed and nothing
134
- // said which of its 8 reports came after its last pass). The latest entry must be a Fail or an Adjusted (out of
135
- // tolerance as found). Suspect = reports dated after the last good calibration before it: up to today for a Fail
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.
140
- function eqCalSuspect(e, tests, todayIso) {
134
+ // said which of its 8 reports came after its last pass). Every Fail or Adjusted (out of tolerance as found) entry opens
135
+ // a window: reports dated after the last good calibration before it, up to the failure's repair (the first good entry
136
+ // after it), or to today while it still fails; an Adjusted one ends at the adjustment. A window stays open until someone
137
+ // closes its review with a reason (e.calReviews, Jun 30 Nov: "Yes, do that"); later calibrations never close it (it
138
+ // used to close "two entries on", and two passes logged the same day cleared every doubt). Retested readings leave it
139
+ // on their own (the retest replaces them). `tests` = the reports that used this unit.
140
+ function eqCalReviews(e) { return (e && Array.isArray(e.calReviews)) ? e.calReviews.filter(r => r && r.calId) : []; }
141
+ // The review on a bad calibration entry, if one is closed (the latest word on it: closed, or reopened).
142
+ function eqCalReviewOf(e, calId) {
143
+ const rs = eqCalReviews(e).filter(r => r.calId === calId).sort((x, y) => String(x.at || '').localeCompare(String(y.at || '')));
144
+ const last = rs[rs.length - 1];
145
+ return last && !last.reopened ? last : null;
146
+ }
147
+ // Every window, newest first: { calId, kind, at, since, until, fixedAt, review }.
148
+ function eqCalWindows(e, todayIso) {
141
149
  const hist = eqCalHistory(e);
142
150
  const res = (c) => String((c && c.result) || '').trim().toLowerCase();
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());
151
+ const good = (c) => ['pass', 'adjusted'].includes(res(c));
152
+ const out = [];
153
+ hist.forEach((bad, i) => {
154
+ const kind = res(bad);
155
+ if (kind !== 'fail' && kind !== 'adjusted') return;
156
+ const before = hist.slice(i + 1).find(good);
157
+ let fixed = null; for (let j = i - 1; j >= 0; j--) { if (good(hist[j])) { fixed = hist[j]; break; } }
158
+ const until = kind === 'adjusted' ? (bad.date || '') : ((fixed && fixed.date) || todayIso || _eqCalToday());
159
+ out.push({ calId: bad.id || '', kind, at: bad.date || '', since: (before && before.date) || '', until, fixedAt: kind === 'fail' && fixed ? (fixed.date || '') : '', review: bad.id ? eqCalReviewOf(e, bad.id) : null });
160
+ });
161
+ return out;
162
+ }
163
+ function _eqCalWindowTests(w, tests) {
149
164
  const day = (t) => String((t && t.testDate) || '').split('T')[0];
150
- const hit = (tests || []).filter(t => { const d = day(t); return d && (!since || d > since) && (!until || d <= until); })
165
+ return (tests || []).filter(t => { const d = day(t); return d && (!w.since || d > w.since) && (!w.until || d <= w.until); })
151
166
  .sort((a, b) => day(a).localeCompare(day(b)));
167
+ }
168
+ // The latest window still open (its review not closed), with its reports and batches; null when none is open.
169
+ // { calId, kind, at, since, until, fixedAt, tests, batches, open (how many windows are open) }
170
+ function eqCalSuspect(e, tests, todayIso) {
171
+ const open = eqCalWindows(e, todayIso).filter(w => !w.review);
172
+ if (!open.length) return null;
173
+ const w = open[0];
174
+ const hit = _eqCalWindowTests(w, tests);
152
175
  const batches = [];
153
176
  hit.forEach(t => {
154
177
  const sm = (typeof db !== 'undefined' && db.samples || []).find(x => x && x.id === t.sampleId);
155
178
  const b = sm && sm.batchId ? (db.batches || []).find(x => x && x.id === sm.batchId && !x._trashed) : null;
156
179
  if (b && !batches.includes(b)) batches.push(b);
157
180
  });
158
- return { kind: res(bad), at: bad.date || '', since, until, fixedAt: fixed ? (fixed.date || '') : '', tests: hit, batches };
181
+ return { calId: w.calId, kind: w.kind, at: w.at, since: w.since, until: w.until, fixedAt: w.fixedAt, tests: hit, batches, open: open.length };
159
182
  }
160
183
 
161
184
  // ---- Readings in doubt (Jun, 30 Nov: "Flag doubtful readings"; shared with the MCP server) ----
@@ -165,24 +188,26 @@ function eqCalSuspect(e, tests, todayIso) {
165
188
  // eqCalDoubtIndex: Map testId → [{ eqId, lname, why }]; eqCalReadingDoubt: { why } or null.
166
189
  function eqCalDoubtIndex(equipment, tests, insOf, todayIso) {
167
190
  const map = new Map();
168
- const res = (c) => String((c && c.result) || '').trim().toLowerCase();
169
191
  (equipment || []).forEach(e => {
170
192
  if (!e || e._trashed) return;
171
- if (!eqCalHistory(e).slice(0, 2).some(c => res(c) === 'fail' || res(c) === 'adjusted')) return; // nothing to doubt
193
+ const open = eqCalWindows(e, todayIso).filter(w => !w.review);
194
+ if (!open.length) return; // nothing to doubt
172
195
  const lname = String(e.name || '').trim().toLowerCase();
173
196
  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
197
  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
198
  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); });
199
+ open.forEach(w => {
200
+ const hit = _eqCalWindowTests(w, used);
201
+ if (!hit.length) return;
202
+ const from = w.since ? `after its last good calibration (${w.since})` : 'before any good calibration on record';
203
+ const why = w.kind === 'adjusted' ? `Taken on ${name} ${from}; it was found out of tolerance on ${w.at}.`
204
+ : w.fixedAt ? `Taken on ${name} ${from} and before the repair passed on ${w.fixedAt}; it failed calibration on ${w.at}.`
205
+ : `Taken on ${name} ${from}; it failed calibration on ${w.at} and has not passed since.`;
206
+ // short: the same in a few words, for compact uses (the AI context).
207
+ const short = `${name} ${w.kind === 'adjusted' ? 'out of tolerance' : 'failed calibration'} ${w.at}`;
208
+ const d = { eqId: e.id, lname, why, short };
209
+ hit.forEach(t => { const l = map.get(t.id) || []; if (!l.some(x => x.eqId === d.eqId)) { l.push(d); map.set(t.id, l); } });
210
+ });
186
211
  });
187
212
  return map;
188
213
  }
@@ -244,8 +269,14 @@ function eqCalCardHtml(e) {
244
269
  // How many already are, once some are (dogfooding 30 Nov: after the hold the link just went away).
245
270
  const onHold = sus.batches.filter(b => b.fgHold && b.fgHold.at && !b.fgHold.releasedAt).length;
246
271
  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>`;
272
+ 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; })()}${
273
+ // Closing the review is a decision with a reason (Jun, 30 Nov): later calibrations no longer close it.
274
+ typeof flEqCloseReviewUI === 'function' && sus.calId ? ` · <a style="cursor:pointer;font-weight:600;color:inherit;text-decoration:underline;white-space:nowrap" onclick="flEqCloseReviewUI('${_eqCalJs(e.id)}','${_eqCalJs(sus.calId)}')">Close the review</a>` : ''}${
275
+ sus.open > 1 ? `<div style="margin-top:4px">${sus.open - 1} earlier ${sus.open - 1 === 1 ? 'failure is' : 'failures are'} still open too.</div>` : ''}</div>`;
248
276
  })() : '';
277
+ // The latest closed review, when nothing is open: who closed it, why, and the way back.
278
+ const lastClosed = !sus ? eqCalWindows(e).find(w => w.review) : null;
279
+ const closedHtml = lastClosed ? `<div class="eq-cal-reviewed" style="margin-top:10px;font-size:12.5px;color:var(--text-muted)">Review of the ${esc(lastClosed.at)} ${lastClosed.kind === 'adjusted' ? 'out-of-tolerance finding' : 'failure'} closed${lastClosed.review.by ? ' by ' + esc(lastClosed.review.by) : ''}${lastClosed.review.at && typeof flLocalDay === 'function' ? ' on ' + esc(flLocalDay(lastClosed.review.at)) : ''}: ${esc(lastClosed.review.reason || '')}${typeof flEqReopenReviewUI === 'function' ? ` · <a style="cursor:pointer;color:var(--primary);white-space:nowrap" onclick="flEqReopenReviewUI('${_eqCalJs(e.id)}','${_eqCalJs(lastClosed.calId)}')">Reopen</a>` : ''}</div>` : '';
249
280
  // Dates never wrap ("2026-11-/30" in a narrow window, 30 Nov Definition tab check).
250
281
  const rows = hist.map(c => `<tr>
251
282
  <td style="font-variant-numeric:tabular-nums;white-space:nowrap">${esc(c.date || '—')}</td>
@@ -262,7 +293,7 @@ function eqCalCardHtml(e) {
262
293
  const freeNote = on ? '' : `<div style="margin-top:10px;font-size:12px;color:var(--text-muted)">Read-only on Free: your calibration records are kept. Logging and due-date alerts are Pro.</div>`;
263
294
  return `<div class="card" id="eq-cal-card" style="margin-top:16px">
264
295
  <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap"><h2>Calibration</h2>${editBtns}</div>
265
- <div class="card-body">${summary}${susHtml}${table}${freeNote}</div></div>`;
296
+ <div class="card-body">${summary}${susHtml}${closedHtml}${table}${freeNote}</div></div>`;
266
297
  }
267
298
 
268
299
  // ---- Interval ----
@@ -358,7 +389,10 @@ function openEqCalLogModal(eqId, calId) {
358
389
  // calibrator may set In service / Out of service (0186); Retired is left alone.
359
390
  const outNow = !c && rec.result === 'fail' && (cur.status || 'In service') === 'In service';
360
391
  if (outNow) patch.status = 'Out of service';
361
- updateEquipment(eqId, patch);
392
+ // The trail says why the status moved (30 Nov: an auditor saw "In service → Out of service" with no reason).
393
+ const _why = outNow ? `In service → Out of service: failed calibration on ${rec.date}` : '';
394
+ if (_why) { try { if (window.__pro && typeof window.__pro.setReason === 'function') window.__pro.setReason('equipment', eqId, _why); } catch (_) {} }
395
+ updateEquipment(eqId, patch, _why ? { auditNote: _why } : undefined);
362
396
  if (typeof renderEquipmentDetail === 'function' && typeof currentView !== 'undefined' && currentView === 'equipment-detail') renderEquipmentDetail(eqId);
363
397
  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.')
364
398
  : (cur.status === 'Out of service' ? 'Calibration logged. The instrument is still Out of service.' : 'Calibration logged.')));