@peopl-health/nexus 5.60.1 → 5.61.0-dev.11181
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/adapters/messageAdapters/TwilioMessageAdapter.js +1 -0
- package/lib/clinical/models/clinicalSourceEventModel.js +32 -0
- package/lib/clinical/services/clinicalCaptureConfigService.js +22 -0
- package/lib/clinical/services/clinicalEventService.js +132 -0
- package/lib/clinical/services/clinicalMessageCaptureService.js +72 -0
- package/lib/clinical/services/gradeSourceService.js +8 -33
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +1 -1
- package/lib/index.d.ts +5 -0
- package/lib/index.js +1 -0
- package/lib/services/messageService.js +4 -1
- package/lib/storage/MongoStorage.js +14 -2
- package/package.json +1 -1
|
@@ -26,6 +26,7 @@ class TwilioMessageAdapter extends MessageAdapter {
|
|
|
26
26
|
processed: false,
|
|
27
27
|
pushName: rawMessage.ProfileName || null,
|
|
28
28
|
body,
|
|
29
|
+
normalizedContent: contactBody ? { type: 'extracted_contact', text: contactBody } : null,
|
|
29
30
|
media,
|
|
30
31
|
interactive,
|
|
31
32
|
quotedMessageId: rawMessage.OriginalRepliedMessageSid || null,
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const mongoose = require('mongoose');
|
|
2
|
+
|
|
3
|
+
const { clinicalConnection } = require('../config/connection');
|
|
4
|
+
|
|
5
|
+
const clinicalSourceEventSchema = new mongoose.Schema({
|
|
6
|
+
_id: { type: String, required: true },
|
|
7
|
+
tenantId: { type: String, required: true, immutable: true },
|
|
8
|
+
sourceSystem: { type: String, required: true, immutable: true },
|
|
9
|
+
sourceRecordId: { type: String, required: true, immutable: true },
|
|
10
|
+
sourceRevision: { type: String, required: true, immutable: true },
|
|
11
|
+
sourceMessageId: { type: String, default: null, immutable: true },
|
|
12
|
+
patientId: { type: String, default: null, immutable: true },
|
|
13
|
+
identity: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
14
|
+
actor: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
15
|
+
experiencer: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
16
|
+
validTime: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
17
|
+
recordTime: { type: Date, required: true, immutable: true },
|
|
18
|
+
evidenceRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
|
|
19
|
+
artifactRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
|
|
20
|
+
normalizedContent: { type: mongoose.Schema.Types.Mixed, default: null, immutable: true },
|
|
21
|
+
payload: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
|
|
22
|
+
schemaVersion: { type: String, required: true, immutable: true },
|
|
23
|
+
policyVersion: { type: String, default: null, immutable: true },
|
|
24
|
+
}, { versionKey: false, autoCreate: false, autoIndex: false });
|
|
25
|
+
|
|
26
|
+
function getClinicalSourceEventModel() {
|
|
27
|
+
const connection = clinicalConnection();
|
|
28
|
+
return connection.models.ClinicalSourceEvent
|
|
29
|
+
|| connection.model('ClinicalSourceEvent', clinicalSourceEventSchema, 'clinicalSourceEvent');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
module.exports = { getClinicalSourceEventModel, clinicalSourceEventSchema };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const { getModelDatabase } = require('../../config/mongoConfig');
|
|
2
|
+
|
|
3
|
+
class ClinicalCaptureConfigError extends Error {
|
|
4
|
+
constructor() {
|
|
5
|
+
super('Clinical source capture configuration invalid');
|
|
6
|
+
this.name = 'ClinicalCaptureConfigError';
|
|
7
|
+
this.code = 'CLINICAL_SOURCE_CONFIG';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function assertClinicalCaptureConfigured(settings) {
|
|
12
|
+
if (settings?.enabled !== true && settings?.enabled !== 'true') return;
|
|
13
|
+
|
|
14
|
+
const tenantId = settings.tenantId;
|
|
15
|
+
const clinicalDb = getModelDatabase('Clinical');
|
|
16
|
+
if (typeof tenantId !== 'string' || !tenantId || tenantId.trim() !== tenantId
|
|
17
|
+
|| typeof clinicalDb !== 'string' || !clinicalDb.trim()) {
|
|
18
|
+
throw new ClinicalCaptureConfigError();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
module.exports = { assertClinicalCaptureConfigured, ClinicalCaptureConfigError };
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
const { createHash } = require('crypto');
|
|
2
|
+
|
|
3
|
+
class ClinicalSourceError extends Error {
|
|
4
|
+
constructor(code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'ClinicalSourceError';
|
|
7
|
+
this.code = code;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function invalidSource() {
|
|
12
|
+
return new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isStableId(value) {
|
|
16
|
+
return typeof value === 'string' && value.length > 0 && value.trim() === value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// JSON only: reject values that would silently disappear or change during persistence.
|
|
20
|
+
function canonical(value, ancestors = new Set()) {
|
|
21
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
|
|
22
|
+
if (typeof value === 'number' && Number.isFinite(value)) return JSON.stringify(value);
|
|
23
|
+
if (typeof value !== 'object' || ancestors.has(value)) throw invalidSource();
|
|
24
|
+
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw invalidSource();
|
|
25
|
+
ancestors.add(value);
|
|
26
|
+
const result = Array.isArray(value)
|
|
27
|
+
? '[' + Array.from(value, item => canonical(item, ancestors)).join(',') + ']'
|
|
28
|
+
: '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key], ancestors)).join(',') + '}';
|
|
29
|
+
ancestors.delete(value);
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function validateClinicalSourceEvent(envelope) {
|
|
34
|
+
if (!envelope || typeof envelope !== 'object') throw invalidSource();
|
|
35
|
+
for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'schemaVersion']) {
|
|
36
|
+
if (!isStableId(envelope[field])) throw invalidSource();
|
|
37
|
+
}
|
|
38
|
+
if (envelope.sourceMessageId != null && !isStableId(envelope.sourceMessageId)) throw invalidSource();
|
|
39
|
+
if (envelope.patientId !== null && !isStableId(envelope.patientId)) throw invalidSource();
|
|
40
|
+
if (!['unknown', 'ambiguous', 'resolved'].includes(envelope.identity?.status) || !Array.isArray(envelope.identity.sourceRefs)) throw invalidSource();
|
|
41
|
+
if ((envelope.patientId !== null) !== (envelope.identity.status === 'resolved')) throw invalidSource();
|
|
42
|
+
for (const field of ['actor', 'experiencer', 'payload']) {
|
|
43
|
+
if (!envelope[field] || typeof envelope[field] !== 'object' || Array.isArray(envelope[field])) throw invalidSource();
|
|
44
|
+
}
|
|
45
|
+
if (!Array.isArray(envelope.evidenceRefs)) throw invalidSource();
|
|
46
|
+
const artifactRefs = envelope.artifactRefs === undefined ? [] : envelope.artifactRefs;
|
|
47
|
+
if (!Array.isArray(artifactRefs)) throw invalidSource();
|
|
48
|
+
const attachmentIndexes = new Set();
|
|
49
|
+
for (const ref of artifactRefs) {
|
|
50
|
+
if (!ref || typeof ref !== 'object' || Array.isArray(ref)
|
|
51
|
+
|| Object.keys(ref).some(key => !['attachmentIndex', 'bucket', 'key'].includes(key))
|
|
52
|
+
|| !Number.isSafeInteger(ref.attachmentIndex) || ref.attachmentIndex < 0
|
|
53
|
+
|| attachmentIndexes.has(ref.attachmentIndex) || !isStableId(ref.bucket) || !isStableId(ref.key)) throw invalidSource();
|
|
54
|
+
attachmentIndexes.add(ref.attachmentIndex);
|
|
55
|
+
}
|
|
56
|
+
const normalizedContent = envelope.normalizedContent ?? null;
|
|
57
|
+
if (normalizedContent !== null && (typeof normalizedContent !== 'object' || Array.isArray(normalizedContent)
|
|
58
|
+
|| Object.keys(normalizedContent).some(key => !['type', 'text'].includes(key))
|
|
59
|
+
|| normalizedContent.type !== 'extracted_contact' || typeof normalizedContent.text !== 'string'
|
|
60
|
+
|| !normalizedContent.text.trim())) throw invalidSource();
|
|
61
|
+
if (!['known', 'unknown'].includes(envelope.validTime?.status)) throw invalidSource();
|
|
62
|
+
if (envelope.validTime.status === 'known' && (typeof envelope.validTime.at !== 'string' || !Number.isFinite(Date.parse(envelope.validTime.at)))) throw invalidSource();
|
|
63
|
+
if (envelope.validTime.status === 'unknown' && envelope.validTime.at != null) throw invalidSource();
|
|
64
|
+
if (envelope.policyVersion !== null && !isStableId(envelope.policyVersion)) throw invalidSource();
|
|
65
|
+
const document = {};
|
|
66
|
+
for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'patientId', 'identity', 'actor', 'experiencer', 'validTime', 'evidenceRefs', 'payload', 'schemaVersion', 'policyVersion']) document[field] = envelope[field];
|
|
67
|
+
document.sourceMessageId = envelope.sourceMessageId ?? null;
|
|
68
|
+
document.artifactRefs = artifactRefs;
|
|
69
|
+
document.normalizedContent = normalizedContent;
|
|
70
|
+
return JSON.parse(canonical(document));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function sourceFingerprint(document) {
|
|
74
|
+
// Identity adjudication, policy selection, capture artifacts and observation time are not source revisions.
|
|
75
|
+
const omitted = new Set(['artifactRefs', 'normalizedContent', 'patientId', 'identity', 'policyVersion', 'recordTime', '_id']);
|
|
76
|
+
const source = Object.fromEntries(Object.entries(document).filter(([key]) => !omitted.has(key)));
|
|
77
|
+
return canonical({ ...source, identitySourceRefs: document.identity.sourceRefs });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function persistenceClassification(stage, error) {
|
|
81
|
+
if (stage === 'unacknowledged') return 'unacknowledged';
|
|
82
|
+
if (stage === 'missing_duplicate') return 'not_found';
|
|
83
|
+
if ([50, 64].includes(error?.code) || error?.name === 'MongoNetworkTimeoutError') return 'timeout';
|
|
84
|
+
if ([13, 18].includes(error?.code)) return 'authorization';
|
|
85
|
+
if ([6, 7, 89, 91].includes(error?.code)
|
|
86
|
+
|| ['MongoNetworkError', 'MongoServerSelectionError'].includes(error?.name)) return 'unavailable';
|
|
87
|
+
return 'unknown';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function ingestClinicalSourceEvent(envelope) {
|
|
91
|
+
const document = validateClinicalSourceEvent(envelope);
|
|
92
|
+
const eventId = createHash('sha256').update(JSON.stringify([
|
|
93
|
+
document.tenantId, document.sourceSystem, document.sourceRecordId, document.sourceRevision,
|
|
94
|
+
])).digest('hex');
|
|
95
|
+
const fingerprint = sourceFingerprint(document);
|
|
96
|
+
let stage = 'model';
|
|
97
|
+
try {
|
|
98
|
+
const { getClinicalSourceEventModel } = require('../models/clinicalSourceEventModel');
|
|
99
|
+
const { collection } = getClinicalSourceEventModel();
|
|
100
|
+
try {
|
|
101
|
+
stage = 'write';
|
|
102
|
+
const result = await collection.insertOne({ ...document, _id: eventId, recordTime: new Date() }, { writeConcern: { w: 'majority', j: true, wtimeoutMS: 10000 } });
|
|
103
|
+
if (!result?.acknowledged) {
|
|
104
|
+
stage = 'unacknowledged';
|
|
105
|
+
throw new Error();
|
|
106
|
+
}
|
|
107
|
+
return { eventId, state: document.patientId === null ? 'identity_pending' : 'recorded' };
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error.code !== 11000) throw error;
|
|
110
|
+
stage = 'duplicate_read';
|
|
111
|
+
const existing = await collection.findOne({ _id: eventId }, { readPreference: 'primary', readConcern: { level: 'majority' } });
|
|
112
|
+
if (!existing) {
|
|
113
|
+
stage = 'missing_duplicate';
|
|
114
|
+
throw new Error();
|
|
115
|
+
}
|
|
116
|
+
stage = 'duplicate_verify';
|
|
117
|
+
if (sourceFingerprint(existing) !== fingerprint) throw new ClinicalSourceError('CLINICAL_SOURCE_CONFLICT', 'Clinical source revision conflict');
|
|
118
|
+
return { eventId, state: 'duplicate' };
|
|
119
|
+
}
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error instanceof ClinicalSourceError && error.code === 'CLINICAL_SOURCE_CONFLICT') throw error;
|
|
122
|
+
try {
|
|
123
|
+
const { logger } = require('../../utils/logger');
|
|
124
|
+
logger.error('[clinicalEventService] Source persistence failed', { stage, classification: persistenceClassification(stage, error) });
|
|
125
|
+
} catch {
|
|
126
|
+
// Diagnostic availability must not change the safe public failure contract.
|
|
127
|
+
}
|
|
128
|
+
throw new ClinicalSourceError('CLINICAL_SOURCE_PERSISTENCE', 'Clinical source persistence failed');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
module.exports = { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const { isBenchMode } = require('../../utils/benchModeHelper');
|
|
2
|
+
const { isShadowRun } = require('../../utils/shadowScope');
|
|
3
|
+
const { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError } = require('./clinicalEventService');
|
|
4
|
+
|
|
5
|
+
function pick(source, fields) {
|
|
6
|
+
if (!source || typeof source !== 'object') return null;
|
|
7
|
+
return Object.fromEntries(fields.filter(field => source[field] !== undefined).map(field => [field, source[field]]));
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function mediaEvidence(media) {
|
|
11
|
+
const fields = ['key', 'bucket', 'bucketName', 'mimeType', 'mediaType', 'contentType', 'filename', 'fileName', 'fileSize', 'caption', 'url', 'size', 'sha256'];
|
|
12
|
+
const evidence = pick(media, fields);
|
|
13
|
+
if (evidence && Array.isArray(media.metadata?.attachments)) {
|
|
14
|
+
evidence.attachments = media.metadata.attachments.map(item => pick(item, fields));
|
|
15
|
+
}
|
|
16
|
+
return evidence;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function privateArtifactRefs(media) {
|
|
20
|
+
const attachments = Array.isArray(media?.metadata?.attachments) ? media.metadata.attachments : [];
|
|
21
|
+
return [media, ...attachments].flatMap((item, attachmentIndex) => {
|
|
22
|
+
const bucket = item?.bucketName ?? item?.bucket;
|
|
23
|
+
if (bucket == null || item?.key == null) return [];
|
|
24
|
+
return [{ attachmentIndex, bucket, key: item.key }];
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function buildClinicalMessageEnvelope(values, tenantId) {
|
|
29
|
+
const raw = values.raw ?? {};
|
|
30
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) throw new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
|
|
31
|
+
const sourceSystem = values.sourceSystem || values.sourceProvider || (raw.MessageSid ? 'twilio' : raw.key?.id ? 'baileys' : 'whatsapp_platform');
|
|
32
|
+
const sourceId = values.sourceRecordId ?? values.message_id;
|
|
33
|
+
const actorId = raw.From || raw.key?.remoteJid || values.contact_code || values.sourceActorId || values.numero || null;
|
|
34
|
+
const providerEvidence = pick(raw, ['MessageSid', 'SmsSid', 'OriginalRepliedMessageSid', 'Body', 'ButtonPayload', 'ButtonText', 'ListId', 'ListTitle', 'ListDescription', 'FlowData', 'InteractiveData', 'NumMedia', 'MediaUrl0', 'MediaContentType0']);
|
|
35
|
+
const mediaFields = Object.keys(raw).filter(key => /^Media(?:Url|ContentType)\d+$/.test(key));
|
|
36
|
+
Object.assign(providerEvidence, pick(raw, mediaFields));
|
|
37
|
+
const hasProviderMedia = mediaFields.some(key => /^MediaUrl\d+$/.test(key));
|
|
38
|
+
const event = {
|
|
39
|
+
tenantId, sourceSystem, sourceRecordId: sourceId, sourceRevision: values.sourceRevision ?? '1',
|
|
40
|
+
sourceMessageId: values.message_id ?? null, patientId: null,
|
|
41
|
+
identity: {
|
|
42
|
+
status: 'unknown', sourceRefs: actorId ? [{ system: 'message_transport', id: actorId }] : [],
|
|
43
|
+
routingEnrichment: { contactRole: values.contact_role || null, patientReference: values.numero || null },
|
|
44
|
+
},
|
|
45
|
+
actor: { type: 'transport_contact', sourceId: actorId, reportedRole: null, authenticatedRole: null },
|
|
46
|
+
experiencer: { patientId: null, status: 'unknown' },
|
|
47
|
+
validTime: { status: 'unknown' },
|
|
48
|
+
evidenceRefs: [],
|
|
49
|
+
artifactRefs: privateArtifactRefs(values.media),
|
|
50
|
+
normalizedContent: values.normalizedContent ?? null,
|
|
51
|
+
payload: {
|
|
52
|
+
sourceTimestamp: values.sourceTimestamp ?? null,
|
|
53
|
+
text: typeof raw.Body === 'string' ? raw.Body : values.sourceText ?? values.plainBody ?? values.body ?? '',
|
|
54
|
+
interactive: pick(values.interactive_data, ['type', 'payload', 'title', 'id', 'description', 'replyId', 'flowData', 'interactiveData']) || (values.interactive_type ? { type: values.interactive_type } : null),
|
|
55
|
+
media: hasProviderMedia ? null : mediaEvidence(values.media),
|
|
56
|
+
providerEvidence,
|
|
57
|
+
quotedMessageId: values.quotedMessageId ?? raw.OriginalRepliedMessageSid ?? null,
|
|
58
|
+
},
|
|
59
|
+
schemaVersion: '1', policyVersion: null,
|
|
60
|
+
};
|
|
61
|
+
return validateClinicalSourceEvent(event);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function captureClinicalMessage(values, settings = {}) {
|
|
65
|
+
const enabled = settings?.enabled;
|
|
66
|
+
if (enabled !== true && enabled !== 'true') return { state: 'skipped', reason: 'disabled' };
|
|
67
|
+
if (isShadowRun() || isBenchMode(values?.numero) || isBenchMode(values?.contact_code)) return { state: 'skipped', reason: 'isolated_run' };
|
|
68
|
+
if (values?.from_me !== false || !['patient', 'whatsapp_platform'].includes(values?.origin)) return { state: 'skipped', reason: 'excluded_message' };
|
|
69
|
+
return ingestClinicalSourceEvent(buildClinicalMessageEnvelope(values, settings.tenantId));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
module.exports = { buildClinicalMessageEnvelope, captureClinicalMessage };
|
|
@@ -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: {
|
package/lib/index.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ declare module '@peopl-health/nexus' {
|
|
|
11
11
|
contactName?: string | null;
|
|
12
12
|
contactLabel?: string | null;
|
|
13
13
|
body?: string;
|
|
14
|
+
/** Derived first-capture contact evidence; never canonical patient identity. */
|
|
15
|
+
normalizedContent?: { type: 'extracted_contact'; text: string } | null;
|
|
14
16
|
message?: string;
|
|
15
17
|
timestamp?: string | Date;
|
|
16
18
|
createdAt?: string | Date;
|
|
@@ -86,6 +88,8 @@ declare module '@peopl-health/nexus' {
|
|
|
86
88
|
}
|
|
87
89
|
|
|
88
90
|
export interface StorageConfig {
|
|
91
|
+
/** Explicit prospective journal configuration. Enabled capture requires tenantId and a Clinical mapping set before Nexus.initialize(). */
|
|
92
|
+
clinicalEventCapture?: { enabled?: boolean | 'true' | 'false'; tenantId?: string };
|
|
89
93
|
mongoUri: string;
|
|
90
94
|
dbName: string;
|
|
91
95
|
collections?: {
|
|
@@ -407,6 +411,7 @@ declare module '@peopl-health/nexus' {
|
|
|
407
411
|
export function requestIdMiddleware(req: any, res: any, next: () => void): void;
|
|
408
412
|
export function getRequestId(): string | null;
|
|
409
413
|
|
|
414
|
+
/** Set the Clinical mapping before initializing MongoStorage with enabled clinicalEventCapture. */
|
|
410
415
|
export function setModelDatabases(mapping: Record<string, string>): void;
|
|
411
416
|
export function setModelDatabase(modelName: string, dbName: string): void;
|
|
412
417
|
export function getModelDatabase(modelName: string): string | null;
|
package/lib/index.js
CHANGED
|
@@ -9,6 +9,8 @@ const { getClinicalContext } = require('../helpers/patientInformationHelper');
|
|
|
9
9
|
|
|
10
10
|
const { updateRecordByFilter } = require('../services/airtableService');
|
|
11
11
|
|
|
12
|
+
const { captureClinicalMessage } = require('../clinical/services/clinicalMessageCaptureService');
|
|
13
|
+
|
|
12
14
|
const INTERNAL_ORIGINS = new Set(['system', 'instruction']);
|
|
13
15
|
|
|
14
16
|
async function getMessages(query, options = {}) {
|
|
@@ -28,8 +30,9 @@ async function aggregateMessages(pipeline, options = {}) {
|
|
|
28
30
|
return Message.aggregate(pipeline, options);
|
|
29
31
|
}
|
|
30
32
|
|
|
31
|
-
async function insertMessage(values) {
|
|
33
|
+
async function insertMessage(values, options = {}) {
|
|
32
34
|
try {
|
|
35
|
+
await captureClinicalMessage(values, options?.clinicalEventCapture);
|
|
33
36
|
if (!values.clinical_context) {
|
|
34
37
|
const { clinicalContext } = await getClinicalContext(values.numero);
|
|
35
38
|
values.clinical_context = clinicalContext;
|
|
@@ -12,10 +12,12 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
|
12
12
|
const { getMessages, insertMessage } = require('../services/messageService');
|
|
13
13
|
|
|
14
14
|
const { getEventBus: getStatusEventBus } = require('../core/NexusMessaging');
|
|
15
|
+
const { assertClinicalCaptureConfigured } = require('../clinical/services/clinicalCaptureConfigService');
|
|
15
16
|
|
|
16
17
|
class MongoStorage {
|
|
17
18
|
constructor(config) {
|
|
18
19
|
this.mongoUri = config.mongoUri;
|
|
20
|
+
this.clinicalEventCapture = config.clinicalEventCapture;
|
|
19
21
|
this.dbName = config.dbName;
|
|
20
22
|
this.collections = config.collections || {
|
|
21
23
|
messages: 'messages',
|
|
@@ -32,6 +34,7 @@ class MongoStorage {
|
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
async connect() {
|
|
37
|
+
assertClinicalCaptureConfigured(this.clinicalEventCapture);
|
|
35
38
|
await mongoConnect(this.mongoUri);
|
|
36
39
|
if (this.dbName) this.db = getDb(this.dbName);
|
|
37
40
|
}
|
|
@@ -39,7 +42,7 @@ class MongoStorage {
|
|
|
39
42
|
async saveMessage(messageData) {
|
|
40
43
|
try {
|
|
41
44
|
const values = this.buildMessageValues(messageData);
|
|
42
|
-
const { doc } = await insertMessage(values);
|
|
45
|
+
const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
|
|
43
46
|
logger.info('[MongoStorage] Message stored');
|
|
44
47
|
if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId);
|
|
45
48
|
return doc;
|
|
@@ -54,7 +57,7 @@ class MongoStorage {
|
|
|
54
57
|
...messageData,
|
|
55
58
|
statusInfo: { status: 'queued', updatedAt: new Date() }
|
|
56
59
|
});
|
|
57
|
-
const { doc } = await insertMessage(values);
|
|
60
|
+
const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
|
|
58
61
|
if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId, 'queued');
|
|
59
62
|
return doc;
|
|
60
63
|
}
|
|
@@ -112,6 +115,15 @@ class MongoStorage {
|
|
|
112
115
|
plainBody: messageData.plainBody || '',
|
|
113
116
|
processed: messageData.processed || false,
|
|
114
117
|
message_id: messageId,
|
|
118
|
+
sourceText: messageData.plainBody ?? messageData.body,
|
|
119
|
+
normalizedContent: messageData.normalizedContent,
|
|
120
|
+
sourceSystem: messageData.sourceSystem,
|
|
121
|
+
sourceProvider: messageData.provider,
|
|
122
|
+
sourceRecordId: messageData.sourceRecordId,
|
|
123
|
+
sourceRevision: messageData.sourceRevision,
|
|
124
|
+
sourceTimestamp: messageData.sourceTimestamp,
|
|
125
|
+
sourceActorId: messageData.from,
|
|
126
|
+
quotedMessageId: messageData.quotedMessageId,
|
|
115
127
|
interactive_type: messageData.interactive?.type || null,
|
|
116
128
|
interactive_data: messageData.interactive || null,
|
|
117
129
|
from_me: messageData.fromMe !== undefined ? messageData.fromMe : true,
|