@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.
@@ -127,6 +127,24 @@ export interface TrackEvidence {
127
127
  observations: number;
128
128
  confidence: number;
129
129
  }
130
+ /**
131
+ * Detection-backed presence facts. Track IDs deliberately remain anonymous:
132
+ * an edit, occlusion, or re-entry may create a new track for the same subject.
133
+ */
134
+ export interface AnonymousPresenceLedger {
135
+ method: 'object-detection-anonymous-tracking';
136
+ sampledFrames: number;
137
+ sampleIntervalSecs?: number;
138
+ tracks: Array<TrackEvidence & {
139
+ timestampsMs: number[];
140
+ }>;
141
+ labels: Array<{
142
+ label: string;
143
+ distinctTrackCount: number;
144
+ maximumSimultaneous: number;
145
+ simultaneousTimestampsMs: number[];
146
+ }>;
147
+ }
130
148
  export interface VisualObservation {
131
149
  timeMs: number;
132
150
  objects: Array<{
@@ -165,6 +183,7 @@ export interface VideoEvidenceBundle {
165
183
  detectedLanguage?: string;
166
184
  visualObservations: VisualObservation[];
167
185
  tracks: TrackEvidence[];
186
+ anonymousPresenceLedger?: AnonymousPresenceLedger;
168
187
  recurringOverlayText?: RecurringOverlayText[];
169
188
  entities: Array<{
170
189
  name: string;
@@ -242,6 +261,15 @@ export interface VideoEvidenceBundle {
242
261
  endMs: number;
243
262
  }>;
244
263
  }>;
264
+ visibleSubjects?: Array<{
265
+ identity: string;
266
+ identityBasis: 'source-named' | 'source-described' | 'unresolved';
267
+ appearances: Array<{
268
+ startMs: number;
269
+ endMs: number;
270
+ confidence: 'direct' | 'partial';
271
+ }>;
272
+ }>;
245
273
  stateHistory: Array<{
246
274
  startMs: number;
247
275
  endMs: number;
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.11";
12
+ readonly version: "0.3.1";
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.11',
14
+ version: '0.3.1',
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 ??
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@larkup/tool-video-intelligence",
3
- "version": "0.2.11",
3
+ "version": "0.3.1",
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.6.0"
58
+ "@larkup/core": "0.7.1"
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.8"
64
+ "@larkup/marketplace": "0.3.2"
65
65
  },
66
66
  "publishConfig": {
67
67
  "access": "public"
@@ -53,7 +53,7 @@ class Settings:
53
53
  ),
54
54
  disable_heavy_operators=_bool("LARKUP_VIDEO_DISABLE_HEAVY_OPERATORS", False),
55
55
  semantic_vision_enabled=_bool("LARKUP_VIDEO_SEMANTIC_VISION", True),
56
- # Vercel AI Gateway model ids, not local HuggingFace paths -- both
56
+ # Vercel AI Gateway model ids, not local HuggingFace paths, both
57
57
  # run entirely through gateway_vision.GatewayVisionClient, which
58
58
  # reads these same env vars itself. Kept here too so /v1/health
59
59
  # can report them. The bulk model captions every clip cheaply;
@@ -1,7 +1,3 @@
1
- """FastAPI app entry point: creates the app, wires CORS and exception
2
- handlers, and mounts the v1 API. Run with `uv run larkup-video-runtime`.
3
- """
4
-
5
1
  from __future__ import annotations
6
2
 
7
3
  from fastapi import FastAPI
@@ -16,7 +16,7 @@ import re
16
16
  import time
17
17
  from concurrent.futures import ThreadPoolExecutor, as_completed
18
18
  from dataclasses import asdict, dataclass, field
19
- from typing import Any
19
+ from typing import Any, Callable
20
20
 
21
21
  import requests
22
22
 
@@ -138,7 +138,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
138
138
  "overview": {"type": "string", "maxLength": 1200},
139
139
  "participants": {
140
140
  "type": "array",
141
- "maxItems": 64,
141
+ "maxItems": 16,
142
142
  "items": {
143
143
  "type": "object",
144
144
  "properties": {
@@ -154,9 +154,42 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
154
154
  "additionalProperties": False,
155
155
  },
156
156
  },
157
+ "visibleSubjects": {
158
+ "type": "array",
159
+ "maxItems": 24,
160
+ "items": {
161
+ "type": "object",
162
+ "properties": {
163
+ "identity": {"type": "string", "maxLength": 180},
164
+ "identityBasis": {
165
+ "type": "string",
166
+ "enum": ["source-named", "source-described", "unresolved"],
167
+ },
168
+ "appearances": {
169
+ "type": "array",
170
+ "maxItems": 32,
171
+ "items": {
172
+ "type": "object",
173
+ "properties": {
174
+ "startMs": {"type": "number"},
175
+ "endMs": {"type": "number"},
176
+ "confidence": {
177
+ "type": "string",
178
+ "enum": ["direct", "partial"],
179
+ },
180
+ },
181
+ "required": ["startMs", "endMs", "confidence"],
182
+ "additionalProperties": False,
183
+ },
184
+ },
185
+ },
186
+ "required": ["identity", "identityBasis", "appearances"],
187
+ "additionalProperties": False,
188
+ },
189
+ },
157
190
  "stateHistory": {
158
191
  "type": "array",
159
- "maxItems": 32,
192
+ "maxItems": 16,
160
193
  "items": {
161
194
  "type": "object",
162
195
  "properties": {
@@ -171,7 +204,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
171
204
  },
172
205
  "keyEvents": {
173
206
  "type": "array",
174
- "maxItems": 64,
207
+ "maxItems": 24,
175
208
  "items": {
176
209
  "type": "object",
177
210
  "properties": {
@@ -186,7 +219,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
186
219
  },
187
220
  "narrative": {
188
221
  "type": "array",
189
- "maxItems": 64,
222
+ "maxItems": 24,
190
223
  "items": {
191
224
  "type": "object",
192
225
  "properties": {
@@ -201,7 +234,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
201
234
  },
202
235
  "context": {
203
236
  "type": "array",
204
- "maxItems": 32,
237
+ "maxItems": 16,
205
238
  "items": {
206
239
  "type": "object",
207
240
  "properties": {
@@ -218,13 +251,14 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
218
251
  },
219
252
  "uncertainties": {
220
253
  "type": "array",
221
- "maxItems": 16,
254
+ "maxItems": 8,
222
255
  "items": {"type": "string", "maxLength": 240},
223
256
  },
224
257
  },
225
258
  "required": [
226
259
  "overview",
227
260
  "participants",
261
+ "visibleSubjects",
228
262
  "stateHistory",
229
263
  "keyEvents",
230
264
  "narrative",
@@ -239,7 +273,7 @@ SOURCE_INVENTORY_JSON_SCHEMA: dict[str, Any] = {
239
273
  "properties": {
240
274
  "items": {
241
275
  "type": "array",
242
- "maxItems": 256,
276
+ "maxItems": 48,
243
277
  "items": {
244
278
  "type": "object",
245
279
  "properties": {
@@ -517,7 +551,7 @@ class PlannerDiagnostics:
517
551
  # bounds, but the bounds themselves do not overlap in the direction that
518
552
  # matters: the densest plan Fast can propose is still lighter than the
519
553
  # lightest plan Balanced can, and likewise for Balanced against Thorough. That
520
- # is what makes the three modes mean something -- with overlapping ranges a
554
+ # is what makes the three modes mean something, with overlapping ranges a
521
555
  # Fast run could legitimately come out slower than a Balanced one, which is
522
556
  # what a user picking Fast is choosing against.
523
557
  MODE_BOUNDS: dict[str, dict[str, tuple[float, float]]] = {
@@ -754,6 +788,7 @@ class AgentPlanner:
754
788
  semantic_observations=semantic_observations,
755
789
  transcript=transcript,
756
790
  overlay_text=overlay_text or [],
791
+ compact=True,
757
792
  )
758
793
  started = time.monotonic()
759
794
  try:
@@ -762,21 +797,9 @@ class AgentPlanner:
762
797
  self.requests += 1
763
798
  try:
764
799
  raw, usage = self._complete(
765
- (
766
- prompt
767
- if attempt == 0 and self.provider != "google"
768
- else _synthesis_prompt(
769
- brief=brief,
770
- duration_secs=duration_secs,
771
- plan=plan,
772
- semantic_observations=semantic_observations,
773
- transcript=transcript,
774
- overlay_text=overlay_text or [],
775
- compact=True,
776
- )
777
- ),
800
+ prompt,
778
801
  [],
779
- max_output_tokens=10_000,
802
+ max_output_tokens=6_000,
780
803
  timeout_seconds=75,
781
804
  json_schema=KNOWLEDGE_JSON_SCHEMA,
782
805
  request_attempts=1,
@@ -798,7 +821,7 @@ class AgentPlanner:
798
821
  )
799
822
  # The audit is a second read of the same evidence. It pays
800
823
  # for itself only when the draft actually makes claims that
801
- # can contradict each other across time -- two states, or a
824
+ # can contradict each other across time - two states, or a
802
825
  # state plus an event that would move it.
803
826
  if len(summary["stateHistory"]) >= 2 or (
804
827
  summary["stateHistory"] and len(summary["keyEvents"]) >= 2
@@ -854,6 +877,7 @@ class AgentPlanner:
854
877
  transcript: list[dict[str, Any]],
855
878
  semantic_observations: list[dict[str, Any]],
856
879
  overlay_text: list[dict[str, Any]] | None = None,
880
+ on_progress: Callable[[int, int], None] | None = None,
857
881
  ) -> list[dict[str, Any]]:
858
882
  """Map source units and source-established layouts in bounded time chunks."""
859
883
  fallback = _fallback_source_inventory(semantic_observations, duration_secs)
@@ -885,6 +909,7 @@ class AgentPlanner:
885
909
  completed: dict[int, list[dict[str, Any]]] = {}
886
910
  completed_structures: dict[int, list[dict[str, Any]]] = {}
887
911
  completed_tasks: dict[int, list[dict[str, Any]]] = {}
912
+ completed_raw_item_counts: dict[int, int] = {}
888
913
  errors: list[str] = []
889
914
  usage_totals = {"promptTokens": 0, "completionTokens": 0}
890
915
 
@@ -892,8 +917,8 @@ class AgentPlanner:
892
917
  raw, usage = self._complete(
893
918
  _source_inventory_prompt(chunk),
894
919
  [],
895
- max_output_tokens=10_000,
896
- timeout_seconds=30,
920
+ max_output_tokens=6_000,
921
+ timeout_seconds=75,
897
922
  json_schema=SOURCE_INVENTORY_JSON_SCHEMA,
898
923
  request_attempts=1,
899
924
  )
@@ -924,13 +949,15 @@ class AgentPlanner:
924
949
  items,
925
950
  _validated_source_activity_structures(raw, duration_secs, chunk),
926
951
  tasks,
952
+ len(raw.get("items") or []) if isinstance(raw, dict) else 0,
927
953
  usage,
928
954
  )
929
955
 
930
956
  try:
931
- # These requests contain disjoint time ranges and are independent.
932
- # Four concurrent maps keep an hour-long source to one short wave.
933
- with ThreadPoolExecutor(max_workers=min(4, len(chunks))) as executor:
957
+ # These requests contain disjoint time ranges. Two concurrent maps
958
+ # keep a long source responsive without making several transcript-
959
+ # sized requests contend for the same hosted-model window.
960
+ with ThreadPoolExecutor(max_workers=min(2, len(chunks))) as executor:
934
961
  futures = {
935
962
  executor.submit(map_chunk, index, chunk): index
936
963
  for index, chunk in enumerate(chunks)
@@ -938,10 +965,11 @@ class AgentPlanner:
938
965
  for future in as_completed(futures):
939
966
  self.requests += 1
940
967
  try:
941
- index, items, structures, tasks, usage = future.result()
968
+ index, items, structures, tasks, raw_item_count, usage = future.result()
942
969
  completed[index] = items
943
970
  completed_structures[index] = structures
944
971
  completed_tasks[index] = tasks
972
+ completed_raw_item_counts[index] = raw_item_count
945
973
  usage_totals["promptTokens"] += usage.get("promptTokens", 0)
946
974
  usage_totals["completionTokens"] += usage.get("completionTokens", 0)
947
975
  except Exception as error:
@@ -949,6 +977,8 @@ class AgentPlanner:
949
977
  f"source inventory chunk {futures[future]}: "
950
978
  f"{type(error).__name__}: {error}"[:500]
951
979
  )
980
+ if on_progress:
981
+ on_progress(len(completed) + len(errors), len(chunks))
952
982
  self.prompt_tokens += usage_totals["promptTokens"]
953
983
  self.completion_tokens += usage_totals["completionTokens"]
954
984
  if errors:
@@ -957,6 +987,8 @@ class AgentPlanner:
957
987
  "complete": len(completed) == len(chunks) and not errors,
958
988
  "totalWindows": len(chunks),
959
989
  "processedWindows": len(completed),
990
+ "modelItems": sum(completed_raw_item_counts.values()),
991
+ "acceptedItems": sum(len(items) for items in completed.values()),
960
992
  **(
961
993
  {}
962
994
  if len(completed) == len(chunks) and not errors
@@ -1343,7 +1375,9 @@ def _source_inventory_chunks(
1343
1375
  semantic_observations: list[dict[str, Any]],
1344
1376
  overlay_text: list[dict[str, Any]],
1345
1377
  ) -> list[dict[str, Any]]:
1346
- window_ms = 15 * 60 * 1_000
1378
+ # Keep each map within a bounded evidence window instead of forcing one
1379
+ # completion to compress a quarter-hour of raw speech and visual notes.
1380
+ window_ms = 5 * 60 * 1_000
1347
1381
  duration_ms = max(1, round(duration_secs * 1_000))
1348
1382
  chunks: list[dict[str, Any]] = []
1349
1383
  for start_ms in range(0, duration_ms, window_ms):
@@ -1413,7 +1447,8 @@ def _source_inventory_prompt(chunk: dict[str, Any]) -> str:
1413
1447
  "whose answer is a substantive part of the recording; headings or titles; individual slide, "
1414
1448
  "board, or explicitly enumerated list items; and declarative hints used to solve an explicit "
1415
1449
  "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 "
1450
+ "answer. In a dialogue, a substantive turn that invites an explanation is a source question "
1451
+ "even when phrased informally. A greeting, social check-in, turn-management request, rhetorical question, or casual "
1417
1452
  "banter is not a source question. Do not turn a declarative hint, a description, model "
1418
1453
  "instruction, or analysis prompt into a question: represent an explicit solving hint as kind "
1419
1454
  "'clue' and otherwise omit it. Preserve the source language and wording. For a spoken "
@@ -1435,7 +1470,7 @@ def _source_inventory_prompt(chunk: dict[str, Any]) -> str:
1435
1470
  "portion; its time range must cover that bundle, not the earlier title. A new card/title, an answer "
1436
1471
  "reveal, or another directly observed reset can establish a separate bundle. Do not create a task "
1437
1472
  "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'|"
1473
+ "add outside facts. Return at most 48 items for this bounded portion. JSON only: {items:[{kind:'question'|'clue'|"
1439
1474
  "'heading'|'slide-item'|'board-item'|'list-item',channel:'spoken'|'visible',questionRole:"
1440
1475
  "'primary'|'interactional'|'rhetorical'|'not-question',text:string,answer:string,"
1441
1476
  "respondent:string,startMs:number,endMs:number}],structures:[{kind:'grid'|'sequence'|"
@@ -1487,34 +1522,7 @@ def _source_task_instance_prompt(
1487
1522
 
1488
1523
 
1489
1524
  def _inventory_terms(value: str) -> list[str]:
1490
- return re.findall(r"[\w\u0600-\u06ff]+", value.casefold(), re.UNICODE)
1491
-
1492
-
1493
- def _looks_like_explicit_prompt(value: str) -> bool:
1494
- """Accept a question/request, never a declarative hint with a guessed answer."""
1495
- text = value.strip()
1496
- if re.search(r"[?؟]\s*$", text):
1497
- return True
1498
- cue = re.compile(
1499
- r"^(?:who|what|when|where|why|how|which|whose|whom|is|are|was|were|do|does|did|"
1500
- r"can|could|would|will|name|list|identify|describe|tell|give|guess|choose|select|"
1501
- r"من|ما|ماذا|متى|أين|اين|كيف|كم|هل|أي|اي|لماذا|مين|إيه|ايه|فين|امتى|ازاي|"
1502
- r"اذكر|أذكر|حدد|سم|سمي|اختر|إختر|اكتشف|خمن|خمّن|توقع|أكمل|اكمل|رتب|رتِّب)$",
1503
- re.I,
1504
- )
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
- )
1525
+ return re.findall(r"\w+", value.casefold(), re.UNICODE)
1518
1526
 
1519
1527
 
1520
1528
  def _inventory_item_is_grounded(
@@ -1638,15 +1646,6 @@ def _validated_source_inventory(
1638
1646
  if kind == "question":
1639
1647
  if question_role != "primary":
1640
1648
  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
1649
  elif question_role != "not-question":
1651
1650
  continue
1652
1651
  if source_chunk is not None and not _inventory_item_is_grounded(item, source_chunk):
@@ -1767,13 +1766,29 @@ def _validated_source_task_instances(
1767
1766
  ) -> list[dict[str, Any]]:
1768
1767
  """Validate continued prompt instances without treating their clues as questions."""
1769
1768
  duration_ms = max(1, round(duration_secs * 1_000))
1769
+ # A task can only continue a prompt the mapper already classified as a
1770
+ # primary source question. This is a structural provenance check, not a
1771
+ # vocabulary test for one language: the model is responsible for semantic
1772
+ # question classification and the validator requires it to be consistent
1773
+ # with its own source-backed inventory.
1774
+ source_prompts = {
1775
+ re.sub(r"\s+", " ", str(item.get("text") or "").casefold()).strip()
1776
+ for item in raw.get("items") or []
1777
+ if isinstance(item, dict)
1778
+ and item.get("kind") == "question"
1779
+ and item.get("questionRole", "primary") == "primary"
1780
+ and str(item.get("text") or "").strip()
1781
+ }
1770
1782
  tasks: list[dict[str, Any]] = []
1771
1783
  for candidate in raw.get("taskInstances") or []:
1772
1784
  if not isinstance(candidate, dict):
1773
1785
  continue
1774
1786
  prompt = str(candidate.get("prompt") or "").strip()[:600]
1775
1787
  channel = str(candidate.get("channel") or "").strip()
1776
- if channel not in {"spoken", "visible"} or not _looks_like_explicit_prompt(prompt):
1788
+ if channel not in {"spoken", "visible"}:
1789
+ continue
1790
+ prompt_key = re.sub(r"\s+", " ", prompt.casefold()).strip()
1791
+ if not prompt_key or prompt_key not in source_prompts:
1777
1792
  continue
1778
1793
  try:
1779
1794
  start_ms = min(duration_ms, max(0, round(float(candidate.get("startMs")))))
@@ -2039,6 +2054,13 @@ def _synthesis_prompt(
2039
2054
  "- A later close-up, label, caption, presentation, celebration, or reaction does not identify "
2040
2055
  "who performed an earlier action. Bind the name to that earlier actor only when an uninterrupted "
2041
2056
  "sequence tracks the same subject or the supplied evidence explicitly states the relationship.\n"
2057
+ "- visibleSubjects is an appearance ledger. Include every named or source-distinguished visible "
2058
+ "subject whose appearances the evidence supports. Each appearance range must be one supplied "
2059
+ "range where that subject is actually present; keep separate appearances separate after a real "
2060
+ "absence or edit. identityBasis is source-named only when source evidence binds the name, "
2061
+ "source-described for a stable source-supported descriptor, and unresolved when the evidence "
2062
+ "cannot safely distinguish the subject. Never merge two entries from resemblance alone, and do "
2063
+ "not include a subject merely because they are discussed in speech.\n"
2042
2064
  "- stateHistory tracks things that persist and change: a displayed value, a location, a phase, "
2043
2065
  "a condition. Record each distinct value once with the span it held, and keep the sequence "
2044
2066
  "self-consistent -- one thing cannot hold two values at the same time, and a value it never "
@@ -2064,6 +2086,8 @@ def _synthesis_prompt(
2064
2086
  "where a display existed and when it changed. It never states what that text means: use it to "
2065
2087
  "corroborate or locate, never as a fact on its own.\n"
2066
2088
  "Return JSON only: {overview:string, participants:[{name,role,evidence:[{startMs,endMs}]}], "
2089
+ "visibleSubjects:[{identity,identityBasis:'source-named'|'source-described'|'unresolved',"
2090
+ "appearances:[{startMs,endMs,confidence:'direct'|'partial'}]}], "
2067
2091
  "stateHistory:[{startMs,endMs,state,confidence:'direct'|'partial'}], "
2068
2092
  "keyEvents:[{startMs,endMs,event,confidence:'direct'|'partial'}], "
2069
2093
  "narrative:[{startMs,endMs,text,confidence:'direct'|'partial'}], "
@@ -2309,6 +2333,46 @@ def _validated_knowledge_summary(
2309
2333
  if len(participants) == 50:
2310
2334
  break
2311
2335
 
2336
+ visible_subjects: list[dict[str, Any]] = []
2337
+ for candidate in raw.get("visibleSubjects") or []:
2338
+ if not isinstance(candidate, dict):
2339
+ continue
2340
+ identity = str(candidate.get("identity") or "").strip()[:180]
2341
+ identity_basis = candidate.get("identityBasis")
2342
+ appearances = []
2343
+ for appearance in candidate.get("appearances") or []:
2344
+ if not isinstance(appearance, dict):
2345
+ continue
2346
+ evidence = source_range(appearance)
2347
+ if not evidence:
2348
+ continue
2349
+ appearances.append(
2350
+ {
2351
+ **evidence,
2352
+ "confidence": (
2353
+ appearance.get("confidence")
2354
+ if appearance.get("confidence") in {"direct", "partial"}
2355
+ else "partial"
2356
+ ),
2357
+ }
2358
+ )
2359
+ if (
2360
+ identity
2361
+ and identity_basis in {"source-named", "source-described", "unresolved"}
2362
+ and appearances
2363
+ ):
2364
+ visible_subjects.append(
2365
+ {
2366
+ "identity": identity,
2367
+ "identityBasis": identity_basis,
2368
+ "appearances": sorted(
2369
+ appearances, key=lambda item: (item["startMs"], item["endMs"])
2370
+ )[:32],
2371
+ }
2372
+ )
2373
+ if len(visible_subjects) == 96:
2374
+ break
2375
+
2312
2376
  def timeline(key: str, text_key: str, limit: int) -> list[dict[str, Any]]:
2313
2377
  items: list[dict[str, Any]] = []
2314
2378
  for candidate in raw.get(key) or []:
@@ -2351,6 +2415,7 @@ def _validated_knowledge_summary(
2351
2415
  return {
2352
2416
  "overview": str(raw.get("overview") or "").strip()[:2_000],
2353
2417
  "participants": participants,
2418
+ "visibleSubjects": visible_subjects,
2354
2419
  "stateHistory": timeline("stateHistory", "state", 80),
2355
2420
  "keyEvents": timeline("keyEvents", "event", 80),
2356
2421
  "narrative": timeline("narrative", "text", 64),
@@ -2490,6 +2555,7 @@ def _fallback_knowledge_summary(
2490
2555
  return {
2491
2556
  "overview": overview,
2492
2557
  "participants": list(participants_by_name.values())[:50],
2558
+ "visibleSubjects": [],
2493
2559
  "stateHistory": state_history,
2494
2560
  "keyEvents": key_events,
2495
2561
  "narrative": narrative,
@@ -1,4 +1,4 @@
1
- """Video-clip embeddings for cross-modal search -- "find the clip where this
1
+ """Video-clip embeddings for cross-modal search "find the clip where this
2
2
  happens" from a free-text query. Distinct from vision.py's captions: a
3
3
  caption describes a clip in words, which can miss an action a viewer would
4
4
  recognize but a VLM never put into text. An embedding catches that by