@peopl-health/nexus 5.71.32 → 5.71.34

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.
@@ -22,6 +22,10 @@ function profileSyncOn() {
22
22
  return flagOn('PATIENT_PROFILE_SYNC');
23
23
  }
24
24
 
25
+ function regimenCloserLive() {
26
+ return flagOn('REGIMEN_CLOSER_WRITE_LIVE');
27
+ }
28
+
25
29
  function contextMirrorLive() {
26
30
  return flagOn('CLINICAL_CONTEXT_MIRROR_LIVE') && contextReadLive();
27
31
  }
@@ -33,4 +37,5 @@ module.exports = {
33
37
  contextVerifierLive,
34
38
  profileFromMongo,
35
39
  profileSyncOn,
40
+ regimenCloserLive,
36
41
  };
@@ -1,6 +1,8 @@
1
1
  const { LEGACY_CONCEPT, NO_KNOWN_ALLERGY } = require('../../fhir/constants/variableRegistry');
2
2
  const { ageFrom, genderFrom } = require('../../fhir/resources/Patient');
3
- const { ageInYears } = require('../../utils/dateUtils');
3
+ const {
4
+ ageInYears, daysBetween, isoDay, mexicoDay,
5
+ } = require('../../utils/dateUtils');
4
6
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
5
7
  const { decodePair } = require('./encodedPairHelper');
6
8
 
@@ -11,6 +13,7 @@ const FIELD_LABELS = {
11
13
  diagnostico: 'Diagnóstico',
12
14
  tratamiento_actual: 'Tratamiento actual',
13
15
  medicacion_actual: 'Medicación',
16
+ tratamiento_suspendido: 'Suspendido recientemente',
14
17
  alergias_medicamentos: 'Alergias',
15
18
  comorbilidades: 'Comorbilidades',
16
19
  episodios_intercurrentes: 'Episodios',
@@ -35,8 +38,26 @@ const RETRACTED = new Set(['resolved', 'inactive', 'stopped', 'not-done']);
35
38
  // still stored and covering the field, but not rendered as what the patient has now
36
39
  const NOT_CURRENT = new Set(['completed', 'not-taking', 'preparation']);
37
40
 
41
+ // a stopped drug stays in view while its late toxicity may still show: the sign-off of 2026-10-14 asks a year for
42
+ // checkpoint inhibitors, anthracyclines, ADCs and anti-HER2; every injectable gets it to avoid a catalog read, and
43
+ // an oral anti-HER2 inhibitor gets the 90 days of any oral
44
+ const RECENTLY_STOPPED_DAYS = Object.freeze({
45
+ injectable_onco_summary: 365,
46
+ oral_onco_summary: 90,
47
+ other_meds_summary: 90,
48
+ });
49
+
38
50
  const isRetracted = (status) => RETRACTED.has(status);
39
51
 
52
+ function isRecentlyStopped(row, today = mexicoDay(new Date())) {
53
+ const windowDays = RECENTLY_STOPPED_DAYS[row.variableId];
54
+ if (!windowDays || row.status !== 'stopped') return false;
55
+ const days = daysBetween(isoDay(row.validTime), today);
56
+ return days >= 0 && days <= windowDays;
57
+ }
58
+
59
+ const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
60
+
40
61
  function ageOf(patient) {
41
62
  const derived = ageInYears(patient?.birthDate);
42
63
  if (derived !== null && derived > 0 && derived < MAX_PLAUSIBLE_AGE) return derived;
@@ -54,9 +75,11 @@ function renderableValues(bucket) {
54
75
  return preferring(current, NO_KNOWN_ALLERGY.concept).map((row) => decodePair(row.value));
55
76
  }
56
77
 
57
- function fieldsFromFhir(rows, patient) {
78
+ function fieldsFromFhir(rows, patient, today = mexicoDay(new Date())) {
58
79
  const byVariable = new Map();
80
+ const stopped = [];
59
81
  for (const row of rows) {
82
+ if (row.value && isRecentlyStopped(row, today)) stopped.push(`${decodePair(row.value)} (a más tardar ${dmy(isoDay(row.validTime))})`);
60
83
  if (!row.value || isRetracted(row.status)) continue;
61
84
  const bucket = byVariable.get(row.variableId) || [];
62
85
  bucket.push(row);
@@ -70,6 +93,7 @@ function fieldsFromFhir(rows, patient) {
70
93
  const values = renderableValues(variables.flatMap((variableId) => byVariable.get(variableId) || []));
71
94
  if (values.length) fields[field] = values.join(VALUE_SEPARATOR);
72
95
  }
96
+ if (stopped.length) fields.tratamiento_suspendido = stopped.join(VALUE_SEPARATOR);
73
97
  return fields;
74
98
  }
75
99
 
@@ -131,6 +155,7 @@ module.exports = {
131
155
  withLegacyDemographics,
132
156
  hasClinicalContent,
133
157
  isRetracted,
158
+ isRecentlyStopped,
134
159
  renderContextBlock,
135
160
  swapProfilePortion,
136
161
  VALUE_SEPARATOR,
@@ -1,12 +1,20 @@
1
+ const { regimenCloserLive } = require('../flags/clinicalContextFlags');
1
2
  const { syncContextFacts } = require('./contextSyncService');
2
3
  const { syncLegacyContext } = require('./legacyContextSyncService');
4
+ const { closeStoppedRegimens } = require('./regimenCloserService');
3
5
 
4
6
  // Tier 1 reads what tier 2 wrote, so running them concurrently races a real fact against a floor on one key.
5
7
  async function syncClinicalContext(options = {}) {
6
8
  const facts = await syncContextFacts(options);
7
- if (!facts.ok) return { ok: false, facts, legacy: null };
9
+ if (!facts.ok) return { ok: false, facts, legacy: null, closer: null };
8
10
  const legacy = await syncLegacyContext(options);
9
- return { ok: legacy.ok, facts, legacy };
11
+ // closes what the unit stopped giving after the facts tier wrote, so a fact restated this pass is seen; the
12
+ // per-patient list stays out of the result, which callers log
13
+ const closer = regimenCloserLive()
14
+ ? await closeStoppedRegimens({ dryRun: options.dryRun ?? false, patientScope: options.patientScope ?? null })
15
+ : null;
16
+ const { patients: _patients, ...closerCounts } = closer ?? {};
17
+ return { ok: legacy.ok && (closer?.ok ?? true), facts, legacy, closer: closer ? closerCounts : null };
10
18
  }
11
19
 
12
20
  module.exports = { syncClinicalContext };
@@ -4,7 +4,7 @@ const { readRecordedChemo } = require('../helpers/clinicalProfileHelper');
4
4
  const { getRecordByFilter } = require('../../services/airtableService');
5
5
  const { Quimio_Ops_ID } = require('../../config/airtableConfig');
6
6
  const { MATCH_ALL } = require('../../helpers/airtableFormulaHelper');
7
- const { readContextFacts, listContextFactPatients } = require('../../fhir');
7
+ const { readContextFacts, listContextFactPatients, storeContextFacts } = require('../../fhir');
8
8
  const { mapConcurrent } = require('../../utils/concurrencyUtils');
9
9
  const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
10
10
  const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
@@ -18,6 +18,9 @@ const REGIMEN_MIN_DAYS = 21;
18
18
  // a checkpoint inhibitor is often given every 6 weeks, or held for an immune toxicity
19
19
  const CHECKPOINT_REGIMEN_MIN_DAYS = 84;
20
20
  const INJECTABLE_VARIABLE = 'injectable_onco_summary';
21
+ // the unit's own record: a doctor's role, as trusted as the most trusted extractor source
22
+ const CLOSURE_SOURCE = 'unit';
23
+ const CLOSURE_TRUST = 0.95;
21
24
  const CURRENT_STATUSES = new Set([null, 'taking', 'unknown']);
22
25
  const PROPOSED_STATUS = 'stopped';
23
26
  // the unit's catalog files support care and premedication apart; only its own antineoplastics are closed
@@ -62,12 +65,15 @@ function skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClas
62
65
  return null;
63
66
  }
64
67
 
68
+ // a closure dated on or before the slot's own statement could lose arbitration to it; the regimen start always
69
+ // falls after it, and the drug is absent from that regimen
65
70
  function endOf(row, chemo, identity) {
66
71
  const previous = new Set((chemo.esquemaPrevio?.farmacos ?? []).flatMap((name) => drugsNamed(name, identity).drugs).flatMap(keysOf));
67
72
  const named = drugsNamed(row.concept ?? row.value, identity).drugs.flatMap(keysOf);
68
- return previous.size && named.every((key) => previous.has(key))
73
+ const end = previous.size && named.every((key) => previous.has(key))
69
74
  ? { endDate: chemo.esquemaPrevio.hasta, endFrom: 'esquemaPrevio' }
70
75
  : { endDate: chemo.inicioEsquema.fecha, endFrom: 'inicioEsquema' };
76
+ return end.endDate <= dayOf(row) ? { endDate: chemo.inicioEsquema.fecha, endFrom: 'inicioEsquema' } : end;
71
77
  }
72
78
 
73
79
  // an injectable antineoplastic the unit stopped giving: absent from its current regimen and stated before that regimen began
@@ -103,6 +109,7 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
103
109
  }
104
110
  closures.push({
105
111
  conceptKey: row.conceptKey,
112
+ concept: row.concept,
106
113
  drug: row.value,
107
114
  status: row.status ?? null,
108
115
  since: dayOf(row),
@@ -119,26 +126,69 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
119
126
  return { closures, skipped };
120
127
  }
121
128
 
122
- async function dryRunRegimenClosures({ today = mexicoDay(new Date()) } = {}) {
129
+ const closureOf = (patientId, closure, recordTime) => ({
130
+ patientId,
131
+ variableId: INJECTABLE_VARIABLE,
132
+ concept: closure.concept,
133
+ value: closure.drug,
134
+ status: closure.proposedStatus,
135
+ source: CLOSURE_SOURCE,
136
+ trust: CLOSURE_TRUST,
137
+ validTime: `${closure.endDate}T00:00:00.000Z`,
138
+ recordTime,
139
+ });
140
+
141
+ // an async scope answers with a promise, which is truthy, so every patient would pass
142
+ function inScope(patientIds, patientScope) {
143
+ if (!patientScope) return patientIds;
144
+ const answers = patientIds.map((patientId) => patientScope(patientId));
145
+ return answers.every((answer) => typeof answer === 'boolean') ? patientIds.filter((_, i) => answers[i]) : null;
146
+ }
147
+
148
+ // writes only with a patient scope, like the other context passes; a dry run lists what it would write
149
+ async function closeStoppedRegimens({ dryRun = true, patientScope = null, today = mexicoDay(new Date()) } = {}) {
150
+ const empty = { dryRun, closures: 0, written: 0, failed: 0, unreadable: 0, skipped: {}, patients: [] };
151
+ if (patientScope !== null && typeof patientScope !== 'function') return { ...empty, ok: false, reason: 'patient-scope-must-be-a-function' };
152
+ if (!patientScope && !dryRun) return { ...empty, ok: false, reason: 'patient-scope-required' };
123
153
  const identity = await loadDrugIdentity();
124
- if (!identity) return { ok: false, dryRun: true, reason: 'drug-catalog-unreadable', closures: 0, unreadable: 0, skipped: {}, patients: [] };
154
+ if (!identity) return { ...empty, ok: false, reason: 'drug-catalog-unreadable' };
155
+ const scoped = inScope(await listContextFactPatients(), patientScope);
156
+ if (!scoped) return { ...empty, ok: false, reason: 'patient-scope-must-return-boolean' };
125
157
  const patients = [];
126
158
  const skipped = {};
127
159
  let unreadable = 0;
128
- await mapConcurrent(await listContextFactPatients(), DEFAULT_PATIENT_CONCURRENCY, async (patientId) => {
160
+ let written = 0;
161
+ let failed = 0;
162
+ await mapConcurrent(scoped, DEFAULT_PATIENT_CONCURRENCY, async (patientId) => {
163
+ let result;
129
164
  try {
130
165
  const [chemo, facts] = await Promise.all([readRecordedChemo(patientId), readContextFacts({ patientId })]);
131
- const result = proposeClosures({ chemo, facts, identity, today });
132
- Object.entries(result.skipped).forEach(([reason, n]) => { skipped[reason] = (skipped[reason] ?? 0) + n; });
133
- if (result.closures.length) patients.push({ patientId, closures: result.closures });
166
+ result = proposeClosures({ chemo, facts, identity, today });
134
167
  } catch (error) {
135
168
  unreadable += 1;
136
169
  logger.error('[regimenCloser] Patient unreadable', { code: maskSensitiveValue(patientId), error: error.message });
170
+ return;
171
+ }
172
+ Object.entries(result.skipped).forEach(([reason, n]) => { skipped[reason] = (skipped[reason] ?? 0) + n; });
173
+ if (!result.closures.length) return;
174
+ patients.push({ patientId, closures: result.closures });
175
+ if (dryRun) return;
176
+ const recordTime = new Date().toISOString();
177
+ for (const closure of result.closures) {
178
+ try {
179
+ await storeContextFacts({ patientId, assertions: [closureOf(patientId, closure, recordTime)] });
180
+ written += 1;
181
+ } catch (error) {
182
+ failed += 1;
183
+ logger.error('[regimenCloser] Closure rejected', { code: maskSensitiveValue(patientId), error: error.message });
184
+ }
137
185
  }
138
186
  });
139
187
  const closures = patients.reduce((n, patient) => n + patient.closures.length, 0);
140
- logger.info('[regimenCloser] Dry run complete', { patients: patients.length, closures, unreadable, skipped });
141
- return { ok: !unreadable, dryRun: true, closures, unreadable, skipped, patients };
188
+ logger.info('[regimenCloser] Pass complete', { dryRun, patients: patients.length, closures, written, failed, unreadable, skipped });
189
+ return { ok: !unreadable && !failed, dryRun, closures, written, failed, unreadable, skipped, patients };
142
190
  }
143
191
 
144
- module.exports = { proposeClosures, dryRunRegimenClosures };
192
+ const dryRunRegimenClosures = ({ today } = {}) => closeStoppedRegimens({ dryRun: true, today });
193
+
194
+ module.exports = { proposeClosures, closeStoppedRegimens, dryRunRegimenClosures };
@@ -15,7 +15,7 @@ const NO_KNOWN_ALLERGY = {
15
15
  };
16
16
 
17
17
  const SOURCE_ROLES = {
18
- specialist: DOCTOR, doctor: DOCTOR, oncologist: DOCTOR, auna: DOCTOR, note: DOCTOR, operator: DOCTOR,
18
+ specialist: DOCTOR, doctor: DOCTOR, oncologist: DOCTOR, auna: DOCTOR, note: DOCTOR, operator: DOCTOR, unit: DOCTOR,
19
19
  'legacy-clinician': DOCTOR,
20
20
  self: PATIENT, patient: PATIENT, chat: PATIENT,
21
21
  'legacy-self': PATIENT,
package/lib/index.d.ts CHANGED
@@ -451,6 +451,8 @@ declare module '@peopl-health/nexus' {
451
451
  ok: boolean;
452
452
  facts: ContextSyncResult;
453
453
  legacy: ContextSyncResult | null;
454
+ /** The regimen closer's counts, without the per-patient list; null while REGIMEN_CLOSER_WRITE_LIVE is off. */
455
+ closer: Omit<RegimenCloserResult, 'patients'> | null;
454
456
  }
455
457
 
456
458
  export function syncContextFacts(options?: ContextSyncOptions): Promise<ContextSyncResult>;
@@ -573,6 +575,7 @@ declare module '@peopl-health/nexus' {
573
575
 
574
576
  export interface RegimenClosure {
575
577
  conceptKey: string;
578
+ concept: string | null;
576
579
  drug: string;
577
580
  status: string | null;
578
581
  since: string;
@@ -582,16 +585,23 @@ declare module '@peopl-health/nexus' {
582
585
  evidence: { ultimaAplicacion: ChemoContext['ultimaAplicacion']; esquema: string[]; inicioEsquema: ChemoContext['inicioEsquema']; esquemaPrevio: ChemoContext['esquemaPrevio'] };
583
586
  }
584
587
 
585
- /** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
586
- export function dryRunRegimenClosures(options?: { today?: string }): Promise<{
588
+ export interface RegimenCloserResult {
587
589
  ok: boolean;
588
- dryRun: true;
590
+ dryRun: boolean;
589
591
  closures: number;
592
+ written: number;
593
+ failed: number;
590
594
  unreadable: number;
591
595
  reason?: string;
592
596
  skipped: Record<string, number>;
593
597
  patients: Array<{ patientId: string; closures: RegimenClosure[] }>;
594
- }>;
598
+ }
599
+
600
+ /** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
601
+ export function dryRunRegimenClosures(options?: { today?: string }): Promise<RegimenCloserResult>;
602
+
603
+ /** Writes those closures as `stopped` facts (source `unit`, validTime = end date); a dry run unless `dryRun: false` with a `patientScope`. */
604
+ export function closeStoppedRegimens(options?: { dryRun?: boolean; patientScope?: (patientId: string) => boolean; today?: string }): Promise<RegimenCloserResult>;
595
605
 
596
606
  export const routes: any;
597
607
  export function setupDefaultRoutes(app: any): void;
package/lib/index.js CHANGED
@@ -48,7 +48,7 @@ const { syncLegacyContext } = require('./clinical/services/legacyContextSyncServ
48
48
  const { syncClinicalContext } = require('./clinical/services/contextSyncRunner');
49
49
  const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
50
50
  const { currentRegimen } = require('./clinical/services/currentRegimenService');
51
- const { dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
51
+ const { closeStoppedRegimens, dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
52
52
  const { readRecordedChemo } = require('./clinical/helpers/clinicalProfileHelper');
53
53
  const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
54
54
  const { MapCache } = require('./utils/MapCache');
@@ -364,6 +364,7 @@ module.exports = {
364
364
  runProactiveOutreachSweep,
365
365
  currentRegimen,
366
366
  dryRunRegimenClosures,
367
+ closeStoppedRegimens,
367
368
  readRecordedChemo,
368
369
  syncContextFacts,
369
370
  retractContentlessFacts,
@@ -21,7 +21,7 @@ const { isNetActive } = require('../shared/dtos/ContingencySafetyNet');
21
21
  const { identifierValue } = require('../fhir/helpers/fhirReadHelper');
22
22
  const { resourceDisplayText } = require('../fhir/helpers/resourceDisplayHelper');
23
23
  const { RESULT_SLUG, MENTION_SLUG } = require('../fhir/constants/projectionSlugs');
24
- const { FIELD_VARIABLES, isRetracted } = require('../clinical/helpers/clinicalContextHelper');
24
+ const { FIELD_VARIABLES, isRetracted, isRecentlyStopped } = require('../clinical/helpers/clinicalContextHelper');
25
25
  const { decodePair } = require('../clinical/helpers/encodedPairHelper');
26
26
  const { warningRecord } = require('../fhir/projections/recommendationPlanProjection');
27
27
  const { getTriageRecommendationEventModel } = require('../clinical/models/triageRecommendationEventModel');
@@ -281,6 +281,7 @@ const emptyClinicalContext = () => ({
281
281
  diagnoses: [],
282
282
  treatments: [],
283
283
  medications: [],
284
+ recentlyStopped: [],
284
285
  allergies: [],
285
286
  comorbidities: [],
286
287
  performanceStatus: [],
@@ -315,8 +316,9 @@ function projectClinicalContext(contextFacts = [], riskAssessments = [], snapsho
315
316
  const group = CONTEXT_GROUPS[fact.variableId];
316
317
  const inactiveFollowup = group === 'followup' && ['revoked', 'completed'].includes(fact.status);
317
318
  if (group && !isRetracted(fact.status) && !inactiveFollowup) context[group].push(projectContextFact(fact));
319
+ if (isRecentlyStopped(fact)) context.recentlyStopped.push(projectContextFact(fact));
318
320
  }
319
- for (const group of new Set(Object.values(CONTEXT_GROUPS))) {
321
+ for (const group of new Set([...Object.values(CONTEXT_GROUPS), 'recentlyStopped'])) {
320
322
  context[group].sort((a, b) => Date.parse(b.validAt || b.recordedAt || 0) - Date.parse(a.validAt || a.recordedAt || 0));
321
323
  }
322
324
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.71.32",
3
+ "version": "5.71.34",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",