@larkup/tool-video-intelligence 0.2.10 → 0.3.0

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/dist/agent.js CHANGED
@@ -6,19 +6,14 @@ const TARGET_PADDING_SECS = 8;
6
6
  /** Independent looks dispatched together before the next wave starts. */
7
7
  const MAX_PARALLEL_INSPECTIONS = 4;
8
8
  /** The whole evidence-query fallback shares one deadline, including re-watch. */
9
- const INTERACTIVE_INSPECTION_BUDGET_MS = 45_000;
9
+ const INTERACTIVE_INSPECTION_BUDGET_MS = 30_000;
10
10
  /** Leave part of the shared deadline for a provider-backed inspection if needed. */
11
- const INTERACTIVE_REWATCH_BUDGET_MS = 20_000;
12
- const TRANSITION_LANGUAGE = /chang|updat|finish|final|result|conclud|resolv|settl/i;
13
- const HUMAN_ROLE_LANGUAGE = /\b(?:person|people|individual|man|woman|participant|contestant|player|member|speaker|presenter|host|guest|attendee)\b/i;
14
- const GENERIC_IDENTITY_LANGUAGE = /^(?:(?:unknown|unidentified|unnamed)(?:\s+(?:person|people|participant|contestant|player|member|speaker|presenter|host|guest|attendee|individual|man|woman))?|person|people|participant|contestant|player|member|speaker|presenter|host|guest|attendee|individual|man|woman|team|group|studio participants?)(?:\s+\d+)?$/i;
15
- const ATTRIBUTE_ACTION_LANGUAGE = /\b(?:wear\w*|dress\w*|clothing|clothes|outfit|shirt|jersey|jacket|coat|trousers|pants|skirt|shoe\w*|hat|hold\w*|carr\w*|stand\w*|sit\w*|driv\w*|eat\w*|drink\w*)\b|(?:يرتدي|لابس|ملابس|قميص|تيشيرت|جاكيت|بنطلون|حذاء|قبعة|يمسك|يحمل|يقف|يجلس|يقود|يأكل|يشرب)/iu;
16
- const LIMITATION_LANGUAGE = /\b(?:no explicit|not explicit|does not explicit|not (?:a )?complete|not established|not shown|unclear|unknown|unresolved|incomplete)\b/i;
11
+ const INTERACTIVE_REWATCH_BUDGET_MS = 12_000;
17
12
  /** Chat actions stay inside the installed tool; the host only sees workflow roles. */
18
13
  export const AGENT_TOOLS = [
19
14
  {
20
15
  name: 'queryVideoEvidence',
21
- description: 'Answer a question about an indexed video. Always use the existing RAG index first; perform a bounded direct re-watch only when the retrieved evidence is genuinely incomplete or conflicting. For requests that explicitly ask for every item, the full account, or everything said, set exhaustive=true and follow continuation.nextCursor until hasMore=false.',
16
+ description: 'Answer a question about an indexed video. It uses ranked evidence for focused questions, a chronological scan for source-authored or observed inventories, and a durable aggregate for a whole-source account. Perform a bounded direct re-watch only when returned evidence is genuinely incomplete or conflicting. For a full-source request, follow continuation.nextCursor until hasMore=false.',
22
17
  parameters: {
23
18
  type: 'object',
24
19
  additionalProperties: false,
@@ -26,6 +21,36 @@ export const AGENT_TOOLS = [
26
21
  properties: {
27
22
  mediaAssetId: { type: 'string', minLength: 1 },
28
23
  query: { type: 'string', minLength: 1, maxLength: 2_000 },
24
+ investigation: {
25
+ type: 'object',
26
+ additionalProperties: false,
27
+ required: ['scope', 'goal'],
28
+ properties: {
29
+ scope: { type: 'string', enum: ['focused', 'temporal', 'source'] },
30
+ goal: {
31
+ type: 'string',
32
+ enum: ['answer', 'compare', 'trace', 'enumerate', 'synthesize'],
33
+ },
34
+ evidence: {
35
+ type: 'array',
36
+ maxItems: 4,
37
+ items: { type: 'string', enum: ['speech', 'visible-text', 'visual', 'computed'] },
38
+ },
39
+ recordSet: {
40
+ type: 'string',
41
+ enum: ['all', 'source-authored', 'source-questions', 'observed'],
42
+ },
43
+ timeRange: {
44
+ type: 'object',
45
+ additionalProperties: false,
46
+ required: ['startSecs', 'endSecs'],
47
+ properties: {
48
+ startSecs: { type: 'number', minimum: 0 },
49
+ endSecs: { type: 'number', minimum: 0 },
50
+ },
51
+ },
52
+ },
53
+ },
29
54
  limit: { type: 'integer', minimum: 1, maximum: 48 },
30
55
  exhaustive: { type: 'boolean' },
31
56
  cursor: { type: 'integer', minimum: 0 },
@@ -34,7 +59,7 @@ export const AGENT_TOOLS = [
34
59
  method: 'queryVideoEvidence',
35
60
  workflow: 'evidence-query',
36
61
  evidenceInput: 'media-asset',
37
- systemPromptFragment: 'Use this action for media questions. It reads the existing indexed evidence first and only watches a bounded source moment when that evidence is incomplete or conflicting. Never trigger extra analysis merely to restate an answer the returned evidence already establishes. For an explicit every/all/complete-source request, call with exhaustive=true and keep calling with continuation.nextCursor until hasMore=false; do not mistake one top-K page for the complete answer. Never say you do not know or that the source lacks an answer before this action has attempted its available fallback. State an outcome, final result, identity, count, or exact visible fact only when established. Answer naturally as someone who watched and remembers the material: lead with the answer itself (for example, "X won" or "He wore Y"), not phrases such as "the video shows", "the analysis indicates", or "according to the retrieved evidence". Never mention retrieval, search, indexing, frames, tools, or analysis unless the user asks how the answer was found.',
62
+ systemPromptFragment: 'Use this action for media questions. On every call, derive investigation from the user’s meaning in their own language: use focused for one local moment, temporal for a relationship or development across moments, and source when the answer must account for the recording as a whole. Set answer, compare, trace, enumerate, or synthesize according to the reasoning operation—not the video genre or a word list. If the user supplies a specific source time or range, put its resolved seconds in investigation.timeRange; otherwise omit it. For a source enumeration, set recordSet to source-authored for units authored in the recording, source-questions for only authored questions and their answers, observed for time-grounded observed facts, or all when both are needed. Choose source plus synthesize for the overall narrative. Focused questions use ranked evidence; source enumerations use a chronological database scan; source explanations use a durable navigation aggregate. Never turn a complete-source request into top-K retrieval. For an exhaustive result, follow continuation.nextCursor until hasMore=false; do not mistake one page for the complete answer. Never say you do not know or that the source lacks an answer before this action has attempted its available fallback. State a value, identity, count, or exact visible fact only when established. observedSubjects, when present, is the reconciled frame-grounded visibility ledger: use its ranges for visible-presence and timing claims, never speech, titles, or a source name. Its durations are observed intervals, not inferred continuous screen time. Answer as a viewer who remembers the material: lead with the answer itself, and when natural say "I saw" or "I heard" rather than describing a system. Do not say "the video shows", "the analysis indicates", or "according to retrieved evidence". Never mention retrieval, search, indexing, frames, tools, or analysis unless the user asks how the answer was found.',
38
63
  },
39
64
  {
40
65
  name: 'inspectVideoKnowledge',
@@ -78,30 +103,146 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
78
103
  if (!asset || asset.processingStatus !== 'completed')
79
104
  return { success: false, error: 'A completed video asset is required.' };
80
105
  const focusedQuery = focusQuestion(input.query, asset.fileName);
81
- const plan = mediaEvidence.planQuestion(focusedQuery);
106
+ const directive = validInvestigation(input.investigation)
107
+ ? input.investigation
108
+ : // If the conversational planner is unavailable, preserving the full
109
+ // source is safer than silently reducing an arbitrary question to a
110
+ // Top-K local match. A later planner result may optimize this, but the
111
+ // evidence capability must have a source-complete fallback for every
112
+ // language and kind of recording.
113
+ { scope: 'source', goal: 'synthesize' };
114
+ const plan = mediaEvidence.planQuestion(focusedQuery, directive);
82
115
  const focusedInput = {
83
116
  ...input,
84
117
  query: focusedQuery,
118
+ investigation: directive,
85
119
  // Requests that span a whole recording need deterministic pagination
86
120
  // through the index. Callers should not need to know this tool's query
87
121
  // planner well enough to opt into exhaustive retrieval themselves.
88
- exhaustive: input.exhaustive ??
89
- (plan.kinds.some((kind) => kind === 'question-inventory' ||
90
- kind === 'source-inventory' ||
91
- kind === 'entity-inventory') ||
92
- (plan.requiresBroadCoverage === true && !plan.kinds.includes('evaluation'))),
122
+ exhaustive: input.exhaustive ?? plan.requiresBroadCoverage === true,
93
123
  };
94
124
  const durationSecs = asset.durationSecs;
125
+ // Complete inventories are a deterministic database scan, never an
126
+ // expanded Top-K query. The chat route follows the opaque cursor itself,
127
+ // so a model cannot stop early or mistake its context window for source
128
+ // coverage.
129
+ if (plan.route === 'scan' && mediaEvidence.scan) {
130
+ const sourceInventory = focusedInput.investigation.recordSet === 'source-authored' ||
131
+ focusedInput.investigation.recordSet === 'source-questions';
132
+ const scanned = await mediaEvidence.scan(input.mediaAssetId, {
133
+ kind: sourceInventory ? 'source-inventory' : 'all-evidence',
134
+ cursor: input.cursor,
135
+ limit: input.limit,
136
+ });
137
+ if (scanned) {
138
+ // A source inventory can contain headings, slides, and literal list
139
+ // items too. A question table must contain only source questions;
140
+ // the cursor still follows every raw record so coverage remains an
141
+ // exact chronological scan rather than a filtered Top-K search.
142
+ const scanRecords = focusedInput.investigation.recordSet === 'source-questions'
143
+ ? scanned.records.filter((record) => record.kind === 'question' &&
144
+ record.questionRole !== 'interactional' &&
145
+ record.questionRole !== 'rhetorical')
146
+ : scanned.records;
147
+ const evidence = scanRecords.map(scanRecordToEvidence);
148
+ // Inventory rows are a source-data contract, not prose for the
149
+ // answer model to interpret. The host can aggregate every cursor
150
+ // page and render/search/export the complete result without putting
151
+ // a long recording's authored units in an LLM context window.
152
+ const rows = scanRecords.map(scanRecordToRow);
153
+ // A page is directly grounded when the indexed source coverage is
154
+ // complete. The chat host owns cursor-following and will withhold a
155
+ // final exhaustive rendering until the final page arrives.
156
+ const complete = scanned.coverage.complete;
157
+ void trackUsageEvent({
158
+ type: 'media_processing',
159
+ mediaType: asset.type === 'audio' ? 'audio' : 'video',
160
+ mediaOperation: 'investigation',
161
+ mediaAssetId: input.mediaAssetId,
162
+ queryKind: plan.kinds.join(','),
163
+ cache: 'hit',
164
+ evidenceCount: evidence.length,
165
+ frameCount: 0,
166
+ durationSecs: 0,
167
+ latencyMs: Date.now() - startedAt,
168
+ timestamp: new Date().toISOString(),
169
+ });
170
+ return {
171
+ success: true,
172
+ mediaAssetId: input.mediaAssetId,
173
+ fileName: asset.fileName,
174
+ evidence,
175
+ inventory: {
176
+ recordSet: focusedInput.investigation.recordSet ?? 'all',
177
+ coverage: {
178
+ complete,
179
+ ...(scanned.coverage.reason ? { reason: scanned.coverage.reason } : {}),
180
+ },
181
+ },
182
+ columns: SOURCE_INVENTORY_COLUMNS,
183
+ rows,
184
+ totalRows: rows.length,
185
+ resultHandle: scanned.resultHandle,
186
+ claimVerification: {
187
+ status: complete ? 'directly-established' : 'needs-corroboration',
188
+ directlyEstablished: complete,
189
+ rule: complete
190
+ ? scanned.continuation.hasMore
191
+ ? `This is a chronological page from complete active ${sourceInventory ? 'source inventory' : 'source evidence'}. Follow the cursor before presenting a complete answer.`
192
+ : `This result is a complete chronological scan of active ${sourceInventory ? 'source inventory' : 'source evidence'}. Preserve every returned item and its timestamp.`
193
+ : (scanned.coverage.reason ??
194
+ 'The active index does not prove complete source coverage, so present these items as partial rather than complete.'),
195
+ },
196
+ investigation: {
197
+ answerPath: 'deterministic-scan',
198
+ responseTimeMs: Date.now() - startedAt,
199
+ analyzedRanges: [],
200
+ broadCoverage: true,
201
+ coverage: {
202
+ mode: 'broad',
203
+ totalChapters: 0,
204
+ totalScenes: 0,
205
+ representedRanges: scanned.coverage.scannedRecords,
206
+ },
207
+ },
208
+ continuation: {
209
+ exhaustive: true,
210
+ hasMore: scanned.continuation.hasMore,
211
+ ...(scanned.continuation.nextCursor !== undefined
212
+ ? { nextCursor: scanned.continuation.nextCursor }
213
+ : {}),
214
+ totalItems: scanned.continuation.totalRecords,
215
+ resultHandle: scanned.resultHandle,
216
+ },
217
+ };
218
+ }
219
+ }
220
+ // The compact aggregate is revision-cached and carries protocol-backed
221
+ // source questions and visual sightings that ranked snippets can split
222
+ // apart. It is navigation material, not a substitute for source truth.
223
+ const aggregate = mediaEvidence.aggregate
224
+ ? await mediaEvidence.aggregate(input.mediaAssetId)
225
+ : undefined;
95
226
  // Start with the index alone. Planning and visual locating are useful
96
227
  // fallbacks, but waiting for both before checking an already-complete RAG
97
228
  // answer made simple questions feel like analysis jobs.
98
- let hits = await retrieve(mediaEvidence, focusedInput, plan, durationSecs);
229
+ // A source position supplied by the user is a retrieval boundary, not
230
+ // merely another ranking signal. Read that bounded part of the index
231
+ // first so a whole-recording overview cannot displace its evidence.
232
+ const explicitRanges = directiveTimeRange(directive, durationSecs);
233
+ const [rankedHits, explicitlyScopedHits] = await Promise.all([
234
+ retrieve(mediaEvidence, focusedInput, plan, durationSecs),
235
+ explicitRanges.length > 0
236
+ ? retrieveEvidenceInRanges(mediaEvidence, focusedInput, plan, durationSecs, explicitRanges)
237
+ : Promise.resolve([]),
238
+ ]);
239
+ let hits = mergeHits(explicitlyScopedHits, rankedHits, aggregate ? aggregateToHits(aggregate) : []);
99
240
  let investigation;
100
- let locatedRanges = [];
241
+ let locatedRanges = explicitRanges;
101
242
  let assessment = assessEvidence(hits, focusedInput.query, plan, durationSecs, undefined);
102
243
  if (!assessment.sufficient) {
103
- [investigation, locatedRanges] = await Promise.all([
104
- mediaEvidence.planInvestigation?.(input.mediaAssetId, focusedInput.query),
244
+ const [plannedInvestigation, semanticRanges] = await Promise.all([
245
+ mediaEvidence.planInvestigation?.(input.mediaAssetId, focusedInput.query, focusedInput.investigation),
105
246
  // Where independent indexed signals agree the answer is. This is
106
247
  // measured navigation, not evidence, and only runs after the fast
107
248
  // indexed answer test has failed.
@@ -110,7 +251,10 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
110
251
  maxWindowSecs: MAX_INSPECTION_CHUNK_SECS,
111
252
  }) ?? Promise.resolve([]),
112
253
  ]);
113
- const locatedEvidence = await retrieveEvidenceInRanges(mediaEvidence, focusedInput, plan, durationSecs, locatedRanges);
254
+ investigation = plannedInvestigation;
255
+ const additionalRanges = uniqueRanges(semanticRanges);
256
+ locatedRanges = uniqueRanges([...explicitRanges, ...additionalRanges]);
257
+ const locatedEvidence = await retrieveEvidenceInRanges(mediaEvidence, focusedInput, plan, durationSecs, additionalRanges);
114
258
  hits = mergeHits(locatedEvidence, hits);
115
259
  assessment = assessEvidence(hits, focusedInput.query, plan, durationSecs, investigation);
116
260
  }
@@ -181,7 +325,11 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
181
325
  analyzedRanges: established.map((reading) => reading.range),
182
326
  broadCoverage: plan.requiresBroadCoverage === true,
183
327
  coverage: investigation?.coverage,
328
+ directive: investigationDirectiveForOutput(focusedInput.investigation),
184
329
  },
330
+ ...(shouldIncludeObservedSubjects(aggregate, focusedInput.investigation, plan)
331
+ ? { observedSubjects: aggregate.visibleSubjects }
332
+ : {}),
185
333
  ...(focusedInput.exhaustive
186
334
  ? { continuation: exhaustiveContinuation(hits, assessment, focusedInput) }
187
335
  : {}),
@@ -238,6 +386,12 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
238
386
  const supportingClip = plan.kinds.includes('outcome')
239
387
  ? evidence.at(-1)?.timeRange
240
388
  : evidence[0]?.timeRange;
389
+ // A complete visibility ledger is useful for a source-wide or temporal
390
+ // question, but it is dangerous extra context for a single requested
391
+ // moment: a renderer can accidentally combine a remote appearance with
392
+ // that moment. The selected evidence already carries any ledger entry
393
+ // whose explicit interval overlaps the focused request.
394
+ const includeObservedSubjects = shouldIncludeObservedSubjects(aggregate, focusedInput.investigation, plan);
241
395
  const responseTimeMs = Date.now() - startedAt;
242
396
  const answerPath = analyzedRanges.length > 0 ? 'rag+analysis' : 'rag';
243
397
  void trackUsageEvent({
@@ -282,7 +436,9 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
282
436
  analyzedRanges,
283
437
  broadCoverage: plan.requiresBroadCoverage === true,
284
438
  coverage: investigation?.coverage,
439
+ directive: investigationDirectiveForOutput(focusedInput.investigation),
285
440
  },
441
+ ...(includeObservedSubjects ? { observedSubjects: aggregate.visibleSubjects } : {}),
286
442
  ...(focusedInput.exhaustive
287
443
  ? { continuation: exhaustiveContinuation(hits, assessment, focusedInput) }
288
444
  : {}),
@@ -325,7 +481,173 @@ function windowObjective(plan) {
325
481
  }
326
482
  /** The evidence a reply cites, in the shape the host renders. */
327
483
  function evidenceHitsFor(hits, assessment, plan, input, durationSecs) {
328
- return selectAnswerEvidence(hits, assessment, plan, input, durationSecs).map((hit) => toEvidence(hit, plan));
484
+ // A request can both name a source position and ask for a relationship to
485
+ // the rest of the recording. Keep a direct account of that named position
486
+ // beside the broader trail: otherwise a renderer can attach a remote named
487
+ // subject to the local, merely described subject. This relies only on the
488
+ // typed time boundary, so it applies to any language and kind of media.
489
+ const localAnchor = explicitlyRequestedMomentEvidence(hits, plan, durationSecs);
490
+ return mergeHits(localAnchor, selectAnswerEvidence(hits, assessment, plan, input, durationSecs)).map((hit) => toEvidence(hit, plan));
491
+ }
492
+ function explicitlyRequestedMomentEvidence(hits, plan, durationSecs) {
493
+ const requestedRanges = directiveTimeRange(plan.investigation, durationSecs);
494
+ if (requestedRanges.length === 0)
495
+ return [];
496
+ const scoped = hits.filter((hit) => requestedRanges.some((range) => hit.evidence.timeRange.startSecs < range.endSecs &&
497
+ hit.evidence.timeRange.endSecs > range.startSecs));
498
+ return mergeHits(scoped.filter((hit) => hit.evidence.modality === 'visual' && isAccountOfMoment(hit)), scoped.filter((hit) => {
499
+ const text = evidenceText(hit.evidence.payload);
500
+ return /^Reconciled visible subject:\s*[^\n]+\nIdentity basis:/im.test(text);
501
+ }), scoped.filter(isAccountOfMoment)).slice(0, 4);
502
+ }
503
+ /**
504
+ * Keep the source-navigation decision alongside the evidence it governed.
505
+ * The renderer uses this typed provenance to distinguish a local sighting
506
+ * from a request that also asks how that sighting relates to the full source.
507
+ */
508
+ function investigationDirectiveForOutput(directive) {
509
+ return {
510
+ scope: directive.scope,
511
+ goal: directive.goal,
512
+ ...(directive.recordSet ? { recordSet: directive.recordSet } : {}),
513
+ ...(directive.timeRange ? { timeRange: directive.timeRange } : {}),
514
+ };
515
+ }
516
+ function shouldIncludeObservedSubjects(aggregate, directive, plan) {
517
+ return Boolean(aggregate?.visibleSubjects &&
518
+ (directive.recordSet === 'observed' ||
519
+ directive.scope !== 'focused' ||
520
+ plan.requiresBroadCoverage === true));
521
+ }
522
+ function scanRecordToEvidence(record) {
523
+ const prefix = record.kind === 'question'
524
+ ? `Source question (${record.channel ?? 'spoken'}${record.questionRole ? `, ${record.questionRole}` : ''}): ${record.text}`
525
+ : record.kind === 'evidence'
526
+ ? record.text
527
+ : `Source item (${record.kind}, ${record.channel ?? 'visible'}): ${record.text}`;
528
+ const text = [
529
+ prefix,
530
+ ...(record.taskId ? [`Source task id: ${record.taskId}`] : []),
531
+ ...(record.answer ? [`Source answer: ${record.answer}`] : []),
532
+ ...(record.respondent ? [`Source respondent: ${record.respondent}`] : []),
533
+ ].join('\n');
534
+ return {
535
+ id: record.id,
536
+ evidenceId: record.sourceEvidenceId,
537
+ modality: record.modality,
538
+ timeRange: record.timeRange,
539
+ payload: { text },
540
+ confidence: record.confidence,
541
+ };
542
+ }
543
+ const SOURCE_INVENTORY_COLUMNS = [
544
+ 'Timestamp',
545
+ 'Content',
546
+ 'Answer',
547
+ 'Respondent',
548
+ 'Channel',
549
+ 'Record type',
550
+ ];
551
+ /** Keep the scan's original authored fields intact for generic data-table rendering. */
552
+ function scanRecordToRow(record) {
553
+ return {
554
+ // This stable key is intentionally not a displayed column. It lets the
555
+ // host de-duplicate opaque cursor pages without guessing from content.
556
+ id: record.id,
557
+ Timestamp: formatSourceTimestamp(record.timeRange.startSecs),
558
+ Content: record.text,
559
+ Answer: record.answer ?? '',
560
+ Respondent: record.respondent ?? '',
561
+ Channel: record.channel ?? '',
562
+ 'Record type': record.kind,
563
+ };
564
+ }
565
+ function formatSourceTimestamp(seconds) {
566
+ const total = Math.max(0, Math.floor(seconds));
567
+ const hours = Math.floor(total / 3_600);
568
+ const minutes = Math.floor((total % 3_600) / 60);
569
+ const remainder = total % 60;
570
+ return hours > 0
571
+ ? `${hours}:${String(minutes).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`
572
+ : `${minutes}:${String(remainder).padStart(2, '0')}`;
573
+ }
574
+ function aggregateToHits(aggregate) {
575
+ const createdAt = new Date().toISOString();
576
+ return [
577
+ ...aggregate.participants.map((participant, index) => ({
578
+ evidence: {
579
+ id: `${aggregate.resultHandle}:participant:${index}`,
580
+ modality: 'computed',
581
+ timeRange: participant.timeRange,
582
+ payload: {
583
+ text: `Reconciled participant: ${participant.name} — ${participant.description}`,
584
+ },
585
+ source: { kind: 'provider', provider: 'video-intelligence-index' },
586
+ confidence: { score: 0.8 },
587
+ createdAt,
588
+ },
589
+ score: 1,
590
+ conflict: false,
591
+ })),
592
+ ...aggregate.timeline.map((entry, index) => ({
593
+ evidence: {
594
+ id: `${aggregate.resultHandle}:timeline:${index}`,
595
+ modality: 'computed',
596
+ timeRange: entry.timeRange,
597
+ payload: { text: entry.text },
598
+ source: { kind: 'provider', provider: 'video-intelligence-index' },
599
+ confidence: { score: 0.75 },
600
+ createdAt,
601
+ },
602
+ score: 0.7,
603
+ conflict: false,
604
+ })),
605
+ ...aggregate.sourceItems.map((item, index) => ({
606
+ evidence: {
607
+ id: `${aggregate.resultHandle}:source-item:${index}`,
608
+ modality: 'computed',
609
+ timeRange: item.timeRange,
610
+ payload: {
611
+ text: item.kind === 'question'
612
+ ? `Source question (${item.channel ?? 'spoken'}${item.questionRole ? `, ${item.questionRole}` : ''}): ${item.text}${item.answer ? `\nSource answer: ${item.answer}` : ''}${item.respondent ? `\nSource respondent: ${item.respondent}` : ''}`
613
+ : item.kind === 'structure'
614
+ ? `Source structure: ${item.text}${item.promptSlots === undefined
615
+ ? ''
616
+ : `\nSource prompt slots: ${item.promptSlots}`}`
617
+ : `Source item (${item.kind}): ${item.text}`,
618
+ },
619
+ source: { kind: 'provider', provider: 'video-intelligence-index' },
620
+ confidence: { score: 0.82 },
621
+ createdAt,
622
+ },
623
+ score: 0.8,
624
+ conflict: false,
625
+ })),
626
+ ...aggregate.visibleSubjects.map((subject, index) => ({
627
+ evidence: {
628
+ id: `${aggregate.resultHandle}:visible-subject:${index}`,
629
+ modality: 'computed',
630
+ timeRange: {
631
+ startSecs: subject.appearances[0]?.startSecs ?? 0,
632
+ endSecs: subject.appearances.at(-1)?.endSecs ?? subject.appearances[0]?.endSecs ?? 0,
633
+ precision: 'estimated',
634
+ },
635
+ payload: {
636
+ text: `Reconciled visible subject: ${subject.identity}\n` +
637
+ `Identity basis: ${subject.identityBasis}\n` +
638
+ `Observed appearances: ${subject.appearances
639
+ .map((range) => `${range.startSecs}-${range.endSecs}s`)
640
+ .join('; ')}\n` +
641
+ `Observed visible duration: ${subject.observedDurationSecs}s`,
642
+ },
643
+ source: { kind: 'provider', provider: 'video-intelligence-index' },
644
+ confidence: { score: subject.identityBasis === 'source-named' ? 0.8 : 0.6 },
645
+ createdAt,
646
+ },
647
+ score: 0.8,
648
+ conflict: false,
649
+ })),
650
+ ];
329
651
  }
330
652
  async function retrieve(mediaEvidence, input, plan, durationSecs) {
331
653
  const options = { queryPlan: plan, videoDurationSecs: durationSecs };
@@ -403,10 +725,18 @@ async function retrieveEvidenceInRanges(mediaEvidence, input, plan, durationSecs
403
725
  // provenance and claim verification below to decide which can answer.
404
726
  minimumRangeDistanceSecs: 0,
405
727
  };
406
- const groups = await Promise.all(ranges.map((range) => mediaEvidence.search(input.mediaAssetId, input.query, 24, {
407
- ...options,
408
- timeRange: range,
409
- })));
728
+ const groups = await Promise.all(ranges.map(async (range) => {
729
+ const rangeOptions = { ...options, timeRange: range };
730
+ // Query matching can fail across languages or when an observation uses
731
+ // a natural description instead of the user's wording. The bounded
732
+ // unranked read preserves all accounts from the requested moment; the
733
+ // normal query remains alongside it for relevance ordering.
734
+ const [ranked, bounded] = await Promise.all([
735
+ mediaEvidence.search(input.mediaAssetId, input.query, 24, rangeOptions),
736
+ mediaEvidence.search(input.mediaAssetId, '', 48, rangeOptions),
737
+ ]);
738
+ return mergeHits(ranked, bounded);
739
+ }));
410
740
  return mergeHits(...groups);
411
741
  }
412
742
  function needsSourceWideView(plan) {
@@ -481,7 +811,7 @@ function assessEvidence(hits, question, plan, durationSecs, investigation, watch
481
811
  sequenceReady),
482
812
  };
483
813
  }
484
- const direct = answerEstablishedHits(hits, question, plan.kinds, watched, durationSecs);
814
+ const direct = answerEstablishedHits(hits, question, plan, watched);
485
815
  const reconciled = direct.length === 0 ? indexedReconciledAnswerHits(hits, plan, durationSecs) : [];
486
816
  const trail = direct.length === 0 && reconciled.length === 0 && isCrossEvidenceClaim(plan)
487
817
  ? indexedCrossEvidenceTrail(hits, durationSecs, plan)
@@ -529,29 +859,14 @@ function assessEvidence(hits, question, plan, durationSecs, investigation, watch
529
859
  establishedByTrail: direct.length === 0 && reconciled.length === 0 && established.length > 0,
530
860
  };
531
861
  }
532
- /** Keep compact records that actually bind identities, roles, or memberships. */
533
- function identityInventoryHits(hits, question) {
534
- const asksForPeople = /\b(?:people|persons?|participants?|contestants?|players?|members?|speakers?|presenters?|hosts?|guests?|attendees?|men|women)\b/i.test(question) ||
535
- /(?:الأشخاص|الاشخاص|المشاركين|المتسابقين|اللاعبين|الأعضاء|الاعضاء|المتحدثين|المقدمين|الضيوف|الرجال|السيدات)/u.test(question);
536
- const groupedRequest = /\b(?:each|every|both)\s+(?:team|group|side|department|organization|organisation|class|panel)\b|\bof\s+(?:each|every|both)\b/i.test(question) || /(?:كل|كلا)\s+(?:فريق|مجموعة|قسم|منظمة|فصل)/u.test(question);
862
+ /** Keep compact records that actually bind an entity to source evidence. */
863
+ function identityInventoryHits(hits, _question) {
537
864
  const selected = chronological(hits).filter((hit) => {
538
865
  const text = evidenceText(hit.evidence.payload);
539
- if (/^(?:Reconciled|Indexed) participant:\s*[^—\n]{2,120}/im.test(text))
540
- return true;
541
- const present = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)];
542
- if (!asksForPeople)
543
- return present.length > 0;
544
- return present.some((match) => {
545
- const name = match[1]?.trim() ?? '';
546
- const role = match[2] ?? '';
547
- return HUMAN_ROLE_LANGUAGE.test(role) && !GENERIC_IDENTITY_LANGUAGE.test(name);
548
- });
866
+ return (/^(?:Reconciled|Indexed)\s+(?:participant|visible subject):\s*[^\n]{2,180}/im.test(text) ||
867
+ /^Visible subject:\s*\{/im.test(text) ||
868
+ /^Present:\s*[^—\n]{2,120}\s*—/im.test(text));
549
869
  });
550
- if (groupedRequest) {
551
- const ranked = [...selected].sort((left, right) => groupedIdentityStrength(right) - groupedIdentityStrength(left));
552
- if (ranked.length > 0 && groupedIdentityStrength(ranked[0]) >= 20)
553
- return [ranked[0]];
554
- }
555
870
  const seen = new Set();
556
871
  return selected
557
872
  .filter((hit) => {
@@ -566,20 +881,19 @@ function identityInventoryHits(hits, question) {
566
881
  }
567
882
  function groupedIdentityStrength(hit) {
568
883
  const text = primaryAccount(evidenceText(hit.evidence.payload));
569
- const namedPeople = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)].filter((match) => HUMAN_ROLE_LANGUAGE.test(match[2] ?? '') &&
570
- !GENERIC_IDENTITY_LANGUAGE.test(match[1]?.trim() ?? '')).length;
884
+ const anchoredSubjects = subjectEvidenceCount(text);
571
885
  let groupedBindings = 0;
572
886
  const serializedBindings = text.match(/^Claim bindings:\s*(.+)$/im)?.[1];
573
887
  if (serializedBindings) {
574
888
  try {
575
889
  const bindings = JSON.parse(serializedBindings);
576
- groupedBindings = bindings.filter((binding) => typeof binding?.subject === 'string' && /\s(?:and|&|و)\s|،|,/iu.test(binding.subject)).length;
890
+ groupedBindings = bindings.filter((binding) => typeof binding?.subject === 'string').length;
577
891
  }
578
892
  catch {
579
893
  groupedBindings = 0;
580
894
  }
581
895
  }
582
- return (namedPeople * 4 +
896
+ return (anchoredSubjects * 4 +
583
897
  groupedBindings * 8 +
584
898
  Number(hit.score ?? 0));
585
899
  }
@@ -604,39 +918,26 @@ function evaluationEvidenceHits(hits) {
604
918
  : mergeHits(semanticAccounts, chronological(hits).filter((hit) => hit.evidence.modality === 'transcript' && isAccountOfMoment(hit)));
605
919
  return evenlySpaced(useful, 36);
606
920
  }
607
- /** A comparative judgement needs repeated named human activity, not scenery or score displays. */
921
+ /** A comparative judgement needs repeated source-anchored activity. */
608
922
  function evaluationEvidenceReady(hits) {
609
- const momentsByPerson = new Map();
923
+ const momentsBySubject = new Map();
610
924
  for (const hit of hits) {
611
925
  const text = primaryAccount(evidenceText(hit.evidence.payload));
612
- for (const match of text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)) {
613
- const name = match[1]?.trim() ?? '';
614
- if (!HUMAN_ROLE_LANGUAGE.test(match[2] ?? '') || GENERIC_IDENTITY_LANGUAGE.test(name)) {
615
- continue;
616
- }
617
- const key = name.normalize('NFKC').toLocaleLowerCase();
618
- const moments = momentsByPerson.get(key) ?? new Set();
926
+ for (const identity of subjectIdentities(text)) {
927
+ const key = identity.normalize('NFKC').toLocaleLowerCase();
928
+ const moments = momentsBySubject.get(key) ?? new Set();
619
929
  moments.add(Math.floor(hit.evidence.timeRange.startSecs / 15));
620
- momentsByPerson.set(key, moments);
930
+ momentsBySubject.set(key, moments);
621
931
  }
622
932
  }
623
- return [...momentsByPerson.values()].filter((moments) => moments.size >= 2).length >= 2;
933
+ return [...momentsBySubject.values()].filter((moments) => moments.size >= 2).length >= 2;
624
934
  }
625
- /** Source-wide visible units extracted during indexing, kept separate from narrative notes. */
626
- function sourceInventoryHits(hits, question) {
627
- const text = question.normalize('NFKC').toLocaleLowerCase();
628
- const wantsSlides = /\bslides?\b|(?:الشرائح|السلايدز)/u.test(text);
629
- const wantsBoard = /\b(?:boards?|whiteboards?)\b|(?:السبورة|اللوح)/u.test(text);
935
+ /** Source-wide authored units extracted during indexing, independent of genre or language. */
936
+ function sourceInventoryHits(hits, _question) {
630
937
  const records = chronological(hits).filter((hit) => {
631
938
  const account = evidenceText(hit.evidence.payload);
632
939
  const kind = account.match(/^Source item \((heading|slide-item|board-item|list-item),\s*(?:spoken|visible)\):/im)?.[1];
633
- if (!kind)
634
- return false;
635
- if (wantsSlides)
636
- return kind === 'heading' || kind === 'slide-item';
637
- if (wantsBoard)
638
- return kind === 'heading' || kind === 'board-item';
639
- return true;
940
+ return Boolean(kind);
640
941
  });
641
942
  const seen = new Set();
642
943
  return records.filter((hit) => {
@@ -653,15 +954,14 @@ function temporalSequenceHits(hits) {
653
954
  if (hit.evidence.source?.provider !== 'video-intelligence-index')
654
955
  return false;
655
956
  const text = evidenceText(hit.evidence.payload).trim();
656
- return (/^Reconciled state:/i.test(text) ||
657
- (/^Reconciled event:/i.test(text) && TRANSITION_LANGUAGE.test(text)));
957
+ return /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(text);
658
958
  });
659
959
  // Older indexes may not contain a synthesized trajectory. Preserve their
660
960
  // broad raw account so a targeted inspection can still use it.
661
961
  return reconciled.length >= 3 ? reconciled : hits;
662
962
  }
663
963
  /** Keep only source-authored prompts for an exhaustive question inventory. */
664
- function questionInventoryHits(hits, query) {
964
+ function questionInventoryHits(hits, _query) {
665
965
  const seen = new Set();
666
966
  const candidates = chronological(hits).flatMap((hit) => {
667
967
  // A later chat inspection can itself contain the user's question. It is
@@ -670,10 +970,8 @@ function questionInventoryHits(hits, query) {
670
970
  return [];
671
971
  return sourceQuestionRecordsFromHit(hit).flatMap((record, index) => {
672
972
  const normalizedQuestion = normalizeInventoryText(record.question);
673
- if (!normalizedQuestion ||
674
- /what the person reading (?:these|the) notes cares about|what the (?:viewer|reader) cares about/i.test(normalizedQuestion)) {
973
+ if (!normalizedQuestion)
675
974
  return [];
676
- }
677
975
  const key = [
678
976
  normalizedQuestion,
679
977
  normalizeInventoryText(record.context ?? ''),
@@ -702,39 +1000,14 @@ function questionInventoryHits(hits, query) {
702
1000
  ];
703
1001
  });
704
1002
  });
705
- const asksForFormalPromptSection = /\b(?:competition|contest|quiz|game|exam|test|challenge|round)\b|(?:مسابقة|المسابقة|اختبار|تحدي|جولة|لعبة)/iu.test(query);
706
- const visibleMoments = candidates
707
- .filter((candidate) => candidate
708
- .sourceQuestionChannel === 'visible')
709
- .map((candidate) => candidate.evidence.timeRange.startSecs);
710
- const sectionCandidates = asksForFormalPromptSection && visibleMoments.length > 0
711
- ? candidates.filter((candidate) => {
712
- const record = candidate;
713
- if (record.sourceQuestionChannel === 'visible')
714
- return true;
715
- const at = candidate.evidence.timeRange.startSecs;
716
- if (at < Math.min(...visibleMoments) - 60 || at > Math.max(...visibleMoments) + 60)
717
- return false;
718
- // A standalone prompt should not contain the first-person planning
719
- // and turn-taking language typical of a reaction or answer fragment.
720
- const sourceText = record.sourceQuestionText ?? '';
721
- if (/\b(?:i|i'm|ive|i've|you know|let me|look|wait)\b|(?:\bانا\b|\bأنا\b|\bشوف\b|\bبينا\b|\bيلا\b|\bبعرف\b|\bعارف\b|\bهسه\b)/iu.test(sourceText))
722
- return false;
723
- const questionCues = sourceText
724
- .toLocaleLowerCase()
725
- .match(/[\p{Letter}\p{Number}][\p{Letter}\p{Mark}\p{Number}_-]*/gu)
726
- ?.filter((word) => /^(?:who|what|which|how|why|when|where|من|مين|ما|ماذا|كيف|كم|ايه|إيه|أي|اي)$/iu.test(word)) ?? [];
727
- return !questionCues.some((cue, index) => questionCues.findIndex((other) => normalizeInventoryText(other) === normalizeInventoryText(cue)) !== index);
728
- })
729
- : candidates;
730
1003
  // OCR and ASR often capture the same prompt with slight spelling or
731
1004
  // transcription differences. Collapse nearby copies and retain the visible
732
1005
  // or fullest reading, while preserving genuine repeats later in the source.
733
- return sectionCandidates.filter((candidate) => {
1006
+ return candidates.filter((candidate) => {
734
1007
  const candidateRecord = candidate;
735
1008
  if (!candidateRecord.sourceQuestionText)
736
1009
  return true;
737
- const nearbyCopies = sectionCandidates.filter((other) => {
1010
+ const nearbyCopies = candidates.filter((other) => {
738
1011
  const otherText = other
739
1012
  .sourceQuestionText;
740
1013
  return (Boolean(otherText) &&
@@ -760,15 +1033,10 @@ function normalizeInventoryText(value) {
760
1033
  return value.normalize('NFKC').toLocaleLowerCase().replace(/\s+/g, ' ').trim();
761
1034
  }
762
1035
  function inventoryQuestionTokens(value) {
763
- const normalized = value
764
- .normalize('NFKD')
765
- .replace(/[\u064b-\u065f\u0670]/gu, '')
766
- .replace(/[أإآٱ]/gu, 'ا')
767
- .replace(/ى/gu, 'ي')
768
- .toLocaleLowerCase();
769
- const words = normalized.match(/[\p{Letter}\p{Number}][\p{Letter}\p{Mark}\p{Number}_-]*/gu) ?? [];
770
- const firstCue = words.findIndex((word) => /^(?:who|what|when|where|why|how|which|whose|whom|is|are|was|were|do|does|did|can|could|would|will|name|list|identify|describe|tell|give|من|ما|ماذا|متي|اين|كيف|كم|هل|اي|لماذا|مين|ايه|فين|امتي|ازاي|اذكر|حدد|سم|سمي)$/iu.test(word));
771
- return new Set(firstCue > 0 ? words.slice(firstCue) : words);
1036
+ return new Set(value
1037
+ .normalize('NFKC')
1038
+ .toLocaleLowerCase()
1039
+ .match(/[\p{Letter}\p{Number}][\p{Letter}\p{Mark}\p{Number}_-]*/gu) ?? []);
772
1040
  }
773
1041
  function inventoryQuestionsMatch(left, right) {
774
1042
  const leftTokens = inventoryQuestionTokens(left);
@@ -779,27 +1047,10 @@ function inventoryQuestionsMatch(left, right) {
779
1047
  return overlap / Math.min(leftTokens.size, rightTokens.size) >= 0.6;
780
1048
  }
781
1049
  function isWellFormedSourceQuestion(record) {
782
- const question = record.question.normalize('NFKC').trim();
783
- if (question.length < 4)
784
- return false;
785
- if (record.channel === 'visible')
786
- return true;
787
- const punctuated = /[?؟]\s*$/u.test(question);
788
- // ASR commonly drops question marks. Require a source-language question or
789
- // request cue near the start; an answer/reaction that happens to contain a
790
- // question word much later must not become a source inventory item.
791
- const words = question
792
- .toLocaleLowerCase()
793
- .match(/[\p{Letter}\p{Number}][\p{Letter}\p{Mark}\p{Number}_-]*/gu) ?? [];
794
- const cue = /^(?:who|what|when|where|why|how|which|whose|whom|is|are|was|were|do|does|did|can|could|would|will|name|list|identify|describe|tell|give|من|ما|ماذا|متى|أين|اين|كيف|كم|هل|أي|اي|لماذا|مين|إيه|ايه|فين|امتى|ازاي|اذكر|أذكر|حدد|سم|سمي)$/iu;
795
- const cueIndex = words.slice(0, 4).findIndex((word) => cue.test(word));
796
- if (cueIndex < 0)
797
- return punctuated;
798
- const meaningful = new Set(words.slice(cueIndex + 1));
799
- const deictic = /^(?:this|that|it|one|thing|exactly|first|second|third|دي|ده|دا|هذه|هذا|هي|هو|بالظبط|بالضبط|الاولى|الأولى|الثانية|الثالثة)$/iu;
800
- if (meaningful.size === 1 && [...meaningful].every((word) => deictic.test(word)))
801
- return false;
802
- return true;
1050
+ // The source mapper has already semantically classified this record. The
1051
+ // executor only guards the transport shape and never applies a language
1052
+ // list to decide whether a source sentence is a question.
1053
+ return record.question.normalize('NFKC').trim().length >= 4;
803
1054
  }
804
1055
  function sourceQuestionRecordsFromHit(hit) {
805
1056
  const text = evidenceText(hit.evidence.payload);
@@ -910,7 +1161,7 @@ function indexedReconciledAnswerHits(hits, plan, durationSecs) {
910
1161
  text.length >= 20 &&
911
1162
  (semantic >= 0.05 || lexical >= 0.2) &&
912
1163
  !hasNegativeVerdict(hit) &&
913
- !LIMITATION_LANGUAGE.test(text) &&
1164
+ !hasNegativeVerdict(hit) &&
914
1165
  !spansWholeSource(hit, durationSecs));
915
1166
  });
916
1167
  }
@@ -930,25 +1181,8 @@ function indexedUnboundSubjectAttributes(hits, question, plan) {
930
1181
  (hit.evidence.modality === 'computed' &&
931
1182
  hit.evidence.source?.provider === 'video-intelligence-index')) &&
932
1183
  isAccountOfMoment(hit) &&
933
- // Similarity locates a scene, but a scene can be semantically close
934
- // while describing a different attribute entirely. The account itself
935
- // must contain the generic action/appearance relation requested here.
936
- attributeEvidenceMatchesQuestion(primaryAccount(evidenceText(hit.evidence.payload)), question) &&
937
1184
  !hasNegativeVerdictForQuestion(hit, question));
938
1185
  }
939
- function attributeEvidenceMatchesQuestion(evidence, question) {
940
- if (!ATTRIBUTE_ACTION_LANGUAGE.test(evidence))
941
- return false;
942
- const requested = question.match(new RegExp(ATTRIBUTE_ACTION_LANGUAGE.source, 'giu')) ?? [];
943
- if (requested.length === 0)
944
- return true;
945
- const source = evidence.normalize('NFKC').toLocaleLowerCase();
946
- return requested.some((term) => {
947
- const normalized = term.normalize('NFKC').toLocaleLowerCase();
948
- const root = normalized.length >= 5 ? normalized.slice(0, 4) : normalized;
949
- return root.length >= 3 && source.includes(root);
950
- });
951
- }
952
1186
  /** Do not call a two-person description complete when the index establishes a wider group. */
953
1187
  function attributeCoverageReady(attributes, allHits) {
954
1188
  const described = Math.max(0, ...attributes.map(explicitAttributedPeopleInAccount));
@@ -956,42 +1190,41 @@ function attributeCoverageReady(attributes, allHits) {
956
1190
  return described > 0 && (known === 0 || described >= known);
957
1191
  }
958
1192
  function explicitAttributedPeopleInAccount(hit) {
959
- const text = primaryAccount(evidenceText(hit.evidence.payload));
960
- const clauses = text
961
- .split(/[;؛.\n]+/u)
962
- .map((clause) => clause.trim())
963
- .filter((clause) => HUMAN_ROLE_LANGUAGE.test(clause) && ATTRIBUTE_ACTION_LANGUAGE.test(clause));
964
- const positions = new Set(clauses.flatMap((clause) => [
965
- ...clause.matchAll(/\b(left|right|middle|center|centre|front|back)\s+(?:person|participant|contestant|player|member|speaker|presenter|host|guest|attendee|individual|man|woman)\b/gi),
966
- ].map((match) => match[0].toLocaleLowerCase()))).size;
967
- const present = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)].filter((match) => ATTRIBUTE_ACTION_LANGUAGE.test(match[2] ?? '')).length;
968
- const participantRecords = clauses.filter((clause) => /^(?:Reconciled|Indexed) participant:/i.test(clause)).length;
969
- return Math.max(positions, present, participantRecords, clauses.length, 0);
1193
+ return subjectEvidenceCount(primaryAccount(evidenceText(hit.evidence.payload)));
970
1194
  }
971
1195
  function explicitPeopleInAccount(hit) {
972
- const text = primaryAccount(evidenceText(hit.evidence.payload));
973
- const present = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)].filter((match) => HUMAN_ROLE_LANGUAGE.test(match[2] ?? '')).length;
974
- const numeric = [
975
- ...text.matchAll(/\b(\d{1,2})\s+(?:people|persons?|participants?|contestants?|players?|members?|speakers?|presenters?|hosts?|guests?|attendees?|men|women)\b/gi),
976
- ].map((match) => Number(match[1]));
977
- const wordCounts = {
978
- two: 2,
979
- three: 3,
980
- four: 4,
981
- five: 5,
982
- six: 6,
983
- seven: 7,
984
- eight: 8,
985
- nine: 9,
986
- ten: 10,
987
- };
988
- const words = [
989
- ...text.matchAll(/\b(two|three|four|five|six|seven|eight|nine|ten)\s+(?:people|persons?|participants?|contestants?|players?|members?|speakers?|presenters?|hosts?|guests?|attendees?|men|women)\b/gi),
990
- ].map((match) => wordCounts[match[1].toLocaleLowerCase()] ?? 0);
991
- const positionalSubjects = new Set([
992
- ...text.matchAll(/\b(left|right|middle|center|centre|front|back)\s+(?:person|participant|contestant|player|member|speaker|presenter|host|guest|attendee|individual|man|woman)\b/gi),
993
- ].map((match) => match[0].toLocaleLowerCase())).size;
994
- return Math.max(present, positionalSubjects, ...numeric, ...words, 0);
1196
+ return subjectEvidenceCount(primaryAccount(evidenceText(hit.evidence.payload)));
1197
+ }
1198
+ /** Read only the internal evidence protocol, never a user-language role list. */
1199
+ function subjectIdentities(text) {
1200
+ const identities = new Set();
1201
+ for (const match of text.matchAll(/^(?:Reconciled|Indexed)\s+(?:participant|visible subject):\s*([^\n—]{1,180})/gim)) {
1202
+ const value = match[1]?.trim();
1203
+ if (value)
1204
+ identities.add(value);
1205
+ }
1206
+ for (const match of text.matchAll(/^Present:\s*([^—\n]{1,180})\s*—/gim)) {
1207
+ const value = match[1]?.trim();
1208
+ if (value)
1209
+ identities.add(value);
1210
+ }
1211
+ for (const line of text.split(/\r?\n/)) {
1212
+ if (!line.startsWith('Visible subject: '))
1213
+ continue;
1214
+ try {
1215
+ const subject = JSON.parse(line.slice('Visible subject: '.length));
1216
+ if (typeof subject.identity === 'string' && subject.identity.trim()) {
1217
+ identities.add(subject.identity.trim());
1218
+ }
1219
+ }
1220
+ catch {
1221
+ // A malformed note is not source evidence.
1222
+ }
1223
+ }
1224
+ return [...identities];
1225
+ }
1226
+ function subjectEvidenceCount(text) {
1227
+ return subjectIdentities(text).length;
995
1228
  }
996
1229
  function primaryAccount(text) {
997
1230
  return text.split(/\nContinuity from (?:the )?(?:preceding|previous) moment:/i, 1)[0] ?? text;
@@ -1008,10 +1241,8 @@ function indexedCrossEvidenceTrail(hits, durationSecs, plan) {
1008
1241
  const seeds = [...candidates]
1009
1242
  .sort((left, right) => {
1010
1243
  const strength = (hit) => {
1011
- const text = evidenceText(hit.evidence.payload);
1012
1244
  return (Number(hit.score ?? 0) +
1013
- (transitionQuestion && TRANSITION_LANGUAGE.test(text) ? 0.25 : 0) -
1014
- (LIMITATION_LANGUAGE.test(text) ? 0.35 : 0) +
1245
+ (hasNegativeVerdict(hit) ? -0.35 : 0) +
1015
1246
  (transitionQuestion && durationSecs
1016
1247
  ? Math.min(0.1, (hit.evidence.timeRange.endSecs / durationSecs) * 0.1)
1017
1248
  : 0));
@@ -1108,7 +1339,7 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
1108
1339
  // "at the beginning" should inspect the beginning even when a visually
1109
1340
  // similar later moment scores higher. These are generic timeline cues, not
1110
1341
  // assumptions about any particular video genre.
1111
- const requestedPosition = temporalQuestionRanges(question, durationSecs);
1342
+ const requestedPosition = directiveTimeRange(plan.investigation, durationSecs);
1112
1343
  // Who is present is usually established early -- a roster, a title card, an
1113
1344
  // introduction -- so a question about identity is worth one look at the
1114
1345
  // opening. A question about how something concluded is not: its answer is at
@@ -1163,25 +1394,14 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
1163
1394
  .sort((left, right) => left.startSecs - right.startSecs), Math.max(1, budget - transitions.length));
1164
1395
  return uniqueRanges([...transitions, ...spread]).slice(0, budget);
1165
1396
  }
1166
- function temporalQuestionRanges(question, durationSecs) {
1167
- if (!durationSecs || !Number.isFinite(durationSecs) || durationSecs <= 0)
1397
+ function directiveTimeRange(directive, durationSecs) {
1398
+ const requested = directive?.timeRange;
1399
+ if (!requested)
1168
1400
  return [];
1169
- const text = question.normalize('NFKC').toLocaleLowerCase();
1170
- const opening = /\b(?:opening|beginning|start|initial)\b|(?:بداية|بدايه|في\s+الأول|في\s+الاول)/u.test(text);
1171
- const ending = /\b(?:ending|closing|final)\b|(?:النهاية|النهايه|في\s+الآخر|في\s+الاخر)/u.test(text);
1172
- const span = (side) => {
1173
- const match = text.match(/(?:first|opening|beginning|initial|last|ending|closing|final)\s+(\d+(?:\.\d+)?)\s*(seconds?|secs?|minutes?|mins?)/u);
1174
- const amount = match ? Number(match[1]) * (/min/i.test(match[2]) ? 60 : 1) : 60;
1175
- const window = Math.min(durationSecs, Math.max(1, amount));
1176
- return side === 'opening'
1177
- ? { startSecs: 0, endSecs: window }
1178
- : { startSecs: Math.max(0, durationSecs - window), endSecs: durationSecs };
1179
- };
1180
- if (opening && !ending)
1181
- return [span('opening')];
1182
- if (ending && !opening)
1183
- return [span('ending')];
1184
- return [];
1401
+ const limit = durationSecs && Number.isFinite(durationSecs) && durationSecs > 0 ? durationSecs : Infinity;
1402
+ const startSecs = Math.max(0, Math.min(limit, requested.startSecs));
1403
+ const endSecs = Math.max(startSecs, Math.min(limit, requested.endSecs));
1404
+ return endSecs > startSecs ? [{ startSecs, endSecs }] : [];
1185
1405
  }
1186
1406
  /**
1187
1407
  * An indexed account that explicitly describes a late transition is a better
@@ -1194,8 +1414,7 @@ function outcomeTransitionRanges(hits, durationSecs, options = {}) {
1194
1414
  if (!isAccountOfMoment(hit) || hasNegativeVerdict(hit) || spansWholeSource(hit, durationSecs)) {
1195
1415
  return false;
1196
1416
  }
1197
- const text = evidenceText(hit.evidence.payload);
1198
- return TRANSITION_LANGUAGE.test(text) && !LIMITATION_LANGUAGE.test(text);
1417
+ return /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(evidenceText(hit.evidence.payload).trim());
1199
1418
  });
1200
1419
  if (accounts.length === 0)
1201
1420
  return [];
@@ -1402,16 +1621,7 @@ function inspectionEntityHints(hits, plan) {
1402
1621
  if (match[1]?.trim())
1403
1622
  hints.push(match[1].trim());
1404
1623
  }
1405
- if (/^(?:Reconciled|Indexed)\s+(?:state|event|context|overview):/i.test(text)) {
1406
- const account = text.replace(/^(?:Reconciled|Indexed)\s+(?:state|event|context|overview):\s*/i, '');
1407
- // A reconciled display/state can establish names that are not people
1408
- // and therefore do not belong in the participant list. Preserve
1409
- // ordinary title-cased names as reader hints; they remain hints, not
1410
- // identity claims, until the bounded source pass binds them.
1411
- for (const match of account.matchAll(/\b[A-Z][\p{Letter}\p{Mark}'’.-]{2,}(?:\s+[A-Z][\p{Letter}\p{Mark}'’.-]{2,}){0,3}\b/gu)) {
1412
- hints.push(match[0]);
1413
- }
1414
- }
1624
+ hints.push(...subjectIdentities(text));
1415
1625
  }
1416
1626
  }
1417
1627
  return [...new Map(hints.map((hint) => [hint.toLocaleLowerCase(), hint])).values()].slice(0, 20);
@@ -1477,7 +1687,7 @@ function selectAnswerEvidence(hits, assessment, plan, input, durationSecs) {
1477
1687
  const stateChanges = hits
1478
1688
  .filter((hit) => {
1479
1689
  const text = evidenceText(hit.evidence.payload);
1480
- return (TRANSITION_LANGUAGE.test(text) || /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(text));
1690
+ return /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(text);
1481
1691
  })
1482
1692
  .sort((left, right) => right.evidence.timeRange.startSecs - left.evidence.timeRange.startSecs);
1483
1693
  return chronological(mergeHits(identity, stateChanges, assessment.corroborating, hits).slice(0, limit));
@@ -1492,7 +1702,7 @@ function selectAnswerEvidence(hits, assessment, plan, input, durationSecs) {
1492
1702
  // merely because the question also happens to be a comparison or outcome.
1493
1703
  // Those supporting records remain available when no direct answer exists.
1494
1704
  if (assessment.sufficient &&
1495
- assessment.established.some((hit) => isDirectVerdict(hit, input.query))) {
1705
+ assessment.established.some((hit) => isDirectVerdict(hit, input.query, plan))) {
1496
1706
  return reconciledFirst(assessment.established).slice(0, limit);
1497
1707
  }
1498
1708
  // A conclusion, a count, and a comparison are read across the source, so the
@@ -1853,21 +2063,16 @@ function inspectionPurpose(kinds) {
1853
2063
  return 'compare';
1854
2064
  return 'verify-visual';
1855
2065
  }
1856
- function isDirectVerdict(hit, question, durationSecs) {
2066
+ function isDirectVerdict(hit, question, plan) {
1857
2067
  const payload = evidenceText(hit.evidence.payload);
1858
2068
  const questionMatch = payload.match(/Claim question:\s*([^\n"]+)/i);
1859
- const requestedRanges = temporalQuestionRanges(question, durationSecs);
1860
- const asksIndividualNames = /\b(?:player|person|people|participant|speaker|presenter|guest)s?\b[^\n]*\bname|\bname(?:s)?\b[^\n]*\b(?:player|person|people|participant|speaker|presenter|guest)s?\b|(?:اسم|أسماء).{0,40}(?:لاعب|لاعبين|شخص|أشخاص|مشارك)/iu.test(question);
1861
- const claimAnswer = payload.match(/Claim answer:\s*([^\n]+)/i)?.[1] ?? '';
1862
- const substitutesCollectiveForPerson = asksIndividualNames &&
1863
- /\b(?:team|group|organization|organisation|company|side)s?\s+names?\b|(?:أسماء\s+(?:الفرق|المجموعات|المنظمات))/iu.test(claimAnswer);
2069
+ const requestedRanges = directiveTimeRange(plan?.investigation, undefined);
1864
2070
  const isInRequestedRange = requestedRanges.length === 0 ||
1865
2071
  requestedRanges.some((range) => hit.evidence.timeRange.startSecs < range.endSecs &&
1866
2072
  hit.evidence.timeRange.endSecs > range.startSecs);
1867
2073
  return (payload.includes('Claim verdict: direct') &&
1868
2074
  questionMatch !== null &&
1869
2075
  isInRequestedRange &&
1870
- !substitutesCollectiveForPerson &&
1871
2076
  // A bounded reader receives the user's question plus a concise inspection
1872
2077
  // instruction. Its direct claim remains the same question, even though
1873
2078
  // that extra guidance lowers token overlap.
@@ -1878,8 +2083,8 @@ function isDirectVerdict(hit, question, durationSecs) {
1878
2083
  // fresh visual analysis is required.
1879
2084
  questionSimilarity(questionMatch[1], question) >= 0.6);
1880
2085
  }
1881
- function answerEstablishedHits(hits, question, kinds, watched = { ranges: [], since: '' }, durationSecs) {
1882
- const verified = hits.filter((hit) => isDirectVerdict(hit, question, durationSecs));
2086
+ function answerEstablishedHits(hits, question, plan, watched = { ranges: [], since: '' }) {
2087
+ const verified = hits.filter((hit) => isDirectVerdict(hit, question, plan));
1883
2088
  if (verified.length > 0)
1884
2089
  return verified;
1885
2090
  // Evidence recorded *by* watching a range for this question answers it by
@@ -1910,18 +2115,17 @@ function answerEstablishedHits(hits, question, kinds, watched = { ranges: [], si
1910
2115
  // immediately. Aggregates, comparisons, identity attribution, and
1911
2116
  // conclusions stay stricter because they require reasoning across
1912
2117
  // observations rather than reading one source-backed fact.
1913
- const requiresCrossEvidenceReasoning = kinds.some((kind) => [
2118
+ const requiresCrossEvidenceReasoning = plan.kinds.some((kind) => [
1914
2119
  'outcome',
1915
2120
  'state-change',
1916
2121
  'comparison',
1917
2122
  'counting',
1918
2123
  'computation',
1919
2124
  'person-attribute',
1920
- 'visual-fact',
1921
2125
  ].includes(kind));
1922
2126
  if (requiresCrossEvidenceReasoning)
1923
2127
  return [];
1924
- return hits.filter((hit) => isIndexedDirectObservation(hit, question));
2128
+ return hits.filter((hit) => isIndexedDirectObservation(hit, question, plan));
1925
2129
  }
1926
2130
  /**
1927
2131
  * Whether a record recounts what a moment showed, rather than carrying raw
@@ -1941,8 +2145,21 @@ function isAccountOfMoment(hit) {
1941
2145
  // A typed subject/property/value locates a display; it does not describe it.
1942
2146
  return typeof text === 'string' && text.trim().length > 0;
1943
2147
  }
1944
- function isIndexedDirectObservation(hit, question) {
1945
- if (!['transcript', 'ocr', 'visual'].includes(hit.evidence.modality))
2148
+ function isIndexedDirectObservation(hit, question, plan) {
2149
+ const text = evidenceText(hit.evidence.payload);
2150
+ // The durable aggregate is normally navigation context, not a direct fact.
2151
+ // Its visibility ledger is the exception: it is emitted from a typed visual
2152
+ // observation protocol and is precisely the merged record required for an
2153
+ // appearance/timing answer. Keeping this exception protocol-bound prevents
2154
+ // an arbitrary computed summary from bypassing source corroboration.
2155
+ const reconciledVisibility = hit.evidence.modality === 'computed' &&
2156
+ /^Reconciled visible subject:\s*[^\n]+\nIdentity basis:\s*(?:source-named|source-described|unresolved)\nObserved appearances:\s*\d/im.test(text);
2157
+ if (!['transcript', 'ocr', 'visual'].includes(hit.evidence.modality) && !reconciledVisibility)
2158
+ return false;
2159
+ // Raw OCR/detection payloads locate a moment but do not recount what was
2160
+ // observed there. A broad recurring overlay must never become evidence that
2161
+ // a person, animal, event, or other subject was present at that timestamp.
2162
+ if (!reconciledVisibility && !isAccountOfMoment(hit))
1946
2163
  return false;
1947
2164
  const confidence = typeof hit.evidence.confidence === 'object' && hit.evidence.confidence !== null
1948
2165
  ? Number(hit.evidence.confidence.score)
@@ -1951,13 +2168,32 @@ function isIndexedDirectObservation(hit, question) {
1951
2168
  return false;
1952
2169
  if (hasNegativeVerdictForQuestion(hit, question))
1953
2170
  return false;
2171
+ // A previous direct-verdict record is reusable only through
2172
+ // `isDirectVerdict` above, which checks its original question. Letting its
2173
+ // generic semantic score through here would silently reuse a nearby answer
2174
+ // for a different question.
2175
+ if (/Claim question:\s*/i.test(text))
2176
+ return false;
2177
+ const requestedRanges = directiveTimeRange(plan?.investigation, undefined);
2178
+ const establishedRanges = reconciledVisibility ? observedAppearanceRanges(text) : [];
2179
+ if (requestedRanges.length > 0 &&
2180
+ !(establishedRanges.length > 0 ? establishedRanges : [hit.evidence.timeRange]).some((candidate) => requestedRanges.some((range) => candidate.startSecs < range.endSecs && candidate.endSecs > range.startSecs))) {
2181
+ return false;
2182
+ }
1954
2183
  // Retrieval can return a high-quality neighbouring scene even when it does
1955
2184
  // not contain the fact the user asked for. Treat an indexed observation as
1956
2185
  // answer-level evidence only when it shares a meaningful query term or the
1957
2186
  // hybrid retriever explicitly marked it as a semantic match. Otherwise the
1958
2187
  // bounded live reader gets the opportunity to inspect the candidate range.
1959
2188
  const semanticMatch = Number(hit.components?.semantic ?? 0) > 0;
1960
- if (semanticMatch)
2189
+ // A human-selected source range is itself a strict relevance constraint.
2190
+ // Within it, a full visual account can answer even when the question and
2191
+ // account use different languages or different descriptions. Raw
2192
+ // locators remain excluded above, and broad evidence still requires a
2193
+ // lexical or semantic match.
2194
+ const directlyRequestedMoment = requestedRanges.length > 0 &&
2195
+ (establishedRanges.length > 0 ? establishedRanges : [hit.evidence.timeRange]).some((candidate) => requestedRanges.some((range) => candidate.startSecs < range.endSecs && candidate.endSecs > range.startSecs));
2196
+ if (semanticMatch || directlyRequestedMoment)
1961
2197
  return true;
1962
2198
  const questionTerms = new Set(question
1963
2199
  .normalize('NFKC')
@@ -1966,12 +2202,25 @@ function isIndexedDirectObservation(hit, question) {
1966
2202
  ?.filter((term) => term.length > 3) ?? []);
1967
2203
  if (questionTerms.size === 0)
1968
2204
  return false;
1969
- const sourceTerms = new Set(evidenceText(hit.evidence.payload)
2205
+ const sourceTerms = new Set(text
1970
2206
  .normalize('NFKC')
1971
2207
  .toLocaleLowerCase()
1972
2208
  .match(/[\p{Letter}\p{Number}][\p{Letter}\p{Number}\p{Mark}_-]*/gu) ?? []);
1973
2209
  return [...questionTerms].some((term) => sourceTerms.has(term));
1974
2210
  }
2211
+ /** Read only the visibility-ledger protocol's explicit intervals. */
2212
+ function observedAppearanceRanges(text) {
2213
+ const appearances = text.match(/^Observed appearances:\s*([^\n]+)/im)?.[1];
2214
+ if (!appearances)
2215
+ return [];
2216
+ const milliseconds = [...appearances.matchAll(/(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)ms\b/gu)].map((match) => ({ startSecs: Number(match[1]) / 1_000, endSecs: Number(match[2]) / 1_000 }));
2217
+ if (milliseconds.length > 0)
2218
+ return milliseconds;
2219
+ return [...appearances.matchAll(/(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)s\b/gu)].map((match) => ({
2220
+ startSecs: Number(match[1]),
2221
+ endSecs: Number(match[2]),
2222
+ }));
2223
+ }
1975
2224
  function hasNegativeVerdictForQuestion(hit, question) {
1976
2225
  const payload = evidenceText(hit.evidence.payload);
1977
2226
  const questionMatch = payload.match(/Claim question:\s*([^\n"]+)/i);
@@ -2042,8 +2291,8 @@ function focusQuestion(question, fileName) {
2042
2291
  if (!fileName)
2043
2292
  return normalized;
2044
2293
  const comparableTerm = (term) => term
2294
+ .normalize('NFKC')
2045
2295
  .toLocaleLowerCase()
2046
- .replace(/ى/g, 'ي')
2047
2296
  .replace(/\p{Mark}/gu, '');
2048
2297
  const titleTerms = new Set(fileName
2049
2298
  .normalize('NFKC')
@@ -2076,6 +2325,21 @@ function isValidQueryInput(input) {
2076
2325
  typeof input.query === 'string' &&
2077
2326
  input.query.trim().length > 0);
2078
2327
  }
2328
+ function validInvestigation(value) {
2329
+ if (!value || typeof value !== 'object')
2330
+ return false;
2331
+ const directive = value;
2332
+ const timeRange = directive.timeRange;
2333
+ return (['focused', 'temporal', 'source'].includes(String(directive.scope)) &&
2334
+ ['answer', 'compare', 'trace', 'enumerate', 'synthesize'].includes(String(directive.goal)) &&
2335
+ (directive.recordSet === undefined ||
2336
+ ['all', 'source-authored', 'source-questions', 'observed'].includes(directive.recordSet)) &&
2337
+ (timeRange === undefined ||
2338
+ (Number.isFinite(timeRange.startSecs) &&
2339
+ Number.isFinite(timeRange.endSecs) &&
2340
+ timeRange.startSecs >= 0 &&
2341
+ timeRange.endSecs >= timeRange.startSecs)));
2342
+ }
2079
2343
  function isValidInspectionInput(input) {
2080
2344
  return (typeof input.mediaAssetId === 'string' &&
2081
2345
  input.mediaAssetId.length > 0 &&