@larkup/tool-video-intelligence 0.2.10 → 0.2.11

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/README.md CHANGED
@@ -151,7 +151,7 @@ evidence so a caller can audit both speed and extraction quality.
151
151
 
152
152
  For managed cloud jobs, the Data-library asset is the canonical copy. A short-lived, KMS-encrypted processing copy is created only so the GPU worker can decode it; it is deleted when the job settles, including failed and cancelled jobs. Once the app has downloaded the evidence, it acknowledges the result and the cloud result object is deleted too. S3 lifecycle rules remove any abandoned processing source or result within one day as a safety bound.
153
153
 
154
- For a complex chat question, the agent first searches active timestamped evidence. If it is incomplete, it may request one authorized, bounded cloud re-analysis (maximum 30 seconds per request) to add fresh OCR, visual detections, or anonymous tracks, then searches the resulting evidence again. This avoids treating RAG snippets as the final answer. The worker seeks directly to the approved range for model inference; source transfer and scale-to-zero GPU startup can still add latency for large videos.
154
+ For a complex chat question, the agent routes the question before answering: focused facts use ranked timestamped evidence, a request for every source-authored question or written item uses an unranked chronological scan, and people/timeline requests can use a revision-scoped aggregate retained outside the chat context. The source mapper separates content-bearing prompts from interactional speech and declarative clues, stores directly established grids, sequences, and collections independently from their readable prompt text, and records separately resolved instances of a reusable prompt when the source proves their boundaries. That lets chat distinguish a complete source scan from a partially legible layout instead of treating banter or hints as questions. A full-source result is marked complete only when every source-inventory window finished; otherwise the response stays explicitly partial. Answers and respondents attached to an inventoried question are retained only when nearby source evidence contains them. If the selected evidence is incomplete, the agent may request one authorized, bounded cloud re-analysis (maximum 30 seconds per request) and then reads the resulting evidence again. The worker seeks directly to the approved range for model inference; source transfer and scale-to-zero GPU startup can still add latency for large videos.
155
155
 
156
156
  ### Answer memory and corrections
157
157
 
package/dist/agent.js CHANGED
@@ -18,7 +18,7 @@ const LIMITATION_LANGUAGE = /\b(?:no explicit|not explicit|does not explicit|not
18
18
  export const AGENT_TOOLS = [
19
19
  {
20
20
  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.',
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.',
22
22
  parameters: {
23
23
  type: 'object',
24
24
  additionalProperties: false,
@@ -34,7 +34,7 @@ export const AGENT_TOOLS = [
34
34
  method: 'queryVideoEvidence',
35
35
  workflow: 'evidence-query',
36
36
  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.',
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.',
38
38
  },
39
39
  {
40
40
  name: 'inspectVideoKnowledge',
@@ -92,10 +92,92 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
92
92
  (plan.requiresBroadCoverage === true && !plan.kinds.includes('evaluation'))),
93
93
  };
94
94
  const durationSecs = asset.durationSecs;
95
+ // Complete inventories are a deterministic database scan, never an
96
+ // expanded Top-K query. The chat route follows the opaque cursor itself,
97
+ // so a model cannot stop early or mistake its context window for source
98
+ // coverage.
99
+ if (plan.route === 'scan' && mediaEvidence.scan) {
100
+ const sourceInventory = plan.kinds.includes('question-inventory') || plan.kinds.includes('source-inventory');
101
+ const scanned = await mediaEvidence.scan(input.mediaAssetId, {
102
+ kind: sourceInventory ? 'source-inventory' : 'all-evidence',
103
+ cursor: input.cursor,
104
+ limit: input.limit,
105
+ });
106
+ if (scanned) {
107
+ // A source inventory can contain headings, slides, and literal list
108
+ // items too. A question table must contain only source questions;
109
+ // the cursor still follows every raw record so coverage remains an
110
+ // exact chronological scan rather than a filtered Top-K search.
111
+ const scanRecords = plan.kinds.includes('question-inventory')
112
+ ? scanned.records.filter((record) => record.kind === 'question' &&
113
+ record.questionRole !== 'interactional' &&
114
+ record.questionRole !== 'rhetorical')
115
+ : scanned.records;
116
+ const evidence = scanRecords.map(scanRecordToEvidence);
117
+ // A page is directly grounded when the indexed source coverage is
118
+ // complete. The chat host owns cursor-following and will withhold a
119
+ // final exhaustive rendering until the final page arrives.
120
+ const complete = scanned.coverage.complete;
121
+ void trackUsageEvent({
122
+ type: 'media_processing',
123
+ mediaType: asset.type === 'audio' ? 'audio' : 'video',
124
+ mediaOperation: 'investigation',
125
+ mediaAssetId: input.mediaAssetId,
126
+ queryKind: plan.kinds.join(','),
127
+ cache: 'hit',
128
+ evidenceCount: evidence.length,
129
+ frameCount: 0,
130
+ durationSecs: 0,
131
+ latencyMs: Date.now() - startedAt,
132
+ timestamp: new Date().toISOString(),
133
+ });
134
+ return {
135
+ success: true,
136
+ mediaAssetId: input.mediaAssetId,
137
+ fileName: asset.fileName,
138
+ evidence,
139
+ resultHandle: scanned.resultHandle,
140
+ claimVerification: {
141
+ status: complete ? 'directly-established' : 'needs-corroboration',
142
+ directlyEstablished: complete,
143
+ rule: complete
144
+ ? scanned.continuation.hasMore
145
+ ? `This is a chronological page from complete active ${sourceInventory ? 'source inventory' : 'source evidence'}. Follow the cursor before presenting a complete answer.`
146
+ : `This result is a complete chronological scan of active ${sourceInventory ? 'source inventory' : 'source evidence'}. Preserve every returned item and its timestamp.`
147
+ : (scanned.coverage.reason ??
148
+ 'The active index does not prove complete source coverage, so present these items as partial rather than complete.'),
149
+ },
150
+ investigation: {
151
+ answerPath: 'deterministic-scan',
152
+ responseTimeMs: Date.now() - startedAt,
153
+ analyzedRanges: [],
154
+ broadCoverage: true,
155
+ coverage: {
156
+ mode: 'broad',
157
+ totalChapters: 0,
158
+ totalScenes: 0,
159
+ representedRanges: scanned.coverage.scannedRecords,
160
+ },
161
+ },
162
+ continuation: {
163
+ exhaustive: true,
164
+ hasMore: scanned.continuation.hasMore,
165
+ ...(scanned.continuation.nextCursor !== undefined
166
+ ? { nextCursor: scanned.continuation.nextCursor }
167
+ : {}),
168
+ totalItems: scanned.continuation.totalRecords,
169
+ resultHandle: scanned.resultHandle,
170
+ },
171
+ };
172
+ }
173
+ }
174
+ const aggregate = plan.route === 'aggregate' && mediaEvidence.aggregate
175
+ ? await mediaEvidence.aggregate(input.mediaAssetId)
176
+ : undefined;
95
177
  // Start with the index alone. Planning and visual locating are useful
96
178
  // fallbacks, but waiting for both before checking an already-complete RAG
97
179
  // answer made simple questions feel like analysis jobs.
98
- let hits = await retrieve(mediaEvidence, focusedInput, plan, durationSecs);
180
+ let hits = mergeHits(await retrieve(mediaEvidence, focusedInput, plan, durationSecs), aggregate ? aggregateToHits(aggregate) : []);
99
181
  let investigation;
100
182
  let locatedRanges = [];
101
183
  let assessment = assessEvidence(hits, focusedInput.query, plan, durationSecs, undefined);
@@ -327,6 +409,81 @@ function windowObjective(plan) {
327
409
  function evidenceHitsFor(hits, assessment, plan, input, durationSecs) {
328
410
  return selectAnswerEvidence(hits, assessment, plan, input, durationSecs).map((hit) => toEvidence(hit, plan));
329
411
  }
412
+ function scanRecordToEvidence(record) {
413
+ const prefix = record.kind === 'question'
414
+ ? `Source question (${record.channel ?? 'spoken'}${record.questionRole ? `, ${record.questionRole}` : ''}): ${record.text}`
415
+ : record.kind === 'evidence'
416
+ ? record.text
417
+ : `Source item (${record.kind}, ${record.channel ?? 'visible'}): ${record.text}`;
418
+ const text = [
419
+ prefix,
420
+ ...(record.taskId ? [`Source task id: ${record.taskId}`] : []),
421
+ ...(record.answer ? [`Source answer: ${record.answer}`] : []),
422
+ ...(record.respondent ? [`Source respondent: ${record.respondent}`] : []),
423
+ ].join('\n');
424
+ return {
425
+ id: record.id,
426
+ evidenceId: record.sourceEvidenceId,
427
+ modality: record.modality,
428
+ timeRange: record.timeRange,
429
+ payload: { text },
430
+ confidence: record.confidence,
431
+ };
432
+ }
433
+ function aggregateToHits(aggregate) {
434
+ const createdAt = new Date().toISOString();
435
+ return [
436
+ ...aggregate.participants.map((participant, index) => ({
437
+ evidence: {
438
+ id: `${aggregate.resultHandle}:participant:${index}`,
439
+ modality: 'computed',
440
+ timeRange: participant.timeRange,
441
+ payload: {
442
+ text: `Reconciled participant: ${participant.name} — ${participant.description}`,
443
+ },
444
+ source: { kind: 'provider', provider: 'video-intelligence-index' },
445
+ confidence: { score: 0.8 },
446
+ createdAt,
447
+ },
448
+ score: 1,
449
+ conflict: false,
450
+ })),
451
+ ...aggregate.timeline.map((entry, index) => ({
452
+ evidence: {
453
+ id: `${aggregate.resultHandle}:timeline:${index}`,
454
+ modality: 'computed',
455
+ timeRange: entry.timeRange,
456
+ payload: { text: entry.text },
457
+ source: { kind: 'provider', provider: 'video-intelligence-index' },
458
+ confidence: { score: 0.75 },
459
+ createdAt,
460
+ },
461
+ score: 0.7,
462
+ conflict: false,
463
+ })),
464
+ ...aggregate.sourceItems.map((item, index) => ({
465
+ evidence: {
466
+ id: `${aggregate.resultHandle}:source-item:${index}`,
467
+ modality: 'computed',
468
+ timeRange: item.timeRange,
469
+ payload: {
470
+ text: item.kind === 'question'
471
+ ? `Source question (${item.channel ?? 'spoken'}${item.questionRole ? `, ${item.questionRole}` : ''}): ${item.text}`
472
+ : item.kind === 'structure'
473
+ ? `Source structure: ${item.text}${item.promptSlots === undefined
474
+ ? ''
475
+ : `\nSource prompt slots: ${item.promptSlots}`}`
476
+ : `Source item (${item.kind}): ${item.text}`,
477
+ },
478
+ source: { kind: 'provider', provider: 'video-intelligence-index' },
479
+ confidence: { score: 0.82 },
480
+ createdAt,
481
+ },
482
+ score: 0.8,
483
+ conflict: false,
484
+ })),
485
+ ];
486
+ }
330
487
  async function retrieve(mediaEvidence, input, plan, durationSecs) {
331
488
  const options = { queryPlan: plan, videoDurationSecs: durationSecs };
332
489
  // A named person and an identity anchor are extra retrieval handles for the
@@ -268,13 +268,41 @@ export interface VideoEvidenceBundle {
268
268
  }>;
269
269
  }>;
270
270
  sourceItems?: Array<{
271
- kind: 'question' | 'heading' | 'slide-item' | 'board-item' | 'list-item';
271
+ kind: 'question' | 'clue' | 'heading' | 'slide-item' | 'board-item' | 'list-item';
272
272
  channel: 'spoken' | 'visible';
273
+ questionRole?: 'primary' | 'interactional' | 'rhetorical' | 'not-question';
273
274
  text: string;
274
275
  answer: string;
276
+ respondent?: string;
275
277
  startMs: number;
276
278
  endMs: number;
277
279
  }>;
280
+ sourceActivityStructures?: Array<{
281
+ kind: 'grid' | 'sequence' | 'collection';
282
+ label: string;
283
+ dimensions: Array<{
284
+ label: string;
285
+ values: string[];
286
+ }>;
287
+ promptCount?: number;
288
+ startMs: number;
289
+ endMs: number;
290
+ }>;
291
+ sourceTaskInstances?: Array<{
292
+ id: string;
293
+ prompt: string;
294
+ channel: 'spoken' | 'visible';
295
+ answer: string;
296
+ respondent?: string;
297
+ startMs: number;
298
+ endMs: number;
299
+ }>;
300
+ sourceInventoryCoverage?: {
301
+ complete: boolean;
302
+ totalWindows: number;
303
+ processedWindows: number;
304
+ reason?: string;
305
+ };
278
306
  uncertainties: string[];
279
307
  };
280
308
  answeringGuide: {
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ export * from './ui.js';
9
9
  export declare const TOOL_META: {
10
10
  readonly id: "video-intelligence";
11
11
  readonly name: "Video Intelligence";
12
- readonly version: "0.2.9";
12
+ readonly version: "0.2.11";
13
13
  };
14
14
  export declare const TOOL_EXTENSION: {
15
15
  id: "video-intelligence";
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ export * from './ui.js';
11
11
  export const TOOL_META = {
12
12
  id: 'video-intelligence',
13
13
  name: 'Video Intelligence',
14
- version: '0.2.9',
14
+ version: '0.2.11',
15
15
  };
16
16
  /** Managed infrastructure stays an implementation detail of Larkup Cloud. */
17
17
  const MANAGED_CLOUD_ENDPOINT = process.env.LARKUP_VIDEO_INTELLIGENCE_CLOUD_ENDPOINT ??
@@ -287,6 +287,7 @@ function createClientFromContext(context) {
287
287
  const { mode, endpoint, apiKey } = resolveClientOptions(context.config);
288
288
  return attachVideoIntelligenceAgentClient(new VideoIntelligenceClient({ mode, endpoint, apiKey, fetch: context.fetch }), context.fetch);
289
289
  }
290
+ const PROVIDER_VERIFICATION_MAX_TOKENS = 16;
290
291
  async function verifyProviderModel(label, provider, apiKey, model, request = globalThis.fetch) {
291
292
  if (!provider || !apiKey || !model) {
292
293
  throw new Error(`${label} needs a provider, model, and API key before it can be verified.`);
@@ -302,7 +303,7 @@ async function verifyProviderModel(label, provider, apiKey, model, request = glo
302
303
  headers: { 'Content-Type': 'application/json' },
303
304
  body: JSON.stringify({
304
305
  contents: [{ role: 'user', parts: [{ text: 'Reply with OK.' }] }],
305
- generationConfig: { maxOutputTokens: 8 },
306
+ generationConfig: { maxOutputTokens: PROVIDER_VERIFICATION_MAX_TOKENS },
306
307
  }),
307
308
  });
308
309
  }
@@ -317,7 +318,7 @@ async function verifyProviderModel(label, provider, apiKey, model, request = glo
317
318
  body: JSON.stringify({
318
319
  model: normalizedModel,
319
320
  messages: [{ role: 'user', content: 'Reply with OK.' }],
320
- max_tokens: 8,
321
+ max_tokens: PROVIDER_VERIFICATION_MAX_TOKENS,
321
322
  }),
322
323
  });
323
324
  }
@@ -335,7 +336,7 @@ async function verifyProviderModel(label, provider, apiKey, model, request = glo
335
336
  body: JSON.stringify({
336
337
  model: normalizedProvider === 'vercel_ai_gateway' ? model : normalizedModel,
337
338
  messages: [{ role: 'user', content: 'Reply with OK.' }],
338
- max_tokens: 8,
339
+ max_tokens: PROVIDER_VERIFICATION_MAX_TOKENS,
339
340
  }),
340
341
  });
341
342
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@larkup/tool-video-intelligence",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
4
4
  "type": "module",
5
5
  "description": "Installable local and cloud video intelligence with evidence-first indexing.",
6
6
  "main": "./dist/index.js",
@@ -55,13 +55,13 @@
55
55
  }
56
56
  },
57
57
  "dependencies": {
58
- "@larkup/core": "0.5.5"
58
+ "@larkup/core": "0.6.0"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@types/node": "^26",
62
62
  "typescript": "^7.0.2",
63
63
  "vitest": "^5.0.0",
64
- "@larkup/marketplace": "0.2.6"
64
+ "@larkup/marketplace": "0.2.8"
65
65
  },
66
66
  "publishConfig": {
67
67
  "access": "public"
@@ -247,6 +247,7 @@ SOURCE_INVENTORY_JSON_SCHEMA: dict[str, Any] = {
247
247
  "type": "string",
248
248
  "enum": [
249
249
  "question",
250
+ "clue",
250
251
  "heading",
251
252
  "slide-item",
252
253
  "board-item",
@@ -254,24 +255,96 @@ SOURCE_INVENTORY_JSON_SCHEMA: dict[str, Any] = {
254
255
  ],
255
256
  },
256
257
  "channel": {"type": "string", "enum": ["spoken", "visible"]},
258
+ "questionRole": {
259
+ "type": "string",
260
+ "enum": ["primary", "interactional", "rhetorical", "not-question"],
261
+ },
257
262
  "text": {"type": "string", "maxLength": 600},
258
263
  "answer": {"type": "string", "maxLength": 600},
264
+ "respondent": {"type": "string", "maxLength": 240},
259
265
  "startMs": {"type": "number"},
260
266
  "endMs": {"type": "number"},
261
267
  },
262
268
  "required": [
263
269
  "kind",
264
270
  "channel",
271
+ "questionRole",
265
272
  "text",
266
273
  "answer",
274
+ "respondent",
267
275
  "startMs",
268
276
  "endMs",
269
277
  ],
270
278
  "additionalProperties": False,
271
279
  },
272
- }
280
+ },
281
+ "structures": {
282
+ "type": "array",
283
+ "maxItems": 24,
284
+ "items": {
285
+ "type": "object",
286
+ "properties": {
287
+ "kind": {"type": "string", "enum": ["grid", "sequence", "collection"]},
288
+ "label": {"type": "string", "maxLength": 240},
289
+ "dimensions": {
290
+ "type": "array",
291
+ "maxItems": 4,
292
+ "items": {
293
+ "type": "object",
294
+ "properties": {
295
+ "label": {"type": "string", "maxLength": 120},
296
+ "values": {
297
+ "type": "array",
298
+ "maxItems": 24,
299
+ "items": {"type": "string", "maxLength": 120},
300
+ },
301
+ },
302
+ "required": ["label", "values"],
303
+ "additionalProperties": False,
304
+ },
305
+ },
306
+ "startMs": {"type": "number"},
307
+ "endMs": {"type": "number"},
308
+ },
309
+ "required": ["kind", "label", "dimensions", "startMs", "endMs"],
310
+ "additionalProperties": False,
311
+ },
312
+ },
313
+ "taskInstances": {
314
+ "type": "array",
315
+ "maxItems": 128,
316
+ "items": {
317
+ "type": "object",
318
+ "properties": {
319
+ "prompt": {"type": "string", "maxLength": 600},
320
+ "channel": {"type": "string", "enum": ["spoken", "visible"]},
321
+ "answer": {"type": "string", "maxLength": 600},
322
+ "respondent": {"type": "string", "maxLength": 240},
323
+ "startMs": {"type": "number"},
324
+ "endMs": {"type": "number"},
325
+ },
326
+ "required": [
327
+ "prompt",
328
+ "channel",
329
+ "answer",
330
+ "respondent",
331
+ "startMs",
332
+ "endMs",
333
+ ],
334
+ "additionalProperties": False,
335
+ },
336
+ },
273
337
  },
274
- "required": ["items"],
338
+ "required": ["items", "structures", "taskInstances"],
339
+ "additionalProperties": False,
340
+ }
341
+
342
+ TASK_INSTANCE_JSON_SCHEMA: dict[str, Any] = {
343
+ "type": "object",
344
+ "properties": {
345
+ "taskInstances": SOURCE_INVENTORY_JSON_SCHEMA["properties"]["taskInstances"],
346
+ },
347
+ "required": ["taskInstances"],
275
348
  "additionalProperties": False,
276
349
  }
277
350
 
@@ -579,6 +652,14 @@ class AgentPlanner:
579
652
  self.last_error: str | None = None
580
653
  self.errors: list[str] = []
581
654
  self.fallback_used = False
655
+ self.source_inventory_coverage: dict[str, Any] = {
656
+ "complete": False,
657
+ "totalWindows": 0,
658
+ "processedWindows": 0,
659
+ "reason": "source inventory has not run",
660
+ }
661
+ self.source_activity_structures: list[dict[str, Any]] = []
662
+ self.source_task_instances: list[dict[str, Any]] = []
582
663
 
583
664
  def plan(
584
665
  self,
@@ -774,9 +855,17 @@ class AgentPlanner:
774
855
  semantic_observations: list[dict[str, Any]],
775
856
  overlay_text: list[dict[str, Any]] | None = None,
776
857
  ) -> list[dict[str, Any]]:
777
- """Map every source-authored question and visible list unit in bounded time chunks."""
858
+ """Map source units and source-established layouts in bounded time chunks."""
778
859
  fallback = _fallback_source_inventory(semantic_observations, duration_secs)
860
+ self.source_activity_structures = []
861
+ self.source_task_instances = []
779
862
  if not self.enabled or not self.api_key:
863
+ self.source_inventory_coverage = {
864
+ "complete": False,
865
+ "totalWindows": 0,
866
+ "processedWindows": 0,
867
+ "reason": "source inventory model is unavailable",
868
+ }
780
869
  return fallback
781
870
  chunks = _source_inventory_chunks(
782
871
  duration_secs=duration_secs,
@@ -785,9 +874,17 @@ class AgentPlanner:
785
874
  overlay_text=overlay_text or [],
786
875
  )
787
876
  if not chunks:
877
+ self.source_inventory_coverage = {
878
+ "complete": False,
879
+ "totalWindows": 0,
880
+ "processedWindows": 0,
881
+ "reason": "no source evidence was available to scan",
882
+ }
788
883
  return fallback
789
884
  started = time.monotonic()
790
885
  completed: dict[int, list[dict[str, Any]]] = {}
886
+ completed_structures: dict[int, list[dict[str, Any]]] = {}
887
+ completed_tasks: dict[int, list[dict[str, Any]]] = {}
791
888
  errors: list[str] = []
792
889
  usage_totals = {"promptTokens": 0, "completionTokens": 0}
793
890
 
@@ -800,7 +897,35 @@ class AgentPlanner:
800
897
  json_schema=SOURCE_INVENTORY_JSON_SCHEMA,
801
898
  request_attempts=1,
802
899
  )
803
- return index, _validated_source_inventory(raw, duration_secs, chunk), usage
900
+ items = _validated_source_inventory(raw, duration_secs, chunk)
901
+ tasks = _validated_source_task_instances(raw, duration_secs, chunk)
902
+ if not tasks and any(item["kind"] == "question" for item in items) and sum(
903
+ item["kind"] == "clue" for item in items
904
+ ) >= 2:
905
+ task_raw, task_usage = self._complete(
906
+ _source_task_instance_prompt(chunk["range"], items),
907
+ [],
908
+ max_output_tokens=4_000,
909
+ timeout_seconds=30,
910
+ json_schema=TASK_INSTANCE_JSON_SCHEMA,
911
+ request_attempts=1,
912
+ )
913
+ tasks = _validated_source_task_instances(
914
+ task_raw, duration_secs, chunk
915
+ )
916
+ usage = {
917
+ "promptTokens": usage.get("promptTokens", 0)
918
+ + task_usage.get("promptTokens", 0),
919
+ "completionTokens": usage.get("completionTokens", 0)
920
+ + task_usage.get("completionTokens", 0),
921
+ }
922
+ return (
923
+ index,
924
+ items,
925
+ _validated_source_activity_structures(raw, duration_secs, chunk),
926
+ tasks,
927
+ usage,
928
+ )
804
929
 
805
930
  try:
806
931
  # These requests contain disjoint time ranges and are independent.
@@ -813,8 +938,10 @@ class AgentPlanner:
813
938
  for future in as_completed(futures):
814
939
  self.requests += 1
815
940
  try:
816
- index, items, usage = future.result()
941
+ index, items, structures, tasks, usage = future.result()
817
942
  completed[index] = items
943
+ completed_structures[index] = structures
944
+ completed_tasks[index] = tasks
818
945
  usage_totals["promptTokens"] += usage.get("promptTokens", 0)
819
946
  usage_totals["completionTokens"] += usage.get("completionTokens", 0)
820
947
  except Exception as error:
@@ -826,10 +953,46 @@ class AgentPlanner:
826
953
  self.completion_tokens += usage_totals["completionTokens"]
827
954
  if errors:
828
955
  self.errors.extend(errors[-3:])
829
- return _merge_source_inventory(
956
+ self.source_inventory_coverage = {
957
+ "complete": len(completed) == len(chunks) and not errors,
958
+ "totalWindows": len(chunks),
959
+ "processedWindows": len(completed),
960
+ **(
961
+ {}
962
+ if len(completed) == len(chunks) and not errors
963
+ else {"reason": "one or more source inventory windows failed"}
964
+ ),
965
+ }
966
+ self.source_activity_structures = _merge_source_activity_structures(
967
+ *[
968
+ completed_structures[index]
969
+ for index in sorted(completed_structures)
970
+ ]
971
+ )
972
+ merged_items = _merge_source_inventory(
830
973
  fallback,
831
974
  *[completed[index] for index in sorted(completed)],
832
975
  )
976
+ task_instances = _merge_source_task_instances(
977
+ *[completed_tasks[index] for index in sorted(completed_tasks)]
978
+ )
979
+ self.source_task_instances = [
980
+ task
981
+ for task in task_instances
982
+ if not any(
983
+ item["kind"] == "question"
984
+ and item["channel"] == task["channel"]
985
+ and re.sub(r"\s+", " ", item["text"].casefold()).strip()
986
+ == re.sub(r"\s+", " ", task["prompt"].casefold()).strip()
987
+ # A held card can be inventoried several times while its
988
+ # timer runs. It is still the same direct prompt, not a
989
+ # continued instance, even when the readings are a minute
990
+ # apart.
991
+ and abs(item["startMs"] - task["startMs"]) <= 120_000
992
+ for item in merged_items
993
+ )
994
+ ]
995
+ return merged_items
833
996
  finally:
834
997
  self.latency_ms += round((time.monotonic() - started) * 1_000)
835
998
 
@@ -1247,38 +1410,111 @@ def _source_inventory_prompt(chunk: dict[str, Any]) -> str:
1247
1410
  return (
1248
1411
  "Create an exhaustive inventory of discrete source-authored units in this timestamped "
1249
1412
  "portion of a recording. The source can be any kind of recording. Extract only: questions "
1250
- "actually asked by a speaker or visibly written; headings or titles; individual slide, "
1251
- "board, or explicitly enumerated list items. Do not turn ordinary narration, conversation, "
1252
- "descriptions, model instructions, or analysis prompts into inventory items. Preserve the "
1253
- "source language and wording. For a spoken question, start at the actual interrogative or "
1254
- "request and omit surrounding banter, answers, and reactions. If a nearby source passage "
1255
- "explicitly answers a question, "
1256
- "copy the answer; otherwise use an empty answer. Give the narrowest supplied timestamp "
1413
+ "whose answer is a substantive part of the recording; headings or titles; individual slide, "
1414
+ "board, or explicitly enumerated list items; and declarative hints used to solve an explicit "
1415
+ "prompt. Use kind 'question' only for a standalone, content-bearing prompt that asks for an "
1416
+ "answer. A greeting, social check-in, turn-management request, rhetorical question, or casual "
1417
+ "banter is not a source question. Do not turn a declarative hint, a description, model "
1418
+ "instruction, or analysis prompt into a question: represent an explicit solving hint as kind "
1419
+ "'clue' and otherwise omit it. Preserve the source language and wording. For a spoken "
1420
+ "question, start at the actual interrogative or request and omit surrounding banter, answers, "
1421
+ "and reactions. Set questionRole to 'primary' only for a content-bearing question; use "
1422
+ "'interactional' for social or turn-management speech, 'rhetorical' when no answer is sought, "
1423
+ "and 'not-question' for every other kind. It is safer to omit an ambiguous spoken question "
1424
+ "than to label ordinary conversation as primary. If a nearby source passage explicitly answers a question, "
1425
+ "copy the answer; otherwise use an empty answer. If the answer itself names the person who "
1426
+ "gave it, copy only that supplied name or role into respondent; otherwise use an empty "
1427
+ "respondent. Give the narrowest supplied timestamp "
1257
1428
  "that supports each item. A recurring header is one item in this portion, while separate "
1258
- "questions or differently worded items remain separate. Never infer missing words or add "
1259
- "outside facts. Return JSON only: {items:[{kind:'question'|'heading'|'slide-item'|"
1260
- "'board-item'|'list-item',channel:'spoken'|'visible',text:string,answer:string,"
1429
+ "questions or differently worded items remain separate. Also record a structure only when "
1430
+ "the source itself establishes a repeated arrangement: 'grid' for independent labeled axes, "
1431
+ "'sequence' for an ordered run, or 'collection' for a named set. Preserve only labels and "
1432
+ "values directly present in the source; do not infer missing dimensions or entries. For a reusable "
1433
+ "source prompt followed by separately resolved clue bundles, add one taskInstances record for each "
1434
+ "separately resolved bundle. Its prompt must copy the exact reusable question already present in this "
1435
+ "portion; its time range must cover that bundle, not the earlier title. A new card/title, an answer "
1436
+ "reveal, or another directly observed reset can establish a separate bundle. Do not create a task "
1437
+ "instance from a clue alone or carry a prompt in from another portion. Never infer missing words or "
1438
+ "add outside facts. Return JSON only: {items:[{kind:'question'|'clue'|"
1439
+ "'heading'|'slide-item'|'board-item'|'list-item',channel:'spoken'|'visible',questionRole:"
1440
+ "'primary'|'interactional'|'rhetorical'|'not-question',text:string,answer:string,"
1441
+ "respondent:string,startMs:number,endMs:number}],structures:[{kind:'grid'|'sequence'|"
1442
+ "'collection',label:string,dimensions:[{label:string,values:string[]}],startMs:number,endMs:number}],"
1443
+ "taskInstances:[{prompt:string,channel:'spoken'|'visible',answer:string,respondent:string,"
1261
1444
  "startMs:number,endMs:number}]}.\nINPUT:\n"
1262
1445
  + json.dumps(chunk, ensure_ascii=False, separators=(",", ":"))
1263
1446
  )
1264
1447
 
1265
1448
 
1449
+ def _source_task_instance_prompt(
1450
+ source_range: dict[str, Any], items: list[dict[str, Any]]
1451
+ ) -> str:
1452
+ return (
1453
+ "Reconcile reusable source prompts with their already-grounded clue items in one bounded "
1454
+ "portion of a recording. The input is chronological source evidence, not a topic summary. "
1455
+ "When one exact, explicit prompt introduces a repeated activity and later clue bundles are "
1456
+ "separately resolved, return one task instance per separately resolved bundle. Copy prompt "
1457
+ "exactly from an input question; do not turn a clue into a prompt or bring in a prompt not in "
1458
+ "the input. A new displayed item, a revealed answer, or an independently bounded run of clues "
1459
+ "can establish a new instance. Keep an empty answer/respondent if the input does not directly "
1460
+ "supply it. If the input does not establish separate instances, return an empty list. Return JSON only: "
1461
+ "{taskInstances:[{prompt:string,channel:'spoken'|'visible',answer:string,respondent:string,"
1462
+ "startMs:number,endMs:number}]}.\nINPUT:\n"
1463
+ + json.dumps(
1464
+ {
1465
+ "range": source_range,
1466
+ "items": [
1467
+ {
1468
+ key: item[key]
1469
+ for key in (
1470
+ "kind",
1471
+ "channel",
1472
+ "text",
1473
+ "answer",
1474
+ "respondent",
1475
+ "startMs",
1476
+ "endMs",
1477
+ )
1478
+ }
1479
+ for item in items
1480
+ if item["kind"] in {"question", "clue"}
1481
+ ],
1482
+ },
1483
+ ensure_ascii=False,
1484
+ separators=(",", ":"),
1485
+ )
1486
+ )
1487
+
1488
+
1266
1489
  def _inventory_terms(value: str) -> list[str]:
1267
1490
  return re.findall(r"[\w\u0600-\u06ff]+", value.casefold(), re.UNICODE)
1268
1491
 
1269
1492
 
1270
- def _looks_like_spoken_question(value: str) -> bool:
1493
+ def _looks_like_explicit_prompt(value: str) -> bool:
1494
+ """Accept a question/request, never a declarative hint with a guessed answer."""
1271
1495
  text = value.strip()
1272
1496
  if re.search(r"[?؟]\s*$", text):
1273
1497
  return True
1274
1498
  cue = re.compile(
1275
1499
  r"^(?:who|what|when|where|why|how|which|whose|whom|is|are|was|were|do|does|did|"
1276
- r"can|could|would|will|name|list|identify|describe|tell|give|"
1500
+ r"can|could|would|will|name|list|identify|describe|tell|give|guess|choose|select|"
1277
1501
  r"من|ما|ماذا|متى|أين|اين|كيف|كم|هل|أي|اي|لماذا|مين|إيه|ايه|فين|امتى|ازاي|"
1278
- r"اذكر|أذكر|حدد|سم|سمي)$",
1502
+ r"اذكر|أذكر|حدد|سم|سمي|اختر|إختر|اكتشف|خمن|خمّن|توقع|أكمل|اكمل|رتب|رتِّب)$",
1279
1503
  re.I,
1280
1504
  )
1281
- return any(cue.match(term) for term in _inventory_terms(text)[:4])
1505
+ terms = _inventory_terms(text)
1506
+ if not terms:
1507
+ return False
1508
+ if cue.match(terms[0]):
1509
+ return True
1510
+ # Arabic (and other languages) can put a preposition before a question
1511
+ # word, e.g. "في أي سنة…". Looking through every early token would make
1512
+ # a declarative clue such as "لعبت … من الدوريات" look interrogative.
1513
+ return (
1514
+ len(terms) >= 2
1515
+ and terms[0] in {"في", "ب", "على", "الى", "إلى"}
1516
+ and cue.match(terms[1]) is not None
1517
+ )
1282
1518
 
1283
1519
 
1284
1520
  def _inventory_item_is_grounded(
@@ -1307,23 +1543,78 @@ def _inventory_item_is_grounded(
1307
1543
  return matched / len(candidate_terms) >= 0.7
1308
1544
 
1309
1545
 
1546
+ def _inventory_detail_is_grounded(
1547
+ value: str, item: dict[str, Any], source_chunk: dict[str, Any]
1548
+ ) -> bool:
1549
+ """Keep answer metadata only when the nearby source evidence contains it."""
1550
+ candidate_terms = _inventory_terms(value)
1551
+ if not candidate_terms:
1552
+ return True
1553
+ start_ms = item["startMs"]
1554
+ end_ms = item["endMs"]
1555
+ nearby = [
1556
+ source
1557
+ for source in (
1558
+ list(source_chunk.get("spokenEvidence") or [])
1559
+ + list(source_chunk.get("visibleEvidence") or [])
1560
+ )
1561
+ if float(source.get("startMs") or 0) <= end_ms + 15_000
1562
+ and float(source.get("endMs") or source.get("startMs") or 0)
1563
+ >= start_ms - 5_000
1564
+ ]
1565
+ if not nearby:
1566
+ nearby = list(source_chunk.get("spokenEvidence") or []) + list(
1567
+ source_chunk.get("visibleEvidence") or []
1568
+ )
1569
+ source_terms = set(
1570
+ _inventory_terms(" ".join(str(source.get("text") or "") for source in nearby))
1571
+ )
1572
+ matched = sum(1 for term in candidate_terms if term in source_terms)
1573
+ # Metadata is more dangerous than the question text: a fabricated name can
1574
+ # share generic words such as "starts the round" with a real answer. Keep
1575
+ # it only for a near-exact match (or an exact short name/role).
1576
+ required_ratio = 1 if len(candidate_terms) <= 2 else 0.9
1577
+ return matched / len(candidate_terms) >= required_ratio
1578
+
1579
+
1310
1580
  def _validated_source_inventory(
1311
1581
  raw: dict[str, Any],
1312
1582
  duration_secs: float,
1313
1583
  source_chunk: dict[str, Any] | None = None,
1314
1584
  ) -> list[dict[str, Any]]:
1315
1585
  duration_ms = max(1, round(duration_secs * 1_000))
1316
- allowed_kinds = {"question", "heading", "slide-item", "board-item", "list-item"}
1586
+ allowed_kinds = {
1587
+ "question",
1588
+ "clue",
1589
+ "heading",
1590
+ "slide-item",
1591
+ "board-item",
1592
+ "list-item",
1593
+ }
1317
1594
  allowed_channels = {"spoken", "visible"}
1595
+ allowed_question_roles = {
1596
+ "primary",
1597
+ "interactional",
1598
+ "rhetorical",
1599
+ "not-question",
1600
+ }
1318
1601
  items: list[dict[str, Any]] = []
1319
1602
  for candidate in raw.get("items") or []:
1320
1603
  if not isinstance(candidate, dict):
1321
1604
  continue
1322
1605
  kind = str(candidate.get("kind") or "").strip()
1323
1606
  channel = str(candidate.get("channel") or "").strip()
1607
+ question_role = str(candidate.get("questionRole") or "").strip()
1324
1608
  text = str(candidate.get("text") or "").strip()[:600]
1325
1609
  if kind not in allowed_kinds or channel not in allowed_channels or not text:
1326
1610
  continue
1611
+ if not question_role:
1612
+ # Older runtimes did not emit a role. Keep their direct questions
1613
+ # readable after an upgrade, but require the new mapper to make
1614
+ # the distinction explicitly.
1615
+ question_role = "primary" if kind == "question" else "not-question"
1616
+ if question_role not in allowed_question_roles:
1617
+ continue
1327
1618
  try:
1328
1619
  start_ms = min(
1329
1620
  duration_ms, max(0, round(float(candidate.get("startMs"))))
@@ -1337,19 +1628,185 @@ def _validated_source_inventory(
1337
1628
  item = {
1338
1629
  "kind": kind,
1339
1630
  "channel": channel,
1631
+ "questionRole": question_role,
1340
1632
  "text": text,
1341
1633
  "answer": str(candidate.get("answer") or "").strip()[:600],
1634
+ "respondent": str(candidate.get("respondent") or "").strip()[:240],
1342
1635
  "startMs": start_ms,
1343
1636
  "endMs": end_ms,
1344
1637
  }
1345
- if kind == "question" and channel == "spoken" and not _looks_like_spoken_question(text):
1638
+ if kind == "question":
1639
+ if question_role != "primary":
1640
+ continue
1641
+ if not _looks_like_explicit_prompt(text):
1642
+ if channel != "visible":
1643
+ continue
1644
+ # The text remains useful source evidence, but a declarative
1645
+ # card is a clue to an implicit task—not a question in the
1646
+ # requested question inventory. This is deliberately based on
1647
+ # linguistic form, never a source genre or topic.
1648
+ item["kind"] = "clue"
1649
+ item["questionRole"] = "not-question"
1650
+ elif question_role != "not-question":
1346
1651
  continue
1347
1652
  if source_chunk is not None and not _inventory_item_is_grounded(item, source_chunk):
1348
1653
  continue
1654
+ if source_chunk is not None:
1655
+ if item["answer"] and not _inventory_detail_is_grounded(
1656
+ item["answer"], item, source_chunk
1657
+ ):
1658
+ item["answer"] = ""
1659
+ if item["respondent"] and not _inventory_detail_is_grounded(
1660
+ item["respondent"], item, source_chunk
1661
+ ):
1662
+ item["respondent"] = ""
1349
1663
  items.append(item)
1350
1664
  return items
1351
1665
 
1352
1666
 
1667
+ def _validated_source_activity_structures(
1668
+ raw: dict[str, Any],
1669
+ duration_secs: float,
1670
+ source_chunk: dict[str, Any] | None = None,
1671
+ ) -> list[dict[str, Any]]:
1672
+ """Keep only explicitly evidenced layouts; never manufacture a prompt count."""
1673
+ duration_ms = max(1, round(duration_secs * 1_000))
1674
+ allowed_kinds = {"grid", "sequence", "collection"}
1675
+ structures: list[dict[str, Any]] = []
1676
+ for candidate in raw.get("structures") or []:
1677
+ if not isinstance(candidate, dict):
1678
+ continue
1679
+ kind = str(candidate.get("kind") or "").strip()
1680
+ label = str(candidate.get("label") or "").strip()[:240]
1681
+ if kind not in allowed_kinds:
1682
+ continue
1683
+ try:
1684
+ start_ms = min(duration_ms, max(0, round(float(candidate.get("startMs")))))
1685
+ end_ms = min(
1686
+ duration_ms,
1687
+ max(start_ms, round(float(candidate.get("endMs")))),
1688
+ )
1689
+ except (TypeError, ValueError):
1690
+ continue
1691
+ dimensions: list[dict[str, Any]] = []
1692
+ for raw_dimension in candidate.get("dimensions") or []:
1693
+ if not isinstance(raw_dimension, dict):
1694
+ continue
1695
+ dimension_label = str(raw_dimension.get("label") or "").strip()[:120]
1696
+ values: list[str] = []
1697
+ for raw_value in raw_dimension.get("values") or []:
1698
+ value = str(raw_value or "").strip()[:120]
1699
+ normalized = re.sub(r"\s+", " ", value.casefold())
1700
+ if value and normalized not in {
1701
+ re.sub(r"\s+", " ", previous.casefold()) for previous in values
1702
+ }:
1703
+ values.append(value)
1704
+ if dimension_label and values:
1705
+ dimensions.append({"label": dimension_label, "values": values})
1706
+ if kind == "grid" and (
1707
+ len(dimensions) < 2 or any(len(item["values"]) < 2 for item in dimensions)
1708
+ ):
1709
+ continue
1710
+ if kind in {"sequence", "collection"} and not dimensions:
1711
+ continue
1712
+ structure = {
1713
+ "kind": kind,
1714
+ "label": label,
1715
+ "dimensions": dimensions,
1716
+ "startMs": start_ms,
1717
+ "endMs": end_ms,
1718
+ }
1719
+ if kind == "grid":
1720
+ structure["promptCount"] = math.prod(
1721
+ len(dimension["values"]) for dimension in dimensions
1722
+ )
1723
+ # A layout claim is valuable only if its labels/values occur in the
1724
+ # same bounded source window. Empty labels are permitted because many
1725
+ # real source grids have labels only on their axes.
1726
+ direct_terms = " ".join(
1727
+ [label]
1728
+ + [
1729
+ f"{dimension['label']} {' '.join(dimension['values'])}"
1730
+ for dimension in dimensions
1731
+ ]
1732
+ ).strip()
1733
+ if source_chunk is not None and direct_terms and not _inventory_detail_is_grounded(
1734
+ direct_terms,
1735
+ structure,
1736
+ source_chunk,
1737
+ ):
1738
+ continue
1739
+ structures.append(structure)
1740
+ return structures
1741
+
1742
+
1743
+ def _source_text_is_grounded_anywhere(
1744
+ value: str, channel: str, source_chunk: dict[str, Any]
1745
+ ) -> bool:
1746
+ source_key = "spokenEvidence" if channel == "spoken" else "visibleEvidence"
1747
+ candidate_terms = _inventory_terms(value)
1748
+ if not candidate_terms:
1749
+ return False
1750
+ source_terms = set(
1751
+ _inventory_terms(
1752
+ " ".join(
1753
+ str(source.get("text") or "")
1754
+ for source in source_chunk.get(source_key) or []
1755
+ )
1756
+ )
1757
+ )
1758
+ return sum(1 for term in candidate_terms if term in source_terms) / len(
1759
+ candidate_terms
1760
+ ) >= 0.8
1761
+
1762
+
1763
+ def _validated_source_task_instances(
1764
+ raw: dict[str, Any],
1765
+ duration_secs: float,
1766
+ source_chunk: dict[str, Any] | None = None,
1767
+ ) -> list[dict[str, Any]]:
1768
+ """Validate continued prompt instances without treating their clues as questions."""
1769
+ duration_ms = max(1, round(duration_secs * 1_000))
1770
+ tasks: list[dict[str, Any]] = []
1771
+ for candidate in raw.get("taskInstances") or []:
1772
+ if not isinstance(candidate, dict):
1773
+ continue
1774
+ prompt = str(candidate.get("prompt") or "").strip()[:600]
1775
+ channel = str(candidate.get("channel") or "").strip()
1776
+ if channel not in {"spoken", "visible"} or not _looks_like_explicit_prompt(prompt):
1777
+ continue
1778
+ try:
1779
+ start_ms = min(duration_ms, max(0, round(float(candidate.get("startMs")))))
1780
+ end_ms = min(
1781
+ duration_ms,
1782
+ max(start_ms, round(float(candidate.get("endMs")))),
1783
+ )
1784
+ except (TypeError, ValueError):
1785
+ continue
1786
+ task = {
1787
+ "id": f"task-{start_ms}",
1788
+ "prompt": prompt,
1789
+ "channel": channel,
1790
+ "answer": str(candidate.get("answer") or "").strip()[:600],
1791
+ "respondent": str(candidate.get("respondent") or "").strip()[:240],
1792
+ "startMs": start_ms,
1793
+ "endMs": end_ms,
1794
+ }
1795
+ if source_chunk is not None:
1796
+ if not _source_text_is_grounded_anywhere(prompt, channel, source_chunk):
1797
+ continue
1798
+ if task["answer"] and not _inventory_detail_is_grounded(
1799
+ task["answer"], task, source_chunk
1800
+ ):
1801
+ task["answer"] = ""
1802
+ if task["respondent"] and not _inventory_detail_is_grounded(
1803
+ task["respondent"], task, source_chunk
1804
+ ):
1805
+ task["respondent"] = ""
1806
+ tasks.append(task)
1807
+ return tasks
1808
+
1809
+
1353
1810
  def _fallback_source_inventory(
1354
1811
  semantic_observations: list[dict[str, Any]], duration_secs: float
1355
1812
  ) -> list[dict[str, Any]]:
@@ -1362,17 +1819,29 @@ def _fallback_source_inventory(
1362
1819
  )
1363
1820
  if not match:
1364
1821
  continue
1365
- answer_match = (
1366
- re.match(r"^Source answer:\s*(.*)$", lines[index + 1].strip(), re.I)
1367
- if index + 1 < len(lines)
1368
- else None
1369
- )
1822
+ answer = ""
1823
+ respondent = ""
1824
+ for detail_line in lines[index + 1 : index + 4]:
1825
+ if re.match(r"^Source question \(", detail_line.strip(), re.I):
1826
+ break
1827
+ answer_match = re.match(
1828
+ r"^Source answer:\s*(.*)$", detail_line.strip(), re.I
1829
+ )
1830
+ respondent_match = re.match(
1831
+ r"^Source respondent:\s*(.*)$", detail_line.strip(), re.I
1832
+ )
1833
+ if answer_match:
1834
+ answer = answer_match.group(1).strip()[:600]
1835
+ if respondent_match:
1836
+ respondent = respondent_match.group(1).strip()[:240]
1370
1837
  items.append(
1371
1838
  {
1372
1839
  "kind": "question",
1373
1840
  "channel": match.group(1).lower(),
1841
+ "questionRole": "primary",
1374
1842
  "text": match.group(2).strip()[:600],
1375
- "answer": (answer_match.group(1).strip()[:600] if answer_match else ""),
1843
+ "answer": answer,
1844
+ "respondent": respondent,
1376
1845
  "startMs": observation.get("startMs") or 0,
1377
1846
  "endMs": observation.get("endMs") or observation.get("startMs") or 0,
1378
1847
  }
@@ -1382,20 +1851,108 @@ def _fallback_source_inventory(
1382
1851
 
1383
1852
  def _merge_source_inventory(*groups: list[dict[str, Any]]) -> list[dict[str, Any]]:
1384
1853
  merged: list[dict[str, Any]] = []
1385
- seen: set[tuple[str, str, int]] = set()
1854
+ positions: dict[tuple[str, str, int], int] = {}
1386
1855
  for item in sorted(
1387
1856
  (item for group in groups for item in group),
1388
1857
  key=lambda value: (value["startMs"], value["endMs"], value["kind"]),
1389
1858
  ):
1390
1859
  normalized = re.sub(r"\s+", " ", item["text"].casefold()).strip()
1391
1860
  key = (item["kind"], normalized, round(item["startMs"] / 5_000))
1392
- if not normalized or key in seen:
1861
+ if not normalized:
1862
+ continue
1863
+ existing_index = positions.get(key)
1864
+ if existing_index is not None:
1865
+ existing = merged[existing_index]
1866
+ if not existing.get("answer") and item.get("answer"):
1867
+ existing["answer"] = item["answer"]
1868
+ if not existing.get("respondent") and item.get("respondent"):
1869
+ existing["respondent"] = item["respondent"]
1393
1870
  continue
1394
- seen.add(key)
1871
+ positions[key] = len(merged)
1395
1872
  merged.append(item)
1396
1873
  return merged[:2_000]
1397
1874
 
1398
1875
 
1876
+ def _merge_source_activity_structures(
1877
+ *groups: list[dict[str, Any]],
1878
+ ) -> list[dict[str, Any]]:
1879
+ """Merge overlapping readings of the same layout without joining later repeats."""
1880
+ merged: list[dict[str, Any]] = []
1881
+ positions: dict[tuple[str, str, int], int] = {}
1882
+ for structure in sorted(
1883
+ (item for group in groups for item in group),
1884
+ key=lambda value: (value["startMs"], value["endMs"], value["kind"]),
1885
+ ):
1886
+ normalized_label = re.sub(r"\s+", " ", structure["label"].casefold()).strip()
1887
+ key = (structure["kind"], normalized_label, round(structure["startMs"] / 5_000))
1888
+ existing_index = positions.get(key)
1889
+ if existing_index is None:
1890
+ positions[key] = len(merged)
1891
+ merged.append(
1892
+ {
1893
+ **structure,
1894
+ "dimensions": [
1895
+ {"label": item["label"], "values": list(item["values"])}
1896
+ for item in structure["dimensions"]
1897
+ ],
1898
+ }
1899
+ )
1900
+ continue
1901
+ existing = merged[existing_index]
1902
+ existing["endMs"] = max(existing["endMs"], structure["endMs"])
1903
+ dimensions_by_label = {
1904
+ re.sub(r"\s+", " ", item["label"].casefold()).strip(): item
1905
+ for item in existing["dimensions"]
1906
+ }
1907
+ for dimension in structure["dimensions"]:
1908
+ dimension_key = re.sub(r"\s+", " ", dimension["label"].casefold()).strip()
1909
+ target = dimensions_by_label.get(dimension_key)
1910
+ if target is None:
1911
+ target = {"label": dimension["label"], "values": []}
1912
+ existing["dimensions"].append(target)
1913
+ dimensions_by_label[dimension_key] = target
1914
+ known = {
1915
+ re.sub(r"\s+", " ", value.casefold()).strip()
1916
+ for value in target["values"]
1917
+ }
1918
+ for value in dimension["values"]:
1919
+ value_key = re.sub(r"\s+", " ", value.casefold()).strip()
1920
+ if value_key not in known:
1921
+ target["values"].append(value)
1922
+ known.add(value_key)
1923
+ if existing["kind"] == "grid":
1924
+ existing["promptCount"] = math.prod(
1925
+ len(dimension["values"]) for dimension in existing["dimensions"]
1926
+ )
1927
+ return merged[:256]
1928
+
1929
+
1930
+ def _merge_source_task_instances(
1931
+ *groups: list[dict[str, Any]],
1932
+ ) -> list[dict[str, Any]]:
1933
+ """Collapse overlapping reads of one continued task, retaining later turns."""
1934
+ merged: list[dict[str, Any]] = []
1935
+ positions: dict[tuple[str, str, int], int] = {}
1936
+ for task in sorted(
1937
+ (item for group in groups for item in group),
1938
+ key=lambda value: (value["startMs"], value["endMs"], value["prompt"]),
1939
+ ):
1940
+ prompt_key = re.sub(r"\s+", " ", task["prompt"].casefold()).strip()
1941
+ key = (task["channel"], prompt_key, round(task["startMs"] / 5_000))
1942
+ existing_index = positions.get(key)
1943
+ if existing_index is None:
1944
+ positions[key] = len(merged)
1945
+ merged.append(dict(task))
1946
+ continue
1947
+ existing = merged[existing_index]
1948
+ existing["endMs"] = max(existing["endMs"], task["endMs"])
1949
+ if len(task.get("answer") or "") > len(existing.get("answer") or ""):
1950
+ existing["answer"] = task["answer"]
1951
+ if len(task.get("respondent") or "") > len(existing.get("respondent") or ""):
1952
+ existing["respondent"] = task["respondent"]
1953
+ return merged[:512]
1954
+
1955
+
1399
1956
  def _synthesis_prompt(
1400
1957
  *,
1401
1958
  brief: dict[str, Any],
@@ -1785,6 +1785,14 @@ def _run_pipeline(
1785
1785
  "narrative": [],
1786
1786
  "context": [],
1787
1787
  "sourceItems": [],
1788
+ "sourceActivityStructures": [],
1789
+ "sourceTaskInstances": [],
1790
+ "sourceInventoryCoverage": {
1791
+ "complete": False,
1792
+ "totalWindows": 0,
1793
+ "processedWindows": 0,
1794
+ "reason": "interactive inspection does not run a full source inventory",
1795
+ },
1788
1796
  "uncertainties": [],
1789
1797
  }
1790
1798
  else:
@@ -1810,6 +1818,9 @@ def _run_pipeline(
1810
1818
  semantic_observations=semantic_evidence,
1811
1819
  overlay_text=recurring_overlay_text,
1812
1820
  )
1821
+ knowledge_summary["sourceActivityStructures"] = planner.source_activity_structures
1822
+ knowledge_summary["sourceTaskInstances"] = planner.source_task_instances
1823
+ knowledge_summary["sourceInventoryCoverage"] = planner.source_inventory_coverage
1813
1824
  elapsed_seconds = round(time.monotonic() - pipeline_started, 3)
1814
1825
  result = {
1815
1826
  "schemaVersion": 1,
@@ -7,7 +7,7 @@
7
7
  "description": "Help your AI understand your videos, so you can ask questions and get answers from the right moments.",
8
8
  "longDescription": "Turn videos into knowledge your AI can understand. It listens to what is said, reads what appears on screen, and helps you find the moments that matter.",
9
9
  "category": "media",
10
- "version": "0.2.10",
10
+ "version": "0.2.11",
11
11
  "pricing": "free",
12
12
  "emoji": "🎥",
13
13
  "icon": "Film",