@peopl-health/nexus 5.60.1 → 5.61.0-dev.11184
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/AssistantProcessor.js +16 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +54 -0
- package/lib/clinical/services/gradeSourceService.js +8 -33
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +1 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +3 -0
- package/lib/models/escalationReviewModel.js +24 -0
- package/lib/services/escalationReviewService.js +90 -4
- package/package.json +1 -1
|
@@ -15,6 +15,7 @@ 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');
|
|
18
19
|
const { resolveTurnContext, TURN_KIND } = require('./context/turnContext');
|
|
19
20
|
|
|
20
21
|
const traceContingency = (net) => ({
|
|
@@ -256,6 +257,21 @@ class AssistantProcessor {
|
|
|
256
257
|
});
|
|
257
258
|
}
|
|
258
259
|
|
|
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
|
+
|
|
259
275
|
const run = runResult?.run;
|
|
260
276
|
|
|
261
277
|
return {
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
const { objectArg } = require('../../utils/jsonUtils');
|
|
2
|
+
const { isToolFailure } = require('./toolResultHelper');
|
|
3
|
+
|
|
4
|
+
const IMPRESSION_TOOLS = ['openCondition', 'recordClinicalImpression'];
|
|
5
|
+
const CHARACTERIZATION_TOOLS = ['extractClinicalInfo', ...IMPRESSION_TOOLS, 'reportMedicalEscalation'];
|
|
6
|
+
const MAX_PATIENT_TEXT = 500;
|
|
7
|
+
|
|
8
|
+
const textOf = (value) => {
|
|
9
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
10
|
+
return text && text.toLowerCase() !== 'none' ? text : null;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const gradeOf = (gradeEstimate) => {
|
|
14
|
+
const grade = objectArg(gradeEstimate)?.best_estimate;
|
|
15
|
+
return Number.isInteger(grade) ? grade : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const impressionOf = (call) => {
|
|
19
|
+
const args = objectArg(call.tool_arguments) || {};
|
|
20
|
+
const result = objectArg(call.tool_output)?.data;
|
|
21
|
+
return {
|
|
22
|
+
caseId: textOf(args.case_id) || textOf(result?.case_id),
|
|
23
|
+
ctcaeTerm: textOf(args.ctcae_term),
|
|
24
|
+
event: call.tool_name === 'openCondition' ? 'opened' : textOf(args.event),
|
|
25
|
+
// A carried-forward grade is resolved by the tool, so its result holds the grade the call omitted.
|
|
26
|
+
grade: gradeOf(args.grade_estimate) ?? gradeOf(result?.grade_estimate),
|
|
27
|
+
trajectory: textOf(args.trajectory_direction),
|
|
28
|
+
missingForHigherGrade: textOf(args.missing_for_higher_grade),
|
|
29
|
+
checkInQuestion: textOf(args.check_in_question),
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const flagNameOf = (flag) => textOf(typeof flag === 'string' ? flag : flag?.flag);
|
|
34
|
+
|
|
35
|
+
// What the agent characterized this turn, or null when it did not characterize anything:
|
|
36
|
+
// a courtesy reply runs the extractor too, but leaves no mention, impression or escalation behind.
|
|
37
|
+
function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText = null, at = new Date() } = {}) {
|
|
38
|
+
const calls = toolHistory.filter((call) => CHARACTERIZATION_TOOLS.includes(call?.tool_name) && !isToolFailure(call.tool_output));
|
|
39
|
+
const mentionCount = Array.isArray(signals?.clinicalMentions) ? signals.clinicalMentions.length : 0;
|
|
40
|
+
const safetyFlags = (Array.isArray(signals?.safetyFlags) ? signals.safetyFlags : []).map(flagNameOf).filter(Boolean);
|
|
41
|
+
const assessed = calls.some((call) => call.tool_name !== 'extractClinicalInfo');
|
|
42
|
+
if (!turnId || (!assessed && mentionCount === 0 && !safetyFlags.length)) return null;
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
turnId,
|
|
46
|
+
tools: [...new Set(calls.map((call) => call.tool_name))],
|
|
47
|
+
patientText: textOf(patientText)?.slice(0, MAX_PATIENT_TEXT) || null,
|
|
48
|
+
impressions: calls.filter((call) => IMPRESSION_TOOLS.includes(call.tool_name)).map(impressionOf),
|
|
49
|
+
safetyFlags,
|
|
50
|
+
at,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
module.exports = { reviewUpdateOf };
|
|
@@ -4,34 +4,20 @@ 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'];
|
|
9
7
|
|
|
10
8
|
const populated = (grades) => !!grades && Object.keys(grades).length > 0;
|
|
11
9
|
|
|
12
|
-
function
|
|
10
|
+
function gradesDefined(ctcaeTerm) {
|
|
11
|
+
let scale = null;
|
|
13
12
|
try {
|
|
14
|
-
|
|
15
|
-
return populated(scale) ? scale : null;
|
|
13
|
+
scale = getCtcaeCatalog().getGradeScale(ctcaeTerm);
|
|
16
14
|
} catch {
|
|
17
15
|
return null;
|
|
18
16
|
}
|
|
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
|
-
|
|
35
21
|
function ladderReachedModel(trace, ctcaeTerm) {
|
|
36
22
|
if (!ctcaeTerm) return false;
|
|
37
23
|
const steps = Array.isArray(trace?.steps) ? trace.steps : [];
|
|
@@ -46,10 +32,6 @@ function ladderReachedModel(trace, ctcaeTerm) {
|
|
|
46
32
|
const entry = payload.data?.entry || payload.entry;
|
|
47
33
|
if (entry?.ctcae_term === ctcaeTerm && populated(entry.grades)) return true;
|
|
48
34
|
}
|
|
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;
|
|
53
35
|
}
|
|
54
36
|
return false;
|
|
55
37
|
}
|
|
@@ -119,16 +101,9 @@ function noCuratedRubric(ctcaeTerm) {
|
|
|
119
101
|
}
|
|
120
102
|
|
|
121
103
|
function missingLadder(ctcaeTerm) {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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.';
|
|
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.';
|
|
132
107
|
}
|
|
133
108
|
|
|
134
109
|
module.exports = {
|
|
@@ -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`, `
|
|
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.',
|
|
6
6
|
strict: false,
|
|
7
7
|
replayScope: 'turn',
|
|
8
8
|
parameters: {
|
|
@@ -241,6 +241,9 @@ 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,
|
|
244
247
|
},
|
|
245
248
|
});
|
|
246
249
|
queued = await recordEmergency({
|
|
@@ -21,9 +21,30 @@ const alarmSchema = new mongoose.Schema({
|
|
|
21
21
|
suspectedCondition: { type: String, default: null },
|
|
22
22
|
recommendedAction: { type: String, default: null },
|
|
23
23
|
justification: { type: String, default: null },
|
|
24
|
+
indicators: { type: [String], default: undefined },
|
|
25
|
+
turnId: { type: String, default: null },
|
|
24
26
|
raisedAt: { type: Date, required: true },
|
|
25
27
|
}, { _id: false });
|
|
26
28
|
|
|
29
|
+
const impressionUpdateSchema = new mongoose.Schema({
|
|
30
|
+
caseId: { type: String, default: null },
|
|
31
|
+
ctcaeTerm: { type: String, default: null },
|
|
32
|
+
event: { type: String, default: null },
|
|
33
|
+
grade: { type: Number, default: null },
|
|
34
|
+
trajectory: { type: String, default: null },
|
|
35
|
+
missingForHigherGrade: { type: String, default: null },
|
|
36
|
+
checkInQuestion: { type: String, default: null },
|
|
37
|
+
}, { _id: false });
|
|
38
|
+
|
|
39
|
+
const reviewUpdateSchema = new mongoose.Schema({
|
|
40
|
+
turnId: { type: String, required: true },
|
|
41
|
+
tools: { type: [String], default: [] },
|
|
42
|
+
patientText: { type: String, default: null },
|
|
43
|
+
impressions: { type: [impressionUpdateSchema], default: [] },
|
|
44
|
+
safetyFlags: { type: [String], default: [] },
|
|
45
|
+
at: { type: Date, required: true },
|
|
46
|
+
}, { _id: false });
|
|
47
|
+
|
|
27
48
|
const noteFactSchema = new mongoose.Schema({
|
|
28
49
|
variableId: { type: String, required: true },
|
|
29
50
|
concept: { type: String, default: null },
|
|
@@ -126,6 +147,9 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
126
147
|
openedBy: { type: String, required: true },
|
|
127
148
|
assistantPausedByReview: { type: Boolean, default: false },
|
|
128
149
|
alarms: { type: [alarmSchema], default: [] },
|
|
150
|
+
updates: { type: [reviewUpdateSchema], default: [] },
|
|
151
|
+
updatedSinceSeen: { type: Boolean, default: false },
|
|
152
|
+
previousReviewId: { type: String, default: null },
|
|
129
153
|
callLogs: { type: [callLogSchema], default: [] },
|
|
130
154
|
noteFacts: { type: [noteFactSchema], default: [] },
|
|
131
155
|
drafts: { type: [draftSchema], default: [] },
|
|
@@ -33,6 +33,8 @@ const { switchThreadStoppedStatus } = require('./threadService');
|
|
|
33
33
|
|
|
34
34
|
const AUDIT_SOURCE = 'escalation_review';
|
|
35
35
|
const RECENT_REVIEW_LIMIT = 20;
|
|
36
|
+
const MAX_REVIEW_UPDATES = 50;
|
|
37
|
+
const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
36
38
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
37
39
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
38
40
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
@@ -412,6 +414,59 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
|
|
|
412
414
|
}
|
|
413
415
|
|
|
414
416
|
const BOT_OPERATOR = 'bot:reportMedicalEscalation';
|
|
417
|
+
const AGENT_OPERATOR = 'bot:clinicalAgent';
|
|
418
|
+
|
|
419
|
+
async function previousReviewIdOf(EscalationReview, patientCode, now) {
|
|
420
|
+
try {
|
|
421
|
+
const previous = await EscalationReview
|
|
422
|
+
.findOne({ patientCode, closedAt: { $gte: new Date(now.getTime() - PREVIOUS_REVIEW_WINDOW_MS) } }, { _id: 1 })
|
|
423
|
+
.sort({ closedAt: -1 })
|
|
424
|
+
.lean();
|
|
425
|
+
return previous ? String(previous._id) : null;
|
|
426
|
+
} catch (error) {
|
|
427
|
+
logger.warn('[EscalationReview] The previous review lookup failed; opening the review unlinked', { error: redactedError(error) });
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// Files what the agent characterized after the escalation on the patient's open review, and sends a
|
|
433
|
+
// returned review back to the queue. Never opens a review: only an escalation does.
|
|
434
|
+
async function recordReviewUpdate({ code, update } = {}) {
|
|
435
|
+
if (!update) return null;
|
|
436
|
+
try {
|
|
437
|
+
const patientCode = patientCodeOf(code);
|
|
438
|
+
const EscalationReview = getEscalationReview();
|
|
439
|
+
const pushed = await EscalationReview.findOneAndUpdate(
|
|
440
|
+
{ patientCode, closedAt: null },
|
|
441
|
+
{ $push: { updates: { $each: [update], $slice: -MAX_REVIEW_UPDATES } } },
|
|
442
|
+
{ new: true },
|
|
443
|
+
).lean();
|
|
444
|
+
if (!pushed) return null;
|
|
445
|
+
|
|
446
|
+
// The turn that opened the review seeds its draft, but it is not news to whoever opens it.
|
|
447
|
+
const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
|
|
448
|
+
const updated = openingTurn ? pushed : (await EscalationReview
|
|
449
|
+
.findOneAndUpdate({ _id: pushed._id }, { $set: { updatedSinceSeen: true } }, { new: true })
|
|
450
|
+
.lean()) ?? pushed;
|
|
451
|
+
const requeued = updated.status === 'returned'
|
|
452
|
+
? await EscalationReview
|
|
453
|
+
.findOneAndUpdate({ _id: updated._id, status: 'returned' }, { $set: { status: 'documenting' } }, { new: true })
|
|
454
|
+
.lean()
|
|
455
|
+
: null;
|
|
456
|
+
await audit(updated, AGENT_OPERATOR, null, {
|
|
457
|
+
action: 'case_updated',
|
|
458
|
+
turnId: update.turnId,
|
|
459
|
+
tools: update.tools,
|
|
460
|
+
...(requeued && { statusFrom: 'returned', statusTo: 'documenting' }),
|
|
461
|
+
});
|
|
462
|
+
return requeued || updated;
|
|
463
|
+
} catch (error) {
|
|
464
|
+
logger.error('[EscalationReview] The agent update was not recorded against the review', {
|
|
465
|
+
error: redactedError(error), stack: redactedStack(error),
|
|
466
|
+
});
|
|
467
|
+
return null;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
415
470
|
|
|
416
471
|
async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
417
472
|
try {
|
|
@@ -434,7 +489,11 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
|
434
489
|
}
|
|
435
490
|
try {
|
|
436
491
|
return (await EscalationReview.create({
|
|
437
|
-
patientCode,
|
|
492
|
+
patientCode,
|
|
493
|
+
openedBy: BOT_OPERATOR,
|
|
494
|
+
alarms: [entry],
|
|
495
|
+
assistantPausedByReview: false,
|
|
496
|
+
previousReviewId: await previousReviewIdOf(EscalationReview, patientCode, now),
|
|
438
497
|
})).toObject();
|
|
439
498
|
} catch (error) {
|
|
440
499
|
if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
|
|
@@ -513,6 +572,15 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
|
|
|
513
572
|
const reviewId = reviewIdOf(id);
|
|
514
573
|
const operator = requiredText(requestedBy, 'requestedBy');
|
|
515
574
|
const review = await loadReview(reviewId);
|
|
575
|
+
if (review.updatedSinceSeen) {
|
|
576
|
+
// Only clears what this read returned: an update that lands meanwhile changes updatedAt and stays unread.
|
|
577
|
+
await getEscalationReview()
|
|
578
|
+
// A read is not a change: leaving updatedAt alone keeps handoff claims and grace periods intact.
|
|
579
|
+
.updateOne({ _id: review._id, updatedAt: review.updatedAt }, { $set: { updatedSinceSeen: false } }, { timestamps: false })
|
|
580
|
+
.catch((error) => logger.warn('[EscalationReview] The updated mark was not cleared', {
|
|
581
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
582
|
+
}));
|
|
583
|
+
}
|
|
516
584
|
return { review, isApprover: await isEscalationApprover(operator) };
|
|
517
585
|
}
|
|
518
586
|
|
|
@@ -857,6 +925,9 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
857
925
|
if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
|
|
858
926
|
throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
|
|
859
927
|
}
|
|
928
|
+
if (draftedAt && (review.updates ?? []).some((entry) => new Date(entry.at).getTime() > draftedAt)) {
|
|
929
|
+
throw httpError(409, 'The agent characterized the case after this draft was written; review it and save a new draft before sending it to the doctor');
|
|
930
|
+
}
|
|
860
931
|
const identity = await readDoctorIdentity(review);
|
|
861
932
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
862
933
|
const link = doctorLink(review);
|
|
@@ -872,7 +943,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
872
943
|
reviewId,
|
|
873
944
|
[review.status],
|
|
874
945
|
{ $set: { status: 'handing_off', operationClaim: claim } },
|
|
875
|
-
|
|
946
|
+
// updatedAt moves with every write, so an agent update filed since the read fails the claim.
|
|
947
|
+
{ drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
|
|
876
948
|
);
|
|
877
949
|
let delivery = {};
|
|
878
950
|
let updated;
|
|
@@ -975,6 +1047,17 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
975
1047
|
throw httpError(409, 'This decision carries no approved text to send to the patient');
|
|
976
1048
|
}
|
|
977
1049
|
|
|
1050
|
+
const decidedAt = claimed.decisions[decisionNumber - 1].createdAt;
|
|
1051
|
+
if (decidedAt && (claimed.updates ?? []).some((entry) => new Date(entry.at) > new Date(decidedAt))) {
|
|
1052
|
+
// Back to documenting: the decision is spent, and a new draft and decision have to follow.
|
|
1053
|
+
await releaseReview(reviewId, 'sending', 'documenting', claim).catch((releaseError) => {
|
|
1054
|
+
logger.error('[EscalationReview] The claim was not released after a decision new information overtook', {
|
|
1055
|
+
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
1056
|
+
});
|
|
1057
|
+
});
|
|
1058
|
+
throw httpError(409, 'The agent characterized the case after this decision; it went back to documenting for a new draft and decision');
|
|
1059
|
+
}
|
|
1060
|
+
|
|
978
1061
|
// Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
|
|
979
1062
|
let message;
|
|
980
1063
|
try {
|
|
@@ -1161,13 +1244,15 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
|
|
|
1161
1244
|
|
|
1162
1245
|
let review;
|
|
1163
1246
|
try {
|
|
1247
|
+
// Once the doctor has seen or decided the review, cancelling it needs a reason whatever its status.
|
|
1164
1248
|
review = await updateReview(reviewId, allowed, {
|
|
1165
1249
|
$set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
|
|
1166
|
-
});
|
|
1250
|
+
}, notes ? {} : { 'doctorHandoffs.0': { $exists: false }, 'decisions.0': { $exists: false } });
|
|
1167
1251
|
} catch (error) {
|
|
1168
1252
|
if (error?.statusCode !== 409 || notes) throw error;
|
|
1169
1253
|
const current = await loadReview(reviewId);
|
|
1170
|
-
|
|
1254
|
+
const doctorInvolved = Boolean(current.doctorHandoffs?.length || current.decisions?.length);
|
|
1255
|
+
if (doctorInvolved || CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
|
|
1171
1256
|
throw error;
|
|
1172
1257
|
}
|
|
1173
1258
|
|
|
@@ -1193,6 +1278,7 @@ module.exports = {
|
|
|
1193
1278
|
openEscalationReview,
|
|
1194
1279
|
recordEscalationAlarm,
|
|
1195
1280
|
recordDoctorDecision,
|
|
1281
|
+
recordReviewUpdate,
|
|
1196
1282
|
sendApprovedIndications,
|
|
1197
1283
|
setReviewCases,
|
|
1198
1284
|
suggestDraft,
|