@peopl-health/nexus 5.63.0-dev.11427 → 5.63.0-dev.11429
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/clinical/models/supportLightModel.js +0 -3
- package/lib/clinical/services/supportLightService.js +8 -87
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +1 -8
- package/lib/index.d.ts +0 -12
- package/lib/models/escalationReviewModel.js +2 -1
- package/lib/services/escalationReviewService.js +12 -7
- package/lib/services/reviewBoardService.js +1 -1
- package/package.json +1 -1
- package/lib/clinical/flags/supportLightFlags.js +0 -7
|
@@ -46,7 +46,6 @@ const supportLightSchema = new mongoose.Schema({
|
|
|
46
46
|
supportLightSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_light_per_service' });
|
|
47
47
|
supportLightSchema.index({ service: 1, color: 1 });
|
|
48
48
|
supportLightSchema.index({ 'pendingImprovement.proposedAt': 1 }, { sparse: true });
|
|
49
|
-
supportLightSchema.index({ 'outbox.at': 1 }, { sparse: true });
|
|
50
49
|
|
|
51
50
|
const supportLightEventSchema = new mongoose.Schema({
|
|
52
51
|
patientId: { type: String, required: true },
|
|
@@ -56,8 +55,6 @@ const supportLightEventSchema = new mongoose.Schema({
|
|
|
56
55
|
|
|
57
56
|
supportLightEventSchema.index({ patientId: 1, service: 1, revision: 1 }, { unique: true, name: 'one_event_per_light_revision' });
|
|
58
57
|
supportLightEventSchema.index({ patientId: 1, at: -1 });
|
|
59
|
-
supportLightEventSchema.index({ service: 1, to: 1, at: 1 });
|
|
60
|
-
supportLightEventSchema.index({ at: 1 });
|
|
61
58
|
|
|
62
59
|
const supportLightSweepSchema = new mongoose.Schema({
|
|
63
60
|
patientId: { type: String, required: true, unique: true },
|
|
@@ -1,14 +1,10 @@
|
|
|
1
1
|
const { getSupportLightModel, getSupportLightEventModel } = require('../models/supportLightModel');
|
|
2
2
|
const { logger } = require('../../utils/logger');
|
|
3
|
-
const { supportLightFromChatLive } = require('../flags/supportLightFlags');
|
|
4
3
|
const { nextLight } = require('./supportInvitability');
|
|
5
4
|
|
|
6
5
|
const AI_ACTOR = 'ai';
|
|
7
6
|
const BOARD_LIMIT = 2000;
|
|
8
7
|
const HISTORY_READ_LIMIT = 200;
|
|
9
|
-
const EVENT_READ_LIMIT = 500;
|
|
10
|
-
const MAX_CHAT_REASON_CHARS = 1000;
|
|
11
|
-
const RISK_FIELD = { nutrition: 'nutritionRisk', psychology: 'psychologyRisk' };
|
|
12
8
|
|
|
13
9
|
function requireText(value, name) {
|
|
14
10
|
if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
|
|
@@ -140,26 +136,6 @@ async function readSupportLights(patientId, { Model = getSupportLightModel() } =
|
|
|
140
136
|
return Model.find({ patientId }).select('-outbox').lean();
|
|
141
137
|
}
|
|
142
138
|
|
|
143
|
-
function eventKey(event) {
|
|
144
|
-
return `${event.patientId}:${event.service}:${event.revision}`;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function withOutboxEvents(stored, lights) {
|
|
148
|
-
const byKey = new Map(stored.map((event) => [eventKey(event), event]));
|
|
149
|
-
for (const light of lights) {
|
|
150
|
-
for (const outboxEvent of light.outbox || []) {
|
|
151
|
-
const event = { ...outboxEvent, patientId: light.patientId, service: light.service };
|
|
152
|
-
if (!byKey.has(eventKey(event))) byKey.set(eventKey(event), event);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return [...byKey.values()];
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
function byTimeThenIdentity(left, right) {
|
|
159
|
-
return new Date(left.at) - new Date(right.at) || left.patientId.localeCompare(right.patientId)
|
|
160
|
-
|| left.service.localeCompare(right.service) || left.revision - right.revision;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
139
|
async function readSupportLightHistory(patientId, {
|
|
164
140
|
service = null, limit = HISTORY_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel(),
|
|
165
141
|
} = {}) {
|
|
@@ -170,7 +146,14 @@ async function readSupportLightHistory(patientId, {
|
|
|
170
146
|
EventModel.find(scope).sort({ at: -1, revision: -1, service: 1 }).limit(bounded).lean(),
|
|
171
147
|
Model.find(scope).select('patientId service outbox').lean(),
|
|
172
148
|
]);
|
|
173
|
-
|
|
149
|
+
const byKey = new Map(stored.map((event) => [`${event.service}:${event.revision}`, event]));
|
|
150
|
+
for (const light of lights) {
|
|
151
|
+
for (const event of light.outbox || []) {
|
|
152
|
+
const key = `${light.service}:${event.revision}`;
|
|
153
|
+
if (!byKey.has(key)) byKey.set(key, { ...event, patientId: light.patientId, service: light.service });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return [...byKey.values()]
|
|
174
157
|
.sort((left, right) => new Date(right.at) - new Date(left.at) || right.revision - left.revision
|
|
175
158
|
|| left.service.localeCompare(right.service))
|
|
176
159
|
.slice(0, bounded);
|
|
@@ -207,70 +190,8 @@ async function readSupportLightBoard({ service = null, color = null, isPendingOn
|
|
|
207
190
|
]).option({ maxTimeMS: 10000, allowDiskUse: true });
|
|
208
191
|
}
|
|
209
192
|
|
|
210
|
-
async function readSupportLightEvents({
|
|
211
|
-
since, service = null, outcome = null, to = null,
|
|
212
|
-
} = {}, { limit = EVENT_READ_LIMIT, Model = getSupportLightModel(), EventModel = getSupportLightEventModel() } = {}) {
|
|
213
|
-
const from = since == null ? null : new Date(since);
|
|
214
|
-
if (!from || Number.isNaN(from.getTime())) throw new Error('since is required');
|
|
215
|
-
const bounded = Number.isInteger(limit) && limit > 0 ? Math.min(limit, EVENT_READ_LIMIT) : EVENT_READ_LIMIT;
|
|
216
|
-
const filters = { ...(outcome ? { outcome } : {}), ...(to ? { to } : {}) };
|
|
217
|
-
const [stored, lights] = await Promise.all([
|
|
218
|
-
EventModel.find({ at: { $gte: from }, ...(service ? { service } : {}), ...filters })
|
|
219
|
-
.sort({ at: 1, patientId: 1, service: 1, revision: 1 }).limit(bounded).lean(),
|
|
220
|
-
Model.aggregate([
|
|
221
|
-
{ $match: { ...(service ? { service } : {}), outbox: { $elemMatch: { at: { $gte: from }, ...filters } } } },
|
|
222
|
-
{ $unwind: '$outbox' },
|
|
223
|
-
{ $match: { 'outbox.at': { $gte: from }, ...Object.fromEntries(Object.entries(filters).map(([field, value]) => [`outbox.${field}`, value])) } },
|
|
224
|
-
{ $sort: { 'outbox.at': 1, patientId: 1, service: 1, 'outbox.revision': 1 } },
|
|
225
|
-
{ $limit: bounded },
|
|
226
|
-
{ $project: { _id: 0, patientId: 1, service: 1, outbox: ['$outbox'] } },
|
|
227
|
-
]),
|
|
228
|
-
]);
|
|
229
|
-
return withOutboxEvents(stored, lights).sort(byTimeThenIdentity).slice(0, bounded);
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
function chatReading(recommendation, decision) {
|
|
233
|
-
const color = decision[RISK_FIELD[decision.service]];
|
|
234
|
-
if (!color) return null;
|
|
235
|
-
const summaries = decision.evidence.map((item) => item.summary).filter(Boolean);
|
|
236
|
-
const reason = (summaries.length ? summaries : decision.reasonCodes).join('; ').slice(0, MAX_CHAT_REASON_CHARS) || null;
|
|
237
|
-
return {
|
|
238
|
-
patientId: recommendation.patientId,
|
|
239
|
-
service: decision.service,
|
|
240
|
-
color,
|
|
241
|
-
source: 'ai',
|
|
242
|
-
reason,
|
|
243
|
-
evidence: decision.evidence.map((item) => ({ source: 'chat', sourceId: item.sourceId, summary: item.summary ?? item.code ?? null })),
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
async function applyChatSupportReadings(recommendation, {
|
|
248
|
-
acceptedServices = null, isTurnLive = () => true, now = new Date(), isLive = supportLightFromChatLive, apply = applySupportLight,
|
|
249
|
-
} = {}) {
|
|
250
|
-
if (!isLive()) return [];
|
|
251
|
-
const results = [];
|
|
252
|
-
const decisions = (recommendation.decisions || []).filter((decision) => !acceptedServices || acceptedServices.includes(decision.service));
|
|
253
|
-
for (const decision of decisions) {
|
|
254
|
-
const reading = chatReading(recommendation, decision);
|
|
255
|
-
if (!reading) continue;
|
|
256
|
-
if (!isTurnLive()) break;
|
|
257
|
-
try {
|
|
258
|
-
const { light, outcome } = await apply({ ...reading, now });
|
|
259
|
-
results.push({ service: reading.service, color: reading.color, outcome, revision: light?.revision ?? null });
|
|
260
|
-
} catch (error) {
|
|
261
|
-
logger.error('[supportLight] chat reading not applied', {
|
|
262
|
-
code: recommendation.patientId, service: reading.service, error: error.message, stack: error.stack,
|
|
263
|
-
});
|
|
264
|
-
results.push({ service: reading.service, color: reading.color, outcome: 'error', revision: null });
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
return results;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
193
|
module.exports = {
|
|
271
|
-
applyChatSupportReadings,
|
|
272
194
|
applySupportLight,
|
|
273
|
-
readSupportLightEvents,
|
|
274
195
|
readSupportLightBoard,
|
|
275
196
|
resolvePendingImprovement,
|
|
276
197
|
readSupportLights,
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
const { ZodError } = require('zod');
|
|
2
2
|
|
|
3
3
|
const { recordSupportRoutingRecommendation } = require('../services/supportCandidateService');
|
|
4
|
-
const { applyChatSupportReadings } = require('../services/supportLightService');
|
|
5
4
|
const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
|
|
6
5
|
|
|
7
6
|
const decisionProperties = {
|
|
@@ -44,7 +43,7 @@ const decisionProperties = {
|
|
|
44
43
|
|
|
45
44
|
const definition = {
|
|
46
45
|
name: 'submitSupportRoutingRecommendation',
|
|
47
|
-
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation.
|
|
46
|
+
description: '**Does:** Records a nutrition or psychology support-routing recommendation from the current patient conversation. Use only when the conversation contains explicit support-relevant evidence. Psychology policy is strict: green → group; orange → individual; red → escalated; insufficient evidence → reviewRequired. Nutrition group eligibility and urgent-intake eligibility are independent. This tool creates or updates one candidate per patient and service, and repeated calls append evidence without sending an invitation. Suicidal or immediate risk must be handled through reportCrisis as well.\n\n**Required inputs:** decisions[] with service-specific risk, disposition, group eligibility, confidence, reason codes, evidence tied to this turn, and safety flags. Nutrition decisions also include urgent-intake eligibility.\n\n**Side effects:** persists or updates the canonical support candidate.',
|
|
48
47
|
strict: false,
|
|
49
48
|
parameters: {
|
|
50
49
|
type: 'object',
|
|
@@ -117,11 +116,6 @@ async function handler(args = {}, context = {}) {
|
|
|
117
116
|
});
|
|
118
117
|
if (!isRuntimeLive(runtime)) return inactiveTurn();
|
|
119
118
|
const candidates = await recordSupportRoutingRecommendation(recommendation);
|
|
120
|
-
const lights = isRuntimeLive(runtime)
|
|
121
|
-
? await applyChatSupportReadings(recommendation, {
|
|
122
|
-
acceptedServices: candidates.map((candidate) => candidate.service), isTurnLive: () => isRuntimeLive(runtime),
|
|
123
|
-
})
|
|
124
|
-
: [];
|
|
125
119
|
runtime.trace?.setSignals?.({
|
|
126
120
|
supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
|
|
127
121
|
});
|
|
@@ -134,7 +128,6 @@ async function handler(args = {}, context = {}) {
|
|
|
134
128
|
service: candidate.service,
|
|
135
129
|
disposition: candidate.disposition,
|
|
136
130
|
})),
|
|
137
|
-
lights,
|
|
138
131
|
invitation_sent: false,
|
|
139
132
|
},
|
|
140
133
|
});
|
package/lib/index.d.ts
CHANGED
|
@@ -1006,18 +1006,6 @@ declare module '@peopl-health/nexus' {
|
|
|
1006
1006
|
isPendingOnly?: boolean;
|
|
1007
1007
|
}, options?: { limit?: number; offset?: number; Model?: unknown }): Promise<SupportLightBoardRecord[]>;
|
|
1008
1008
|
readSupportLightHistory(patientId: string, options?: { service?: SupportService | null; limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
|
|
1009
|
-
readSupportLightEvents(filters: {
|
|
1010
|
-
since: Date | string;
|
|
1011
|
-
service?: SupportService | null;
|
|
1012
|
-
outcome?: SupportLightEventRecord['outcome'] | null;
|
|
1013
|
-
to?: SupportLightColor | null;
|
|
1014
|
-
}, options?: { limit?: number; Model?: unknown; EventModel?: unknown }): Promise<SupportLightEventRecord[]>;
|
|
1015
|
-
applyChatSupportReadings(recommendation: Pick<SupportRoutingRecommendationInput, 'patientId' | 'decisions'>, options?: { acceptedServices?: SupportService[] | null; isTurnLive?: () => boolean; now?: Date; isLive?: () => boolean; apply?: unknown }): Promise<Array<{
|
|
1016
|
-
service: SupportService;
|
|
1017
|
-
color: SupportLightColor;
|
|
1018
|
-
outcome: SupportLightOutcome | 'stale' | 'error';
|
|
1019
|
-
revision: number | null;
|
|
1020
|
-
}>>;
|
|
1021
1009
|
};
|
|
1022
1010
|
|
|
1023
1011
|
export const supportInvitability: {
|
|
@@ -11,7 +11,7 @@ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
|
11
11
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
12
12
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
13
13
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
14
|
-
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'direct_chat'];
|
|
14
|
+
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
15
15
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
16
16
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
17
17
|
|
|
@@ -168,6 +168,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
168
168
|
'sending',
|
|
169
169
|
'indications_queued',
|
|
170
170
|
'indications_sent',
|
|
171
|
+
'monitoring',
|
|
171
172
|
'closed',
|
|
172
173
|
'cancelled',
|
|
173
174
|
],
|
|
@@ -51,10 +51,12 @@ const DUPLICATE_KEY_ERROR = 11000;
|
|
|
51
51
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
52
52
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
53
53
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
54
|
-
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'needs_intervention'];
|
|
54
|
+
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
|
|
55
55
|
const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
|
|
56
56
|
const DECIDABLE_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
57
|
-
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued'];
|
|
57
|
+
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
|
|
58
|
+
const SETTLEABLE_STATUSES = ['indications_sent', 'monitoring'];
|
|
59
|
+
const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
|
|
58
60
|
const SETTLED_TRAJECTORIES = ['improving', 'stable'];
|
|
59
61
|
const ALERTED_URGENCIES = ['stat', 'asap'];
|
|
60
62
|
const ALERT_MARKS = { stat: '🔴', asap: '🟠' };
|
|
@@ -93,7 +95,8 @@ const configured = (key) => {
|
|
|
93
95
|
return value;
|
|
94
96
|
};
|
|
95
97
|
|
|
96
|
-
const
|
|
98
|
+
const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
|
|
99
|
+
const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
|
|
97
100
|
|
|
98
101
|
const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
99
102
|
? review.patientCaseRecordIds
|
|
@@ -1028,7 +1031,7 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
|
|
|
1028
1031
|
|
|
1029
1032
|
if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
|
|
1030
1033
|
const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
|
|
1031
|
-
if (!settled || review.status
|
|
1034
|
+
if (!settled || !SETTLEABLE_STATUSES.includes(review.status)) {
|
|
1032
1035
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
|
|
1033
1036
|
return review;
|
|
1034
1037
|
}
|
|
@@ -1382,11 +1385,13 @@ async function recordDoctorDecision({
|
|
|
1382
1385
|
}
|
|
1383
1386
|
|
|
1384
1387
|
const review = await loadReview(reviewId);
|
|
1385
|
-
|
|
1388
|
+
const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
|
|
1389
|
+
const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
|
|
1390
|
+
if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
1386
1391
|
const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
|
|
1387
1392
|
const draftNumber = handoff?.draftNumber ?? review.drafts.length;
|
|
1388
1393
|
const draft = review.drafts[draftNumber - 1];
|
|
1389
|
-
if (!draft) throw httpError(409, STATUS_CONFLICT);
|
|
1394
|
+
if (!draft && !isDraftless) throw httpError(409, STATUS_CONFLICT);
|
|
1390
1395
|
if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
|
|
1391
1396
|
|
|
1392
1397
|
let approvedText = null;
|
|
@@ -1411,7 +1416,7 @@ async function recordDoctorDecision({
|
|
|
1411
1416
|
}
|
|
1412
1417
|
const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
|
|
1413
1418
|
|
|
1414
|
-
const updated = await updateReview(reviewId,
|
|
1419
|
+
const updated = await updateReview(reviewId, allowedStatuses, {
|
|
1415
1420
|
$push: {
|
|
1416
1421
|
decisions: {
|
|
1417
1422
|
decision,
|
|
@@ -3,7 +3,7 @@ const { URGENCY_RANK, getEscalationReview } = require('../models/escalationRevie
|
|
|
3
3
|
|
|
4
4
|
const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
5
5
|
const RETURNED_STATUSES = ['returned'];
|
|
6
|
-
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued'];
|
|
6
|
+
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
|
|
7
7
|
const DONE_STATUSES = ['closed', 'cancelled'];
|
|
8
8
|
const BOARD_BUCKETS = ['pending', 'returned', 'followup', 'done'];
|
|
9
9
|
const BOARD_FILTER_PREFIX = 'clinical-review-';
|
package/package.json
CHANGED