@peopl-health/nexus 5.56.10 → 5.56.13

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.
@@ -16,6 +16,7 @@ const TRIAGE_GATE_DEFAULTS = { presetId: '' };
16
16
  const TRIAGE_PLAN_DEFAULTS = { presetId: '' };
17
17
  const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
18
18
  const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
19
+ const ESCALATION_NOTE_FACTS_DEFAULTS = { presetId: '' };
19
20
 
20
21
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
21
22
 
@@ -61,7 +62,11 @@ async function load() {
61
62
  if (byKey.ESCALATION_QUESTIONS && !isPlainObject(parsedEscalationQuestions)) throw new Error('subAgents config ESCALATION_QUESTIONS is not a JSON object');
62
63
  const escalationQuestions = { ...ESCALATION_QUESTIONS_DEFAULTS, ...(parsedEscalationQuestions || {}) };
63
64
 
64
- const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions };
65
+ const parsedNoteFacts = safeParse(byKey.ESCALATION_NOTE_FACTS, null);
66
+ if (byKey.ESCALATION_NOTE_FACTS && !isPlainObject(parsedNoteFacts)) throw new Error('subAgents config ESCALATION_NOTE_FACTS is not a JSON object');
67
+ const escalationNoteFacts = { ...ESCALATION_NOTE_FACTS_DEFAULTS, ...(parsedNoteFacts || {}) };
68
+
69
+ const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts };
65
70
  cache.set(CACHE_KEY, config);
66
71
  return config;
67
72
  }
@@ -79,4 +84,5 @@ module.exports = {
79
84
  getTriagePlan: () => get('TRIAGE_PLAN'),
80
85
  getEscalationDraft: () => get('ESCALATION_DRAFT'),
81
86
  getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
87
+ getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
82
88
  };
@@ -0,0 +1,131 @@
1
+ const { getEscalationNoteFacts } = require('../config/subAgentsConfig');
2
+
3
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
4
+ const { createLLMProvider } = require('../providers/createLLMProvider');
5
+
6
+ const { VARIABLE_REGISTRY } = require('../../fhir/constants/variableRegistry');
7
+
8
+ const { logger } = require('../../utils/logger');
9
+ const { safeParse } = require('../../utils/jsonUtils');
10
+ const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
11
+ const { withTiming } = require('../../utils/tracingDecorator');
12
+
13
+ const MAX_FACTS = 6;
14
+
15
+ const NOTE_TRUST = 0.5;
16
+ const NOTE_SOURCE = 'note';
17
+
18
+ const trimmed = (value) => String(value ?? '').trim();
19
+
20
+ const variables = () => Object.entries(VARIABLE_REGISTRY)
21
+ .map(([variableId, entry]) => ({ variableId, kind: entry.kind, singleton: entry.singleton === true }));
22
+
23
+ function buildNoteFactsInput({ note, clinicalContext, now }) {
24
+ return {
25
+ now: new Date(now).toISOString(),
26
+ limits: { facts: MAX_FACTS },
27
+ variables: variables(),
28
+ clinicalContext: clinicalContext ?? null,
29
+ note: trimmed(note),
30
+ };
31
+ }
32
+
33
+ function storable(candidate) {
34
+ const variableId = trimmed(candidate?.variableId);
35
+ const entry = VARIABLE_REGISTRY[variableId];
36
+ if (!entry) return null;
37
+ const value = trimmed(candidate?.value);
38
+ if (!value) return null;
39
+ const concept = trimmed(candidate?.concept) || null;
40
+ if (!entry.singleton && !concept) return null;
41
+
42
+ const validTime = new Date(candidate?.validTime ?? '');
43
+ return {
44
+ variableId,
45
+ concept,
46
+ value,
47
+ status: trimmed(candidate?.status) || null,
48
+ validTime: Number.isFinite(validTime.getTime()) ? validTime.toISOString() : null,
49
+ quote: trimmed(candidate?.quote) || null,
50
+ };
51
+ }
52
+
53
+ const factKey = (fact) => (VARIABLE_REGISTRY[fact.variableId]?.singleton
54
+ ? fact.variableId
55
+ : `${fact.variableId}\n${(fact.concept ?? '').toLowerCase()}`);
56
+
57
+ function deduplicated(facts) {
58
+ const seen = new Set();
59
+ return facts.filter((fact) => {
60
+ const key = factKey(fact);
61
+ if (seen.has(key)) return false;
62
+ seen.add(key);
63
+ return true;
64
+ });
65
+ }
66
+
67
+ function noteFactsProvider() {
68
+ try {
69
+ return createLLMProvider({ variant: 'anthropic' });
70
+ } catch (error) {
71
+ logger.warn('[escalationNoteFacts] no provider available; not reading the note', { error: error.message });
72
+ return null;
73
+ }
74
+ }
75
+
76
+ async function readNoteFacts({ note, clinicalContext = null, provider, trace = null, reviewId = null, now = Date.now() } = {}) {
77
+ if (!trimmed(note)) return { completed: false, facts: [], reason: 'the note is empty' };
78
+
79
+ const { presetId } = await getEscalationNoteFacts();
80
+ const llm = provider ?? noteFactsProvider();
81
+ if (!presetId || !llm?.runStructured) {
82
+ return { completed: false, configured: false, facts: [], reason: 'reading call notes is not configured' };
83
+ }
84
+
85
+ const input = buildNoteFactsInput({ note, clinicalContext, now });
86
+
87
+ let result;
88
+ let durationMs;
89
+ try {
90
+ ({ result, durationMs } = await withTiming(() => llm.runStructured({
91
+ presetId,
92
+ input: [{ role: 'user', content: JSON.stringify(input) }],
93
+ metadata: { generator: 'escalation-note-facts', reviewId: reviewId ?? undefined },
94
+ })));
95
+ } catch (error) {
96
+ logger.error('[escalationNoteFacts] the provider failed', {
97
+ error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')), reviewId,
98
+ });
99
+ return { completed: false, attempted: true, facts: [], reason: 'the model could not be reached' };
100
+ }
101
+ trace?.addSubCall({ response: result, durationMs, presetId });
102
+
103
+ if (result?.status && result.status !== 'completed') {
104
+ return { completed: false, attempted: true, facts: [], reason: `reading incomplete: status=${result.status}` };
105
+ }
106
+
107
+ const text = readStructuredText(result);
108
+ const parsed = safeParse(text, null);
109
+ if (parsed === null && trimmed(text)) {
110
+ return { completed: false, attempted: true, facts: [], reason: 'the model did not answer in the expected shape' };
111
+ }
112
+
113
+ const facts = deduplicated((Array.isArray(parsed?.facts) ? parsed.facts : []).map(storable).filter(Boolean))
114
+ .slice(0, MAX_FACTS);
115
+
116
+ return { completed: true, attempted: true, facts };
117
+ }
118
+
119
+ const assertionOf = (fact, { patientId, now }) => ({
120
+ patientId,
121
+ variableId: fact.variableId,
122
+ concept: fact.concept ?? null,
123
+ value: fact.value,
124
+ status: fact.status ?? null,
125
+ source: NOTE_SOURCE,
126
+ trust: NOTE_TRUST,
127
+ validTime: fact.validTime ?? new Date(now).toISOString(),
128
+ recordTime: new Date(now).toISOString(),
129
+ });
130
+
131
+ module.exports = { readNoteFacts, buildNoteFactsInput, storable, assertionOf, MAX_FACTS, NOTE_TRUST, NOTE_SOURCE };
@@ -15,6 +15,7 @@ const {
15
15
  setReviewCases,
16
16
  suggestDraft,
17
17
  suggestKeyQuestions,
18
+ confirmNoteFacts,
18
19
  syncEscalationReviewCase,
19
20
  } = require('../services/escalationReviewService');
20
21
 
@@ -81,6 +82,18 @@ const addEscalationReviewCallLogController = async (req, res) => {
81
82
  }
82
83
  };
83
84
 
85
+ const confirmEscalationReviewNoteFactsController = async (req, res) => {
86
+ try {
87
+ const { accepted, declined, triggeredBy } = req.body || {};
88
+ const review = await confirmNoteFacts({
89
+ id: req.params.id, accepted, declined, confirmedBy: triggeredBy, requestId: req.requestId,
90
+ });
91
+ res.status(200).json({ success: true, review });
92
+ } catch (error) {
93
+ respondWithError(res, error, 'confirming escalation review note facts', { reviewId: req.params?.id });
94
+ }
95
+ };
96
+
84
97
  const suggestEscalationReviewDraftController = async (req, res) => {
85
98
  try {
86
99
  const { triggeredBy } = req.body || {};
@@ -206,6 +219,7 @@ const syncEscalationReviewCaseController = async (req, res) => {
206
219
 
207
220
  module.exports = {
208
221
  addEscalationReviewCallLogController,
222
+ confirmEscalationReviewNoteFactsController,
209
223
  addEscalationReviewDraftController,
210
224
  cancelEscalationReviewController,
211
225
  closeEscalationReviewController,
@@ -12,6 +12,7 @@ const {
12
12
  getRecommendationCarousels,
13
13
  getRecommendationCarouselImage,
14
14
  } = require('../services/recommendationCarouselService');
15
+ const { recordRecommendationReview } = require('../fhir');
15
16
 
16
17
  const MAX_CONCURRENT_CAROUSEL_IMAGES = 8;
17
18
  let activeCarouselImageRequests = 0;
@@ -72,6 +73,33 @@ const getPatientCarePlanController = async (req, res) => {
72
73
  }
73
74
  };
74
75
 
76
+ // `reviewedBy` is trusted from the caller: the interface derives it from the session.
77
+ const reviewPatientCarePlanCardController = async (req, res) => {
78
+ const code = String(req.params.code || '').trim();
79
+ const recommendationId = String(req.params.cardId || '').trim();
80
+ try {
81
+ if (!code) return res.status(400).json({ success: false, error: 'WhatsApp ID is required' });
82
+ if (!recommendationId) return res.status(400).json({ success: false, error: 'cardId is required' });
83
+
84
+ const { verdict, note = null, correctedText = null, reviewedBy, eventKey = null } = req.body || {};
85
+ const result = await recordRecommendationReview({
86
+ patientId: code, recommendationId, verdict, note, correctedText, reviewedBy, eventKey,
87
+ });
88
+ if (result.skipped) {
89
+ return res.status(503).json({ success: false, error: 'The review was not recorded: writes are suppressed in this scope' });
90
+ }
91
+ if (!result.recorded && !result.duplicate) {
92
+ return res.status(404).json({ success: false, error: 'No card with that id for this patient' });
93
+ }
94
+ return res.status(200).json({ success: true, ...result });
95
+ } catch (error) {
96
+ const isCallerError = /^(invalid |reviewedBy is required|a corrected verdict)/.test(error.message || '');
97
+ if (isCallerError) return res.status(400).json({ success: false, error: error.message });
98
+ logger.error('Error recording care plan review:', { error: error.message, stack: error.stack, code, recommendationId });
99
+ return res.status(500).json({ success: false, error: 'Failed to record the care plan review' });
100
+ }
101
+ };
102
+
75
103
  const getPatientTasksController = async (req, res) => {
76
104
  try {
77
105
  const tasks = await getPatientTasks(req.params.code);
@@ -261,6 +289,7 @@ module.exports = {
261
289
  getPatientInfoController,
262
290
  getPatientTriageInfoController,
263
291
  getPatientCarePlanController,
292
+ reviewPatientCarePlanCardController,
264
293
  getPatientEscalationContextController,
265
294
  getPatientTasksController,
266
295
  getPatientRecommendationCarouselsController,
@@ -88,6 +88,12 @@ const RECOMMENDATION_EXT = {
88
88
  REC_FOLLOWUP_URGENCY: 'recommendation-followup-urgency',
89
89
  PRODUCED_BY_MODEL: 'recommendation-produced-by-model',
90
90
  METHOD_VERSION: 'recommendation-method-version',
91
+ REVIEW_VERDICT: 'recommendation-review-verdict',
92
+ REVIEW_NOTE: 'recommendation-review-note',
93
+ REVIEW_CORRECTED_TEXT: 'recommendation-review-corrected-text',
94
+ REVIEW_BY: 'recommendation-review-by',
95
+ REVIEW_RECORDED_AT: 'recommendation-review-recorded-at',
96
+ REVIEW_EVENT: 'recommendation-review-event',
91
97
  };
92
98
 
93
99
  const SAFETY_GATE_EXT = {
@@ -1,3 +1,5 @@
1
+ const { createHash } = require('crypto');
2
+
1
3
  const { FHIR_ID_MAX } = require('./fhirHelper');
2
4
 
3
5
  const TRIAGE_RUN_PREFIX = 'recrun-triage-';
@@ -9,6 +11,19 @@ const recommendationId = (runId, rank) => {
9
11
  return `${sanitize(runId).slice(0, FHIR_ID_MAX - suffix.length)}${suffix}`;
10
12
  };
11
13
 
14
+ // `recommendationId` fills the id budget, so appending would drop its `-recN` suffix.
15
+ const reviewProvenanceId = (recommendationId, discriminator) => {
16
+ const digest = createHash('sha1').update(`${recommendationId}|${discriminator}`).digest('hex');
17
+ return `rev-${digest.slice(0, 40)}`;
18
+ };
19
+
20
+ // Sanitising alone maps `a_b@` and `a-b@` onto one id.
21
+ const REVIEWER_DIGEST_LENGTH = 12;
22
+ const reviewerId = (reviewer) => {
23
+ const digest = createHash('sha1').update(String(reviewer)).digest('hex').slice(0, REVIEWER_DIGEST_LENGTH);
24
+ return `${sanitize(reviewer).slice(0, FHIR_ID_MAX - digest.length - 1)}-${digest}`;
25
+ };
26
+
12
27
  const runIdOf = (id) => id.replace(/-rec[^-]*$/, '');
13
28
 
14
29
  const rankOf = (id) => {
@@ -20,6 +35,8 @@ const sourceOfRun = (runId) => (runId.startsWith(TRIAGE_RUN_PREFIX) ? 'triage' :
20
35
 
21
36
  module.exports = {
22
37
  recommendationId,
38
+ reviewProvenanceId,
39
+ reviewerId,
23
40
  runIdOf,
24
41
  rankOf,
25
42
  sourceOfRun,
@@ -11,14 +11,17 @@ function baseResource(resourceType, id, slug, patientId = null) {
11
11
  };
12
12
  }
13
13
 
14
- function provenance({ provenanceId, targetRefs, recordedAt, activity, agentDevice = null, onBehalfOf = null }) {
14
+ function provenance({
15
+ provenanceId, targetRefs, recordedAt, activity,
16
+ agentDevice = null, onBehalfOf = null, agentWho = null,
17
+ }) {
15
18
  return {
16
19
  resourceType: 'Provenance',
17
20
  id: fhirId(provenanceId),
18
21
  target: targetRefs,
19
22
  recorded: toIso(recordedAt),
20
23
  agent: [{
21
- who: reference('Device', agentDevice || getDeviceId()),
24
+ who: agentWho || reference('Device', agentDevice || getDeviceId()),
22
25
  onBehalfOf: reference('Organization', onBehalfOf || getOrganizationId()),
23
26
  }],
24
27
  activity,
package/lib/fhir/index.js CHANGED
@@ -12,6 +12,7 @@ const {
12
12
  readActiveRecommendations,
13
13
  readRecommendationPlans,
14
14
  recordRecommendationOutcome,
15
+ recordRecommendationReview,
15
16
  } = require('./services/recommendationService');
16
17
  const { storeContingency, readContingencies } = require('./services/contingencyService');
17
18
  const { readDispatchedEscalations } = require('./services/escalationService');
@@ -65,6 +66,7 @@ module.exports = {
65
66
  readActiveRecommendations,
66
67
  readRecommendationPlans,
67
68
  recordRecommendationOutcome,
69
+ recordRecommendationReview,
68
70
  storeContingency,
69
71
  readContingencies,
70
72
  readDispatchedEscalations,
@@ -9,6 +9,7 @@ const { PALLIATIVE_CAREPLAN_SLUG, PALLIATIVE_CAREPLAN_REC_SLUG } = require('../c
9
9
  const { PALLIATIVE_EXT } = require('../constants/extensionSlugs');
10
10
  const { PalliativeCarePlan } = require('../../shared/dtos/PalliativeCarePlan');
11
11
  const { logger } = require('../../utils/logger');
12
+ const { reviewHistoryOf } = require('./recommendationPlanProjection');
12
13
 
13
14
  const ACTIVITY_TEXT = 'palliative-careplan';
14
15
  const NOTE_SEPARATOR = ': ';
@@ -109,7 +110,17 @@ function fromFhir(resources, { patientId }) {
109
110
  if (resource.resourceType !== 'CarePlan') continue;
110
111
  if (!identifierValue(resource, PALLIATIVE_CAREPLAN_SLUG)) continue;
111
112
  try {
112
- out.push(new PalliativeCarePlan(reconstruct(resource, tasksByReference, patientId)));
113
+ const tasks = recommendationTasks(resource, tasksByReference);
114
+ const carePlan = new PalliativeCarePlan(reconstruct(resource, tasksByReference, patientId));
115
+ // The DTO is strict, so reviews are attached after validation rather than inside it.
116
+ const reviewsByRank = new Map(tasks.map((task) => [
117
+ extMap(task)[PALLIATIVE_EXT.CAREPLAN_REC_RANK],
118
+ reviewHistoryOf(task),
119
+ ]));
120
+ for (const recommendation of carePlan.recommendations) {
121
+ recommendation.reviewHistory = reviewsByRank.get(recommendation.rank) || [];
122
+ }
123
+ out.push(carePlan);
113
124
  } catch (error) {
114
125
  if (error instanceof ZodError) {
115
126
  logger.warn({ careplanId: resource.id }, 'skipping malformed palliative CarePlan');
@@ -121,12 +132,13 @@ function fromFhir(resources, { patientId }) {
121
132
  return out;
122
133
  }
123
134
 
135
+ const recommendationTasks = (plan, tasksByReference) => (plan.activity || [])
136
+ .map((activity) => tasksByReference.get(activity.plannedActivityReference?.reference))
137
+ .filter(Boolean);
138
+
124
139
  function reconstruct(plan, tasksByReference, patientId) {
125
140
  const ext = extMap(plan);
126
- const recommendations = (plan.activity || [])
127
- .map((activity) => tasksByReference.get(activity.plannedActivityReference?.reference))
128
- .filter(Boolean)
129
- .map(reconstructRecommendation);
141
+ const recommendations = recommendationTasks(plan, tasksByReference).map(reconstructRecommendation);
130
142
  return {
131
143
  careplanId: identifierValue(plan, PALLIATIVE_CAREPLAN_SLUG),
132
144
  patientId,
@@ -15,6 +15,8 @@ const {
15
15
  const PROJECTOR_NAME = 'recommendationPlan';
16
16
  const ACTIVITY_TEXT = 'recommendations-process';
17
17
  const OUTCOME_KEY = 'recommendation-outcome';
18
+ const REVIEW_KEY = 'recommendation-review';
19
+ const REVIEW_VERDICTS = ['confirmed', 'corrected', 'rejected'];
18
20
  const NOTE_SEPARATOR = ': ';
19
21
  const CARE_PLAN_CATEGORY = 'symptom_management';
20
22
  const NOTE_LABELS = {
@@ -253,11 +255,64 @@ function outcomeEntry({ outcome, adherence, notes, source, recordedAt, eventKey
253
255
  return entry;
254
256
  }
255
257
 
256
- // A retried run rewrites the same outcome with a new timestamp; the event key is what makes it recognisable.
257
- function hasOutcomeEvent(task, eventKey) {
258
- return (task?.output || []).some((entry) => extMap(entry)[RECOMMENDATION_EXT.OUTCOME_EVENT] === eventKey);
258
+ function reviewEntry({ verdict, note, correctedText, reviewedBy, recordedAt, eventKey }) {
259
+ const entry = {
260
+ type: codeableConcept(REVIEW_KEY),
261
+ valueCodeableConcept: codeableConcept(verdict, { code: verdict, system: codeSystemUrl(REVIEW_KEY) }),
262
+ extension: [
263
+ extension(RECOMMENDATION_EXT.REVIEW_VERDICT, { valueString: verdict }),
264
+ extension(RECOMMENDATION_EXT.REVIEW_BY, { valueString: reviewedBy }),
265
+ extension(RECOMMENDATION_EXT.REVIEW_RECORDED_AT, { valueDateTime: recordedAt }),
266
+ ],
267
+ };
268
+ if (note) entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_NOTE, { valueString: note }));
269
+ if (correctedText) {
270
+ entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_CORRECTED_TEXT, { valueString: correctedText }));
271
+ }
272
+ if (eventKey) entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_EVENT, { valueString: eventKey }));
273
+ return entry;
259
274
  }
260
275
 
276
+ const hasReviewEvent = (task, eventKey) => hasEvent(task, eventKey, RECOMMENDATION_EXT.REVIEW_EVENT);
277
+
278
+ const reviewOf = (entry) => {
279
+ const ext = extMap(entry);
280
+ return {
281
+ verdict: ext[RECOMMENDATION_EXT.REVIEW_VERDICT] || null,
282
+ note: ext[RECOMMENDATION_EXT.REVIEW_NOTE] || null,
283
+ correctedText: ext[RECOMMENDATION_EXT.REVIEW_CORRECTED_TEXT] || null,
284
+ reviewedBy: ext[RECOMMENDATION_EXT.REVIEW_BY] || null,
285
+ recordedAt: ext[RECOMMENDATION_EXT.REVIEW_RECORDED_AT] || null,
286
+ };
287
+ };
288
+
289
+ function reviewByEvent(task, eventKey) {
290
+ const entry = (task?.output || []).find((row) => (
291
+ row.type?.text === REVIEW_KEY && extMap(row)[RECOMMENDATION_EXT.REVIEW_EVENT] === eventKey
292
+ ));
293
+ return entry ? reviewOf(entry) : null;
294
+ }
295
+
296
+ // By `recordedAt`, not insertion order: concurrent writes timestamp before they upsert.
297
+ function reviewHistoryOf(task) {
298
+ return (task.output || [])
299
+ .filter((entry) => entry.type?.text === REVIEW_KEY)
300
+ .map(reviewOf)
301
+ .map((review, index) => ({ review, index, at: Date.parse(review.recordedAt ?? '') }))
302
+ .sort((a, b) => {
303
+ const left = Number.isFinite(a.at) ? a.at : -Infinity;
304
+ const right = Number.isFinite(b.at) ? b.at : -Infinity;
305
+ return left === right ? a.index - b.index : left - right;
306
+ })
307
+ .map(({ review }) => review);
308
+ }
309
+
310
+ function hasEvent(task, eventKey, slug) {
311
+ return (task?.output || []).some((entry) => extMap(entry)[slug] === eventKey);
312
+ }
313
+
314
+ const hasOutcomeEvent = (task, eventKey) => hasEvent(task, eventKey, RECOMMENDATION_EXT.OUTCOME_EVENT);
315
+
261
316
  function outcomeHistoryOf(task) {
262
317
  return (task.output || [])
263
318
  .filter((entry) => entry.type?.text === OUTCOME_KEY)
@@ -396,6 +451,7 @@ function reconstructElement(finding, index, runId, tasksById) {
396
451
  recommendationId: task ? identifierValue(task, RECOMMENDATION_REC_SLUG) : null,
397
452
  latestOutcome: task ? mergedOutcome(task) : null,
398
453
  outcomeHistory: task ? outcomeHistoryOf(task) : [],
454
+ reviewHistory: task ? reviewHistoryOf(task) : [],
399
455
  };
400
456
  }
401
457
 
@@ -492,4 +548,9 @@ module.exports = {
492
548
  outcomeHistoryOf,
493
549
  mergedOutcome,
494
550
  warningRecord,
551
+ reviewEntry,
552
+ hasReviewEvent,
553
+ reviewByEvent,
554
+ reviewHistoryOf,
555
+ REVIEW_VERDICTS,
495
556
  };
@@ -30,7 +30,15 @@ async function storeResources(resources, { store = null, merge = null } = {}) {
30
30
  return { stored };
31
31
  }
32
32
 
33
+ // A plan rewrite reprojects its Tasks with no `output`, where the outcomes and verdicts live.
34
+ const keepTaskOutput = {
35
+ merge: (prior, incoming) => (prior.resourceType === 'Task' && prior.output?.length
36
+ ? { ...incoming, output: prior.output }
37
+ : incoming),
38
+ };
39
+
33
40
  module.exports = {
41
+ keepTaskOutput,
34
42
  registerProjector: registry.register,
35
43
  project,
36
44
  storeResources,
@@ -3,7 +3,7 @@ const { PALLIATIVE_ASSESSMENT_SLUG, PALLIATIVE_CAREPLAN_SLUG } = require('../con
3
3
  const { getFhirStore } = require('../stores/fhirStore');
4
4
  const { toFhir: assessmentToFhir, fromFhir: assessmentFromFhir } = require('../projections/palliativeProjection');
5
5
  const { toFhir: carePlanToFhir, fromFhir: carePlanFromFhir } = require('../projections/palliativeCarePlanProjection');
6
- const { storeResources } = require('./fhirService');
6
+ const { storeResources, keepTaskOutput } = require('./fhirService');
7
7
 
8
8
  async function storePalliativeAssessment({ patientId, assessment }) {
9
9
  if (assessment.patientId !== patientId) {
@@ -40,7 +40,7 @@ async function storePalliativeCarePlan({ patientId, carePlan }) {
40
40
  if (carePlan.patientId !== patientId) {
41
41
  throw new Error(`storePalliativeCarePlan patientId mismatch: expected ${patientId}`);
42
42
  }
43
- const { stored } = await storeResources(carePlanToFhir(carePlan));
43
+ const { stored } = await storeResources(carePlanToFhir(carePlan), keepTaskOutput);
44
44
  return { count: stored.length, ids: stored };
45
45
  }
46
46
 
@@ -1,7 +1,11 @@
1
+ const { randomUUID } = require('crypto');
2
+
1
3
  const { fhirId, identifierSystem } = require('../helpers/fhirHelper');
4
+ const { reference, codeableConcept, patientReference } = require('../helpers/elementHelper');
5
+ const { provenance } = require('../helpers/resourceHelper');
2
6
  const { toIso } = require('../helpers/elementHelper');
3
7
  const { identifierValue } = require('../helpers/fhirReadHelper');
4
- const { runIdOf, rankOf, sourceOfRun } = require('../helpers/recommendationIds');
8
+ const { runIdOf, rankOf, sourceOfRun, reviewProvenanceId, reviewerId } = require('../helpers/recommendationIds');
5
9
  const { keyOf, aliasClosure } = require('../helpers/symptomAliasHelper');
6
10
  const {
7
11
  toFhir,
@@ -11,15 +15,20 @@ const {
11
15
  outcomeEntry,
12
16
  hasOutcomeEvent,
13
17
  mergedOutcome,
18
+ reviewEntry,
19
+ hasReviewEvent,
20
+ reviewByEvent,
21
+ REVIEW_VERDICTS,
14
22
  } = require('../projections/recommendationPlanProjection');
15
23
  const {
16
24
  RECOMMENDATION_PLAN_SLUG,
17
25
  RECOMMENDATION_ELEMENTS_SLUG,
18
26
  RECOMMENDATION_REC_SLUG,
27
+ PALLIATIVE_CAREPLAN_REC_SLUG,
19
28
  } = require('../constants/projectionSlugs');
20
29
  const { getFhirStore } = require('../stores/fhirStore');
21
30
  const { logger } = require('../../utils/logger');
22
- const { storeResources } = require('./fhirService');
31
+ const { storeResources, keepTaskOutput } = require('./fhirService');
23
32
  const { safetyGateExists } = require('./riskService');
24
33
  const { getCatalog } = require('./terminologyService');
25
34
 
@@ -37,6 +46,7 @@ async function storeRecommendationPlan({
37
46
  const hasSafetyGate = await safetyGateExists({ runId: plan.runId });
38
47
  const { stored } = await storeResources(
39
48
  toFhir({ plan, hasSafetyGate, anchorAgainst, qualityWarnings, producedBy }),
49
+ keepTaskOutput,
40
50
  );
41
51
  return { count: stored.length, ids: stored };
42
52
  }
@@ -169,11 +179,109 @@ async function recordRecommendationOutcome({
169
179
  };
170
180
  }
171
181
 
182
+ const REVIEW_ACTIVITY = 'recommendation-review';
183
+ const REVIEW_TEXT_MAX = 4000;
184
+ const REVIEW_KEY_MAX = 200;
185
+ // RFC 5321 allows 254 characters for an address.
186
+ const REVIEWER_MAX = 254;
187
+
188
+ function optionalText(value, field, max) {
189
+ if (value === null || value === undefined) return null;
190
+ if (typeof value !== 'string') throw new Error(`invalid ${field}: must be a string when present.`);
191
+ const trimmed = value.trim();
192
+ if (!trimmed) return null;
193
+ if (trimmed.length > max) throw new Error(`invalid ${field}: must be at most ${max} characters.`);
194
+ return trimmed;
195
+ }
196
+
197
+ async function recordRecommendationReview({
198
+ patientId, recommendationId, verdict, note = null,
199
+ correctedText = null, reviewedBy, eventKey = null,
200
+ }) {
201
+ if (!REVIEW_VERDICTS.includes(verdict)) {
202
+ throw new Error(`invalid verdict: ${JSON.stringify(verdict)}. Must be one of ${JSON.stringify(REVIEW_VERDICTS)}.`);
203
+ }
204
+ if (reviewedBy !== null && reviewedBy !== undefined && typeof reviewedBy !== 'string') {
205
+ throw new Error('invalid reviewedBy: must be a string when present.');
206
+ }
207
+ const reviewer = optionalText(reviewedBy, 'reviewedBy', REVIEWER_MAX);
208
+ if (!reviewer) throw new Error('reviewedBy is required: a review with no reviewer is not a review.');
209
+ const reviewNote = optionalText(note, 'note', REVIEW_TEXT_MAX);
210
+ const correction = optionalText(correctedText, 'correctedText', REVIEW_TEXT_MAX);
211
+ const key = optionalText(eventKey, 'eventKey', REVIEW_KEY_MAX);
212
+ if (verdict === 'corrected' && !correction) {
213
+ throw new Error('a corrected verdict requires correctedText: naming the correction is the point.');
214
+ }
215
+
216
+ const target = await resolveTask({ patientId, recommendationId });
217
+ if (!target) return { recorded: false };
218
+
219
+ const recordedAt = toIso(new Date());
220
+ const output = reviewEntry({
221
+ verdict, note: reviewNote, correctedText: correction, reviewedBy: reviewer, recordedAt, eventKey: key,
222
+ });
223
+ const provenanceId = reviewProvenanceId(target.recommendationId, key || `${recordedAt}|${randomUUID()}`);
224
+ let duplicate = false;
225
+ let retained = null;
226
+ const write = await storeResources([target.task], {
227
+ merge: (prior, incoming) => {
228
+ duplicate = Boolean(key) && hasReviewEvent(prior, key);
229
+ if (duplicate) {
230
+ retained = reviewByEvent(prior, key);
231
+ return { ...incoming, output: prior.output };
232
+ }
233
+ return { ...incoming, output: [...(prior.output || []), output] };
234
+ },
235
+ });
236
+ if (write.skipped) return { recorded: false, skipped: write.skipped, recommendation_id: target.recommendationId };
237
+ const stored = {
238
+ verdict: retained?.verdict ?? verdict,
239
+ note: retained ? retained.note : reviewNote,
240
+ correctedText: retained ? retained.correctedText : correction,
241
+ reviewedBy: retained?.reviewedBy ?? reviewer,
242
+ recordedAt: retained?.recordedAt ?? recordedAt,
243
+ };
244
+
245
+ // Runs on the duplicate path too: a retry must still repair a Provenance that never landed.
246
+ const store = getFhirStore();
247
+ if (!await store.getByReference(`Provenance/${fhirId(provenanceId)}`)) {
248
+ await storeResources([provenance({
249
+ provenanceId,
250
+ targetRefs: [{ reference: `Task/${fhirId(target.recommendationId)}` }],
251
+ recordedAt: stored.recordedAt,
252
+ activity: codeableConcept(REVIEW_ACTIVITY),
253
+ agentWho: { ...reference('Practitioner', reviewerId(stored.reviewedBy)), display: stored.reviewedBy },
254
+ })]);
255
+ }
256
+
257
+ return {
258
+ recorded: !duplicate,
259
+ duplicate,
260
+ recommendation_id: target.recommendationId,
261
+ verdict: stored.verdict,
262
+ note: stored.note,
263
+ corrected_text: stored.correctedText,
264
+ reviewed_by: stored.reviewedBy,
265
+ recorded_at: stored.recordedAt,
266
+ };
267
+ }
268
+
269
+ // A card id reaches this code straight from a URL, so it is not proof of access.
270
+ const belongsToPatient = (task, patientId) => task?.for?.reference === patientReference(patientId).reference;
271
+
272
+ const cardIdOf = (task) => identifierValue(task, RECOMMENDATION_REC_SLUG)
273
+ || identifierValue(task, PALLIATIVE_CAREPLAN_REC_SLUG)
274
+ || null;
275
+
172
276
  async function resolveTask({ patientId, recommendationId, ctcaeTerm }) {
173
277
  const store = getFhirStore();
174
278
  if (recommendationId) {
175
279
  const task = await store.getByReference(`Task/${fhirId(recommendationId)}`);
176
- return task ? { task, recommendationId: identifierValue(task, RECOMMENDATION_REC_SLUG) || recommendationId } : null;
280
+ if (!task || !belongsToPatient(task, patientId)) return null;
281
+ // `fhirId()` is lossy, so a mangled or over-long id can normalise onto a real card.
282
+ const cardId = cardIdOf(task);
283
+ if (cardId !== recommendationId) return null;
284
+ return { task, recommendationId: cardId };
177
285
  }
178
286
  const termKeys = filterKeysFor(ctcaeTerm);
179
287
  if (!termKeys) return null;
@@ -181,7 +289,8 @@ async function resolveTask({ patientId, recommendationId, ctcaeTerm }) {
181
289
  const match = active.recommendations.find((item) => item.symptoms.some((symptom) => termKeys.has(keyOf(symptom))));
182
290
  if (!match) return null;
183
291
  const task = await store.getByReference(`Task/${fhirId(match.recommendation_id)}`);
184
- return task ? { task, recommendationId: match.recommendation_id } : null;
292
+ if (!task || !belongsToPatient(task, patientId)) return null;
293
+ return { task, recommendationId: match.recommendation_id };
185
294
  }
186
295
 
187
296
  function reconstructRecommendation(task, recommendationId, runId, isActive) {
@@ -205,6 +314,7 @@ function reconstructRecommendation(task, recommendationId, runId, isActive) {
205
314
 
206
315
  module.exports = {
207
316
  storeRecommendationPlan,
317
+ recordRecommendationReview,
208
318
  recommendationPlanExists,
209
319
  readActiveRecommendations,
210
320
  readRecommendationPlans,
@@ -27,7 +27,9 @@ class FhirStore {
27
27
  const resourceKey = model.resourceKeyOf(incoming);
28
28
  for (let attempt = 0; attempt < UPSERT_ATTEMPTS; attempt++) {
29
29
  const priorVersion = await model.findOne({ resourceKey }).lean();
30
- const resource = merge && priorVersion ? this._toStoredResource(merge(priorVersion.resource, incoming)) : incoming;
30
+ // Every merge reads `prior` as the live resource, and an upsert clears the tombstone.
31
+ const mergeable = priorVersion && !priorVersion.meta.deleted;
32
+ const resource = merge && mergeable ? this._toStoredResource(merge(priorVersion.resource, incoming)) : incoming;
31
33
  if (resource !== incoming && model.resourceKeyOf(resource) !== resourceKey) {
32
34
  throw new Error(`merge changed the resource key for ${resourceKey}`);
33
35
  }
@@ -12,6 +12,18 @@ const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLAB
12
12
  const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
13
13
  const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
14
14
 
15
+ const noteFactSchema = new mongoose.Schema({
16
+ variableId: { type: String, required: true },
17
+ concept: { type: String, default: null },
18
+ value: { type: String, required: true },
19
+ status: { type: String, default: null },
20
+ validTime: { type: String, default: null },
21
+ quote: { type: String, default: null },
22
+ callLogNumber: { type: Number, required: true },
23
+ state: { type: String, enum: ['proposed', 'settling', 'confirmed', 'declined'], default: 'proposed' },
24
+ settledBy: { type: String, default: null },
25
+ }, { timestamps: { createdAt: true, updatedAt: false } });
26
+
15
27
  const callLogSchema = new mongoose.Schema({
16
28
  outcome: { type: String, enum: CALL_OUTCOMES, required: true },
17
29
  notes: { type: String, default: null },
@@ -93,6 +105,7 @@ const escalationReviewSchema = new mongoose.Schema({
93
105
  openedBy: { type: String, required: true },
94
106
  assistantPausedByReview: { type: Boolean, default: false },
95
107
  callLogs: { type: [callLogSchema], default: [] },
108
+ noteFacts: { type: [noteFactSchema], default: [] },
96
109
  drafts: { type: [draftSchema], default: [] },
97
110
  doctorHandoffs: { type: [doctorHandoffSchema], default: [] },
98
111
  decisions: { type: [decisionSchema], default: [] },
@@ -70,6 +70,7 @@ const patientRouteDefinitions = {
70
70
  'GET /:code': 'getPatientInfoController',
71
71
  'GET /triage/:code': 'getPatientTriageInfoController',
72
72
  'GET /careplan/:code': 'getPatientCarePlanController',
73
+ 'PATCH /careplan/:code/cards/:cardId/review': 'reviewPatientCarePlanCardController',
73
74
  'GET /escalation-context/:code': 'getPatientEscalationContextController',
74
75
  'GET /tasks/:code': 'getPatientTasksController',
75
76
  'PATCH /:code': 'updatePatientController',
@@ -124,6 +125,7 @@ const escalationReviewRouteDefinitions = {
124
125
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
125
126
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
126
127
  'POST /:id/key-questions': 'suggestEscalationReviewQuestionsController',
128
+ 'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
127
129
  'POST /:id/drafts': 'addEscalationReviewDraftController',
128
130
  'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
129
131
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
@@ -233,6 +235,7 @@ const builtInControllers = {
233
235
  getPatientInfoController: patientController.getPatientInfoController,
234
236
  getPatientTriageInfoController: patientController.getPatientTriageInfoController,
235
237
  getPatientCarePlanController: patientController.getPatientCarePlanController,
238
+ reviewPatientCarePlanCardController: patientController.reviewPatientCarePlanCardController,
236
239
  getPatientEscalationContextController: patientController.getPatientEscalationContextController,
237
240
  getPatientTasksController: patientController.getPatientTasksController,
238
241
  getPatientRecommendationCarouselsController: patientController.getPatientRecommendationCarouselsController,
@@ -287,6 +290,7 @@ const builtInControllers = {
287
290
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
288
291
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
289
292
  suggestEscalationReviewQuestionsController: escalationReviewController.suggestEscalationReviewQuestionsController,
293
+ confirmEscalationReviewNoteFactsController: escalationReviewController.confirmEscalationReviewNoteFactsController,
290
294
  addEscalationReviewDraftController: escalationReviewController.addEscalationReviewDraftController,
291
295
  handOffEscalationReviewController: escalationReviewController.handOffEscalationReviewController,
292
296
  recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
@@ -30,7 +30,10 @@ const DEFAULT_LIMIT = 20;
30
30
  const FAILED_CURRENT_STATE = Symbol('currentStateUnavailable');
31
31
  const ESCALATION_LOOKBACK_MS = 365 * 24 * 60 * 60 * 1000;
32
32
 
33
- const cardOf = ({ id, rank, nameShort, type, ctcaeTerms, patient, internal, outcome = null, outcomeHistory = [] }) => ({
33
+ const cardOf = ({
34
+ id, rank, nameShort, type, ctcaeTerms, patient, internal,
35
+ outcome = null, outcomeHistory = [], reviewHistory = [],
36
+ }) => ({
34
37
  id,
35
38
  rank,
36
39
  nameShort,
@@ -40,6 +43,7 @@ const cardOf = ({ id, rank, nameShort, type, ctcaeTerms, patient, internal, outc
40
43
  internal,
41
44
  outcome,
42
45
  outcomeHistory,
46
+ reviewHistory,
43
47
  });
44
48
 
45
49
  const emptyEscalation = { urgentUnder24h: false, maxActionTimeHours: null, routes: [], clinicalCriteria: null };
@@ -98,6 +102,7 @@ function recommendationCards(plan) {
98
102
  },
99
103
  outcome: element.latestOutcome,
100
104
  outcomeHistory: element.outcomeHistory,
105
+ reviewHistory: element.reviewHistory || [],
101
106
  }));
102
107
  }
103
108
 
@@ -143,6 +148,7 @@ function palliativeCards(carePlan, findingsByRank) {
143
148
  auditNotes: finding?.auditNotes ?? null,
144
149
  clusterNote: finding?.clusterNote ?? null,
145
150
  },
151
+ reviewHistory: recommendation.reviewHistory || [],
146
152
  });
147
153
  });
148
154
  }
@@ -19,6 +19,8 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
19
19
  const { sendMessage } = require('../core/NexusMessaging');
20
20
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
21
21
  const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
22
+ const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
23
+ const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
22
24
 
23
25
  const { getPatientInformation, logPatientChange } = require('./patientService');
24
26
  const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
@@ -545,7 +547,8 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
545
547
  ? await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting' } })
546
548
  : await appendKeepingDraft(reviewId, entry);
547
549
  await audit(review, operator, requestId, { action: 'call_logged', outcome });
548
- return review;
550
+ if (outcome !== 'contacted') return review;
551
+ return proposeNoteFacts(review, operator, requestId);
549
552
  }
550
553
 
551
554
  // Generation writes nothing: it fills the two boxes the navigator then edits and saves with addDraft.
@@ -587,6 +590,121 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
587
590
  return draft;
588
591
  }
589
592
 
593
+ async function noteFactsContext(review) {
594
+ try {
595
+ return await readContextFacts({ patientId: review.patientCode });
596
+ } catch (error) {
597
+ logger.warn('[EscalationReview] The clinical context could not be read for the call note', {
598
+ escalationReviewId: String(review._id), error: error.message,
599
+ });
600
+ return null;
601
+ }
602
+ }
603
+
604
+ async function proposeNoteFacts(review, operator, requestId) {
605
+ try {
606
+ const callLogNumber = review.callLogs.length;
607
+ const note = review.callLogs[callLogNumber - 1]?.notes;
608
+ if (!String(note ?? '').trim()) return review;
609
+
610
+ const read = await readNoteFacts({
611
+ note, clinicalContext: await noteFactsContext(review), reviewId: String(review._id),
612
+ });
613
+ if (read.attempted) {
614
+ await audit(review, operator, requestId, read.completed
615
+ ? { action: 'note_facts_proposed', count: read.facts.length }
616
+ : { action: 'note_facts_reading_failed', reason: redactedError({ message: read.reason }) });
617
+ }
618
+ if (!read.facts.length) return review;
619
+
620
+ const proposed = read.facts.map((fact) => ({ ...fact, callLogNumber, state: 'proposed' }));
621
+ const updated = await getEscalationReview()
622
+ .findOneAndUpdate({ _id: review._id }, { $push: { noteFacts: { $each: proposed } } }, { new: true })
623
+ .lean();
624
+ return updated ?? review;
625
+ } catch (error) {
626
+ logger.error('[EscalationReview] The call note could not be read for facts', {
627
+ escalationReviewId: String(review._id), error: error.message, stack: redactedStack(error),
628
+ });
629
+ return review;
630
+ }
631
+ }
632
+
633
+ function factIndexes(values, field) {
634
+ if (!Array.isArray(values)) throw httpError(400, `${field} must be an array`);
635
+ const indexes = new Set();
636
+ for (const value of values) {
637
+ if (!Number.isInteger(value) || value < 0) throw httpError(400, `${field} must hold whole indexes`);
638
+ if (indexes.has(value)) throw httpError(400, `${field} names the same fact twice`);
639
+ indexes.add(value);
640
+ }
641
+ return indexes;
642
+ }
643
+
644
+ async function confirmNoteFacts({ id, accepted = [], declined = [], confirmedBy, requestId = null, now = new Date() } = {}) {
645
+ const reviewId = reviewIdOf(id);
646
+ const operator = requiredText(confirmedBy, 'confirmedBy');
647
+ const wanted = factIndexes(accepted, 'accepted');
648
+ const refused = factIndexes(declined, 'declined');
649
+ const both = [...wanted].find((index) => refused.has(index));
650
+ if (both !== undefined) throw httpError(400, 'A fact cannot be accepted and declined at once');
651
+
652
+ const review = await loadReview(reviewId);
653
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
654
+ const proposed = (review.noteFacts ?? []).map((fact, index) => ({ fact, index }))
655
+ .filter(({ fact }) => fact.state === 'proposed');
656
+ const unknown = [...wanted, ...refused].find((index) => !proposed.some((entry) => entry.index === index));
657
+ if (unknown !== undefined) throw httpError(409, 'That fact is not waiting to be confirmed');
658
+ if (!wanted.size && !refused.size) return review;
659
+
660
+ // Nothing is final until the record has taken it, declines included: a request that fails
661
+ // halfway has to leave the whole selection offerable again.
662
+ const claim = { _id: reviewId, status: { $in: DOCUMENTING_STATUSES } };
663
+ const claimed = {};
664
+ for (const index of [...wanted, ...refused]) {
665
+ claim[`noteFacts.${index}.state`] = 'proposed';
666
+ claimed[`noteFacts.${index}.state`] = 'settling';
667
+ claimed[`noteFacts.${index}.settledBy`] = operator;
668
+ }
669
+ const held = await getEscalationReview().findOneAndUpdate(claim, { $set: claimed }, { new: true }).lean();
670
+ if (!held) throw httpError(409, 'That fact is not waiting to be confirmed');
671
+
672
+ // One fact at a time: storeResources writes sequentially and does not roll back, so a batch that
673
+ // throws can already have written part of itself. Stored is the only thing we can prove.
674
+ const stored = new Set();
675
+ let failure = null;
676
+ for (const { fact, index } of proposed.filter((entry) => wanted.has(entry.index))) {
677
+ try {
678
+ await storeContextFacts({
679
+ patientId: review.patientCode,
680
+ assertions: [assertionOf(fact, { patientId: review.patientCode, now })],
681
+ });
682
+ stored.add(index);
683
+ } catch (error) {
684
+ failure = error;
685
+ break;
686
+ }
687
+ }
688
+
689
+ const settle = {};
690
+ for (const index of wanted) settle[`noteFacts.${index}.state`] = stored.has(index) ? 'confirmed' : 'proposed';
691
+ for (const index of refused) settle[`noteFacts.${index}.state`] = failure ? 'proposed' : 'declined';
692
+ const updated = await getEscalationReview()
693
+ .findOneAndUpdate({ _id: reviewId }, { $set: settle }, { new: true }).lean()
694
+ .catch((error) => {
695
+ logger.error('[EscalationReview] The note facts were written but could not be settled', {
696
+ escalationReviewId: String(reviewId), stored: stored.size, error: error.message,
697
+ });
698
+ return null;
699
+ });
700
+
701
+ await audit(updated ?? held, operator, requestId, {
702
+ action: 'note_facts_settled', confirmed: stored.size, declined: failure ? 0 : refused.size,
703
+ });
704
+ if (failure) throw failure;
705
+ return updated ?? held;
706
+ }
707
+
590
708
  async function suggestKeyQuestions({ id, requestedBy, requestId = null } = {}) {
591
709
  const reviewId = reviewIdOf(id);
592
710
  const operator = requiredText(requestedBy, 'requestedBy');
@@ -882,5 +1000,6 @@ module.exports = {
882
1000
  setReviewCases,
883
1001
  suggestDraft,
884
1002
  suggestKeyQuestions,
1003
+ confirmNoteFacts,
885
1004
  syncEscalationReviewCase,
886
1005
  };
@@ -6,7 +6,7 @@ const { Thread } = require('../models/threadModel');
6
6
  const { botIsPaused } = require('../helpers/pausedThreadHelper');
7
7
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
8
8
  const { inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
9
- const { recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
9
+ const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
10
10
  const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
11
11
  const { getMessages, countMessages, aggregateMessages } = require('./messageService');
12
12
 
@@ -24,6 +24,7 @@ const recoveryClaims = new WriteClaimStore({ namespace: 'inbound-recovery', ttlM
24
24
  const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
25
25
 
26
26
  const FAILED_SEND = { 'statusInfo.status': 'failed', message_id: null };
27
+ const UNANSWERED_QUESTION = 'El paciente escribió y no recibió respuesta.';
27
28
 
28
29
  async function unansweredThreads(now) {
29
30
  return Thread.find(
@@ -67,9 +68,17 @@ async function stillUnanswered(code, now = new Date()) {
67
68
  return replies === 0 ? newest : null;
68
69
  }
69
70
 
70
- async function fileTicket(code, alert) {
71
+ // This sweep only ever looks at the last hour, so minutes is the only unit it can reach.
72
+ const waitedFor = (ageMs) => `lleva ${Math.max(0, Math.round(ageMs / 60000))} min sin respuesta`;
73
+
74
+ async function fileTicket(code, alert, ageMs) {
71
75
  try {
72
- return Boolean(await alert({ code, category: 'contact_team_member', question: 'El paciente escribió y no recibió respuesta.' }));
76
+ return Boolean(await alert({
77
+ code,
78
+ category: 'contact_team_member',
79
+ question: UNANSWERED_QUESTION,
80
+ details: formatOpsAlert(code, { label: 'Paciente sin respuesta', summary: waitedFor(ageMs) }),
81
+ }));
73
82
  } catch (error) {
74
83
  logger.error('[inboundRecovery] could not file the ops ticket', { code, error: error.message });
75
84
  return false;
@@ -142,7 +151,7 @@ async function sweepUnansweredInbound({
142
151
  if (ticket !== 'acquired') { skipped += 1; continue; }
143
152
 
144
153
  logger.error('[inboundRecovery] a replay already ran and the patient is still unanswered', { code, ageMs });
145
- if (await fileTicket(code, alert)) {
154
+ if (await fileTicket(code, alert, ageMs)) {
146
155
  alerted += 1;
147
156
  } else {
148
157
  await ticketGate.release(key);
@@ -168,7 +177,7 @@ async function sweepUnansweredInbound({
168
177
  logger.error('[inboundRecovery] patient was left unanswered', {
169
178
  code, ageMs, recoveryLive: canRecover, reachable,
170
179
  });
171
- if (await fileTicket(code, alert)) {
180
+ if (await fileTicket(code, alert, ageMs)) {
172
181
  alerted += 1;
173
182
  } else {
174
183
  await claims.release(key);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.56.10",
3
+ "version": "5.56.13",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",