@peopl-health/nexus 5.56.0-dev.8527 → 5.56.0-dev.8530

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.
@@ -258,6 +258,7 @@ async function handleSafetyNetTap({ code, payload, title }) {
258
258
  if (!claim.acquired) return { handled: true, choice, reason: 'concurrent_tap' };
259
259
 
260
260
  let acknowledged = false;
261
+ let filed = true;
261
262
  try {
262
263
  if (!await offerIsLive(code)) {
263
264
  acknowledged = await sendAck(code, choice, { queued: true, pledge: null, repeated: false, stale: true });
@@ -273,17 +274,18 @@ async function handleSafetyNetTap({ code, payload, title }) {
273
274
  if (!repeated) {
274
275
  try {
275
276
  outcome = { ...await applyChoice(code, choice), repeated: false };
276
- await tapClaims().set(code, choice);
277
+ if (outcome.queued) await tapClaims().set(code, choice);
277
278
  } catch (error) {
278
279
  logger.error('[PausedSafetyNet] Could not record the tap', { code, choice, error: error.message });
279
280
  outcome = { queued: false, pledge: null, repeated: false };
280
281
  }
282
+ filed = outcome.queued;
281
283
  }
282
284
 
283
285
  acknowledged = await sendAck(code, effective, outcome);
284
286
  return { handled: true, choice: effective, ...outcome };
285
287
  } finally {
286
- if (acknowledged) await completeSendClaim(claim.claimId);
288
+ if (acknowledged && filed) await completeSendClaim(claim.claimId);
287
289
  else await releaseSendClaim(claim.claimId);
288
290
  }
289
291
  }
@@ -5,7 +5,7 @@ const { logger } = require('../../utils/logger');
5
5
 
6
6
  const definition = {
7
7
  'name': 'reportResultsReceived',
8
- 'description': '**Does:** Logs the receipt of patient-shared medical results (labs, imaging, pathology, numeric values, attachments) and records an oncologist-review intent on the turn trace (the team-queue notification is a downstream slice). Emits FHIR `Observation` + `Provenance` resources directly when `observations[]` is passed.\n\n**Required inputs:** `patient_verbatim` (LITERAL copy of the values and words the patient wrote — never interpreted), `result_type` (`lab` | `imaging` | `pathology` | `numeric_values` | `attachment` | `other`); optional `study_name`, `result_date`.\n\n**Required when `patient_verbatim` contains numeric values:** `observations` — flat list of items, NOT FHIR shapes. Each item: `{code: str, value: number|str, unit: str|None (e.g. "g/dL", "mmHg", "°C", "10^9/L"), effective: ISO8601 str|None}`. Without `observations[]` the audit lane stays empty and the system stamps the result `degraded` with reason `observations_should_have_been_passed_text_contains_numbers`.\n\n**Examples:**\n- Patient says *"hemoglobina 8.5 g/dL, neutrofilos 0.7"* → `observations=[{code: "hemoglobin", value: 8.5, unit: "g/dL"}, {code: "neutrophils", value: 0.7, unit: "10^9/L"}]`.\n- Patient says *"me tomaron la presión 140/90 y la temperatura 38.5"* → `observations=[{code: "systolic-blood-pressure", value: 140, unit: "mmHg"}, {code: "diastolic-blood-pressure", value: 90, unit: "mmHg"}, {code: "body-temperature", value: 38.5, unit: "°C"}]`.\n- Patient shares a PDF / image / prose WITHOUT numbers → omit `observations` (workflow notification only).\n\n**When to call:** the patient is SHARING raw data — values, attachments, study names with findings. Trigger phrases: "te mando los resultados", "aquí están mis análisis", "hemoglobina 9.1", "mi TAC salió…", PDF/photo of a study, any clinical number from the patient. Takes precedence over `extractClinicalInfo` when the primary event is "results shared".\n\n**`patient_verbatim` is a quote, not a summary.** Copy the words as they reached you. When the values did NOT come from a message the patient typed — a photo of a device or a lab sheet, or an audio — you MUST set `source` to `image_analysis` or `audio_transcript` and paste the analysis or transcript line itself. NEVER compose first-person wording the patient never said (no “Buenos días, soy X, mi presión es…”): that files a fabricated quote in the review queue the oncologist reads. The team is shown which of the three sources the text came from.\n\n**When NOT to call:**\n- Patient is narrating news from the team WITHOUT sharing the data — use `extractClinicalInfo` with the matching `detected_tags` (e.g. `[\'lab_value\']` or `[\'diagnosis\']`).\n- Medical emergency / escalation, including a symptom that persists or worsens — use `reportMedicalEscalation`.\n- Mental-health crisis — use `reportCrisis`.\n- Administrative / operative request — use `reportUnresolvedRequestv2`.\n\n**Hard rule on the subsequent `DeliverPatientMessage`:** NEVER interpret values or findings; NEVER say "está bien / está mal / es normal / está bajo / está alto"; NEVER compare against reference ranges; NEVER repeat the values back to the patient. Confirm receipt only ("recibí tus resultados y quedaron registrados para tu equipo; te avisan en cuanto los revisen", `purpose=\'deliver_escalation\'`).\n\n**Returns:** `result_id` + `result_slug`. `observations_not_stored` appears when the audit lane suppressed the write: `fhir_observation_count` is 0, `degraded` is True and the reason names the suppression, not a missing `observations[]` — re-issuing will not help. `observation_rejected_count` is still reported alongside it when some items were dropped for a missing `code`, since that is a payload problem a retry CAN fix (`result_type` is returned only when an out-of-enum value was coerced to `other`). With `observations[]`: also `fhir_observation_count` + `observation_ids` (the FHIR bodies live on the audit lane, not on this result), and `observation_rejected_count` when some items were dropped for a missing `code`. On the numeric-miss branch: `degraded=True`, `degraded_reasons` — re-issue with `observations[]`.\n\n**Side effects:** Records the result + oncologist-review intent on the turn trace (the team-queue notification is a downstream slice); writes one FHIR `Observation` per structured observation plus a single linking `Provenance`.',
8
+ 'description': '**Does:** Logs the receipt of patient-shared medical results (labs, imaging, pathology, numeric values, attachments) and records an oncologist-review intent on the turn trace (the team-queue notification is a downstream slice). Emits FHIR `Observation` + `Provenance` resources directly when `observations[]` is passed.\n\n**Required inputs:** `patient_verbatim` (LITERAL copy of the values and words the patient wrote — never interpreted), `result_type` (`lab` | `imaging` | `pathology` | `numeric_values` | `attachment` | `other`); optional `study_name`, `result_date`.\n\n**Required when `patient_verbatim` contains numeric values:** `observations` — flat list of items, NOT FHIR shapes. Each item: `{code: str, value: number|str, unit: str|None (e.g. "g/dL", "mmHg", "°C", "10^9/L"), effective: ISO8601 str|None}`. Without `observations[]` the audit lane stays empty and the system stamps the result `degraded` with reason `observations_should_have_been_passed_text_contains_numbers`.\n\n**Examples:**\n- Patient says *"hemoglobina 8.5 g/dL, neutrofilos 0.7"* → `observations=[{code: "hemoglobin", value: 8.5, unit: "g/dL"}, {code: "neutrophils", value: 0.7, unit: "10^9/L"}]`.\n- Patient says *"me tomaron la presión 140/90 y la temperatura 38.5"* → `observations=[{code: "systolic-blood-pressure", value: 140, unit: "mmHg"}, {code: "diastolic-blood-pressure", value: 90, unit: "mmHg"}, {code: "body-temperature", value: 38.5, unit: "°C"}]`.\n- Patient shares a PDF / image / prose WITHOUT numbers → omit `observations` (workflow notification only).\n\n**When to call:** the patient is SHARING raw data — values, attachments, study names with findings. Trigger phrases: "te mando los resultados", "aquí están mis análisis", "hemoglobina 9.1", "mi TAC salió…", PDF/photo of a study, any clinical number from the patient. Takes precedence over `extractClinicalInfo` when the primary event is "results shared".\n\n**`patient_verbatim` is a quote, not a summary.** Copy the words as they reached you. When the values did NOT come from a message the patient typed — a photo of a device or a lab sheet, or an audio — you MUST set `source` to `image_analysis` or `audio_transcript` and paste the analysis or transcript line itself. NEVER compose first-person wording the patient never said (no “Buenos días, soy X, mi presión es…”): that files a fabricated quote in the review queue the oncologist reads. The team is shown which of the three sources the text came from.\n\n**When NOT to call:**\n- Patient is narrating news from the team WITHOUT sharing the data — use `extractClinicalInfo` with the matching `detected_tags` (e.g. `[\'lab_value\']` or `[\'diagnosis\']`).\n- Medical emergency / escalation, including a symptom that persists or worsens — use `reportMedicalEscalation`.\n- Mental-health crisis — use `reportCrisis`.\n- Administrative / operative request — use `reportUnresolvedRequestv2`.\n\n**Hard rule on the subsequent `DeliverPatientMessage`:** NEVER interpret values or findings; NEVER say "está bien / está mal / es normal / está bajo / está alto"; NEVER compare against reference ranges; NEVER repeat the values back to the patient. Confirm receipt only ("recibí tus resultados y quedaron registrados para tu equipo; te avisan en cuanto los revisen", `purpose=\'deliver_escalation\'`) — unless the result carries `queued: false` (see Returns).\n\n**Returns:** `result_id` + `result_slug`. If the results review could not be queued to the team it comes back with `queued: false` — do NOT tell the patient the results were registered for the team in that case; acknowledge receipt and say you are still working on it. `observations_not_stored` appears when the audit lane suppressed the write: `fhir_observation_count` is 0, `degraded` is True and the reason names the suppression, not a missing `observations[]` — re-issuing will not help. `observation_rejected_count` is still reported alongside it when some items were dropped for a missing `code`, since that is a payload problem a retry CAN fix (`result_type` is returned only when an out-of-enum value was coerced to `other`). With `observations[]`: also `fhir_observation_count` + `observation_ids` (the FHIR bodies live on the audit lane, not on this result), and `observation_rejected_count` when some items were dropped for a missing `code`. On the numeric-miss branch: `degraded=True`, `degraded_reasons` — re-issue with `observations[]`.\n\n**Side effects:** Records the result + oncologist-review intent on the turn trace (the team-queue notification is a downstream slice); writes one FHIR `Observation` per structured observation plus a single linking `Provenance`.',
9
9
  'strict': false,
10
10
  'parameters': {
11
11
  'type': 'object',
@@ -120,7 +120,7 @@ async function handler(args = {}, context = {}) {
120
120
  logger.warn('[reportResultsReceived] no trace on runtime context; results-received signal not recorded', { turnId: runtime.turnId });
121
121
  }
122
122
 
123
- await recordUnresolvedRequest({
123
+ const queued = await recordUnresolvedRequest({
124
124
  code: runtime.patientCode,
125
125
  trace,
126
126
  question: ['Resultados recibidos:', resultType, studyName].filter(Boolean).join(' '),
@@ -131,6 +131,13 @@ async function handler(args = {}, context = {}) {
131
131
 
132
132
  const data = { result_id: resultId, result_slug: resultSlug };
133
133
  if (resultType !== rawType) data.result_type = resultType;
134
+ if (!queued) {
135
+ data.queued = false;
136
+ logger.error('[reportResultsReceived] Results review not queued — the team was not notified', {
137
+ patientCode: runtime.patientCode || null,
138
+ reason: 'airtable_write_failed',
139
+ });
140
+ }
134
141
 
135
142
  const observations = Array.isArray(args?.observations) ? args.observations : [];
136
143
  if (observations.length) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.56.0-dev.8527",
3
+ "version": "5.56.0-dev.8530",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",