@peopl-health/nexus 6.4.3 → 6.4.5
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/services/clinicalExtractionService.js +9 -2
- package/lib/controllers/escalationReviewController.js +15 -2
- package/lib/services/escalationCaseStateService.js +68 -0
- package/lib/services/reviewBoardService.js +24 -6
- package/lib/services/untakenAlertService.js +7 -5
- package/lib/utils/textMatchUtils.js +52 -18
- package/package.json +1 -1
|
@@ -3,7 +3,7 @@ const { getExtractor } = require('../config/subAgentsConfig');
|
|
|
3
3
|
const { detectSafetyFlags } = require('../helpers/safetyFlagsHelper');
|
|
4
4
|
const { buildExtractorInput, toClinicalMention } = require('../helpers/clinicalMentionHelper');
|
|
5
5
|
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
6
|
-
const { isQuoteAnchored } = require('../../utils/textMatchUtils');
|
|
6
|
+
const { isQuoteAnchored, negationNearQuote } = require('../../utils/textMatchUtils');
|
|
7
7
|
const { foldAccents } = require('../../utils/formatUtils');
|
|
8
8
|
const { getClinicalContext } = require('../../helpers/patientInformationHelper');
|
|
9
9
|
const { withTiming } = require('../../utils/tracingDecorator');
|
|
@@ -110,6 +110,7 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
|
|
|
110
110
|
let unanchored = 0;
|
|
111
111
|
let unusable = 0;
|
|
112
112
|
let forcedPending = 0;
|
|
113
|
+
let polarityConflicts = 0;
|
|
113
114
|
rawMentions.forEach((raw, index) => {
|
|
114
115
|
if (!raw || typeof raw !== 'object') {
|
|
115
116
|
unusable += 1;
|
|
@@ -126,10 +127,12 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
|
|
|
126
127
|
return;
|
|
127
128
|
}
|
|
128
129
|
const quotes = mention.provenance.verbatimQuotes;
|
|
129
|
-
|
|
130
|
+
const negated = Boolean(mention.fact.assertion?.negated);
|
|
131
|
+
if (!quotes.some((quote) => isQuoteAnchored(quote, text, { negated }))) {
|
|
130
132
|
unanchored += 1;
|
|
131
133
|
return;
|
|
132
134
|
}
|
|
135
|
+
if (!negated && quotes.every((quote) => negationNearQuote(quote, text))) polarityConflicts += 1;
|
|
133
136
|
if (!mention.provenance.needsConfirmation && !endsNamedLine(raw, mention.fact)
|
|
134
137
|
&& namesNothingSpecific(mention.fact.canonicalTerm, vagueWords)) {
|
|
135
138
|
forcedPending += 1;
|
|
@@ -148,10 +151,14 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
|
|
|
148
151
|
if (forcedPending) {
|
|
149
152
|
logger.warn('[clinicalExtraction] mentions held back: the term names no specific clinical entity', { turnId, forcedPending });
|
|
150
153
|
}
|
|
154
|
+
if (polarityConflicts) {
|
|
155
|
+
logger.warn('[clinicalExtraction] mentions read as present despite a nearby negation', { turnId, polarityConflicts });
|
|
156
|
+
}
|
|
151
157
|
trace?.setSignals?.({
|
|
152
158
|
clinicalMentionsUnanchored: unanchored,
|
|
153
159
|
clinicalMentionsPending: pendingMentions.length,
|
|
154
160
|
clinicalMentionsForcedPending: forcedPending,
|
|
161
|
+
clinicalMentionsPolarityConflict: polarityConflicts,
|
|
155
162
|
});
|
|
156
163
|
|
|
157
164
|
const patientMentions = [...clinicalMentions, ...pendingMentions]
|
|
@@ -23,6 +23,8 @@ const {
|
|
|
23
23
|
syncEscalationReviewCase,
|
|
24
24
|
} = require('../services/escalationReviewService');
|
|
25
25
|
const { listReviewBoard } = require('../services/reviewBoardService');
|
|
26
|
+
const { caseStateOf } = require('../services/escalationCaseStateService');
|
|
27
|
+
const { responseDeadlinePolicy } = require('../services/reviewDeadlineService');
|
|
26
28
|
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
27
29
|
|
|
28
30
|
const respondWithError = (res, error, action, context) => {
|
|
@@ -34,6 +36,12 @@ const respondWithError = (res, error, action, context) => {
|
|
|
34
36
|
res.status(error.statusCode || 500).json({ success: false, error: error.message, ...(error.errorCode && { errorCode: error.errorCode }) });
|
|
35
37
|
};
|
|
36
38
|
|
|
39
|
+
// The review still reads when its case state cannot be worked out.
|
|
40
|
+
const safeCaseStateOf = (review) => caseStateOf(review, { policy: responseDeadlinePolicy() }).catch((error) => {
|
|
41
|
+
logger.warn('[EscalationReview] Could not read the case state', { escalationReviewId: String(review?._id), error: redactDirectIdentifiers(String(error?.message || error)) });
|
|
42
|
+
return null;
|
|
43
|
+
});
|
|
44
|
+
|
|
37
45
|
const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
|
|
38
46
|
|
|
39
47
|
const openEscalationReviewController = async (req, res) => {
|
|
@@ -55,7 +63,8 @@ const openEscalationReviewController = async (req, res) => {
|
|
|
55
63
|
const getEscalationReviewController = async (req, res) => {
|
|
56
64
|
try {
|
|
57
65
|
const { review, isApprover, responseDeadline, proposedPlan, prescribers } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
|
|
58
|
-
|
|
66
|
+
const caseState = await safeCaseStateOf(review);
|
|
67
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, caseState, proposedPlan, prescribers });
|
|
59
68
|
} catch (error) {
|
|
60
69
|
respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
|
|
61
70
|
}
|
|
@@ -82,7 +91,11 @@ const getReviewTimelineController = async (req, res) => {
|
|
|
82
91
|
const listEscalationReviewsController = async (req, res) => {
|
|
83
92
|
try {
|
|
84
93
|
const reviews = await listEscalationReviews({ code: req.params.code });
|
|
85
|
-
|
|
94
|
+
// Only the open review gets its state, so the panel's poll stays fresh without reading the review as seen.
|
|
95
|
+
const listed = await Promise.all(reviews.map(async (review) => (review.closedAt
|
|
96
|
+
? withCaseStatus(review)
|
|
97
|
+
: { ...withCaseStatus(review), caseState: await safeCaseStateOf(review) })));
|
|
98
|
+
res.status(200).json({ success: true, reviews: listed });
|
|
86
99
|
} catch (error) {
|
|
87
100
|
respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
|
|
88
101
|
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
3
|
+
const { FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
|
|
4
|
+
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
5
|
+
const { escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
|
|
6
|
+
|
|
7
|
+
const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenReason } = require('./escalationReviewService');
|
|
8
|
+
const { graveMissingOf, isDraftCurrent } = require('./gravePendingService');
|
|
9
|
+
const { pendingWaitMinutes } = require('./reviewDeadlineService');
|
|
10
|
+
const { dueStageOf, untakenClockOf } = require('./untakenAlertService');
|
|
11
|
+
|
|
12
|
+
const WITH_DOCTOR_STATUSES = ['handing_off', 'awaiting_doctor'];
|
|
13
|
+
const DONE_STATUSES = ['closed', 'cancelled'];
|
|
14
|
+
const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
|
|
15
|
+
const timeOf = (value) => new Date(value).getTime();
|
|
16
|
+
|
|
17
|
+
const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, graveFlags: [], ...fields });
|
|
18
|
+
|
|
19
|
+
// The stage the sweep sends on its next tick, else the next one still to come; none while untaken alerts are off.
|
|
20
|
+
function nextAlertOf(review, clock, now) {
|
|
21
|
+
if (!escalationUntakenAlertsLive()) return null;
|
|
22
|
+
const next = dueStageOf(review, clock, now) ?? clock.stages.find((stage) => stage.dueAt && stage.dueAt > now);
|
|
23
|
+
return next ? { stage: next.stage, dueAt: next.dueAt } : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The bot's question for its current draft, while the patient still has the level's wait to answer it.
|
|
27
|
+
function waitingOn(review, clock, now) {
|
|
28
|
+
const latest = (review.drafts ?? []).at(-1);
|
|
29
|
+
const wait = pendingWaitMinutes(clock.level);
|
|
30
|
+
if (review.status !== 'draft_ready' || !wait || latest?.writtenBy !== DRAFT_OPERATOR) return null;
|
|
31
|
+
if (timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return null;
|
|
32
|
+
const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
|
|
33
|
+
if (!ask || ask.skippedReason || (ask.outcome != null && !ANSWERABLE_OUTCOMES.includes(ask.outcome))) return null;
|
|
34
|
+
const dueAt = new Date(timeOf(ask.sentAt) + wait * 60000);
|
|
35
|
+
return dueAt > now ? { since: new Date(ask.sentAt), dueAt, question: ask.question ?? null } : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function takenOf(review, clock) {
|
|
39
|
+
try {
|
|
40
|
+
return await caseTakenReason(review, clock.since, clock.level);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
logger.warn('[EscalationCaseState] Could not tell whether the case was taken', {
|
|
43
|
+
escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
|
|
44
|
+
});
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// One state per case for the team: where it is, who has it and what comes next.
|
|
50
|
+
async function caseStateOf(review, { now = new Date(), policy } = {}) {
|
|
51
|
+
const label = CASE_STATUS_BY_REVIEW_STATUS[review.status]?.label ?? null;
|
|
52
|
+
if (review.closedAt || DONE_STATUSES.includes(review.status)) return state('closed', label);
|
|
53
|
+
if (FOLLOWUP_STATUSES.includes(review.status)) return state('followup', label);
|
|
54
|
+
const clock = PRE_DECISION_STATUSES.includes(review.status) ? untakenClockOf(review, policy) : null;
|
|
55
|
+
if (!clock) return state('in_progress', label);
|
|
56
|
+
|
|
57
|
+
const nextAlert = nextAlertOf(review, clock, now);
|
|
58
|
+
const taken = await takenOf(review, clock);
|
|
59
|
+
if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken });
|
|
60
|
+
const grave = graveMissingOf(review, clock, now).map(({ flag }) => flag);
|
|
61
|
+
if (grave.length) return state('grave_missing', 'Falta dato grave', { since: clock.since, nextAlert, graveFlags: grave });
|
|
62
|
+
if (WITH_DOCTOR_STATUSES.includes(review.status)) return state('with_doctor', label, { since: clock.since, nextAlert });
|
|
63
|
+
const waiting = waitingOn(review, clock, now);
|
|
64
|
+
if (waiting) return state('waiting_patient', 'Esperando paciente', { since: waiting.since, dueAt: waiting.dueAt, nextAlert });
|
|
65
|
+
return state('untaken', 'Sin tomar', { since: clock.since, dueAt: nextAlert?.dueAt ?? null, nextAlert });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
module.exports = { caseStateOf };
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
+
const { mapConcurrent } = require('../utils/concurrencyUtils');
|
|
1
2
|
const { httpError } = require('../utils/httpErrorUtils');
|
|
3
|
+
const { logger } = require('../utils/logger');
|
|
4
|
+
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
2
5
|
const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
6
|
|
|
4
7
|
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
5
8
|
const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
9
|
+
const { caseStateOf } = require('./escalationCaseStateService');
|
|
10
|
+
const { UNTAKEN_PROJECTION } = require('./untakenAlertService');
|
|
6
11
|
|
|
7
12
|
const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
8
13
|
const DONE_STATUSES = ['closed', 'cancelled'];
|
|
9
14
|
const BOARD_BUCKETS = ['pending', 'followup', 'done'];
|
|
15
|
+
const STATE_CONCURRENCY = 10;
|
|
10
16
|
const BOARD_FILTER_PREFIX = 'clinical-review-';
|
|
11
17
|
|
|
12
18
|
const bucketQuery = (bucket, now) => {
|
|
@@ -22,7 +28,7 @@ const bucketQuery = (bucket, now) => {
|
|
|
22
28
|
}
|
|
23
29
|
};
|
|
24
30
|
|
|
25
|
-
const boardRowOf = (review, bucket, deadlinePolicy) => {
|
|
31
|
+
const boardRowOf = (review, bucket, deadlinePolicy, state) => {
|
|
26
32
|
const alarms = review.alarms || [];
|
|
27
33
|
const lead = effectiveUrgencyOf(review);
|
|
28
34
|
const raised = alarms.map((alarm) => alarm.raisedAt).filter(Boolean);
|
|
@@ -40,9 +46,21 @@ const boardRowOf = (review, bucket, deadlinePolicy) => {
|
|
|
40
46
|
closedAt: review.closedAt || null,
|
|
41
47
|
updatedSinceSeen: review.updatedSinceSeen === true,
|
|
42
48
|
responseDeadline: responseDeadlineOf(review, deadlinePolicy),
|
|
49
|
+
caseState: state,
|
|
43
50
|
};
|
|
44
51
|
};
|
|
45
52
|
|
|
53
|
+
const ROW_PROJECTION = {
|
|
54
|
+
patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
|
|
55
|
+
'decisions.createdAt': 1, urgencyReclassifications: 1,
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// A row whose state cannot be read still shows, with its case status.
|
|
59
|
+
const stateOf = (review, now, policy) => caseStateOf(review, { now, policy }).catch((error) => {
|
|
60
|
+
logger.warn('[ReviewBoard] Could not read the case state of a row', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
|
|
61
|
+
return null;
|
|
62
|
+
});
|
|
63
|
+
|
|
46
64
|
const byUrgencyThenAge = (a, b) => (URGENCY_RANK[b.urgency] || 0) - (URGENCY_RANK[a.urgency] || 0)
|
|
47
65
|
|| new Date(a.since) - new Date(b.since);
|
|
48
66
|
|
|
@@ -50,13 +68,13 @@ const byMostRecentlyClosed = (a, b) => new Date(b.closedAt) - new Date(a.closedA
|
|
|
50
68
|
|
|
51
69
|
async function listReviewBoard({ bucket, now = new Date() } = {}) {
|
|
52
70
|
const reviews = await getEscalationReview()
|
|
53
|
-
.find(bucketQuery(bucket, now), {
|
|
54
|
-
patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
|
|
55
|
-
'decisions.createdAt': 1, urgencyReclassifications: 1,
|
|
56
|
-
})
|
|
71
|
+
.find(bucketQuery(bucket, now), bucket === 'pending' ? { ...UNTAKEN_PROJECTION, createdAt: 1, updatedSinceSeen: 1 } : ROW_PROJECTION)
|
|
57
72
|
.lean();
|
|
58
73
|
const deadlinePolicy = responseDeadlinePolicy();
|
|
59
|
-
|
|
74
|
+
// Each open case reads its thread and messages, so a long board must not open hundreds of queries at once.
|
|
75
|
+
const states = [];
|
|
76
|
+
await mapConcurrent(reviews, STATE_CONCURRENCY, async (review, index) => { states[index] = await stateOf(review, now, deadlinePolicy); });
|
|
77
|
+
const rows = reviews.map((review, index) => boardRowOf(review, bucket, deadlinePolicy, states[index]))
|
|
60
78
|
.sort(bucket === 'done' ? byMostRecentlyClosed : byUrgencyThenAge);
|
|
61
79
|
const seen = new Set();
|
|
62
80
|
return rows.filter((row) => !seen.has(row.patientCode) && seen.add(row.patientCode));
|
|
@@ -26,6 +26,11 @@ const ACTIONS = {
|
|
|
26
26
|
urgent: 'Tomar el caso: escribir o llamar y registrar la llamada',
|
|
27
27
|
};
|
|
28
28
|
const MAX_QUESTION_LENGTH = 200;
|
|
29
|
+
// Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
|
|
30
|
+
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
31
|
+
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
32
|
+
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
33
|
+
};
|
|
29
34
|
|
|
30
35
|
const duration = (minutes) => {
|
|
31
36
|
const hours = Math.floor(minutes / 60);
|
|
@@ -177,10 +182,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
177
182
|
closedAt: null,
|
|
178
183
|
status: { $in: PRE_DECISION_STATUSES },
|
|
179
184
|
alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
|
|
180
|
-
},
|
|
181
|
-
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
182
|
-
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
183
|
-
})
|
|
185
|
+
}, UNTAKEN_PROJECTION)
|
|
184
186
|
.sort({ _id: -1 })
|
|
185
187
|
.limit(SWEEP_LIMIT)
|
|
186
188
|
.lean();
|
|
@@ -217,4 +219,4 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
217
219
|
return sent;
|
|
218
220
|
}
|
|
219
221
|
|
|
220
|
-
module.exports = { sweepUntakenAlerts };
|
|
222
|
+
module.exports = { UNTAKEN_PROJECTION, dueStageOf, sweepUntakenAlerts, untakenClockOf };
|
|
@@ -30,47 +30,81 @@ function anchorTokens(value) {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
const NEGATION_WORDS = new Set(['no', 'ni', 'nunca', 'jamas', 'tampoco']);
|
|
33
|
+
// These only flag a conflict, never drop: «no hay un día sin fiebre» is a fever.
|
|
34
|
+
const CONFLICT_CUES = new Set([...NEGATION_WORDS, 'sin', 'niego', 'nego', 'ningun', 'ninguna']);
|
|
35
|
+
// Words a cue may reach across before the symptom: «no he tenido fiebre», «sin la fiebre».
|
|
36
|
+
const CUE_BRIDGE = new Set(['he', 'ha', 'me', 'le', 'tengo', 'tenido', 'el', 'la', 'de']);
|
|
37
|
+
const CUE_REACH = 2;
|
|
38
|
+
const CLAUSE_BREAK = /[.,;:!?¿¡\n]+/;
|
|
33
39
|
|
|
34
40
|
function hasNegation(text) {
|
|
35
41
|
return text.split(' ').some((word) => NEGATION_WORDS.has(word));
|
|
36
42
|
}
|
|
37
43
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
return
|
|
44
|
+
// Each word with whether a clause starts at it, so «No. Fiebre desde ayer» does not read as negated.
|
|
45
|
+
function clauseWords(value, forAnchor) {
|
|
46
|
+
return String(value ?? '').split(CLAUSE_BREAK).flatMap((clause) => {
|
|
47
|
+
const words = forAnchor(clause).split(' ').filter(Boolean);
|
|
48
|
+
return words.map((word, index) => ({ word, opensClause: index === 0 }));
|
|
49
|
+
});
|
|
41
50
|
}
|
|
42
51
|
|
|
43
|
-
|
|
52
|
+
// «nada de fiebre» negates and «nada más» means only; the «de» must precede the quote («de sangre» is not negated).
|
|
53
|
+
const isCueAt = (words, index, at, cues) => cues.has(words[index].word)
|
|
54
|
+
|| (words[index].word === 'nada' && words[index + 1]?.word === 'de' && index + 1 < at);
|
|
55
|
+
|
|
56
|
+
function cueBefore(words, at, { reach, cues }) {
|
|
57
|
+
for (let index = at - 1, bridged = 0; index >= 0 && !words[index + 1].opensClause; index -= 1) {
|
|
58
|
+
if (isCueAt(words, index, at, cues)) return true;
|
|
59
|
+
if (!CUE_BRIDGE.has(words[index].word) || ++bridged > reach) return false;
|
|
60
|
+
}
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function occurrencesOf(needle, words) {
|
|
65
|
+
const starts = [];
|
|
66
|
+
for (let at = 0; at + needle.length <= words.length; at += 1) {
|
|
67
|
+
if (needle.every((word, offset) => words[at + offset].word === word)) starts.push(at);
|
|
68
|
+
}
|
|
69
|
+
return starts;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function prepare(quote, source, strict) {
|
|
44
73
|
const forAnchor = strict ? (value) => normalizeForAnchor(nameComparators(value)) : normalizeForAnchor;
|
|
45
|
-
const
|
|
74
|
+
const words = clauseWords(strict ? nameComparators(source) : source, normalizeForAnchor);
|
|
46
75
|
const needle = forAnchor(quote);
|
|
47
|
-
|
|
76
|
+
return { words, needle, starts: needle ? occurrencesOf(needle.split(' '), words) : [] };
|
|
77
|
+
}
|
|
48
78
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const
|
|
79
|
+
// A quote read as present must not follow «no» directly («no fiebre»); one read as negated may sit anywhere.
|
|
80
|
+
function isQuoteAnchored(quote, source, { strict = false, negated = false } = {}) {
|
|
81
|
+
const { words, needle, starts } = prepare(quote, source, strict);
|
|
82
|
+
if (!words.length || !needle) return false;
|
|
52
83
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if (quoteNegated || !precededByNegation(padded, at)) return true;
|
|
57
|
-
at = padded.indexOf(target, at + 1);
|
|
58
|
-
}
|
|
59
|
-
if (anyOccurrence) return false;
|
|
60
|
-
if (strict) return false;
|
|
84
|
+
const quoteNegated = hasNegation(needle);
|
|
85
|
+
if (starts.some((at) => quoteNegated || negated || !cueBefore(words, at, { reach: 0, cues: NEGATION_WORDS }))) return true;
|
|
86
|
+
if (starts.length || strict) return false;
|
|
61
87
|
|
|
62
88
|
const tokens = anchorTokens(quote);
|
|
63
89
|
if (!tokens.length) return false;
|
|
64
|
-
if (quoteNegated && !
|
|
90
|
+
if (quoteNegated && !words.some(({ word }) => NEGATION_WORDS.has(word))) return false;
|
|
65
91
|
const present = new Set(anchorTokens(source));
|
|
66
92
|
const matched = tokens.filter((token) => present.has(token)).length;
|
|
67
93
|
return matched / tokens.length >= QUOTE_ANCHOR_MIN_OVERLAP;
|
|
68
94
|
}
|
|
69
95
|
|
|
96
|
+
// A cue a few words before a quote read as present («no he tenido fiebre») contradicts the model's polarity.
|
|
97
|
+
function negationNearQuote(quote, source) {
|
|
98
|
+
const { needle, words, starts } = prepare(quote, source, false);
|
|
99
|
+
if (!needle || needle.split(' ').some((word) => CONFLICT_CUES.has(word))) return false;
|
|
100
|
+
return starts.length > 0 && starts.every((at) => cueBefore(words, at, { reach: CUE_REACH, cues: CONFLICT_CUES }));
|
|
101
|
+
}
|
|
102
|
+
|
|
70
103
|
const escapeRegExp = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
71
104
|
|
|
72
105
|
module.exports = {
|
|
73
106
|
escapeRegExp,
|
|
74
107
|
isQuoteAnchored,
|
|
108
|
+
negationNearQuote,
|
|
75
109
|
normalizeForAnchor,
|
|
76
110
|
};
|