@peopl-health/nexus 5.61.0-dev.11186 → 5.61.0-dev.11231

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.
@@ -15,7 +15,6 @@ const { isContingencyCancelOnReplyLive } = require('./flags/contingencyFlags');
15
15
  const { maybeWarmPatientRisk } = require('./services/riskAssessmentService');
16
16
  const { settleClaimedDelivery } = require('./services/deliverySettlementService');
17
17
  const { ToolRuntimeContext } = require('./context/ToolRuntimeContext');
18
- const { reviewUpdateOf } = require('./helpers/reviewUpdateHelper');
19
18
  const { resolveTurnContext, TURN_KIND } = require('./context/turnContext');
20
19
 
21
20
  const traceContingency = (net) => ({
@@ -257,21 +256,6 @@ class AssistantProcessor {
257
256
  });
258
257
  }
259
258
 
260
- if (traceStored && !runOptions.shadow) {
261
- const update = reviewUpdateOf({
262
- turnId: ctx.turnId,
263
- toolHistory: ctx.toolHistory,
264
- signals: ctx.trace?.signals,
265
- patientText: ctx.patientInput?.text,
266
- });
267
- if (update) {
268
- // Required here: escalationReviewService reaches this module through NexusMessaging.
269
- const { recordReviewUpdate } = require('../services/escalationReviewService');
270
- // Awaited so it lands before the turn returns; it never throws and never fails the reply.
271
- await recordReviewUpdate({ code: thread.code, update });
272
- }
273
- }
274
-
275
259
  const run = runResult?.run;
276
260
 
277
261
  return {
@@ -17,6 +17,7 @@ const TRIAGE_PLAN_DEFAULTS = { presetId: '' };
17
17
  const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
18
18
  const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
19
19
  const ESCALATION_NOTE_FACTS_DEFAULTS = { presetId: '' };
20
+ const SUPPORT_LIGHT_DEFAULTS = { presetId: '' };
20
21
 
21
22
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
22
23
 
@@ -66,7 +67,11 @@ async function load() {
66
67
  if (byKey.ESCALATION_NOTE_FACTS && !isPlainObject(parsedNoteFacts)) throw new Error('subAgents config ESCALATION_NOTE_FACTS is not a JSON object');
67
68
  const escalationNoteFacts = { ...ESCALATION_NOTE_FACTS_DEFAULTS, ...(parsedNoteFacts || {}) };
68
69
 
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 };
70
+ const parsedSupportLight = safeParse(byKey.SUPPORT_LIGHT, null);
71
+ if (byKey.SUPPORT_LIGHT && !isPlainObject(parsedSupportLight)) throw new Error('subAgents config SUPPORT_LIGHT is not a JSON object');
72
+ const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(parsedSupportLight || {}) };
73
+
74
+ 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, SUPPORT_LIGHT: supportLight };
70
75
  cache.set(CACHE_KEY, config);
71
76
  return config;
72
77
  }
@@ -85,4 +90,5 @@ module.exports = {
85
90
  getEscalationDraft: () => get('ESCALATION_DRAFT'),
86
91
  getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
87
92
  getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
93
+ getSupportLightEvaluator: () => get('SUPPORT_LIGHT'),
88
94
  };
@@ -56,6 +56,13 @@ const supportLightEventSchema = new mongoose.Schema({
56
56
  supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
57
57
  supportLightEventSchema.index({ patientId: 1, at: -1 });
58
58
 
59
+ const supportLightSweepSchema = new mongoose.Schema({
60
+ patientId: { type: String, required: true, unique: true },
61
+ lastAttemptAt: { type: Date, required: true },
62
+ lastEvaluatedAt: { type: Date, default: null },
63
+ lastOutcome: { type: String, required: true },
64
+ }, { timestamps: true });
65
+
59
66
  function getSupportLightModel() {
60
67
  const conn = clinicalConnection();
61
68
  return conn.models.SupportLight || conn.model('SupportLight', supportLightSchema, 'supportLights');
@@ -67,6 +74,17 @@ function getSupportLightEventModel() {
67
74
  || conn.model('SupportLightEvent', supportLightEventSchema, 'supportLightEvents');
68
75
  }
69
76
 
77
+ function getSupportLightSweepModel() {
78
+ const conn = clinicalConnection();
79
+ return conn.models.SupportLightSweep
80
+ || conn.model('SupportLightSweep', supportLightSweepSchema, 'supportLightSweeps');
81
+ }
82
+
70
83
  module.exports = {
71
- getSupportLightModel, getSupportLightEventModel, supportLightSchema, supportLightEventSchema,
84
+ getSupportLightModel,
85
+ getSupportLightEventModel,
86
+ getSupportLightSweepModel,
87
+ supportLightSchema,
88
+ supportLightEventSchema,
89
+ supportLightSweepSchema,
72
90
  };
@@ -45,14 +45,7 @@ function settleProposal(parsed) {
45
45
  return valid ? { proposal, withheldReason: null, strippedItems: 0 } : { invalid: issues };
46
46
  }
47
47
 
48
- const textList = (value) => (Array.isArray(value) ? value.map(trimmed).filter(Boolean) : []);
49
-
50
- function suggestCallOf(value) {
51
- if (typeof value?.value !== 'boolean') return null;
52
- return { value: value.value, reason: trimmed(value.reason) || null };
53
- }
54
-
55
- function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null }) {
48
+ function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
56
49
  const conversation = Array.isArray(context?.conversation)
57
50
  ? context.conversation.slice(-CONVERSATION_TURNS)
58
51
  : context?.conversation ?? null;
@@ -65,7 +58,6 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharac
65
58
  protocolVersion: FORMULARY_VERSION,
66
59
  protocol,
67
60
  alarms,
68
- agentCharacterization,
69
61
  patient: {
70
62
  clinicalContext: context?.agentContext ?? null,
71
63
  conversation,
@@ -91,9 +83,7 @@ function draftProvider() {
91
83
  }
92
84
  }
93
85
 
94
- async function generateEscalationDraft({
95
- code, callLogs = [], alarms = [], agentCharacterization = null, provider, trace = null, reviewId = null, now = Date.now(),
96
- } = {}) {
86
+ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
97
87
  const { presetId } = await getEscalationDraft();
98
88
  const llm = provider ?? draftProvider();
99
89
 
@@ -102,7 +92,7 @@ async function generateEscalationDraft({
102
92
  }
103
93
 
104
94
  const context = await getEscalationContext({ code, now });
105
- const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms, agentCharacterization });
95
+ const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms });
106
96
 
107
97
  // Past this point a generation run was issued. Whether the request actually left the process is
108
98
  // not knowable here — the provider resolves the preset and validates the schema before it calls
@@ -175,10 +165,6 @@ async function generateEscalationDraft({
175
165
  doctorText,
176
166
  patientMessage,
177
167
  protocolVersion: FORMULARY_VERSION,
178
- keyQuestions: textList(parsed?.keyQuestions),
179
- unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
180
- missingCharacterization: textList(parsed?.missingCharacterization),
181
- suggestCall: suggestCallOf(parsed?.suggestCall),
182
168
  sectionsUnavailable: context.degradedSections ?? [],
183
169
  };
184
170
  }
@@ -4,20 +4,34 @@ const { objectArg } = require('../../utils/jsonUtils');
4
4
 
5
5
  const EXTRACTION_TOOL = 'extractClinicalInfo';
6
6
  const LOOKUP_TOOL = 'lookupCtcaeEntry';
7
+ const LANDSCAPE_TOOLS = ['getRouterContextBundle', 'getActiveSymptomLandscape'];
8
+ const IMPRESSION_TOOLS = ['openCondition', 'recordClinicalImpression'];
7
9
 
8
10
  const populated = (grades) => !!grades && Object.keys(grades).length > 0;
9
11
 
10
- function gradesDefined(ctcaeTerm) {
11
- let scale = null;
12
+ function catalogScale(ctcaeTerm) {
12
13
  try {
13
- scale = getCtcaeCatalog().getGradeScale(ctcaeTerm);
14
+ const scale = getCtcaeCatalog().getGradeScale(ctcaeTerm);
15
+ return populated(scale) ? scale : null;
14
16
  } catch {
15
17
  return null;
16
18
  }
17
- const keys = Object.keys(scale || {});
18
- return keys.length ? keys : null;
19
19
  }
20
20
 
21
+ function gradesDefined(ctcaeTerm) {
22
+ const scale = catalogScale(ctcaeTerm);
23
+ return scale ? Object.keys(scale) : null;
24
+ }
25
+
26
+ // The refusal below prints the scale after this mark, so a retry in the same turn has read it.
27
+ const scaleDeliveredMark = (ctcaeTerm) => `CTCAE grade_scale for '${ctcaeTerm}':`;
28
+
29
+ const landscapeCases = (payload) => {
30
+ const data = payload.data || payload;
31
+ const cases = data?.landscape?.active_cases || data?.active_cases;
32
+ return Array.isArray(cases) ? cases : [];
33
+ };
34
+
21
35
  function ladderReachedModel(trace, ctcaeTerm) {
22
36
  if (!ctcaeTerm) return false;
23
37
  const steps = Array.isArray(trace?.steps) ? trace.steps : [];
@@ -32,6 +46,10 @@ function ladderReachedModel(trace, ctcaeTerm) {
32
46
  const entry = payload.data?.entry || payload.entry;
33
47
  if (entry?.ctcae_term === ctcaeTerm && populated(entry.grades)) return true;
34
48
  }
49
+ if (LANDSCAPE_TOOLS.includes(step.tool_name)
50
+ && landscapeCases(payload).some((c) => c?.ctcae_term === ctcaeTerm && populated(c?.grade_scale))) return true;
51
+ if (IMPRESSION_TOOLS.includes(step.tool_name)
52
+ && typeof payload.error === 'string' && payload.error.includes(scaleDeliveredMark(ctcaeTerm))) return true;
35
53
  }
36
54
  return false;
37
55
  }
@@ -101,9 +119,16 @@ function noCuratedRubric(ctcaeTerm) {
101
119
  }
102
120
 
103
121
  function missingLadder(ctcaeTerm) {
104
- return `source is 'agent_adjudicated' but the ${ctcaeTerm} grade scale did not reach you this turn, so there was no rubric to adjudicate against. `
105
- + `Call lookupCtcaeEntry for '${ctcaeTerm}' and grade from the clauses it returns; if it has no ladder, declare the grade `
106
- + '\'proctcae_composite\' or \'carried_forward\', or drop best_estimate AND source together and record possible_range alone.';
122
+ const head = `source is 'agent_adjudicated' but the ${ctcaeTerm} grade scale did not reach you this turn, so there was no rubric to adjudicate against.`;
123
+ const scale = catalogScale(ctcaeTerm);
124
+ // Without the catalog the lookup may fail too, so the ungraded record stays available as the way out.
125
+ if (!scale) {
126
+ return `${head} Call lookupCtcaeEntry for '${ctcaeTerm}' and grade from the clauses it returns. `
127
+ + 'If the lookup cannot return the scale, drop best_estimate AND source together and record possible_range alone.';
128
+ }
129
+ return `${head} Here it is — ${scaleDeliveredMark(ctcaeTerm)} ${JSON.stringify(scale)}. `
130
+ + 'Read what the patient reported against these clauses, set matched_grade to the clause the evidence meets, '
131
+ + 'and re-issue the call with the grade that clause supports. Keep best_estimate: a graded read is what the case needs.';
107
132
  }
108
133
 
109
134
  module.exports = {
@@ -0,0 +1,159 @@
1
+ const { requireGatewayProvider } = require('../config/llmConfig');
2
+ const { getSupportLightEvaluator } = require('../config/subAgentsConfig');
3
+ const { getSupportLightSweepModel } = require('../models/supportLightModel');
4
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
5
+ const { getMessages, aggregateMessages } = require('../../services/messageService');
6
+ const { safeParse } = require('../../utils/jsonUtils');
7
+ const { logger } = require('../../utils/logger');
8
+ const { LIGHT_SCALE } = require('./supportInvitability');
9
+ const { applySupportLight } = require('./supportLightService');
10
+
11
+ const HOUR_MS = 60 * 60 * 1000;
12
+ const DAY_MS = 24 * HOUR_MS;
13
+ const DEFAULT_CADENCE_HOURS = 48;
14
+ const RETRY_HOURS = 6;
15
+ const DEFAULT_WINDOW_DAYS = 14;
16
+ const MAX_MESSAGES = 60;
17
+ const MAX_PATIENT_MESSAGES = 20;
18
+ const CANDIDATE_PAGE = 200;
19
+ const SETTLED_OUTCOMES = ['evaluated', 'no_messages'];
20
+ const MAX_REASON_CHARS = 500;
21
+ const MAX_EVIDENCE = 5;
22
+ const INTERNAL_ORIGINS = ['system', 'instruction'];
23
+ const SERVICES = Object.keys(LIGHT_SCALE);
24
+
25
+ function transcriptOf(messages) {
26
+ return messages.map((message, index) => {
27
+ const at = new Date(message.createdAt).toISOString().slice(0, 16).replace('T', ' ');
28
+ return `[${index}] ${at} ${message.from_me ? 'Equipo' : 'Paciente'}: ${String(message.body || '').trim()}`;
29
+ }).join('\n');
30
+ }
31
+
32
+ function readingFor(service, raw, messages) {
33
+ const color = raw?.color;
34
+ if (color !== 'unknown' && !LIGHT_SCALE[service].includes(color)) return null;
35
+ const evidence = (Array.isArray(raw?.evidence) ? raw.evidence : [])
36
+ .filter((item) => Number.isInteger(item?.message_index) && messages[item.message_index] && typeof item.summary === 'string')
37
+ .slice(0, MAX_EVIDENCE)
38
+ .map((item) => ({ source: 'sweep', sourceId: String(messages[item.message_index]._id), summary: item.summary.slice(0, MAX_REASON_CHARS) }));
39
+ const reason = typeof raw?.reason === 'string' ? raw.reason.slice(0, MAX_REASON_CHARS) : null;
40
+ return { color, reason, evidence };
41
+ }
42
+
43
+ async function readRecentMessages(patientId, { now, windowDays, readMessages }) {
44
+ const query = {
45
+ numero: patientId,
46
+ createdAt: { $gte: new Date(now.getTime() - windowDays * DAY_MS) },
47
+ origin: { $nin: INTERNAL_ORIGINS },
48
+ body: { $regex: '\\S' },
49
+ };
50
+ const options = { sort: { createdAt: -1 }, select: '_id body from_me createdAt' };
51
+ const [recent, fromPatient] = await Promise.all([
52
+ readMessages(query, { ...options, limit: MAX_MESSAGES }),
53
+ readMessages({ ...query, from_me: false }, { ...options, limit: MAX_PATIENT_MESSAGES }),
54
+ ]);
55
+ const byId = new Map([...(recent || []), ...(fromPatient || [])].map((message) => [String(message._id), message]));
56
+ return [...byId.values()].sort((left, right) => new Date(left.createdAt) - new Date(right.createdAt));
57
+ }
58
+
59
+ async function evaluatePatientSupport({
60
+ patientId, now = new Date(), windowDays = DEFAULT_WINDOW_DAYS,
61
+ }, {
62
+ provider = null, getConfig = getSupportLightEvaluator, readMessages = getMessages, applyLight = applySupportLight,
63
+ } = {}) {
64
+ const { presetId } = await getConfig();
65
+ if (!presetId) return { outcome: 'not_configured' };
66
+ const messages = await readRecentMessages(patientId, { now, windowDays, readMessages });
67
+ if (!messages.some((message) => !message.from_me)) return { outcome: 'no_messages' };
68
+
69
+ const result = await (provider || requireGatewayProvider()).runStructured({
70
+ presetId,
71
+ input: [{ role: 'user', content: transcriptOf(messages) }],
72
+ metadata: { subAgent: 'support-light' },
73
+ });
74
+ if (result?.status && result.status !== 'completed') return { outcome: 'incomplete' };
75
+ const parsed = safeParse(readStructuredText(result), null);
76
+ if (!parsed || typeof parsed !== 'object') return { outcome: 'unparseable' };
77
+
78
+ const changes = [];
79
+ let isPartial = false;
80
+ for (const service of SERVICES) {
81
+ const reading = readingFor(service, parsed[service], messages);
82
+ if (!reading) {
83
+ isPartial = true;
84
+ logger.warn('[supportLightEvaluation] reading skipped: missing or invalid colour', { code: patientId, service });
85
+ continue;
86
+ }
87
+ const { light, outcome } = await applyLight({ patientId, service, source: 'ai', now, ...reading });
88
+ if (outcome !== 'unchanged') changes.push({ service, outcome, color: reading.color, revision: light?.revision ?? null });
89
+ }
90
+ return { outcome: isPartial ? 'partial' : 'evaluated', changes };
91
+ }
92
+
93
+ async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel }) {
94
+ const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
95
+ const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
96
+ const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
97
+ const selected = [];
98
+ for (let page = 0; selected.length < limit; page += 1) {
99
+ const active = await aggregateMessages([
100
+ { $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
101
+ { $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
102
+ { $sort: { lastInboundAt: -1, _id: 1 } },
103
+ { $skip: page * CANDIDATE_PAGE },
104
+ { $limit: CANDIDATE_PAGE },
105
+ ]);
106
+ const ids = (active || []).map((row) => row._id);
107
+ if (!ids.length) break;
108
+ const recent = await SweepModel.find({
109
+ patientId: { $in: ids },
110
+ $or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }],
111
+ }).select('patientId').lean();
112
+ const done = new Set(recent.map((row) => row.patientId));
113
+ selected.push(...ids.filter((id) => !done.has(id)));
114
+ if (ids.length < CANDIDATE_PAGE) break;
115
+ }
116
+ return selected.slice(0, limit);
117
+ }
118
+
119
+ function validPatientIds(ids) {
120
+ return [...new Set(ids.filter((id) => /^whatsapp:\+\d{6,20}$/.test(String(id))))];
121
+ }
122
+
123
+ function sweepState(outcome, now) {
124
+ return { lastAttemptAt: now, lastOutcome: outcome, ...(SETTLED_OUTCOMES.includes(outcome) ? { lastEvaluatedAt: now } : {}) };
125
+ }
126
+
127
+ async function runSupportLightSweep({
128
+ now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
129
+ } = {}, { SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, ...deps } = {}) {
130
+ const candidates = Array.isArray(patientIds)
131
+ ? validPatientIds(patientIds).slice(0, limit)
132
+ : await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
133
+ const summary = { evaluated: 0, skipped: 0, failed: 0, changes: [] };
134
+ for (const patientId of candidates) {
135
+ let outcome = 'error';
136
+ try {
137
+ const result = await evaluate({ patientId, now, windowDays }, deps);
138
+ if (result.outcome === 'not_configured') return { ...summary, outcome: 'not_configured' };
139
+ outcome = result.outcome;
140
+ if (outcome === 'evaluated' || outcome === 'partial') {
141
+ summary.evaluated += 1;
142
+ summary.changes.push(...result.changes.map((change) => ({ patientId, ...change })));
143
+ } else {
144
+ summary.skipped += 1;
145
+ }
146
+ } catch (error) {
147
+ summary.failed += 1;
148
+ logger.error('[supportLightEvaluation] patient evaluation failed', { code: patientId, error: error.message, stack: error.stack });
149
+ }
150
+ try {
151
+ await SweepModel.updateOne({ patientId }, { $set: sweepState(outcome, now) }, { upsert: true });
152
+ } catch (stateError) {
153
+ logger.error('[supportLightEvaluation] sweep state not recorded', { code: patientId, error: stateError.message });
154
+ }
155
+ }
156
+ return { ...summary, outcome: 'completed' };
157
+ }
158
+
159
+ module.exports = { evaluatePatientSupport, runSupportLightSweep };
@@ -102,14 +102,10 @@ function resolvedDrugs(proposals) {
102
102
  });
103
103
  }
104
104
 
105
- function drugsNamedIn(text) {
106
- const padded = ` ${key(text)} `;
107
- return DRUG_NAMES.filter((name) => padded.includes(` ${name} `));
108
- }
109
-
110
105
  function unproposedDrugsIn(text, proposals) {
111
106
  const proposed = new Set(resolvedDrugs(proposals).flatMap(({ drug }) => namesOf(drug)));
112
- return drugsNamedIn(text).filter((name) => !proposed.has(name));
107
+ const padded = ` ${key(text)} `;
108
+ return DRUG_NAMES.filter((name) => !proposed.has(name) && padded.includes(` ${name} `));
113
109
  }
114
110
 
115
111
  function crossSymptomIssues(proposals) {
@@ -131,6 +127,5 @@ function crossSymptomIssues(proposals) {
131
127
  module.exports = {
132
128
  validateProposal,
133
129
  unproposedDrugsIn,
134
- drugsNamedIn,
135
130
  crossSymptomIssues,
136
131
  };
@@ -2,7 +2,7 @@ const { assembleLandscape } = require('../services/symptomLandscapeService');
2
2
 
3
3
  const definition = {
4
4
  name: 'getActiveSymptomLandscape',
5
- description: '**Does:** Returns a snapshot of ALL the patient\'s open symptom cases (`characterizing` | `monitoring`), each fusing the Condition with its head impression, plus active clusters. Read-only.\n\n**Required inputs:** none. Optional `minimum_priority` (`low` (default) returns everything; `medium` returns high+medium; `high` returns only high).\n\n**When to call:** only for a targeted re-read of the case landscape once `getRouterContextBundle` has already loaded the turn\'s context — for example after opening a case, or to narrow with a different `minimum_priority`. The routine load at the start of routing is the bundle\'s `landscape` section, not this tool.\n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**When NOT to call:** for the current turn\'s observations (use `extractClinicalInfo`) or closed-case history.\n\n**Returns:** `active_cases[]` (each: `case_id`, `ctcae_term`, `status`, `opened_at`, `current_episode_id`, `mention_ids` (the evidence already on the case — on a turn that extracts nothing new, re-cite one of these with `source: \'carried_forward\'`), `grade_estimate`, `decision_posture`, `trajectory`, derived `priority` + `attention_flags`, `last_assessed_at`, `days_since_evidence`) sorted priority desc then most-recently-opened; `active_clusters[]` (each: `cluster_id`, `label`, `hypothesis_type`, `status`, `confidence`, `clinical_significance`, `member_case_ids`, `relationship_model`); `active_contingencies[]` — the safety nets already armed (each: `plan_id`, `related_case_id`, `related_cluster_id`, `concern`, `awaiting_characterization`, `status`, `created_at`, `expires_at`, `patient_fires_after_silence_minutes`). A target that already appears here does NOT need another `setContingencyPlan` arm — a duplicate is rejected; use `action: \'rearm\'` to replace its net or `action: \'resolve\'` to stand it down.',
5
+ description: '**Does:** Returns a snapshot of ALL the patient\'s open symptom cases (`characterizing` | `monitoring`), each fusing the Condition with its head impression, plus active clusters. Read-only.\n\n**Required inputs:** none. Optional `minimum_priority` (`low` (default) returns everything; `medium` returns high+medium; `high` returns only high).\n\n**When to call:** only for a targeted re-read of the case landscape once `getRouterContextBundle` has already loaded the turn\'s context — for example after opening a case, or to narrow with a different `minimum_priority`. The routine load at the start of routing is the bundle\'s `landscape` section, not this tool.\n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**When NOT to call:** for the current turn\'s observations (use `extractClinicalInfo`) or closed-case history.\n\n**Returns:** `active_cases[]` (each: `case_id`, `ctcae_term`, `status`, `opened_at`, `current_episode_id`, `mention_ids` (the evidence already on the case — on a turn that extracts nothing new, re-cite one of these with `source: \'carried_forward\'`), `grade_estimate`, `grade_scale` (the CTCAE clauses for the case\'s term — grade against these; they count as the rubric for an `agent_adjudicated` grade this turn), `decision_posture`, `trajectory`, derived `priority` + `attention_flags`, `last_assessed_at`, `days_since_evidence`) sorted priority desc then most-recently-opened; `active_clusters[]` (each: `cluster_id`, `label`, `hypothesis_type`, `status`, `confidence`, `clinical_significance`, `member_case_ids`, `relationship_model`); `active_contingencies[]` — the safety nets already armed (each: `plan_id`, `related_case_id`, `related_cluster_id`, `concern`, `awaiting_characterization`, `status`, `created_at`, `expires_at`, `patient_fires_after_silence_minutes`). A target that already appears here does NOT need another `setContingencyPlan` arm — a duplicate is rejected; use `action: \'rearm\'` to replace its net or `action: \'resolve\'` to stand it down.',
6
6
  strict: false,
7
7
  replayScope: 'turn',
8
8
  parameters: {
@@ -241,9 +241,6 @@ async function handler(args, context = {}) {
241
241
  suspectedCondition: details.suspected_condition || null,
242
242
  recommendedAction: details.recommended_action || null,
243
243
  justification: args?.urgency_justification || null,
244
- indicators: (Array.isArray(details.indicators) ? details.indicators : [])
245
- .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
246
- turnId: runtime.turnId || null,
247
244
  },
248
245
  });
249
246
  queued = await recordEmergency({
@@ -6,7 +6,6 @@ const { _clearClinicalContextCache } = require('../helpers/patientInformationHel
6
6
  const { setPreprocessingHandler } = require('../services/preprocessingService');
7
7
  const { clearTriageHistoryCache } = require('../services/triageHistoryService');
8
8
  const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
9
- const { stopReviewDraftSweep } = require('../services/reviewDraftSweepService');
10
9
  const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
11
10
  const { _resetDefaultInstance } = require('../core/NexusMessaging');
12
11
  const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
@@ -21,9 +20,7 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
21
20
  const SWEEP_STOP_MS = 2000;
22
21
 
23
22
  function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
24
- const stopped = Promise.allSettled([
25
- stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep(), stopReviewDraftSweep(),
26
- ]);
23
+ const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep()]);
27
24
  return withTimeout(stopped, timeoutMs, 'sweeps.stop')
28
25
  .catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
29
26
  }
@@ -7,7 +7,6 @@ const {
7
7
  cancelEscalationReview,
8
8
  closeEscalationReview,
9
9
  getEscalationReviewById,
10
- getReviewTimeline,
11
10
  handOffToDoctor,
12
11
  listEscalationReviews,
13
12
  openEscalationReview,
@@ -54,15 +53,6 @@ const getEscalationReviewController = async (req, res) => {
54
53
  }
55
54
  };
56
55
 
57
- const getReviewTimelineController = async (req, res) => {
58
- try {
59
- const timeline = await getReviewTimeline({ id: req.params.id });
60
- res.status(200).json({ success: true, timeline });
61
- } catch (error) {
62
- respondWithError(res, error, 'reading the escalation review timeline', { reviewId: req.params?.id });
63
- }
64
- };
65
-
66
56
  const listEscalationReviewsController = async (req, res) => {
67
57
  try {
68
58
  const reviews = await listEscalationReviews({ code: req.params.code });
@@ -153,8 +143,6 @@ const recordEscalationReviewDecisionController = async (req, res) => {
153
143
  comment = null,
154
144
  doctorName = null,
155
145
  doctorReply = null,
156
- reason = null,
157
- draftNumber = null,
158
146
  triggeredBy,
159
147
  } = req.body || {};
160
148
  const review = await recordDoctorDecision({
@@ -165,8 +153,6 @@ const recordEscalationReviewDecisionController = async (req, res) => {
165
153
  comment,
166
154
  doctorName,
167
155
  doctorReply,
168
- reason,
169
- draftNumber,
170
156
  recordedBy: triggeredBy,
171
157
  requestId: req.requestId,
172
158
  });
@@ -238,7 +224,6 @@ module.exports = {
238
224
  cancelEscalationReviewController,
239
225
  closeEscalationReviewController,
240
226
  getEscalationReviewController,
241
- getReviewTimelineController,
242
227
  handOffEscalationReviewController,
243
228
  listEscalationReviewsController,
244
229
  openEscalationReviewController,
@@ -2,7 +2,6 @@ const moment = require('moment-timezone');
2
2
  const mongoose = require('mongoose');
3
3
 
4
4
  const { logger } = require('../utils/logger');
5
- const { withTimeout } = require('../utils/timeoutUtils');
6
5
 
7
6
  const { ScheduledMessage } = require('../models/agendaMessageModel.js');
8
7
  const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel.js');
@@ -14,9 +13,6 @@ const { CAREGIVER_ROLE, resolveCaregiver } = require('../helpers/caregiverHelper
14
13
 
15
14
  const { getRecordByFilter } = require('../services/airtableService');
16
15
  const { getMessages } = require('../services/messageService');
17
- const { recordDirectIndication } = require('../services/escalationReviewService');
18
-
19
- const INDICATION_WAIT_MS = 5000;
20
16
 
21
17
  const { sendMessage, sendScheduledMessage, getDefaultInstance } = require('../core/NexusMessaging');
22
18
 
@@ -73,8 +69,7 @@ const sendMessageController = async (req, res) => {
73
69
  frontendId = null,
74
70
  triggeredBy = null,
75
71
  idempotencyKey = null,
76
- contactCode = null,
77
- asIndication = false
72
+ contactCode = null
78
73
  } = req.body || {};
79
74
 
80
75
  const formattedCode = ensureWhatsAppFormat(code);
@@ -105,21 +100,6 @@ const sendMessageController = async (req, res) => {
105
100
  variables: finalVariables, code: formattedCode,
106
101
  frontendId, triggeredBy, idempotencyKey, ...contact
107
102
  });
108
- // Only a message the approver explicitly sent as the indication resolves the clinical review.
109
- if (asIndication === true && result?.success && triggeredBy && message && !contentSid && !contact.contactCode) {
110
- // Awaited so the review is usually settled before the reply returns, but never for long: the
111
- // message already went out, and a slow lookup finishes in the background. It never throws.
112
- await withTimeout(recordDirectIndication({
113
- code: formattedCode,
114
- triggeredBy,
115
- body: message,
116
- messageId: _pickMessageId(result, null),
117
- status: result?.status ?? null,
118
- deferred: result?.deferred === true || result?.preemptive === true,
119
- }), INDICATION_WAIT_MS, 'clinical review resolution').catch((error) => {
120
- logger.warn('[sendMessageController] The clinical review is still resolving in the background', { error: error.message });
121
- });
122
- }
123
103
  return res.status(200).json({
124
104
  success: result?.success ?? true,
125
105
  messageId: _pickMessageId(result, null),
package/lib/index.d.ts CHANGED
@@ -355,8 +355,6 @@ declare module '@peopl-health/nexus' {
355
355
  ner?: NerOptions;
356
356
  recommendationRecovery?: RecommendationRecoveryOptions;
357
357
  inboundRecovery?: InboundRecoveryOptions;
358
- reviewDrafts?: ReviewDraftsOptions;
359
- reviewAlerts?: ReviewAlertsOptions;
360
358
  }
361
359
 
362
360
  export interface RecommendationRecoveryOptions {
@@ -364,18 +362,6 @@ declare module '@peopl-health/nexus' {
364
362
  intervalMs?: number;
365
363
  }
366
364
 
367
- export interface ReviewDraftsOptions {
368
- /** Writes the clinical review draft automatically after each alarm or agent update. */
369
- enabled?: boolean;
370
- intervalMs?: number;
371
- }
372
-
373
- export interface ReviewAlertsOptions {
374
- /** WhatsApps the approver on stat/asap reviews and re-alerts an unanswered stat review. */
375
- enabled?: boolean;
376
- intervalMs?: number;
377
- }
378
-
379
365
  export interface InboundRecoveryOptions {
380
366
  enabled: boolean;
381
367
  intervalMs?: number;
@@ -1029,6 +1015,39 @@ declare module '@peopl-health/nexus' {
1029
1015
  supportWeek(date: Date | string): string | null;
1030
1016
  };
1031
1017
 
1018
+ export interface SupportLightSweepChange {
1019
+ patientId: string;
1020
+ service: SupportService;
1021
+ outcome: SupportLightOutcome;
1022
+ color: SupportLightColor;
1023
+ revision: number | null;
1024
+ }
1025
+
1026
+ export const supportLightEvaluationService: {
1027
+ evaluatePatientSupport(request: {
1028
+ patientId: string;
1029
+ now?: Date;
1030
+ windowDays?: number;
1031
+ }, options?: { provider?: unknown; getConfig?: unknown; readMessages?: unknown; applyLight?: unknown }): Promise<{
1032
+ outcome: 'evaluated' | 'partial' | 'not_configured' | 'no_messages' | 'incomplete' | 'unparseable';
1033
+ changes?: Omit<SupportLightSweepChange, 'patientId'>[];
1034
+ }>;
1035
+ runSupportLightSweep(request?: {
1036
+ now?: Date;
1037
+ patientIds?: string[] | null;
1038
+ scope?: string[] | null;
1039
+ cadenceHours?: number;
1040
+ windowDays?: number;
1041
+ limit?: number;
1042
+ }, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
1043
+ outcome: 'completed' | 'not_configured';
1044
+ evaluated: number;
1045
+ skipped: number;
1046
+ failed: number;
1047
+ changes: SupportLightSweepChange[];
1048
+ }>;
1049
+ };
1050
+
1032
1051
  // BatchingManager — per-chatId concurrency control
1033
1052
  export interface BatchingConfig {
1034
1053
  enabled?: boolean;
package/lib/index.js CHANGED
@@ -32,8 +32,6 @@ const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNet
32
32
  const { ensureOnePledgePerContact, startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
33
33
  const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
34
34
  const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
35
- const { startReviewDraftSweep } = require('./services/reviewDraftSweepService');
36
- const { startReviewAlertSweep } = require('./services/reviewAlertSweepService');
37
35
  const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
38
36
  const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
39
37
  const { DrainingError } = require('./core/BatchingManager');
@@ -52,6 +50,7 @@ const { registerDashboardProvider } = require('./services/dashboard-provider-reg
52
50
  const supportActionService = require('./clinical/services/supportActionService');
53
51
  const supportLightService = require('./clinical/services/supportLightService');
54
52
  const supportInvitability = require('./clinical/services/supportInvitability');
53
+ const supportLightEvaluationService = require('./clinical/services/supportLightEvaluationService');
55
54
  const {
56
55
  NutritionSafetyDecision,
57
56
  FINDING_CODES,
@@ -205,24 +204,6 @@ class Nexus {
205
204
  logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
206
205
  }
207
206
 
208
- try {
209
- if (options.reviewDrafts?.enabled === true) {
210
- startReviewDraftSweep({ intervalMs: options.reviewDrafts.intervalMs });
211
- logger.info('[Nexus] clinical review draft sweep armed');
212
- }
213
- } catch (e) {
214
- logger.warn('Warning: failed to arm the clinical review draft sweep:', e?.message || e);
215
- }
216
-
217
- try {
218
- if (options.reviewAlerts?.enabled === true) {
219
- startReviewAlertSweep({ intervalMs: options.reviewAlerts.intervalMs });
220
- logger.info('[Nexus] clinical review doctor alert sweep armed');
221
- }
222
- } catch (e) {
223
- logger.warn('Warning: failed to arm the clinical review doctor alert sweep:', e?.message || e);
224
- }
225
-
226
207
  try {
227
208
  if (options.inboundRecovery?.enabled === true) {
228
209
  startInboundRecoverySweep({
@@ -379,6 +360,7 @@ module.exports = {
379
360
  supportActionService,
380
361
  supportLightService,
381
362
  supportInvitability,
363
+ supportLightEvaluationService,
382
364
  NutritionSafetyDecision,
383
365
  FINDING_CODES,
384
366
  FINDING_VALUES,