@larkup/tool-video-intelligence 0.2.11 → 0.3.1

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. It uses the right source operation automatically: ranked evidence for focused questions, chronological scan for every source-authored item, and aggregate facts for people or a whole-source account. Perform a bounded direct re-watch only when returned 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 selects a source operation before asking a model to synthesize: focused questions use ranked evidence; complete source inventories use a chronological database scan; person and timeline questions may use a compact aggregate. Never turn a complete-source request into top-K retrieval. 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 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,18 +103,23 @@ 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;
95
125
  // Complete inventories are a deterministic database scan, never an
@@ -97,7 +127,8 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
97
127
  // so a model cannot stop early or mistake its context window for source
98
128
  // coverage.
99
129
  if (plan.route === 'scan' && mediaEvidence.scan) {
100
- const sourceInventory = plan.kinds.includes('question-inventory') || plan.kinds.includes('source-inventory');
130
+ const sourceInventory = focusedInput.investigation.recordSet === 'source-authored' ||
131
+ focusedInput.investigation.recordSet === 'source-questions';
101
132
  const scanned = await mediaEvidence.scan(input.mediaAssetId, {
102
133
  kind: sourceInventory ? 'source-inventory' : 'all-evidence',
103
134
  cursor: input.cursor,
@@ -108,12 +139,17 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
108
139
  // items too. A question table must contain only source questions;
109
140
  // the cursor still follows every raw record so coverage remains an
110
141
  // exact chronological scan rather than a filtered Top-K search.
111
- const scanRecords = plan.kinds.includes('question-inventory')
142
+ const scanRecords = focusedInput.investigation.recordSet === 'source-questions'
112
143
  ? scanned.records.filter((record) => record.kind === 'question' &&
113
144
  record.questionRole !== 'interactional' &&
114
145
  record.questionRole !== 'rhetorical')
115
146
  : scanned.records;
116
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);
117
153
  // A page is directly grounded when the indexed source coverage is
118
154
  // complete. The chat host owns cursor-following and will withhold a
119
155
  // final exhaustive rendering until the final page arrives.
@@ -136,6 +172,16 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
136
172
  mediaAssetId: input.mediaAssetId,
137
173
  fileName: asset.fileName,
138
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,
139
185
  resultHandle: scanned.resultHandle,
140
186
  claimVerification: {
141
187
  status: complete ? 'directly-established' : 'needs-corroboration',
@@ -171,19 +217,32 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
171
217
  };
172
218
  }
173
219
  }
174
- const aggregate = plan.route === 'aggregate' && mediaEvidence.aggregate
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
175
224
  ? await mediaEvidence.aggregate(input.mediaAssetId)
176
225
  : undefined;
177
226
  // Start with the index alone. Planning and visual locating are useful
178
227
  // fallbacks, but waiting for both before checking an already-complete RAG
179
228
  // answer made simple questions feel like analysis jobs.
180
- let hits = mergeHits(await retrieve(mediaEvidence, focusedInput, plan, durationSecs), aggregate ? aggregateToHits(aggregate) : []);
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) : []);
181
240
  let investigation;
182
- let locatedRanges = [];
241
+ let locatedRanges = explicitRanges;
183
242
  let assessment = assessEvidence(hits, focusedInput.query, plan, durationSecs, undefined);
184
243
  if (!assessment.sufficient) {
185
- [investigation, locatedRanges] = await Promise.all([
186
- mediaEvidence.planInvestigation?.(input.mediaAssetId, focusedInput.query),
244
+ const [plannedInvestigation, semanticRanges] = await Promise.all([
245
+ mediaEvidence.planInvestigation?.(input.mediaAssetId, focusedInput.query, focusedInput.investigation),
187
246
  // Where independent indexed signals agree the answer is. This is
188
247
  // measured navigation, not evidence, and only runs after the fast
189
248
  // indexed answer test has failed.
@@ -192,7 +251,10 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
192
251
  maxWindowSecs: MAX_INSPECTION_CHUNK_SECS,
193
252
  }) ?? Promise.resolve([]),
194
253
  ]);
195
- 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);
196
258
  hits = mergeHits(locatedEvidence, hits);
197
259
  assessment = assessEvidence(hits, focusedInput.query, plan, durationSecs, investigation);
198
260
  }
@@ -263,7 +325,11 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
263
325
  analyzedRanges: established.map((reading) => reading.range),
264
326
  broadCoverage: plan.requiresBroadCoverage === true,
265
327
  coverage: investigation?.coverage,
328
+ directive: investigationDirectiveForOutput(focusedInput.investigation),
266
329
  },
330
+ ...(shouldIncludeObservedSubjects(aggregate, focusedInput.investigation, plan)
331
+ ? { observedSubjects: aggregate.visibleSubjects }
332
+ : {}),
267
333
  ...(focusedInput.exhaustive
268
334
  ? { continuation: exhaustiveContinuation(hits, assessment, focusedInput) }
269
335
  : {}),
@@ -320,6 +386,12 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
320
386
  const supportingClip = plan.kinds.includes('outcome')
321
387
  ? evidence.at(-1)?.timeRange
322
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);
323
395
  const responseTimeMs = Date.now() - startedAt;
324
396
  const answerPath = analyzedRanges.length > 0 ? 'rag+analysis' : 'rag';
325
397
  void trackUsageEvent({
@@ -364,7 +436,9 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
364
436
  analyzedRanges,
365
437
  broadCoverage: plan.requiresBroadCoverage === true,
366
438
  coverage: investigation?.coverage,
439
+ directive: investigationDirectiveForOutput(focusedInput.investigation),
367
440
  },
441
+ ...(includeObservedSubjects ? { observedSubjects: aggregate.visibleSubjects } : {}),
368
442
  ...(focusedInput.exhaustive
369
443
  ? { continuation: exhaustiveContinuation(hits, assessment, focusedInput) }
370
444
  : {}),
@@ -407,7 +481,43 @@ function windowObjective(plan) {
407
481
  }
408
482
  /** The evidence a reply cites, in the shape the host renders. */
409
483
  function evidenceHitsFor(hits, assessment, plan, input, durationSecs) {
410
- 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));
411
521
  }
412
522
  function scanRecordToEvidence(record) {
413
523
  const prefix = record.kind === 'question'
@@ -430,6 +540,37 @@ function scanRecordToEvidence(record) {
430
540
  confidence: record.confidence,
431
541
  };
432
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
+ }
433
574
  function aggregateToHits(aggregate) {
434
575
  const createdAt = new Date().toISOString();
435
576
  return [
@@ -468,7 +609,7 @@ function aggregateToHits(aggregate) {
468
609
  timeRange: item.timeRange,
469
610
  payload: {
470
611
  text: item.kind === 'question'
471
- ? `Source question (${item.channel ?? 'spoken'}${item.questionRole ? `, ${item.questionRole}` : ''}): ${item.text}`
612
+ ? `Source question (${item.channel ?? 'spoken'}${item.questionRole ? `, ${item.questionRole}` : ''}): ${item.text}${item.answer ? `\nSource answer: ${item.answer}` : ''}${item.respondent ? `\nSource respondent: ${item.respondent}` : ''}`
472
613
  : item.kind === 'structure'
473
614
  ? `Source structure: ${item.text}${item.promptSlots === undefined
474
615
  ? ''
@@ -482,6 +623,30 @@ function aggregateToHits(aggregate) {
482
623
  score: 0.8,
483
624
  conflict: false,
484
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
+ })),
485
650
  ];
486
651
  }
487
652
  async function retrieve(mediaEvidence, input, plan, durationSecs) {
@@ -560,10 +725,18 @@ async function retrieveEvidenceInRanges(mediaEvidence, input, plan, durationSecs
560
725
  // provenance and claim verification below to decide which can answer.
561
726
  minimumRangeDistanceSecs: 0,
562
727
  };
563
- const groups = await Promise.all(ranges.map((range) => mediaEvidence.search(input.mediaAssetId, input.query, 24, {
564
- ...options,
565
- timeRange: range,
566
- })));
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
+ }));
567
740
  return mergeHits(...groups);
568
741
  }
569
742
  function needsSourceWideView(plan) {
@@ -638,7 +811,7 @@ function assessEvidence(hits, question, plan, durationSecs, investigation, watch
638
811
  sequenceReady),
639
812
  };
640
813
  }
641
- const direct = answerEstablishedHits(hits, question, plan.kinds, watched, durationSecs);
814
+ const direct = answerEstablishedHits(hits, question, plan, watched);
642
815
  const reconciled = direct.length === 0 ? indexedReconciledAnswerHits(hits, plan, durationSecs) : [];
643
816
  const trail = direct.length === 0 && reconciled.length === 0 && isCrossEvidenceClaim(plan)
644
817
  ? indexedCrossEvidenceTrail(hits, durationSecs, plan)
@@ -686,29 +859,14 @@ function assessEvidence(hits, question, plan, durationSecs, investigation, watch
686
859
  establishedByTrail: direct.length === 0 && reconciled.length === 0 && established.length > 0,
687
860
  };
688
861
  }
689
- /** Keep compact records that actually bind identities, roles, or memberships. */
690
- function identityInventoryHits(hits, question) {
691
- const asksForPeople = /\b(?:people|persons?|participants?|contestants?|players?|members?|speakers?|presenters?|hosts?|guests?|attendees?|men|women)\b/i.test(question) ||
692
- /(?:الأشخاص|الاشخاص|المشاركين|المتسابقين|اللاعبين|الأعضاء|الاعضاء|المتحدثين|المقدمين|الضيوف|الرجال|السيدات)/u.test(question);
693
- 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) {
694
864
  const selected = chronological(hits).filter((hit) => {
695
865
  const text = evidenceText(hit.evidence.payload);
696
- if (/^(?:Reconciled|Indexed) participant:\s*[^—\n]{2,120}/im.test(text))
697
- return true;
698
- const present = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)];
699
- if (!asksForPeople)
700
- return present.length > 0;
701
- return present.some((match) => {
702
- const name = match[1]?.trim() ?? '';
703
- const role = match[2] ?? '';
704
- return HUMAN_ROLE_LANGUAGE.test(role) && !GENERIC_IDENTITY_LANGUAGE.test(name);
705
- });
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));
706
869
  });
707
- if (groupedRequest) {
708
- const ranked = [...selected].sort((left, right) => groupedIdentityStrength(right) - groupedIdentityStrength(left));
709
- if (ranked.length > 0 && groupedIdentityStrength(ranked[0]) >= 20)
710
- return [ranked[0]];
711
- }
712
870
  const seen = new Set();
713
871
  return selected
714
872
  .filter((hit) => {
@@ -723,20 +881,19 @@ function identityInventoryHits(hits, question) {
723
881
  }
724
882
  function groupedIdentityStrength(hit) {
725
883
  const text = primaryAccount(evidenceText(hit.evidence.payload));
726
- const namedPeople = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)].filter((match) => HUMAN_ROLE_LANGUAGE.test(match[2] ?? '') &&
727
- !GENERIC_IDENTITY_LANGUAGE.test(match[1]?.trim() ?? '')).length;
884
+ const anchoredSubjects = subjectEvidenceCount(text);
728
885
  let groupedBindings = 0;
729
886
  const serializedBindings = text.match(/^Claim bindings:\s*(.+)$/im)?.[1];
730
887
  if (serializedBindings) {
731
888
  try {
732
889
  const bindings = JSON.parse(serializedBindings);
733
- 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;
734
891
  }
735
892
  catch {
736
893
  groupedBindings = 0;
737
894
  }
738
895
  }
739
- return (namedPeople * 4 +
896
+ return (anchoredSubjects * 4 +
740
897
  groupedBindings * 8 +
741
898
  Number(hit.score ?? 0));
742
899
  }
@@ -761,39 +918,26 @@ function evaluationEvidenceHits(hits) {
761
918
  : mergeHits(semanticAccounts, chronological(hits).filter((hit) => hit.evidence.modality === 'transcript' && isAccountOfMoment(hit)));
762
919
  return evenlySpaced(useful, 36);
763
920
  }
764
- /** A comparative judgement needs repeated named human activity, not scenery or score displays. */
921
+ /** A comparative judgement needs repeated source-anchored activity. */
765
922
  function evaluationEvidenceReady(hits) {
766
- const momentsByPerson = new Map();
923
+ const momentsBySubject = new Map();
767
924
  for (const hit of hits) {
768
925
  const text = primaryAccount(evidenceText(hit.evidence.payload));
769
- for (const match of text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)) {
770
- const name = match[1]?.trim() ?? '';
771
- if (!HUMAN_ROLE_LANGUAGE.test(match[2] ?? '') || GENERIC_IDENTITY_LANGUAGE.test(name)) {
772
- continue;
773
- }
774
- const key = name.normalize('NFKC').toLocaleLowerCase();
775
- 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();
776
929
  moments.add(Math.floor(hit.evidence.timeRange.startSecs / 15));
777
- momentsByPerson.set(key, moments);
930
+ momentsBySubject.set(key, moments);
778
931
  }
779
932
  }
780
- return [...momentsByPerson.values()].filter((moments) => moments.size >= 2).length >= 2;
933
+ return [...momentsBySubject.values()].filter((moments) => moments.size >= 2).length >= 2;
781
934
  }
782
- /** Source-wide visible units extracted during indexing, kept separate from narrative notes. */
783
- function sourceInventoryHits(hits, question) {
784
- const text = question.normalize('NFKC').toLocaleLowerCase();
785
- const wantsSlides = /\bslides?\b|(?:الشرائح|السلايدز)/u.test(text);
786
- 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) {
787
937
  const records = chronological(hits).filter((hit) => {
788
938
  const account = evidenceText(hit.evidence.payload);
789
939
  const kind = account.match(/^Source item \((heading|slide-item|board-item|list-item),\s*(?:spoken|visible)\):/im)?.[1];
790
- if (!kind)
791
- return false;
792
- if (wantsSlides)
793
- return kind === 'heading' || kind === 'slide-item';
794
- if (wantsBoard)
795
- return kind === 'heading' || kind === 'board-item';
796
- return true;
940
+ return Boolean(kind);
797
941
  });
798
942
  const seen = new Set();
799
943
  return records.filter((hit) => {
@@ -810,15 +954,14 @@ function temporalSequenceHits(hits) {
810
954
  if (hit.evidence.source?.provider !== 'video-intelligence-index')
811
955
  return false;
812
956
  const text = evidenceText(hit.evidence.payload).trim();
813
- return (/^Reconciled state:/i.test(text) ||
814
- (/^Reconciled event:/i.test(text) && TRANSITION_LANGUAGE.test(text)));
957
+ return /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(text);
815
958
  });
816
959
  // Older indexes may not contain a synthesized trajectory. Preserve their
817
960
  // broad raw account so a targeted inspection can still use it.
818
961
  return reconciled.length >= 3 ? reconciled : hits;
819
962
  }
820
963
  /** Keep only source-authored prompts for an exhaustive question inventory. */
821
- function questionInventoryHits(hits, query) {
964
+ function questionInventoryHits(hits, _query) {
822
965
  const seen = new Set();
823
966
  const candidates = chronological(hits).flatMap((hit) => {
824
967
  // A later chat inspection can itself contain the user's question. It is
@@ -827,10 +970,8 @@ function questionInventoryHits(hits, query) {
827
970
  return [];
828
971
  return sourceQuestionRecordsFromHit(hit).flatMap((record, index) => {
829
972
  const normalizedQuestion = normalizeInventoryText(record.question);
830
- if (!normalizedQuestion ||
831
- /what the person reading (?:these|the) notes cares about|what the (?:viewer|reader) cares about/i.test(normalizedQuestion)) {
973
+ if (!normalizedQuestion)
832
974
  return [];
833
- }
834
975
  const key = [
835
976
  normalizedQuestion,
836
977
  normalizeInventoryText(record.context ?? ''),
@@ -859,39 +1000,14 @@ function questionInventoryHits(hits, query) {
859
1000
  ];
860
1001
  });
861
1002
  });
862
- const asksForFormalPromptSection = /\b(?:competition|contest|quiz|game|exam|test|challenge|round)\b|(?:مسابقة|المسابقة|اختبار|تحدي|جولة|لعبة)/iu.test(query);
863
- const visibleMoments = candidates
864
- .filter((candidate) => candidate
865
- .sourceQuestionChannel === 'visible')
866
- .map((candidate) => candidate.evidence.timeRange.startSecs);
867
- const sectionCandidates = asksForFormalPromptSection && visibleMoments.length > 0
868
- ? candidates.filter((candidate) => {
869
- const record = candidate;
870
- if (record.sourceQuestionChannel === 'visible')
871
- return true;
872
- const at = candidate.evidence.timeRange.startSecs;
873
- if (at < Math.min(...visibleMoments) - 60 || at > Math.max(...visibleMoments) + 60)
874
- return false;
875
- // A standalone prompt should not contain the first-person planning
876
- // and turn-taking language typical of a reaction or answer fragment.
877
- const sourceText = record.sourceQuestionText ?? '';
878
- 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))
879
- return false;
880
- const questionCues = sourceText
881
- .toLocaleLowerCase()
882
- .match(/[\p{Letter}\p{Number}][\p{Letter}\p{Mark}\p{Number}_-]*/gu)
883
- ?.filter((word) => /^(?:who|what|which|how|why|when|where|من|مين|ما|ماذا|كيف|كم|ايه|إيه|أي|اي)$/iu.test(word)) ?? [];
884
- return !questionCues.some((cue, index) => questionCues.findIndex((other) => normalizeInventoryText(other) === normalizeInventoryText(cue)) !== index);
885
- })
886
- : candidates;
887
1003
  // OCR and ASR often capture the same prompt with slight spelling or
888
1004
  // transcription differences. Collapse nearby copies and retain the visible
889
1005
  // or fullest reading, while preserving genuine repeats later in the source.
890
- return sectionCandidates.filter((candidate) => {
1006
+ return candidates.filter((candidate) => {
891
1007
  const candidateRecord = candidate;
892
1008
  if (!candidateRecord.sourceQuestionText)
893
1009
  return true;
894
- const nearbyCopies = sectionCandidates.filter((other) => {
1010
+ const nearbyCopies = candidates.filter((other) => {
895
1011
  const otherText = other
896
1012
  .sourceQuestionText;
897
1013
  return (Boolean(otherText) &&
@@ -917,15 +1033,10 @@ function normalizeInventoryText(value) {
917
1033
  return value.normalize('NFKC').toLocaleLowerCase().replace(/\s+/g, ' ').trim();
918
1034
  }
919
1035
  function inventoryQuestionTokens(value) {
920
- const normalized = value
921
- .normalize('NFKD')
922
- .replace(/[\u064b-\u065f\u0670]/gu, '')
923
- .replace(/[أإآٱ]/gu, 'ا')
924
- .replace(/ى/gu, 'ي')
925
- .toLocaleLowerCase();
926
- const words = normalized.match(/[\p{Letter}\p{Number}][\p{Letter}\p{Mark}\p{Number}_-]*/gu) ?? [];
927
- 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));
928
- 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) ?? []);
929
1040
  }
930
1041
  function inventoryQuestionsMatch(left, right) {
931
1042
  const leftTokens = inventoryQuestionTokens(left);
@@ -936,27 +1047,10 @@ function inventoryQuestionsMatch(left, right) {
936
1047
  return overlap / Math.min(leftTokens.size, rightTokens.size) >= 0.6;
937
1048
  }
938
1049
  function isWellFormedSourceQuestion(record) {
939
- const question = record.question.normalize('NFKC').trim();
940
- if (question.length < 4)
941
- return false;
942
- if (record.channel === 'visible')
943
- return true;
944
- const punctuated = /[?؟]\s*$/u.test(question);
945
- // ASR commonly drops question marks. Require a source-language question or
946
- // request cue near the start; an answer/reaction that happens to contain a
947
- // question word much later must not become a source inventory item.
948
- const words = question
949
- .toLocaleLowerCase()
950
- .match(/[\p{Letter}\p{Number}][\p{Letter}\p{Mark}\p{Number}_-]*/gu) ?? [];
951
- 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;
952
- const cueIndex = words.slice(0, 4).findIndex((word) => cue.test(word));
953
- if (cueIndex < 0)
954
- return punctuated;
955
- const meaningful = new Set(words.slice(cueIndex + 1));
956
- const deictic = /^(?:this|that|it|one|thing|exactly|first|second|third|دي|ده|دا|هذه|هذا|هي|هو|بالظبط|بالضبط|الاولى|الأولى|الثانية|الثالثة)$/iu;
957
- if (meaningful.size === 1 && [...meaningful].every((word) => deictic.test(word)))
958
- return false;
959
- 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;
960
1054
  }
961
1055
  function sourceQuestionRecordsFromHit(hit) {
962
1056
  const text = evidenceText(hit.evidence.payload);
@@ -1067,7 +1161,7 @@ function indexedReconciledAnswerHits(hits, plan, durationSecs) {
1067
1161
  text.length >= 20 &&
1068
1162
  (semantic >= 0.05 || lexical >= 0.2) &&
1069
1163
  !hasNegativeVerdict(hit) &&
1070
- !LIMITATION_LANGUAGE.test(text) &&
1164
+ !hasNegativeVerdict(hit) &&
1071
1165
  !spansWholeSource(hit, durationSecs));
1072
1166
  });
1073
1167
  }
@@ -1087,25 +1181,8 @@ function indexedUnboundSubjectAttributes(hits, question, plan) {
1087
1181
  (hit.evidence.modality === 'computed' &&
1088
1182
  hit.evidence.source?.provider === 'video-intelligence-index')) &&
1089
1183
  isAccountOfMoment(hit) &&
1090
- // Similarity locates a scene, but a scene can be semantically close
1091
- // while describing a different attribute entirely. The account itself
1092
- // must contain the generic action/appearance relation requested here.
1093
- attributeEvidenceMatchesQuestion(primaryAccount(evidenceText(hit.evidence.payload)), question) &&
1094
1184
  !hasNegativeVerdictForQuestion(hit, question));
1095
1185
  }
1096
- function attributeEvidenceMatchesQuestion(evidence, question) {
1097
- if (!ATTRIBUTE_ACTION_LANGUAGE.test(evidence))
1098
- return false;
1099
- const requested = question.match(new RegExp(ATTRIBUTE_ACTION_LANGUAGE.source, 'giu')) ?? [];
1100
- if (requested.length === 0)
1101
- return true;
1102
- const source = evidence.normalize('NFKC').toLocaleLowerCase();
1103
- return requested.some((term) => {
1104
- const normalized = term.normalize('NFKC').toLocaleLowerCase();
1105
- const root = normalized.length >= 5 ? normalized.slice(0, 4) : normalized;
1106
- return root.length >= 3 && source.includes(root);
1107
- });
1108
- }
1109
1186
  /** Do not call a two-person description complete when the index establishes a wider group. */
1110
1187
  function attributeCoverageReady(attributes, allHits) {
1111
1188
  const described = Math.max(0, ...attributes.map(explicitAttributedPeopleInAccount));
@@ -1113,42 +1190,41 @@ function attributeCoverageReady(attributes, allHits) {
1113
1190
  return described > 0 && (known === 0 || described >= known);
1114
1191
  }
1115
1192
  function explicitAttributedPeopleInAccount(hit) {
1116
- const text = primaryAccount(evidenceText(hit.evidence.payload));
1117
- const clauses = text
1118
- .split(/[;؛.\n]+/u)
1119
- .map((clause) => clause.trim())
1120
- .filter((clause) => HUMAN_ROLE_LANGUAGE.test(clause) && ATTRIBUTE_ACTION_LANGUAGE.test(clause));
1121
- const positions = new Set(clauses.flatMap((clause) => [
1122
- ...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),
1123
- ].map((match) => match[0].toLocaleLowerCase()))).size;
1124
- const present = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)].filter((match) => ATTRIBUTE_ACTION_LANGUAGE.test(match[2] ?? '')).length;
1125
- const participantRecords = clauses.filter((clause) => /^(?:Reconciled|Indexed) participant:/i.test(clause)).length;
1126
- return Math.max(positions, present, participantRecords, clauses.length, 0);
1193
+ return subjectEvidenceCount(primaryAccount(evidenceText(hit.evidence.payload)));
1127
1194
  }
1128
1195
  function explicitPeopleInAccount(hit) {
1129
- const text = primaryAccount(evidenceText(hit.evidence.payload));
1130
- const present = [...text.matchAll(/^Present:\s*([^—\n]{2,120})\s*—\s*([^\n]+)/gim)].filter((match) => HUMAN_ROLE_LANGUAGE.test(match[2] ?? '')).length;
1131
- const numeric = [
1132
- ...text.matchAll(/\b(\d{1,2})\s+(?:people|persons?|participants?|contestants?|players?|members?|speakers?|presenters?|hosts?|guests?|attendees?|men|women)\b/gi),
1133
- ].map((match) => Number(match[1]));
1134
- const wordCounts = {
1135
- two: 2,
1136
- three: 3,
1137
- four: 4,
1138
- five: 5,
1139
- six: 6,
1140
- seven: 7,
1141
- eight: 8,
1142
- nine: 9,
1143
- ten: 10,
1144
- };
1145
- const words = [
1146
- ...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),
1147
- ].map((match) => wordCounts[match[1].toLocaleLowerCase()] ?? 0);
1148
- const positionalSubjects = new Set([
1149
- ...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),
1150
- ].map((match) => match[0].toLocaleLowerCase())).size;
1151
- 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;
1152
1228
  }
1153
1229
  function primaryAccount(text) {
1154
1230
  return text.split(/\nContinuity from (?:the )?(?:preceding|previous) moment:/i, 1)[0] ?? text;
@@ -1165,10 +1241,8 @@ function indexedCrossEvidenceTrail(hits, durationSecs, plan) {
1165
1241
  const seeds = [...candidates]
1166
1242
  .sort((left, right) => {
1167
1243
  const strength = (hit) => {
1168
- const text = evidenceText(hit.evidence.payload);
1169
1244
  return (Number(hit.score ?? 0) +
1170
- (transitionQuestion && TRANSITION_LANGUAGE.test(text) ? 0.25 : 0) -
1171
- (LIMITATION_LANGUAGE.test(text) ? 0.35 : 0) +
1245
+ (hasNegativeVerdict(hit) ? -0.35 : 0) +
1172
1246
  (transitionQuestion && durationSecs
1173
1247
  ? Math.min(0.1, (hit.evidence.timeRange.endSecs / durationSecs) * 0.1)
1174
1248
  : 0));
@@ -1265,7 +1339,7 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
1265
1339
  // "at the beginning" should inspect the beginning even when a visually
1266
1340
  // similar later moment scores higher. These are generic timeline cues, not
1267
1341
  // assumptions about any particular video genre.
1268
- const requestedPosition = temporalQuestionRanges(question, durationSecs);
1342
+ const requestedPosition = directiveTimeRange(plan.investigation, durationSecs);
1269
1343
  // Who is present is usually established early -- a roster, a title card, an
1270
1344
  // introduction -- so a question about identity is worth one look at the
1271
1345
  // opening. A question about how something concluded is not: its answer is at
@@ -1320,25 +1394,14 @@ function inspectionTargets(hits, question, plan, assessment, durationSecs, inves
1320
1394
  .sort((left, right) => left.startSecs - right.startSecs), Math.max(1, budget - transitions.length));
1321
1395
  return uniqueRanges([...transitions, ...spread]).slice(0, budget);
1322
1396
  }
1323
- function temporalQuestionRanges(question, durationSecs) {
1324
- if (!durationSecs || !Number.isFinite(durationSecs) || durationSecs <= 0)
1397
+ function directiveTimeRange(directive, durationSecs) {
1398
+ const requested = directive?.timeRange;
1399
+ if (!requested)
1325
1400
  return [];
1326
- const text = question.normalize('NFKC').toLocaleLowerCase();
1327
- const opening = /\b(?:opening|beginning|start|initial)\b|(?:بداية|بدايه|في\s+الأول|في\s+الاول)/u.test(text);
1328
- const ending = /\b(?:ending|closing|final)\b|(?:النهاية|النهايه|في\s+الآخر|في\s+الاخر)/u.test(text);
1329
- const span = (side) => {
1330
- const match = text.match(/(?:first|opening|beginning|initial|last|ending|closing|final)\s+(\d+(?:\.\d+)?)\s*(seconds?|secs?|minutes?|mins?)/u);
1331
- const amount = match ? Number(match[1]) * (/min/i.test(match[2]) ? 60 : 1) : 60;
1332
- const window = Math.min(durationSecs, Math.max(1, amount));
1333
- return side === 'opening'
1334
- ? { startSecs: 0, endSecs: window }
1335
- : { startSecs: Math.max(0, durationSecs - window), endSecs: durationSecs };
1336
- };
1337
- if (opening && !ending)
1338
- return [span('opening')];
1339
- if (ending && !opening)
1340
- return [span('ending')];
1341
- 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 }] : [];
1342
1405
  }
1343
1406
  /**
1344
1407
  * An indexed account that explicitly describes a late transition is a better
@@ -1351,8 +1414,7 @@ function outcomeTransitionRanges(hits, durationSecs, options = {}) {
1351
1414
  if (!isAccountOfMoment(hit) || hasNegativeVerdict(hit) || spansWholeSource(hit, durationSecs)) {
1352
1415
  return false;
1353
1416
  }
1354
- const text = evidenceText(hit.evidence.payload);
1355
- return TRANSITION_LANGUAGE.test(text) && !LIMITATION_LANGUAGE.test(text);
1417
+ return /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(evidenceText(hit.evidence.payload).trim());
1356
1418
  });
1357
1419
  if (accounts.length === 0)
1358
1420
  return [];
@@ -1559,16 +1621,7 @@ function inspectionEntityHints(hits, plan) {
1559
1621
  if (match[1]?.trim())
1560
1622
  hints.push(match[1].trim());
1561
1623
  }
1562
- if (/^(?:Reconciled|Indexed)\s+(?:state|event|context|overview):/i.test(text)) {
1563
- const account = text.replace(/^(?:Reconciled|Indexed)\s+(?:state|event|context|overview):\s*/i, '');
1564
- // A reconciled display/state can establish names that are not people
1565
- // and therefore do not belong in the participant list. Preserve
1566
- // ordinary title-cased names as reader hints; they remain hints, not
1567
- // identity claims, until the bounded source pass binds them.
1568
- 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)) {
1569
- hints.push(match[0]);
1570
- }
1571
- }
1624
+ hints.push(...subjectIdentities(text));
1572
1625
  }
1573
1626
  }
1574
1627
  return [...new Map(hints.map((hint) => [hint.toLocaleLowerCase(), hint])).values()].slice(0, 20);
@@ -1634,7 +1687,7 @@ function selectAnswerEvidence(hits, assessment, plan, input, durationSecs) {
1634
1687
  const stateChanges = hits
1635
1688
  .filter((hit) => {
1636
1689
  const text = evidenceText(hit.evidence.payload);
1637
- return (TRANSITION_LANGUAGE.test(text) || /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(text));
1690
+ return /^(?:Reconciled|Indexed)\s+(?:state|event):/i.test(text);
1638
1691
  })
1639
1692
  .sort((left, right) => right.evidence.timeRange.startSecs - left.evidence.timeRange.startSecs);
1640
1693
  return chronological(mergeHits(identity, stateChanges, assessment.corroborating, hits).slice(0, limit));
@@ -1649,7 +1702,7 @@ function selectAnswerEvidence(hits, assessment, plan, input, durationSecs) {
1649
1702
  // merely because the question also happens to be a comparison or outcome.
1650
1703
  // Those supporting records remain available when no direct answer exists.
1651
1704
  if (assessment.sufficient &&
1652
- assessment.established.some((hit) => isDirectVerdict(hit, input.query))) {
1705
+ assessment.established.some((hit) => isDirectVerdict(hit, input.query, plan))) {
1653
1706
  return reconciledFirst(assessment.established).slice(0, limit);
1654
1707
  }
1655
1708
  // A conclusion, a count, and a comparison are read across the source, so the
@@ -2010,21 +2063,16 @@ function inspectionPurpose(kinds) {
2010
2063
  return 'compare';
2011
2064
  return 'verify-visual';
2012
2065
  }
2013
- function isDirectVerdict(hit, question, durationSecs) {
2066
+ function isDirectVerdict(hit, question, plan) {
2014
2067
  const payload = evidenceText(hit.evidence.payload);
2015
2068
  const questionMatch = payload.match(/Claim question:\s*([^\n"]+)/i);
2016
- const requestedRanges = temporalQuestionRanges(question, durationSecs);
2017
- 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);
2018
- const claimAnswer = payload.match(/Claim answer:\s*([^\n]+)/i)?.[1] ?? '';
2019
- const substitutesCollectiveForPerson = asksIndividualNames &&
2020
- /\b(?:team|group|organization|organisation|company|side)s?\s+names?\b|(?:أسماء\s+(?:الفرق|المجموعات|المنظمات))/iu.test(claimAnswer);
2069
+ const requestedRanges = directiveTimeRange(plan?.investigation, undefined);
2021
2070
  const isInRequestedRange = requestedRanges.length === 0 ||
2022
2071
  requestedRanges.some((range) => hit.evidence.timeRange.startSecs < range.endSecs &&
2023
2072
  hit.evidence.timeRange.endSecs > range.startSecs);
2024
2073
  return (payload.includes('Claim verdict: direct') &&
2025
2074
  questionMatch !== null &&
2026
2075
  isInRequestedRange &&
2027
- !substitutesCollectiveForPerson &&
2028
2076
  // A bounded reader receives the user's question plus a concise inspection
2029
2077
  // instruction. Its direct claim remains the same question, even though
2030
2078
  // that extra guidance lowers token overlap.
@@ -2035,8 +2083,8 @@ function isDirectVerdict(hit, question, durationSecs) {
2035
2083
  // fresh visual analysis is required.
2036
2084
  questionSimilarity(questionMatch[1], question) >= 0.6);
2037
2085
  }
2038
- function answerEstablishedHits(hits, question, kinds, watched = { ranges: [], since: '' }, durationSecs) {
2039
- 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));
2040
2088
  if (verified.length > 0)
2041
2089
  return verified;
2042
2090
  // Evidence recorded *by* watching a range for this question answers it by
@@ -2067,18 +2115,17 @@ function answerEstablishedHits(hits, question, kinds, watched = { ranges: [], si
2067
2115
  // immediately. Aggregates, comparisons, identity attribution, and
2068
2116
  // conclusions stay stricter because they require reasoning across
2069
2117
  // observations rather than reading one source-backed fact.
2070
- const requiresCrossEvidenceReasoning = kinds.some((kind) => [
2118
+ const requiresCrossEvidenceReasoning = plan.kinds.some((kind) => [
2071
2119
  'outcome',
2072
2120
  'state-change',
2073
2121
  'comparison',
2074
2122
  'counting',
2075
2123
  'computation',
2076
2124
  'person-attribute',
2077
- 'visual-fact',
2078
2125
  ].includes(kind));
2079
2126
  if (requiresCrossEvidenceReasoning)
2080
2127
  return [];
2081
- return hits.filter((hit) => isIndexedDirectObservation(hit, question));
2128
+ return hits.filter((hit) => isIndexedDirectObservation(hit, question, plan));
2082
2129
  }
2083
2130
  /**
2084
2131
  * Whether a record recounts what a moment showed, rather than carrying raw
@@ -2098,8 +2145,21 @@ function isAccountOfMoment(hit) {
2098
2145
  // A typed subject/property/value locates a display; it does not describe it.
2099
2146
  return typeof text === 'string' && text.trim().length > 0;
2100
2147
  }
2101
- function isIndexedDirectObservation(hit, question) {
2102
- 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))
2103
2163
  return false;
2104
2164
  const confidence = typeof hit.evidence.confidence === 'object' && hit.evidence.confidence !== null
2105
2165
  ? Number(hit.evidence.confidence.score)
@@ -2108,13 +2168,32 @@ function isIndexedDirectObservation(hit, question) {
2108
2168
  return false;
2109
2169
  if (hasNegativeVerdictForQuestion(hit, question))
2110
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
+ }
2111
2183
  // Retrieval can return a high-quality neighbouring scene even when it does
2112
2184
  // not contain the fact the user asked for. Treat an indexed observation as
2113
2185
  // answer-level evidence only when it shares a meaningful query term or the
2114
2186
  // hybrid retriever explicitly marked it as a semantic match. Otherwise the
2115
2187
  // bounded live reader gets the opportunity to inspect the candidate range.
2116
2188
  const semanticMatch = Number(hit.components?.semantic ?? 0) > 0;
2117
- 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)
2118
2197
  return true;
2119
2198
  const questionTerms = new Set(question
2120
2199
  .normalize('NFKC')
@@ -2123,12 +2202,25 @@ function isIndexedDirectObservation(hit, question) {
2123
2202
  ?.filter((term) => term.length > 3) ?? []);
2124
2203
  if (questionTerms.size === 0)
2125
2204
  return false;
2126
- const sourceTerms = new Set(evidenceText(hit.evidence.payload)
2205
+ const sourceTerms = new Set(text
2127
2206
  .normalize('NFKC')
2128
2207
  .toLocaleLowerCase()
2129
2208
  .match(/[\p{Letter}\p{Number}][\p{Letter}\p{Number}\p{Mark}_-]*/gu) ?? []);
2130
2209
  return [...questionTerms].some((term) => sourceTerms.has(term));
2131
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
+ }
2132
2224
  function hasNegativeVerdictForQuestion(hit, question) {
2133
2225
  const payload = evidenceText(hit.evidence.payload);
2134
2226
  const questionMatch = payload.match(/Claim question:\s*([^\n"]+)/i);
@@ -2199,8 +2291,8 @@ function focusQuestion(question, fileName) {
2199
2291
  if (!fileName)
2200
2292
  return normalized;
2201
2293
  const comparableTerm = (term) => term
2294
+ .normalize('NFKC')
2202
2295
  .toLocaleLowerCase()
2203
- .replace(/ى/g, 'ي')
2204
2296
  .replace(/\p{Mark}/gu, '');
2205
2297
  const titleTerms = new Set(fileName
2206
2298
  .normalize('NFKC')
@@ -2233,6 +2325,21 @@ function isValidQueryInput(input) {
2233
2325
  typeof input.query === 'string' &&
2234
2326
  input.query.trim().length > 0);
2235
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
+ }
2236
2343
  function isValidInspectionInput(input) {
2237
2344
  return (typeof input.mediaAssetId === 'string' &&
2238
2345
  input.mediaAssetId.length > 0 &&