@camstack/addon-provider-dreo 0.2.29 → 0.2.30

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.
Files changed (3) hide show
  1. package/dist/addon.js +1889 -1816
  2. package/dist/addon.mjs +1889 -1816
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -16403,1760 +16403,1996 @@ var OauthIntegrationDescriptorSchema = object({
16403
16403
  });
16404
16404
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
16405
16405
  /**
16406
- * pipeline-analytics — device-scoped wrapper cap. Refines raw
16407
- * per-frame detections emitted by the pipeline runner into tracked
16408
- * objects, per-kind event collections (motion / object / audio), and
16409
- * persisted media. Owns the post-detection domain end-to-end:
16410
- *
16411
- * runner emits PipelineInferenceResult
16412
- * ↓ (event bus)
16413
- * pipeline-analytics subscriber
16414
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
16415
- * → three DB collections (one per kind), one FS media tree, one
16416
- * unified event emitter (FrameTracked + TrackStarted/Ended +
16417
- * DetectionEvent on bus)
16418
- *
16419
- * Pure subscriber model. No `processFrame` cap method — the runner
16420
- * already publishes the raw frame on the bus. The cap surface is
16421
- * only QUERIES + per-device settings, bound on/off via
16422
- * `device-manager.setWrapperActive`. `defaultActive: true` because
16423
- * every camera with a detection pipeline wants its raw detections
16424
- * refined; operators opt out per-device via BindingsTab when needed.
16425
- *
16426
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
16427
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
16406
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
16407
+ * within the frame, so the executor can re-cut a leaf child ROI at native
16408
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
16428
16409
  */
16429
- var TrackStateSchema = _enum([
16430
- "new",
16431
- "entered",
16432
- "left",
16433
- "moving",
16434
- "idle"
16435
- ]);
16436
- var EventKindSchema = _enum([
16437
- "motion",
16438
- "object",
16439
- "audio"
16440
- ]);
16410
+ var NativeCropRefSchema = object({
16411
+ /** Handle keying the retained native surface (node-pinned to its owner). */
16412
+ handle: FrameHandleSchema,
16413
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
16414
+ cropFrameSpace: object({
16415
+ x: number(),
16416
+ y: number(),
16417
+ w: number(),
16418
+ h: number()
16419
+ })
16420
+ });
16421
+ object({
16422
+ crop: object({
16423
+ left: number(),
16424
+ top: number(),
16425
+ width: number().positive(),
16426
+ height: number().positive()
16427
+ }).optional(),
16428
+ content: object({
16429
+ width: number().int().positive(),
16430
+ height: number().int().positive()
16431
+ }),
16432
+ fit: _enum(["stretch", "contain"]),
16433
+ format: _enum([
16434
+ "rgb",
16435
+ "gray",
16436
+ "jpeg"
16437
+ ])
16438
+ });
16441
16439
  /**
16442
- * Spatial filter for `listTracks` — the rect + polygon variants of the shared
16443
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
16444
- * of the camera frame (top-left origin), matching the drawing-plane editor.
16440
+ * Process-local frame identity. It is serializable so it can ride an in-process
16441
+ * capability call, but `registryId` deliberately prevents resolution in any
16442
+ * other process or execution group.
16445
16443
  */
16446
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
16447
- /** Closed icon vocabulary so clients render a known glyph per kind. */
16448
- var EventKindIconSchema = _enum([
16449
- "motion",
16450
- "audio",
16451
- "person",
16452
- "vehicle",
16453
- "animal",
16454
- "door",
16455
- "pir",
16456
- "smoke",
16457
- "water",
16458
- "button",
16459
- "package",
16460
- "generic"
16444
+ var FrameRefSchema = object({
16445
+ registryId: string().min(1),
16446
+ id: string().min(1),
16447
+ width: number().int().positive(),
16448
+ height: number().int().positive(),
16449
+ format: _enum(["rgb", "gray"]),
16450
+ timestamp: number(),
16451
+ capturedAt: number().optional()
16452
+ });
16453
+ var ModelFormatSchema$1 = _enum([
16454
+ "onnx",
16455
+ "coreml",
16456
+ "openvino",
16457
+ "tflite",
16458
+ "pt",
16459
+ "gguf"
16461
16460
  ]);
16462
- var EventKindCategorySchema = _enum([
16463
- "motion",
16464
- "audio",
16465
- "detection",
16466
- "sensor",
16467
- "control",
16468
- "custom",
16469
- "package"
16461
+ var PipelineSlotSchema = _enum([
16462
+ "detector",
16463
+ "cropper",
16464
+ "classifier",
16465
+ "refiner",
16466
+ "audio-classifier"
16470
16467
  ]);
16471
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
16472
- var EventKindLevelSchema = _enum(["macro", "sub"]);
16473
- var EventKindDescriptorSchema = object({
16474
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
16475
- kind: string(),
16476
- /** i18n key resolved on the UI side; `label` is the English fallback. */
16477
- labelKey: string(),
16478
- /** English fallback label (kept for clients that don't translate). */
16479
- label: string(),
16480
- /** Hex color for timeline/legend rendering. */
16481
- color: string(),
16482
- /** Dictionary id → lucide component on the UI side. */
16483
- iconId: string(),
16484
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
16485
- icon: EventKindIconSchema,
16486
- category: EventKindCategorySchema,
16487
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
16488
- parentKind: string().nullable(),
16489
- /** Derived from `parentKind`, explicit for the client tree. */
16490
- level: EventKindLevelSchema,
16491
- /** Which cap + device contributes this kind. For built-ins the camera
16492
- * itself; for sensor kinds the LINKED source device. */
16493
- source: object({
16494
- capName: string(),
16495
- deviceId: number()
16496
- })
16468
+ var PipelineEngineChoiceSchema = object({
16469
+ runtime: _enum(["node", "python"]),
16470
+ backend: string(),
16471
+ format: ModelFormatSchema$1,
16472
+ device: string().optional()
16497
16473
  });
16498
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
16499
- var EventKindsForDeviceSchema = object({
16500
- deviceId: number(),
16501
- kinds: array(EventKindDescriptorSchema).readonly()
16474
+ var AvailableEngineSchema = object({
16475
+ engine: PipelineEngineChoiceSchema,
16476
+ devices: array(object({
16477
+ id: string(),
16478
+ label: string(),
16479
+ description: string().optional()
16480
+ })).readonly(),
16481
+ defaultDevice: string()
16502
16482
  });
16503
- var SensorEventSchema = object({
16483
+ var PipelineDefaultStepSchema = lazy(() => object({
16484
+ addonId: string(),
16485
+ addonName: string(),
16486
+ slot: PipelineSlotSchema,
16487
+ inputClasses: array(string()).readonly(),
16488
+ outputClasses: array(string()).readonly(),
16489
+ enabled: boolean(),
16490
+ modelId: string(),
16491
+ children: array(PipelineDefaultStepSchema).readonly(),
16492
+ group: string().optional(),
16493
+ settings: record(string(), unknown()).optional()
16494
+ }));
16495
+ var PipelineTemplateStepSchema = lazy(() => object({
16496
+ addonId: string(),
16497
+ enabled: boolean(),
16498
+ modelId: string(),
16499
+ children: array(PipelineTemplateStepSchema).readonly(),
16500
+ settings: record(string(), unknown()).optional()
16501
+ }));
16502
+ var PipelineTemplateSchema$1 = object({
16504
16503
  id: string(),
16505
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
16506
- * yields N rows, one per camera). */
16507
- deviceId: number(),
16508
- /** The linked sensor device whose state changed. */
16509
- sourceDeviceId: number(),
16510
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
16511
- kind: string(),
16512
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
16513
- value: record(string(), unknown()).nullable(),
16514
- timestamp: number()
16504
+ name: string(),
16505
+ createdAt: string(),
16506
+ updatedAt: string(),
16507
+ engine: PipelineEngineChoiceSchema,
16508
+ steps: array(PipelineTemplateStepSchema).readonly()
16515
16509
  });
16516
- var TrackPositionSchema = object({
16517
- x: number(),
16518
- y: number(),
16519
- timestamp: number(),
16520
- bbox: BoundingBoxSchema
16510
+ var PipelineModelOptionSchema = object({
16511
+ id: string(),
16512
+ name: string(),
16513
+ formats: record(string(), object({
16514
+ downloaded: boolean(),
16515
+ sizeMB: number()
16516
+ })),
16517
+ group: ModelVariantGroupSchema.optional(),
16518
+ legacy: boolean().optional(),
16519
+ provider: ModelProviderIdSchema.optional()
16521
16520
  });
16522
- var TrackSnapshotSchema = object({
16523
- timestamp: number(),
16524
- position: TrackPositionSchema,
16525
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
16526
- mediaKey: string()
16521
+ var ConfigFieldBridge = custom();
16522
+ var PipelineAddonSchemaSchema = object({
16523
+ id: string(),
16524
+ name: string(),
16525
+ slot: PipelineSlotSchema,
16526
+ inputClasses: array(string()).readonly(),
16527
+ outputClasses: array(string()).readonly(),
16528
+ childSlots: array(PipelineSlotSchema).readonly(),
16529
+ models: array(PipelineModelOptionSchema).readonly(),
16530
+ defaultModelId: string(),
16531
+ defaultModelIdByFormat: record(string(), string()).optional(),
16532
+ enabledByDefault: boolean().optional(),
16533
+ backfillIntoExistingOverrides: boolean().optional(),
16534
+ defaultConfidence: number(),
16535
+ group: string().optional(),
16536
+ configSchema: array(ConfigFieldBridge).readonly().optional()
16527
16537
  });
16528
- /**
16529
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
16530
- * divided by the track's detection-frame dims), computed at persist time.
16531
- * Absent when the frame dims were unknown when the track was persisted
16532
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
16533
- */
16534
- var TrackEnvelopeSchema = object({
16535
- minX: number(),
16536
- minY: number(),
16537
- maxX: number(),
16538
- maxY: number()
16538
+ var PipelineSlotSchemaSchema = object({
16539
+ id: PipelineSlotSchema,
16540
+ label: string(),
16541
+ priority: number(),
16542
+ parentSlot: PipelineSlotSchema.nullable(),
16543
+ addons: array(PipelineAddonSchemaSchema).readonly()
16539
16544
  });
16540
- /**
16541
- * Row projection for track list queries. `full` (default) returns the
16542
- * complete Track including the frame-rate `positions[]` history and the
16543
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
16544
- * keeps every scalar the list surfaces actually render (ids, class(es),
16545
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
16546
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
16547
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
16548
- * `getTrack`. Mirrors the event-store `projection` convention
16549
- * (`getObjectEvents` et al.).
16550
- */
16551
- var TrackProjectionSchema = _enum(["full", "slim"]);
16552
- /**
16553
- * One audio-classification label heard on the track's camera while the
16554
- * track was alive, aggregated per label. An "episode" is one persisted
16555
- * audio event (the confident-classification path: score ≥ the device's
16556
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
16557
- * one 32 ms inference chunk, so counts stay human-scaled.
16558
- */
16559
- var TrackAudioLabelSchema = object({
16560
- label: string(),
16561
- /** Highest classification score observed across the label's episodes. */
16562
- peakScore: number(),
16563
- /** Number of coalesced audio-event episodes carrying this label. */
16564
- count: number(),
16565
- firstAt: number(),
16566
- lastAt: number()
16545
+ var PipelineSchemaSchema = object({
16546
+ availableEngines: array(AvailableEngineSchema).readonly(),
16547
+ selectedEngine: PipelineEngineChoiceSchema,
16548
+ slots: array(PipelineSlotSchemaSchema).readonly()
16567
16549
  });
16568
- /**
16569
- * How a track was produced. `pipeline` (default / absent) = the spatial
16570
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
16571
- * no positions, a single snapshot, and no bbox trajectory at all:
16572
- *
16573
- * - `sensor` — a linked sensor/control device state change.
16574
- * - `audio` — an audio event on the camera itself that was anomalous for
16575
- * THAT camera, loud, and heard while nothing visual was happening (D62).
16576
- *
16577
- * The spatial subsystems (tracker association, occupancy count, re-id /
16578
- * embedding, resurrection) MUST skip every synthetic source. Test for that
16579
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
16580
- * check silently readmits every source added after it was written.
16581
- */
16582
- var TrackSourceSchema = _enum([
16583
- "pipeline",
16584
- "sensor",
16585
- "audio"
16586
- ]);
16587
- /**
16588
- * Where a track sits in the RETRAIN lifecycle (D81).
16589
- *
16590
- * - `none` — never marked, or un-marked. Evictable.
16591
- * - `staging` — the operator wants this track as training material and has not
16592
- * finished with it. **This is the only state retention holds**: the track and
16593
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
16594
- * the device's age window.
16595
- * - `trained` — the retrain page has taken what it needed. The frames it chose
16596
- * were COPIED into the retrain dataset at selection time, so the dataset no
16597
- * longer depends on the track's media and the track becomes EVICTABLE again.
16598
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
16599
- * a deliberate action of the retrain page, not a side effect of a checkbox.
16600
- *
16601
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
16602
- * the store's filter language has only positive equality and `whereIn` — no
16603
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
16604
- * would make the entire pre-column history immortal in one deploy.
16605
- */
16606
- var RetrainStatusSchema = _enum([
16607
- "none",
16608
- "staging",
16609
- "trained"
16610
- ]);
16611
- /**
16612
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
16613
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
16614
- * so the two surfaces cannot drift.
16615
- *
16616
- * **Absent ≠ false.** A track that has never been touched omits the field; an
16617
- * explicitly un-flagged track carries `false`. Legacy rows written before the
16618
- * columns existed read as absent, and a consumer that needs a boolean should say
16619
- * `flag === true`, not `flag !== false`.
16620
- *
16621
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
16622
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
16623
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
16624
- * `trained` track reports `false` while refusing both writes. The boolean is
16625
- * kept because three surfaces drive a toggle off it; anything that needs to tell
16626
- * "never marked" from "already trained" must read `retrainStatus`.
16627
- *
16628
- * `debug` does NOT pin; it is attention, not durability.
16629
- *
16630
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
16631
- * A favourited track is skipped by retention the same way `staging` is, but
16632
- * it does not enter `none|staging|trained` and has no staging budget.
16633
- */
16634
- var TrackFlagFields = {
16635
- /** Operator marked this track as training material — i.e. `retrainStatus` is
16636
- * `'staging'`. */
16637
- markForTrain: boolean().optional(),
16638
- /** Operator marked this track for diagnostic attention. */
16639
- debug: boolean().optional(),
16640
- /** Operator favourited this track. Pins it against pruning. */
16641
- favourited: boolean().optional()
16642
- };
16643
- /**
16644
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
16645
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
16646
- * write patch, and the status is not something the toggle sets — it is what the
16647
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
16648
- * always present on a persisted row (the column default materialises `'none'`).
16649
- */
16650
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
16651
- /**
16652
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
16653
- * one flag can never clear the other — the toggles are independent and are
16654
- * driven from three surfaces that do not know about each other.
16655
- */
16656
- var TrackFlagsPatchSchema = object(TrackFlagFields);
16657
- /**
16658
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
16659
- * collapses to `false`) so a caller can drive a toggle's checked state off the
16660
- * mutation result without a re-fetch.
16661
- */
16662
- var TrackFlagsSchema = object({
16663
- trackId: string(),
16664
- markForTrain: boolean(),
16665
- debug: boolean(),
16666
- favourited: boolean(),
16667
- /** The lifecycle state the boolean was derived from. Required here (unlike on
16668
- * a track row) because this shape is only ever produced by the write body,
16669
- * which always knows it — and a surface that has just written needs to render
16670
- * `trained` without a re-fetch. */
16671
- retrainStatus: RetrainStatusSchema
16550
+ var EngineProvisioningSchema = object({
16551
+ runtimeId: _enum([
16552
+ "onnx",
16553
+ "openvino",
16554
+ "coreml",
16555
+ "edgetpu"
16556
+ ]).nullable(),
16557
+ device: string().nullable(),
16558
+ state: _enum([
16559
+ "idle",
16560
+ "installing",
16561
+ "verifying",
16562
+ "ready",
16563
+ "failed"
16564
+ ]),
16565
+ progress: number().optional(),
16566
+ error: string().optional(),
16567
+ nextRetryAt: number().optional(),
16568
+ /**
16569
+ * Gate A (config-correctness gate at engine change): human-readable
16570
+ * config issues surfaced EAGERLY when the node's engine changes — model
16571
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
16572
+ * has a <format> build"). Additive/optional: informational only, never
16573
+ * enforced here — `assertEngineReady` (readiness) still gates inference.
16574
+ * Absent/empty when the node-default tree resolves cleanly.
16575
+ */
16576
+ configIssues: array(string()).optional()
16672
16577
  });
16673
- union([literal(1), literal(2)]);
16674
- /**
16675
- * WHO decided a label, and when. Carried per tier so a value can be traced to
16676
- * the step and model that produced it — which is what makes the write rule
16677
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
16678
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
16679
- *
16680
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
16681
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
16682
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
16683
- * that value has no provenance, and the write rule lets ANY properly-attributed
16684
- * write of the same tier replace it regardless of score.
16685
- */
16686
- var LabelAttributionSchema = object({
16687
- stepId: string(),
16578
+ var PipelineStepInputSchema = lazy(() => object({
16579
+ addonId: string(),
16688
16580
  modelId: string().optional(),
16689
- decidedAt: number(),
16581
+ enabled: boolean().default(true),
16582
+ children: array(PipelineStepInputSchema).optional(),
16583
+ settings: record(string(), unknown()).optional(),
16584
+ jumpDeviceKey: string().optional()
16585
+ }));
16586
+ var ModelSubstitutionSchema = object({
16587
+ addonId: string(),
16588
+ chosen: string(),
16589
+ running: string(),
16590
+ format: string()
16591
+ });
16592
+ var PipelineValidationIssueSchema = object({
16593
+ addonId: string(),
16594
+ kind: _enum(["unknown-addon", "no-format-build"]),
16595
+ detail: string()
16596
+ });
16597
+ var PipelineValidationResultSchema = object({
16598
+ ok: boolean(),
16599
+ issues: array(PipelineValidationIssueSchema).readonly(),
16600
+ substitutions: array(ModelSubstitutionSchema).readonly(),
16601
+ /** The node's `currentEngine.format` this validation ran against. */
16602
+ format: string()
16603
+ });
16604
+ var ReferenceImageEntrySchema = object({
16605
+ filename: string(),
16606
+ stepIds: array(string()).readonly().optional()
16607
+ });
16608
+ var ReferenceImageBodySchema = object({
16609
+ base64: string(),
16610
+ filename: string()
16611
+ });
16612
+ var ReferenceAudioEntrySchema = object({
16613
+ filename: string(),
16614
+ sizeKb: number()
16615
+ });
16616
+ var ReferenceAudioBodySchema = object({ base64: string() });
16617
+ var AudioBackendSchema = object({
16618
+ id: string(),
16619
+ name: string(),
16620
+ description: string(),
16621
+ available: boolean(),
16690
16622
  /**
16691
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
16692
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
16693
- *
16694
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
16695
- * notification rule authored on "Gianluca" stopped matching the moment the
16696
- * operator fixed the spelling in the gallery, and nothing said so. The id is
16697
- * the thing that does not move, so it is what a rule matches on
16698
- * (`NcConditions.identities`) and the text is what a human is shown.
16699
- *
16700
- * Absent when the label names no gallery row — a plate the OCR read but no
16701
- * vehicle claims, a sub-class, a species, any tier-1 value.
16623
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
16624
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
16625
+ * the benchmark UI to populate the `enabledMicroClasses` filter
16626
+ * specific to the selected backend without a separate fetch.
16702
16627
  */
16703
- identityId: string().optional()
16628
+ rawLabels: array(string()).readonly().optional()
16629
+ });
16630
+ var AudioCapabilitiesSchema = object({
16631
+ activeBackend: string(),
16632
+ availableBackends: array(AudioBackendSchema).readonly(),
16633
+ sampleRate: number(),
16634
+ chunkDurationMs: number()
16635
+ });
16636
+ var DownloadModelResultSchema = object({
16637
+ filePath: string(),
16638
+ sizeMB: number(),
16639
+ durationMs: number()
16704
16640
  });
16705
16641
  /**
16706
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
16707
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
16708
- * track and its events always answer the same question the same way.
16709
- *
16710
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
16711
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
16712
- * is tier 2, and each carries its own score + attribution.
16713
- *
16714
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
16715
- * finest thing known. Before 4g the single `label` column held the finest
16716
- * value, so a consumer that has not been updated reads the tier-1 slot and
16717
- * shows nothing on a species-only row; that is why the migration puts every
16718
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
16719
- * and why the read surfaces were changed in the same train.
16720
- *
16721
- * **Writing it.** The slots are independent, which is the whole point: a
16722
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
16723
- * migratorius`), so fineness cannot regress by construction. Within a tier the
16724
- * higher score wins. One rule, one implementation — see
16725
- * `pipeline/label-tier.ts` in addon-post-analysis.
16726
- */
16727
- var TieredLabelFields = {
16728
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
16729
- label: string().optional(),
16730
- /** Confidence of the tier-1 value, as reported by the deciding step. */
16731
- labelScore: number().optional(),
16732
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
16733
- labelMeta: LabelAttributionSchema.optional(),
16734
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
16735
- subLabel: string().optional(),
16736
- /** Confidence of the tier-2 value, as reported by the deciding step. */
16737
- subLabelScore: number().optional(),
16738
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
16739
- subLabelMeta: LabelAttributionSchema.optional()
16740
- };
16741
- /** Per-camera slice of a training-export estimate. */
16742
- var TrainingExportDeviceTotalsSchema = object({
16743
- deviceId: number(),
16744
- tracks: number().int(),
16745
- files: number().int(),
16746
- bytes: number().int()
16747
- });
16748
- /**
16749
- * What a training export WOULD contain. Computed from media index rows only —
16750
- * no blob is read to produce this.
16642
+ * Wrapper carrying a single test run's result. Replaces the legacy
16643
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
16644
+ * canonical `AudioResult` from the Phase 6 output rework: one
16645
+ * `AudioDetection` per class above `minScore`, top-N candidates in
16646
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
16647
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
16648
+ * benchmark UI can still report a clean failure when the classifier
16649
+ * cap isn't available.
16751
16650
  */
16752
- var TrainingExportSummarySchema = object({
16753
- generatedAt: number(),
16754
- trackCount: number().int(),
16755
- fileCount: number().int(),
16756
- byteCount: number().int(),
16757
- /** More marked tracks exist than a single pass carries. */
16758
- truncated: boolean(),
16759
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
16651
+ var AudioTestResultSchema = object({
16652
+ success: boolean(),
16653
+ error: string().optional(),
16654
+ frame: custom().optional()
16760
16655
  });
16761
- var TrackSchema = object({
16762
- trackId: string(),
16763
- deviceId: number(),
16764
- className: string(),
16765
- ...TieredLabelFields,
16766
- producingDeviceName: string().optional(),
16767
- /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
16768
- source: TrackSourceSchema.optional(),
16769
- firstSeen: number(),
16770
- lastSeen: number(),
16771
- /** Frame-rate position history (subject to maxPositionHistory cap). */
16772
- positions: array(TrackPositionSchema).readonly(),
16773
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
16774
- * saveThumbnails policy). */
16775
- snapshots: array(TrackSnapshotSchema).readonly(),
16776
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
16777
- zonesVisited: array(string()).readonly(),
16656
+ var PipelineConfigBridge = custom();
16657
+ var ConfigUISchemaBridge = custom();
16658
+ var ConfigUISchemaNullableBridge = custom();
16659
+ var InferenceCapabilitiesBridge = custom();
16660
+ var ModelAvailabilityListBridge = custom();
16661
+ var PipelineRunResultBridge = custom();
16662
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
16663
+ modelId: string(),
16664
+ settings: record(string(), unknown()).readonly()
16665
+ }))), method(object({ steps: record(string(), object({
16666
+ modelId: string(),
16667
+ settings: record(string(), unknown()).readonly()
16668
+ })) }), object({ success: literal(true) }), {
16669
+ kind: "mutation",
16670
+ auth: "admin"
16671
+ }), method(object({ nodeId: string() }), object({
16672
+ success: literal(true),
16673
+ clearedDevices: number()
16674
+ }), {
16675
+ kind: "mutation",
16676
+ auth: "admin"
16677
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
16678
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
16679
+ deviceKey: string(),
16778
16680
  /**
16779
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
16780
- * `zones` capability.
16781
- *
16782
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
16783
- * and no card can render — so every free-text search surface was structurally
16784
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
16785
- * just returned nothing. Resolving here rather than in each client keeps ONE
16786
- * derivation and costs the clients no extra call (the `zones` cap is
16787
- * per-device, so a client-side resolve would be a per-camera fan-out on a
16788
- * surface built to avoid exactly that).
16789
- *
16790
- * Resolved, never invented: a zone deleted since the track was written has no
16791
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
16792
- * two are not positionally aligned. Absent when the track visited no zone, or
16793
- * when the zone catalogue could not be read.
16681
+ * `failed` — the per-device restart budget is exhausted; no pool
16682
+ * will be spawned until an operator re-arms it or the runner
16683
+ * respawns. `backoff` — under budget, waiting out the backoff (or
16684
+ * a cached pool observed dead and not yet condemned).
16794
16685
  */
16795
- zoneNames: array(string()).readonly().optional(),
16796
- /** Deduplicated set of detector classes observed for this track over its
16797
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
16798
- * legacy rows written before class accumulation shipped. */
16799
- classes: array(string()).readonly().optional(),
16800
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
16801
- totalDistance: number(),
16802
- state: TrackStateSchema,
16803
- active: boolean(),
16804
- /** Deterministic key-event importance score in [0,1] (server-computed at
16805
- * track expiry, recomputed on late label). Absent on legacy rows written
16806
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
16807
- importance: number().optional(),
16808
- /** Id of the track's highest-confidence ObjectEvent (its representative
16809
- * "best" frame). Absent when the track produced no object events. */
16810
- bestEventId: string().optional(),
16811
- /** Tag of the importance sub-signal that dominated the score
16812
- * (identity|dwell|proximity|class|confidence|travel|zone). */
16813
- importanceReason: string().optional(),
16814
- /** Audio-classification labels heard on the camera during the track's
16815
- * life (score ≥ device `classificationMinScore`), aggregated per label.
16816
- * Absent on legacy rows / tracks with no confident audio. */
16817
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
16818
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
16819
- * Populated from the persisted envelope columns on historical reads;
16820
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
16821
- envelope: TrackEnvelopeSchema.optional(),
16686
+ state: _enum(["failed", "backoff"]),
16687
+ /** Epoch ms of the death that produced this state. */
16688
+ since: number(),
16689
+ /** Pool deaths inside the current window. */
16690
+ deaths: number(),
16691
+ /** The last death's message. */
16692
+ lastError: string()
16693
+ })).readonly() })), method(object({
16694
+ nodeId: string(),
16695
+ deviceKey: string()
16696
+ }), object({ rearmed: boolean() }), {
16697
+ kind: "mutation",
16698
+ auth: "admin"
16699
+ }), method(_void(), PipelineSchemaSchema), method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()), method(_void(), PipelineConfigBridge), method(_void(), ConfigUISchemaBridge), method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema), method(_void(), array(PipelineTemplateSchema$1).readonly()), method(object({
16700
+ name: string(),
16701
+ steps: array(PipelineTemplateStepSchema).readonly(),
16702
+ engine: PipelineEngineChoiceSchema
16703
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
16704
+ id: string(),
16705
+ name: string().optional(),
16706
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
16707
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
16708
+ addonId: string(),
16709
+ modelId: string(),
16710
+ format: ModelFormatSchema$1
16711
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
16712
+ addonId: string(),
16713
+ modelId: string(),
16714
+ format: ModelFormatSchema$1
16715
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
16716
+ engine: PipelineEngineChoiceSchema.optional(),
16717
+ steps: array(PipelineStepInputSchema).min(1),
16718
+ frame: FrameInputSchema.optional(),
16822
16719
  /**
16823
- * A face DETECTOR found a face on this track — nothing more. It says the
16824
- * detail plane produced a `face` detail; it does NOT say the face was
16825
- * embedded, matched, above `minFacePx`, or that the recognizer was even
16826
- * enabled. Set once and never cleared.
16827
- *
16828
- * **This exists so "face present but not recognised" is expressible.** A
16829
- * recognised identity lands in `subLabel` (attributed to the face chain via
16830
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
16831
- * and a track with no face at all were byte-identical on the wire and no
16832
- * surface could tell them apart. The read is `hasFace === true && subLabel
16833
- * === undefined`.
16834
- *
16835
- * **Absent ≠ false.** Every row written before the column existed omits it,
16836
- * and so does every server that predates the field — a consumer must test
16837
- * `=== true` and render nothing otherwise, never infer "no face".
16720
+ * Process-local lazy frame. Valid only when caller and provider resolve
16721
+ * in the same execution-group process; split/cross-node callers use
16722
+ * `frame`/`image` inline compatibility instead.
16838
16723
  */
16839
- hasFace: boolean().optional(),
16724
+ frameRef: FrameRefSchema.optional(),
16840
16725
  /**
16841
- * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
16842
- * face an operator could ASSIGN to an identity.
16843
- *
16844
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
16845
- * because the two disagree. `hasFace` is stamped at the TOP of the face
16846
- * branch, before every gate, and means no more than "a face detector produced
16847
- * a face detail". This one is stamped at the single moment the gallery row
16848
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
16849
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
16850
- * candidate gate, the imageless-track drop (no crop was ever captured) and
16851
- * the crop-store drop. Everything between the detector and that insert can
16852
- * legitimately refuse the face, so a flag written any earlier promises the
16853
- * operator something to assign and delivers nothing.
16854
- *
16855
- * **Independent of recognition.** A face collected but never auto-matched is
16856
- * still assignable — it is in fact the face an operator most wants to reach —
16857
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
16858
- * `subLabel`; this says only that the raw material exists.
16859
- *
16860
- * **Set once, never cleared.** A track that produced a gallery row produced
16861
- * one; deleting the row later is the gallery's business, not this flag's.
16862
- *
16863
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
16864
- * before the column omits it, and so does every server that predates the
16865
- * field. A consumer must test `=== true` and render nothing otherwise —
16866
- * never infer "no assignable face".
16726
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
16727
+ * the decoded pixels live in. One more member of the one-of
16728
+ * frame/frameHandle/image/imageBase64/referenceImage group.
16867
16729
  */
16868
- hasEmbeddedFace: boolean().optional(),
16730
+ frameHandle: FrameHandleSchema.optional(),
16731
+ imageBase64: string().optional(),
16869
16732
  /**
16870
- * This subject CONTAINS a folded rider — a person the rider-pairing step
16871
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
16872
- * so the passage is tracked once and as a VEHICLE.
16873
- *
16874
- * It exists because the fold's record was dishonest. D34 and the code both
16875
- * said "the person is not lost — it is reported so both entities stay on the
16876
- * record"; in fact the pair went into a per-processor RAM field behind an
16877
- * accessor nobody called, and every durable surface said `vehicle`, full
16878
- * stop. This is the composition note that makes the row true.
16879
- *
16880
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
16881
- * person" is not an answer to "what is this" — both label tiers would refuse
16882
- * a macro token anyway (D89), and correctly. Nothing here changes what the
16883
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
16884
- * and a `person` rule still does not fire for someone cycling past.
16885
- *
16886
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
16887
- * the column, and every hub that predates the field, omits it. Test
16888
- * `=== true` and render nothing otherwise — never infer "no rider".
16733
+ * Binary JPEG bytes — preferred over `imageBase64` on internal
16734
+ * hops (hub → forked worker via Moleculer MsgPack) because it
16735
+ * skips the 33% base64 overhead + the per-call base64 decode on
16736
+ * the detection-pipeline worker. Callers can pass either; exactly
16737
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
16889
16738
  */
16890
- hasRider: boolean().optional(),
16891
- ...TrackFlagFields,
16892
- ...TrackRetrainFields
16893
- });
16894
- var BaseEventFields = {
16895
- id: string(),
16896
- deviceId: number(),
16897
- timestamp: number()
16898
- };
16899
- var MotionEventSchema = object({
16900
- ...BaseEventFields,
16901
- kind: literal("motion"),
16902
- regionCount: number(),
16903
- /** Heavy JSON array — omitted in slim projection. */
16904
- regions: array(object({
16905
- bbox: BoundingBoxSchema,
16906
- pixelCount: number(),
16907
- intensity: number()
16908
- })).readonly().optional(),
16909
- /** Omitted in slim projection. */
16910
- frameWidth: number().optional(),
16911
- /** Omitted in slim projection. */
16912
- frameHeight: number().optional(),
16913
- /** Populated by B5 (recording playback URL for this event). */
16914
- mediaUrl: string().optional()
16915
- });
16739
+ image: _instanceof(Uint8Array).optional(),
16740
+ referenceImage: string().optional(),
16741
+ deviceId: number().optional(),
16742
+ sessionId: string().optional(),
16743
+ /**
16744
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
16745
+ * reference-image, and detail-subtree calls. 'frame' is the live
16746
+ * per-frame dispatch: ONLY root-plane steps run; crop children
16747
+ * (inputClasses ≠ null) are skipped and served per-track via
16748
+ * pipelineRunner.runDetailSubtree (two-plane design).
16749
+ */
16750
+ plane: _enum(["full", "frame"]).optional(),
16751
+ /**
16752
+ * Inference-device selector (Phase 2 multi-device). Format
16753
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
16754
+ * Omitted ⇒ the runner's default device (current single-engine
16755
+ * behaviour). Selects WHICH device pool of the node runs the call.
16756
+ */
16757
+ deviceKey: string().optional(),
16758
+ /**
16759
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
16760
+ * when the parent crop was resolved from the frame's retained NATIVE
16761
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
16762
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
16763
+ * resolution from that surface — the SAME quality path faces already
16764
+ * had — instead of the downscaled parent tile. `handle` keys the native
16765
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
16766
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
16767
+ * the executor's crop-normalized child ROI back into frame-normalized
16768
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
16769
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
16770
+ * (today's behaviour on the fallback path).
16771
+ */
16772
+ nativeCropRef: NativeCropRefSchema.optional()
16773
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
16774
+ engine: PipelineEngineChoiceSchema.optional(),
16775
+ steps: array(PipelineStepInputSchema).min(1),
16776
+ frames: array(FrameInputSchema).min(1).max(255),
16777
+ deviceId: number().optional(),
16778
+ sessionId: string().optional(),
16779
+ /**
16780
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
16781
+ * the batch to the Python pool's bench preprocess cache
16782
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
16783
+ * preprocessed ONCE and every later inference is a pure-inference cache
16784
+ * hit — the sustained-throughput run measures inference, not
16785
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
16786
+ * full preprocess every call, correct). Fresh per sustained run;
16787
+ * released via `uncacheFrame`.
16788
+ */
16789
+ frameId: number().int().nonnegative().optional(),
16790
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
16791
+ deviceKey: string().optional()
16792
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
16793
+ data: _instanceof(Uint8Array),
16794
+ width: number().int().positive(),
16795
+ height: number().int().positive(),
16796
+ format: _enum([
16797
+ "rgb",
16798
+ "bgr",
16799
+ "gray"
16800
+ ])
16801
+ }), object({
16802
+ frameId: number(),
16803
+ width: number(),
16804
+ height: number()
16805
+ }), { kind: "mutation" }), method(object({
16806
+ stepId: string(),
16807
+ frameId: number().int()
16808
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
16809
+ batchMode: string(),
16810
+ windowMs: number(),
16811
+ maxBatchSize: number(),
16812
+ concurrency: number()
16813
+ })), method(_void(), array(object({
16814
+ engineKey: string(),
16815
+ engine: PipelineEngineChoiceSchema,
16816
+ modelsLoaded: array(string()).readonly(),
16817
+ inUseByCameras: array(number()).readonly(),
16818
+ /**
16819
+ * Origin of this resident factory.
16820
+ * - `runtime` — main camera-serving engine (no idle TTL).
16821
+ * - `warm-override` — benchmark/test override held in the warm
16822
+ * cache; auto-disposed after the idle TTL.
16823
+ * - `device-pool` — a concurrent per-device pool (Phase 2
16824
+ * multi-device, keyed by `deviceKey`) resolved
16825
+ * via `resolveDeviceFactory`. Runs alongside the
16826
+ * `runtime` engine on a DIFFERENT accelerator
16827
+ * (NPU / iGPU / Coral) — this is how the
16828
+ * Engines tab shows all pools running at once.
16829
+ */
16830
+ kind: _enum([
16831
+ "runtime",
16832
+ "warm-override",
16833
+ "device-pool"
16834
+ ]),
16835
+ /** Native pid of the underlying Python pool (null when no pool). */
16836
+ poolPid: number().nullable(),
16837
+ /** ms since this factory was last used (null when not warm-tracked). */
16838
+ idleMs: number().nullable(),
16839
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
16840
+ idleTtlMs: number().nullable()
16841
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
16842
+ kind: "mutation",
16843
+ auth: "admin"
16844
+ }), method(object({
16845
+ engine: PipelineEngineChoiceSchema,
16846
+ force: boolean().optional()
16847
+ }), object({
16848
+ success: boolean(),
16849
+ reason: string().optional()
16850
+ }), {
16851
+ kind: "mutation",
16852
+ auth: "admin"
16853
+ }), method(_void(), array(ReferenceImageEntrySchema).readonly()), method(object({ filename: string() }), ReferenceImageBodySchema.nullable()), method(_void(), array(ReferenceAudioEntrySchema).readonly()), method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()), method(_void(), AudioCapabilitiesSchema), method(object({
16854
+ addonId: string(),
16855
+ modelId: string(),
16856
+ filename: string().optional(),
16857
+ settings: record(string(), unknown()).optional()
16858
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
16916
16859
  /**
16917
- * Which detection SOURCE produced an object event. `pipeline` = the ML
16918
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
16919
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
16920
- * tracking, per-kind persistence) but stay distinguishable so consumers
16921
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
16922
- * Absent on legacy rows ⇒ treat as `pipeline`.
16860
+ * Per-stage gating mode applied to the zones a rule references.
16861
+ *
16862
+ * - `include`: the rule contributes to a **whitelist** for its stage.
16863
+ * When at least one `include` rule fires for a stage, only entities
16864
+ * inside one of those zones pass that stage.
16865
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
16866
+ * Entities inside one of those zones are dropped at that stage.
16867
+ *
16868
+ * `monitor`-style observation (count without filtering) is not a rule
16869
+ * mode — zones without any matching rule are observed naturally by
16870
+ * `zone-analytics` (live snapshot + history), so an "I just want to
16871
+ * count, not filter" use case needs no rule at all.
16923
16872
  */
16924
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
16873
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
16925
16874
  /**
16926
- * The confirmed zone crossing that produced an object event. Present ONLY on
16927
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
16928
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
16929
- * appearance event carry none, so a rule asking for a direction fails closed
16930
- * on them.
16875
+ * Per-consumer rule that references existing zones (geometry) and
16876
+ * defines how a specific pipeline stage should treat them. Each
16877
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
16878
+ * settings:
16931
16879
  *
16932
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
16933
- * into its own event, so a frame in which a track enters A while leaving B
16934
- * produces two events with two directions — never one ambiguous row.
16880
+ * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
16881
+ * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
16882
+ * - future: notification rules, audio gating, etc.
16935
16883
  *
16936
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
16937
- * membership the box has NOW, and by definition it no longer contains the zone
16938
- * that was just left. Without the id here, a zone-scoped rule could never match
16939
- * the exit it asked for.
16884
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
16885
+ * express "ignore motion in ALL of {garden, street}" with a single
16886
+ * rule. `classFilter` narrows the rule to specific object classes —
16887
+ * "drop person detections in the street, but keep cars" is one
16888
+ * `exclude` rule with `classFilter: ['person']`.
16889
+ *
16890
+ * `enabled` is a soft toggle — the operator can keep the rule
16891
+ * configured but inert without deleting it.
16940
16892
  */
16941
- var ZoneCrossingSchema = object({
16942
- direction: _enum(["enter", "exit"]),
16943
- /** Admin zone id crossed. */
16944
- zoneId: string(),
16945
- /** Zone display name at crossing time (falls back to the id). */
16946
- zoneName: string().optional()
16947
- });
16948
- var ObjectEventSchema = object({
16949
- ...BaseEventFields,
16950
- kind: literal("object"),
16951
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
16952
- source: DetectionSourceSchema.optional(),
16893
+ var ZoneRuleSchema = object({
16894
+ /** Stable rule id — survives edits, used by the UI for diffing. */
16895
+ id: string(),
16896
+ /** Optional human-readable label rendered in the rule editor. */
16897
+ name: string().optional(),
16898
+ /** Zones this rule targets. The rule's `mode` applies to ALL
16899
+ * listed zones (OR-set: a detection in any one of them counts).
16900
+ * At least one zone id required — a rule with no targets is a
16901
+ * configuration mistake and the form validator rejects it. */
16902
+ zoneIds: array(string()).min(1).readonly(),
16903
+ mode: ZoneRuleModeEnum,
16953
16904
  /**
16954
- * Inference-frame id shared by every object event emitted from the SAME frame
16955
- * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
16956
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
16957
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
16958
- * Optional for backward-compat with pre-existing rows / the slim projection
16959
- * includes it (it is light). Absent on rows written before this field.
16905
+ * Class names this rule applies to. Empty / undefined ⇒ rule
16906
+ * applies to every class. Class strings match the `macroClass`
16907
+ * field on detections (e.g. `person`, `car`, `dog`).
16960
16908
  */
16961
- frameId: string().optional(),
16962
- /** Omitted in slim projection. */
16963
- trackId: string().optional(),
16964
- className: string(),
16965
- ...TieredLabelFields,
16966
- /** Omitted in slim projection. */
16967
- confidence: number().optional(),
16968
- /** Heavy JSON — omitted in slim projection. */
16969
- bbox: BoundingBoxSchema.optional(),
16970
- /** Heavy JSON — omitted in slim projection. */
16971
- zones: array(string()).readonly().optional(),
16972
- /** Omitted in slim projection. */
16973
- state: TrackStateSchema.optional(),
16909
+ classFilter: array(string()).readonly().optional(),
16974
16910
  /**
16975
- * The zone crossing this event IS, when it is one. Absent on every other
16976
- * event kind (movement state, appearance, package) — see
16977
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
16911
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
16912
+ * required to consider an entity "in the zone". Defaults to the
16913
+ * consumer's stage default when omitted. Kept for back-compat with
16914
+ * existing per-rule overrides; new operators pick the value via
16915
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
16916
+ * set, the lower-level engine reads it as a 0–1 fraction.
16978
16917
  */
16979
- zoneCrossing: ZoneCrossingSchema.optional(),
16980
- /** Detection-frame dimensions in pixels — let consumers normalize the
16981
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
16982
- frameWidth: number().optional(),
16983
- frameHeight: number().optional(),
16984
- /** MediaStore key for the crop attached to this event (if any). */
16985
- mediaKey: string().optional(),
16986
- /** Design B: MediaStore key of the track's native-resolution key frame (the
16987
- * best-detection full frame). Resolve via the event-media data-plane
16988
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
16989
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
16990
- * sources — consumers fall back to `mediaKey` (the tight crop). */
16991
- keyFrameMediaKey: string().optional(),
16992
- /** Populated by B5 (recording playback URL for this event). */
16993
- mediaUrl: string().optional(),
16994
- /** The parent track's key-event importance [0,1], propagated to every object
16995
- * event of the track (so an event row can be sorted by importance without a
16996
- * track join). Absent on legacy rows / before the track was scored. */
16997
- importance: number().optional()
16998
- });
16999
- var AudioEventSchema = object({
17000
- ...BaseEventFields,
17001
- kind: literal("audio"),
17002
- rms: number(),
17003
- dbfs: number(),
17004
- classification: object({
17005
- className: string(),
17006
- originalClass: string().optional(),
17007
- score: number()
17008
- }).optional(),
17009
- /** Populated by B5 (recording playback URL for this event). */
17010
- mediaUrl: string().optional()
16918
+ overlapThreshold: number().min(0).max(1).optional(),
16919
+ /**
16920
+ * Operator-friendly version of `overlapThreshold` — the percentage
16921
+ * of the detection's bbox that must lie inside the zone for the
16922
+ * rule to match. Documented default is 85%; the engine substitutes
16923
+ * that when the field is omitted (kept optional so existing rules
16924
+ * stored without it stay valid).
16925
+ *
16926
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
16927
+ * rule, the engine prefers `bboxInclusionPct` because it's the
16928
+ * field exposed in the UI. Internally both feed the same gate.
16929
+ */
16930
+ bboxInclusionPct: number().min(0).max(100).optional(),
16931
+ /**
16932
+ * When `true` and a detection has a segmentation mask, use the
16933
+ * mask for overlap instead of the bbox. Detection-stage only;
16934
+ * motion rules ignore this field.
16935
+ */
16936
+ preferMask: boolean().optional(),
16937
+ /**
16938
+ * Soft-toggle: `false` disables the rule without deleting it.
16939
+ * Defaults to `true` so operators creating a rule via the UI
16940
+ * see it active immediately.
16941
+ */
16942
+ enabled: boolean().default(true)
17011
16943
  });
17012
- var MediaFileKindEnum = _enum([
17013
- "crop",
17014
- "thumbnail",
17015
- "snapshot",
17016
- "firstFrame",
17017
- "lastFrame",
17018
- "fullFrame",
17019
- "fullFrameBoxed",
17020
- "faceCrop",
17021
- "plateCrop",
17022
- "keyFrame",
17023
- "keyFrameSmall",
17024
- "thumbnailSmall"
17025
- ]);
17026
- var MediaFileSchema = object({
17027
- key: string(),
17028
- kind: MediaFileKindEnum,
17029
- base64: string(),
17030
- sizeBytes: number(),
17031
- timestamp: number()
16944
+ array(ZoneRuleSchema).readonly();
16945
+ /**
16946
+ * Zone — pure geometry + identity. NO filtering behaviour.
16947
+ *
16948
+ * Zones describe **where** in the frame the operator wants to flag
16949
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
16950
+ * each pipeline stage uses them. Splitting the two means a single
16951
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
16952
+ * a detection-include rule on `['car']`, and an occupancy aggregate
16953
+ * — without three duplicated polygons.
16954
+ *
16955
+ * Owned by the orchestrator addon (provider) and mirrored into the
16956
+ * `zones` device-state slice on every mutation. Consumers
16957
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
16958
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
16959
+ * mirror with `onChanged`).
16960
+ *
16961
+ * Coordinates are normalised fractions of the frame (0–1) so zones
16962
+ * survive resolution changes and stream profile switches.
16963
+ *
16964
+ * `kind` discriminates between full polygons (closed regions used
16965
+ * for intrusion / occupancy filters) and tripwires (open 2-point
16966
+ * line segments used for cross events). Onboard / firmware-reported
16967
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
16968
+ * task list.
16969
+ */
16970
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
16971
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
16972
+ var PolygonPointSchema = object({
16973
+ x: number(),
16974
+ y: number()
16975
+ });
16976
+ /** A camera detection zone — pure geometry/identity. */
16977
+ var ZoneSchema = object({
16978
+ id: string(),
16979
+ name: string(),
16980
+ kind: ZoneKindEnum.default("polygon"),
16981
+ /** Polygon vertices, fraction of frame (0–1). */
16982
+ polygon: array(PolygonPointSchema).readonly(),
16983
+ /** Visual color for UI rendering. */
16984
+ color: string().default("#3b82f6")
17032
16985
  });
17033
16986
  /**
17034
- * One media row WITHOUT its bytes.
16987
+ * Zones capability — per-camera CRUD over polygon detection zones.
17035
16988
  *
17036
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17037
- * 140 s track), and a client that renders tiles from the media data plane needs
17038
- * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
17039
- * with an immutable cache, instead of all at once inside a tRPC response that
17040
- * blocks the whole view.
16989
+ * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
16990
+ * to per-device settings and mirrors into the `zones` device-state
16991
+ * slice on every mutation, so downstream consumers can subscribe via
16992
+ * `dev.state.zones.onChanged`.
17041
16993
  *
17042
- * `sizeBytes` is carried because it is what lets a client decide between the
17043
- * stored blob and a `?variant=thumb` rendering without fetching either.
16994
+ * The cap surface only handles geometry + identity; filtering
16995
+ * behaviour (per-class, include/exclude, threshold) lives in the
16996
+ * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
16997
+ * `capabilities/schemas/zone-rule.js`.
17044
16998
  */
17045
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
16999
+ var zonesCapability = {
17000
+ name: "zones",
17001
+ scope: "device",
17002
+ mode: "singleton",
17003
+ deviceTypes: [DeviceType.Camera],
17004
+ methods: {
17005
+ listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
17006
+ addZone: method(object({
17007
+ deviceId: number(),
17008
+ zone: ZoneSchema
17009
+ }), _void(), {
17010
+ kind: "mutation",
17011
+ auth: "admin"
17012
+ }),
17013
+ removeZone: method(object({
17014
+ deviceId: number(),
17015
+ zoneId: string()
17016
+ }), _void(), {
17017
+ kind: "mutation",
17018
+ auth: "admin"
17019
+ }),
17020
+ updateZone: method(object({
17021
+ deviceId: number(),
17022
+ zone: ZoneSchema
17023
+ }), _void(), {
17024
+ kind: "mutation",
17025
+ auth: "admin"
17026
+ })
17027
+ },
17028
+ /**
17029
+ * Runtime-state slice — the live zone catalogue mirrored by the
17030
+ * orchestrator on every CRUD mutation. Consumers read via
17031
+ * `device.state.zones.value` / `.watch(...)` without round-tripping
17032
+ * the cap, and the codegen DeviceProxy auto-wires the reactive
17033
+ * handle. Slice shape is `{ zones: Zone[] }` so future extensions
17034
+ * (e.g. zone groupings) can sit alongside the polygon list.
17035
+ */
17036
+ runtimeState: object({ zones: array(ZoneSchema).readonly() }),
17037
+ /**
17038
+ * Runtime-state durability: **restored** — written only on operator mutation, so a camera that never had one has nothing to re-derive from. This is the slice `zone-mirror-hydration.ts` exists to paper over.
17039
+ *
17040
+ * See `RuntimeStateDurability`. Enforced by
17041
+ * `scripts/check-runtime-state-durability.ts`.
17042
+ */
17043
+ durability: "restored"
17044
+ };
17046
17045
  /**
17047
- * The MACRO tier of an annotation — a CLOSED set.
17046
+ * pipeline-analytics — device-scoped wrapper cap. Refines raw
17047
+ * per-frame detections emitted by the pipeline runner into tracked
17048
+ * objects, per-kind event collections (motion / object / audio), and
17049
+ * persisted media. Owns the post-detection domain end-to-end:
17048
17050
  *
17049
- * This is what the exported detector predicts, so a typo here is a new class
17050
- * with one example in it. `label` and `subLabel` are open strings by contrast:
17051
- * the whole point of the page is teaching the model things it does not know
17052
- * yet, and constraining that vocabulary would make it useless.
17051
+ * runner emits PipelineInferenceResult
17052
+ * ↓ (event bus)
17053
+ * pipeline-analytics subscriber
17054
+ * ↓ SORT tracker + zone engine + state analyzer + event emitter
17055
+ * → three DB collections (one per kind), one FS media tree, one
17056
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
17057
+ * DetectionEvent on bus)
17053
17058
  *
17054
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
17055
- * `subLabel` is one of these values, in any casing, because once `person`
17056
- * exists in both tiers "every person box" stops being answerable without
17057
- * knowing every string anyone ever typed — and the damage is retroactive.
17059
+ * Pure subscriber model. No `processFrame` cap method — the runner
17060
+ * already publishes the raw frame on the bus. The cap surface is
17061
+ * only QUERIES + per-device settings, bound on/off via
17062
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
17063
+ * every camera with a detection pipeline wants its raw detections
17064
+ * refined; operators opt out per-device via BindingsTab when needed.
17065
+ *
17066
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
17067
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
17058
17068
  */
17059
- var RetrainMacroClassSchema = _enum([
17069
+ var TrackStateSchema = _enum([
17070
+ "new",
17071
+ "entered",
17072
+ "left",
17073
+ "moving",
17074
+ "idle"
17075
+ ]);
17076
+ var EventKindSchema = _enum([
17077
+ "motion",
17078
+ "object",
17079
+ "audio"
17080
+ ]);
17081
+ /**
17082
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
17083
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
17084
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
17085
+ */
17086
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
17087
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
17088
+ var EventKindIconSchema = _enum([
17089
+ "motion",
17090
+ "audio",
17060
17091
  "person",
17061
17092
  "vehicle",
17062
17093
  "animal",
17094
+ "door",
17095
+ "pir",
17096
+ "smoke",
17097
+ "water",
17098
+ "button",
17063
17099
  "package",
17064
- "face",
17065
- "plate"
17100
+ "generic"
17066
17101
  ]);
17067
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17068
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17069
- /** Did a human draw this box, or did the assist propose it? */
17070
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17071
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17072
- var RetrainBboxSchema = object({
17073
- x: number(),
17074
- y: number(),
17075
- w: number(),
17076
- h: number()
17102
+ var EventKindCategorySchema = _enum([
17103
+ "motion",
17104
+ "audio",
17105
+ "detection",
17106
+ "sensor",
17107
+ "control",
17108
+ "custom",
17109
+ "package"
17110
+ ]);
17111
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
17112
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
17113
+ var EventKindDescriptorSchema = object({
17114
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
17115
+ kind: string(),
17116
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
17117
+ labelKey: string(),
17118
+ /** English fallback label (kept for clients that don't translate). */
17119
+ label: string(),
17120
+ /** Hex color for timeline/legend rendering. */
17121
+ color: string(),
17122
+ /** Dictionary id → lucide component on the UI side. */
17123
+ iconId: string(),
17124
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
17125
+ icon: EventKindIconSchema,
17126
+ category: EventKindCategorySchema,
17127
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
17128
+ parentKind: string().nullable(),
17129
+ /** Derived from `parentKind`, explicit for the client tree. */
17130
+ level: EventKindLevelSchema,
17131
+ /** Which cap + device contributes this kind. For built-ins the camera
17132
+ * itself; for sensor kinds the LINKED source device. */
17133
+ source: object({
17134
+ capName: string(),
17135
+ deviceId: number()
17136
+ })
17077
17137
  });
17078
- /**
17079
- * One annotated subject.
17080
- *
17081
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17082
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17083
- * derived from it at export and never stored — storing them is how one feature
17084
- * space ends up holding two crops of the same subject (D52).
17085
- */
17086
- var RetrainAnnotationSchema = object({
17087
- id: string(),
17088
- trackId: string(),
17138
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
17139
+ var EventKindsForDeviceSchema = object({
17089
17140
  deviceId: number(),
17090
- /** The COPY in retrain storage — never the source track's media key. */
17091
- mediaKey: string(),
17092
- bbox: RetrainBboxSchema,
17093
- macroClass: RetrainMacroClassSchema,
17094
- label: string().optional(),
17095
- subLabel: string().optional(),
17096
- kind: RetrainAnnotationKindSchema,
17097
- source: RetrainAnnotationSourceSchema,
17098
- /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
17099
- assistModelId: string().optional(),
17100
- assistScore: number().optional(),
17101
- exportedInBatch: string().optional(),
17102
- createdAt: number()
17103
- });
17104
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17105
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17106
- id: true,
17107
- trackId: true,
17108
- deviceId: true,
17109
- mediaKey: true,
17110
- createdAt: true,
17111
- exportedInBatch: true
17141
+ kinds: array(EventKindDescriptorSchema).readonly()
17112
17142
  });
17113
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17114
- var RetrainTrackSchema = object({
17115
- trackId: string(),
17143
+ var SensorEventSchema = object({
17144
+ id: string(),
17145
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
17146
+ * yields N rows, one per camera). */
17116
17147
  deviceId: number(),
17117
- className: string(),
17118
- label: string().optional(),
17119
- firstSeen: number(),
17120
- lastSeen: number(),
17121
- /** How many frames the dataset already holds from this track. */
17122
- frameCount: number().int(),
17123
- /** How many subjects have been annotated on those frames. `0` with
17124
- * `frameCount: 0` is exactly "staging, still to work". */
17125
- annotationCount: number().int()
17148
+ /** The linked sensor device whose state changed. */
17149
+ sourceDeviceId: number(),
17150
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
17151
+ kind: string(),
17152
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
17153
+ value: record(string(), unknown()).nullable(),
17154
+ timestamp: number()
17126
17155
  });
17127
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
17128
- var RetrainFrameCandidateSchema = object({
17129
- mediaKey: string(),
17130
- kind: MediaFileKindEnum,
17156
+ var TrackPositionSchema = object({
17157
+ x: number(),
17158
+ y: number(),
17131
17159
  timestamp: number(),
17132
- sizeBytes: number().int(),
17133
- /** A copy of this original already exists — selecting it is free and cannot
17134
- * fail, whatever became of the original. */
17135
- copied: boolean()
17136
- });
17137
- /** A frame the dataset OWNS: bytes copied at selection time. */
17138
- var RetrainFrameSchema = object({
17139
- frameId: string(),
17140
- deviceId: number(),
17141
- trackId: string(),
17142
- /** Provenance only. It may already point at nothing — that is expected. */
17143
- sourceMediaKey: string(),
17144
- sourceKind: MediaFileKindEnum,
17145
- sizeBytes: number().int(),
17146
- width: number().int(),
17147
- height: number().int(),
17148
- copiedAt: number()
17149
- });
17150
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17151
- var RetrainCopyRefusalSchema = _enum([
17152
- "source-missing",
17153
- "unreadable-image",
17154
- "write-failed"
17155
- ]);
17156
- var RetrainFrameSelectionSchema = object({
17157
- copied: array(RetrainFrameSchema).readonly(),
17158
- refused: array(object({
17159
- sourceMediaKey: string(),
17160
- reason: RetrainCopyRefusalSchema
17161
- })).readonly()
17160
+ bbox: BoundingBoxSchema
17162
17161
  });
17163
- var RetrainFrameListSchema = object({
17164
- candidates: array(RetrainFrameCandidateSchema).readonly(),
17165
- copies: array(RetrainFrameSchema).readonly(),
17166
- /** What the page pre-selects — the native key frame when one survives. */
17167
- autoPickMediaKey: string().optional()
17162
+ var TrackSnapshotSchema = object({
17163
+ timestamp: number(),
17164
+ position: TrackPositionSchema,
17165
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
17166
+ mediaKey: string()
17168
17167
  });
17169
- /** What the operator asked the assist to look for. */
17170
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17171
- kind: literal("package"),
17172
- zone: RetrainBboxSchema.optional()
17173
- }), object({
17174
- kind: literal("objects"),
17175
- modelId: string(),
17176
- minScore: number().optional()
17177
- })]);
17178
17168
  /**
17179
- * The assist's answer — a discriminated union, because "the model saw nothing"
17180
- * and "this node cannot run that model" lead to different next moves and a
17181
- * nullable result cannot tell them apart.
17169
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
17170
+ * divided by the track's detection-frame dims), computed at persist time.
17171
+ * Absent when the frame dims were unknown when the track was persisted
17172
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
17182
17173
  */
17183
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17184
- kind: literal("proposed"),
17185
- modelId: string(),
17186
- stepId: string(),
17187
- minScore: number(),
17188
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17189
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
17190
- /** Returned by the runner but removed by the threshold. */
17191
- belowThreshold: number().int()
17192
- }), object({
17193
- kind: literal("refused"),
17194
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17195
- reason: string(),
17196
- detail: string().optional()
17197
- })]);
17198
- /** The outcome of a lifecycle move owned by the retrain page. */
17199
- var RetrainTransitionResultSchema = object({
17200
- trackId: string(),
17201
- /** Where the track ended up, whatever happened. */
17202
- retrainStatus: RetrainStatusSchema,
17203
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17204
- changed: boolean(),
17205
- reason: _enum([
17206
- "unknown-track",
17207
- "no-frames-copied",
17208
- "not-staging",
17209
- "not-trained",
17210
- "unchanged"
17211
- ]).optional()
17212
- });
17213
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17214
- var MAX_EVENT_QUERY_LIMIT = 5e3;
17215
- var DeviceEventQueryInput = object({
17216
- deviceId: number(),
17217
- since: number().optional(),
17218
- until: number().optional(),
17219
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17220
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17221
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17222
- * exact behaviour. Callers may omit this field — the store defaults to
17223
- * `full` when not provided. */
17224
- projection: _enum(["full", "slim"]).optional()
17225
- });
17226
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17227
- var RecentTracksQueryInput = object({
17228
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17229
- deviceIds: array(number()),
17230
- /** Window lower bound on `lastSeen` (inclusive). */
17231
- since: number().optional(),
17232
- /** Window upper bound on `lastSeen` (inclusive). */
17233
- until: number().optional(),
17234
- /** Page size. Default 200, max 1000. */
17235
- limit: number().int().min(1).max(1e3).default(200),
17236
- /** Opaque continuation cursor from a previous page's `nextCursor`.
17237
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
17238
- cursor: string().optional(),
17239
- /** See {@link TrackProjectionSchema}. Default `full`. */
17240
- projection: TrackProjectionSchema.optional(),
17241
- /** Include stationary-promoted rows (parked objects). Default false: the
17242
- * feed lists passages; parking records live on the stationary registry. */
17243
- includeStationary: boolean().optional()
17244
- });
17245
- var RecentTracksPageSchema = object({
17246
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17247
- tracks: array(TrackSchema).readonly(),
17248
- /** Cursor for the next page, or null when this page is the last. */
17249
- nextCursor: string().nullable()
17250
- });
17251
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
17252
- var LIST_GROUPS_MAX_LIMIT = 100;
17253
- var AnalyticsGroupRecordSchema = object({
17254
- id: string(),
17255
- deviceId: number().int(),
17256
- openedAt: number().int(),
17257
- closedAt: number().int(),
17258
- timestamp: number().int(),
17259
- memberCount: number().int(),
17260
- memberTrackIds: array(string()).readonly(),
17261
- className: string(),
17262
- classes: array(string()).readonly(),
17263
- /** Relative event-media path, or null when the group has no picture yet. */
17264
- mediaUrl: string().nullable(),
17265
- singleton: boolean()
17174
+ var TrackEnvelopeSchema = object({
17175
+ minX: number(),
17176
+ minY: number(),
17177
+ maxX: number(),
17178
+ maxY: number()
17266
17179
  });
17267
- var AnalyticsGroupMemberSchema = object({
17268
- trackId: string(),
17269
- deviceId: number().int(),
17270
- className: string(),
17271
- firstSeen: number().int(),
17272
- lastSeen: number().int(),
17273
- mediaUrl: string().nullable()
17274
- });
17275
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17276
- var ListGroupsQueryInput = object({
17277
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17278
- deviceIds: array(number()),
17279
- /** Window lower bound on `closedAt` (inclusive). */
17280
- since: number().optional(),
17281
- /** Window upper bound on `openedAt` (inclusive). */
17282
- until: number().optional(),
17283
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17284
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
17285
- cursor: string().optional()
17286
- });
17287
- var ListGroupsPageSchema = object({
17288
- groups: array(AnalyticsGroupRecordSchema).readonly(),
17289
- nextCursor: string().nullable()
17290
- });
17291
- var KeyEventQueryInput = object({
17292
- deviceId: number(),
17293
- /** Window lower bound (track firstSeen ≥ since). */
17294
- since: number(),
17295
- /** Window upper bound (track firstSeen ≤ until). */
17296
- until: number(),
17297
- limit: number().int().min(1).max(200).default(50),
17298
- /** Drop tracks scoring below this importance. */
17299
- minImportance: number().min(0).max(1).optional(),
17300
- /** Restrict to a single class (e.g. 'person'). */
17301
- classFilter: string().optional()
17302
- });
17303
- var KeyEventSchema = object({
17304
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
17305
- id: string(),
17306
- trackId: string(),
17307
- /** Track start time (firstSeen). */
17308
- timestamp: number(),
17309
- className: string(),
17310
- ...TieredLabelFields,
17311
- importance: number(),
17312
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
17313
- bestEventId: string(),
17314
- /** Track lifetime in ms (lastSeen - firstSeen). */
17315
- windowMs: number().optional(),
17316
- ...TrackFlagFields,
17317
- ...TrackRetrainFields
17318
- });
17319
- object({
17320
- trackId: string(),
17321
- className: string(),
17322
- confidence: number(),
17323
- bbox: BoundingBoxSchema,
17324
- zones: array(string()).readonly(),
17325
- state: TrackStateSchema
17326
- });
17327
- var OverlayDetectionSchema = looseObject({
17328
- id: string(),
17329
- kind: _enum(["first-level", "detail"]),
17330
- macroClass: string(),
17331
- score: number(),
17332
- bbox: object({
17333
- x: number(),
17334
- y: number(),
17335
- width: number(),
17336
- height: number()
17337
- }),
17338
- labels: array(looseObject({
17339
- label: string(),
17340
- score: number()
17341
- })).readonly(),
17342
- parentId: string().optional()
17343
- });
17344
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
17345
- var SearchObjectEventsInput = object({
17346
- text: string(),
17347
- deviceId: number().optional(),
17348
- since: number().optional(),
17349
- until: number().optional(),
17350
- classFilter: string().optional(),
17351
- limit: number().default(50),
17352
- minScore: number().min(0).max(1).default(.2)
17353
- });
17354
- var TrackCascadeCountsSchema = object({
17355
- /** Persisted track roots deleted (authoritative). */
17356
- tracks: number().int(),
17357
- /** Object events removed with their tracks (best-effort; see note above). */
17358
- events: number().int(),
17359
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
17360
- media: number().int(),
17361
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
17362
- faces: number().int(),
17363
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
17364
- plates: number().int(),
17365
- /** Per-track CLIP search vectors removed (best-effort). */
17366
- embeddings: number().int(),
17367
- /** Group membership + group rows removed with their last member (best-effort). */
17368
- groups: number().int()
17369
- });
17370
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
17371
- var DiskReconcileCountsSchema = object({
17372
- mediaDropped: number().int(),
17373
- tracks: number().int(),
17374
- events: number().int()
17375
- });
17376
- /** Event-store footprint for one camera. */
17377
- var EventStoreDeviceFootprintSchema = object({
17378
- deviceId: number(),
17379
- /** Persisted event rows (motion + object + audio) for the camera. */
17380
- rows: number().int(),
17381
- /** Event-owned media bytes on disk for the camera. */
17382
- bytes: number().int()
17383
- });
17384
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
17385
- var EventStoreFootprintSchema = object({
17386
- totalRows: number().int(),
17387
- totalBytes: number().int(),
17388
- devices: array(EventStoreDeviceFootprintSchema).readonly()
17389
- });
17390
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
17391
- var EventPruneCountsSchema = object({
17392
- motion: number().int(),
17393
- object: number().int(),
17394
- audio: number().int()
17180
+ /**
17181
+ * Row projection for track list queries. `full` (default) returns the
17182
+ * complete Track including the frame-rate `positions[]` history and the
17183
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
17184
+ * keeps every scalar the list surfaces actually render (ids, class(es),
17185
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
17186
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
17187
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
17188
+ * `getTrack`. Mirrors the event-store `projection` convention
17189
+ * (`getObjectEvents` et al.).
17190
+ */
17191
+ var TrackProjectionSchema = _enum(["full", "slim"]);
17192
+ /**
17193
+ * One audio-classification label heard on the track's camera while the
17194
+ * track was alive, aggregated per label. An "episode" is one persisted
17195
+ * audio event (the confident-classification path: score ≥ the device's
17196
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
17197
+ * one 32 ms inference chunk, so counts stay human-scaled.
17198
+ */
17199
+ var TrackAudioLabelSchema = object({
17200
+ label: string(),
17201
+ /** Highest classification score observed across the label's episodes. */
17202
+ peakScore: number(),
17203
+ /** Number of coalesced audio-event episodes carrying this label. */
17204
+ count: number(),
17205
+ firstAt: number(),
17206
+ lastAt: number()
17395
17207
  });
17396
17208
  /**
17397
- * Re-embed stored tracks from their key frames.
17209
+ * How a track was produced. `pipeline` (default / absent) = the spatial
17210
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17211
+ * no positions, a single snapshot, and no bbox trajectory at all:
17398
17212
  *
17399
- * The reason this is an operator-callable method and not a migration script:
17400
- * every knob that decides what a vector MEANS — encoder model, crop margin,
17401
- * squaring — is only changeable if the existing vectors can be regenerated.
17402
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
17403
- * symptom is a quality regression with no visible cause.
17213
+ * - `sensor` — a linked sensor/control device state change.
17214
+ * - `audio` — an audio event on the camera itself that was anomalous for
17215
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
17216
+ *
17217
+ * The spatial subsystems (tracker association, occupancy count, re-id /
17218
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
17219
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17220
+ * check silently readmits every source added after it was written.
17404
17221
  */
17405
- var RebuildObjectEmbeddingsInput = object({
17406
- /** Restrict to one camera. Omit for the whole fleet. */
17407
- deviceId: number().optional(),
17408
- since: number().optional(),
17409
- until: number().optional(),
17410
- /** Stop after this many tracks; the result reports whether more remain. */
17411
- maxTracks: number().int().positive().optional(),
17412
- /**
17413
- * Run every embedding on THIS node instead of round-robining the fleet.
17414
- *
17415
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
17416
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
17417
- * calling it that would pin the rebuild REQUEST itself to that node — the
17418
- * rebuild orchestration lives on the hub, and only the per-track step runs
17419
- * remotely. This field is data; the per-track pin is applied inside.
17420
- *
17421
- * Absent ⇒ round-robin over every online node whose runner can serve the
17422
- * pinned model.
17423
- */
17424
- executeOnNodeId: string().optional(),
17425
- /**
17426
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
17427
- * run flat out.
17428
- *
17429
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
17430
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
17431
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
17432
- * force is logged at start and finish so a deliberately slow pass reads
17433
- * differently from a stalled one.
17434
- */
17435
- pacingMs: number().int().nonnegative().optional()
17436
- });
17222
+ var TrackSourceSchema = _enum([
17223
+ "pipeline",
17224
+ "sensor",
17225
+ "audio"
17226
+ ]);
17437
17227
  /**
17438
- * Result of emptying the CLIP index.
17228
+ * Where a track sits in the RETRAIN lifecycle (D81).
17439
17229
  *
17440
- * The clean slate before a policy change: a new crop margin or encoder model
17441
- * leaves two feature spaces in one index whose cosine scores are not
17442
- * comparable, so wiping and rebuilding is the only way to be sure every vector
17443
- * means the same thing.
17230
+ * - `none` — never marked, or un-marked. Evictable.
17231
+ * - `staging` — the operator wants this track as training material and has not
17232
+ * finished with it. **This is the only state retention holds**: the track and
17233
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
17234
+ * the device's age window.
17235
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
17236
+ * were COPIED into the retrain dataset at selection time, so the dataset no
17237
+ * longer depends on the track's media and the track becomes EVICTABLE again.
17238
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17239
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
17240
+ *
17241
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17242
+ * the store's filter language has only positive equality and `whereIn` — no
17243
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17244
+ * would make the entire pre-column history immortal in one deploy.
17444
17245
  */
17445
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
17246
+ var RetrainStatusSchema = _enum([
17247
+ "none",
17248
+ "staging",
17249
+ "trained"
17250
+ ]);
17446
17251
  /**
17447
- * Acknowledgement that a rebuild STARTED.
17252
+ * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
17253
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17254
+ * so the two surfaces cannot drift.
17448
17255
  *
17449
- * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
17450
- * runs detached and this returns immediately. Waiting for it made the client
17451
- * time out while the work carried on server-side, which is the worst of both:
17452
- * no result and no way to know it was still going. Poll
17453
- * `getObjectEmbeddingRebuildStatus` for progress.
17256
+ * **Absent ≠ false.** A track that has never been touched omits the field; an
17257
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
17258
+ * columns existed read as absent, and a consumer that needs a boolean should say
17259
+ * `flag === true`, not `flag !== false`.
17260
+ *
17261
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17262
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17263
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17264
+ * `trained` track reports `false` while refusing both writes. The boolean is
17265
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
17266
+ * "never marked" from "already trained" must read `retrainStatus`.
17267
+ *
17268
+ * `debug` does NOT pin; it is attention, not durability.
17269
+ *
17270
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17271
+ * A favourited track is skipped by retention the same way `staging` is, but
17272
+ * it does not enter `none|staging|trained` and has no staging budget.
17454
17273
  */
17455
- var RebuildObjectEmbeddingsResultSchema = object({
17456
- started: boolean(),
17457
- /** True when a pass was already running; the new request is ignored. */
17458
- alreadyRunning: boolean()
17459
- });
17460
- var RebuildStatusSchema = object({
17461
- running: boolean(),
17462
- scanned: number(),
17463
- rebuilt: number(),
17464
- /** Tracks whose key frame is gone — nothing to re-embed from. */
17465
- missingKeyFrame: number(),
17466
- /** Tracks with no usable detection box. */
17467
- missingBbox: number(),
17468
- /**
17469
- * Tracks an executing node REFUSED rather than broke on — an unreadable key
17470
- * frame, a step that threw. Separate from `failed` because the remedy is
17471
- * different, and because a whole camera silently contributing zero vectors
17472
- * is the shape of failure a rebuild must never hide.
17473
- */
17474
- notRunnable: number(),
17475
- /**
17476
- * The pass stopped because NO node could serve the pinned model.
17477
- *
17478
- * Distinct from `notRunnable` on purpose: that one says "this track was
17479
- * refused", this one says "the cluster cannot do this work at all" — every
17480
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
17481
- * pinned model for its engine format, or dropped out. The remedy is a model /
17482
- * engine change, not a per-camera one. Non-zero here always comes with
17483
- * `complete: false`.
17484
- */
17485
- noCapableNode: number(),
17486
- failed: number(),
17487
- /** Set once a pass ends: true only when EVERYTHING was covered. */
17488
- complete: boolean().nullable(),
17489
- startedAtMs: number().nullable(),
17490
- finishedAtMs: number().nullable(),
17491
- /** Present when the pass ended by throwing. */
17492
- error: string().nullable()
17493
- });
17494
- DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
17495
- deviceId: number(),
17496
- trackId: string()
17497
- }), TrackSchema.nullable()), method(object({
17498
- deviceId: number(),
17499
- since: number().optional(),
17500
- until: number().optional(),
17501
- limit: number().optional(),
17502
- /** Spatial filter — only tracks whose trajectory intersects the zone
17503
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
17504
- * envelope columns, then precisely tested per position. Tracks with
17505
- * an unknown envelope (no frame dims at persist time) always match. */
17506
- zone: TrackZoneFilterSchema.optional(),
17507
- /** See {@link TrackProjectionSchema}. Default `full` (backward
17508
- * compatible — omitting the field keeps today's exact behaviour). */
17509
- projection: TrackProjectionSchema.optional(),
17510
- /** Include stationary-promoted rows (parked objects handed to the
17511
- * stationary registry). Default false: the timeline lists passages,
17512
- * not parking records (operator decision, 2026-08-15). */
17513
- includeStationary: boolean().optional()
17514
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
17515
- deviceId: number(),
17516
- groupId: string().min(1)
17517
- }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
17518
- kind: "mutation",
17519
- auth: "admin"
17520
- }), method(DeviceEventQueryInput, array(MotionEventSchema).readonly()), method(ObjectEventQueryInput, array(ObjectEventSchema).readonly()), method(DeviceEventQueryInput, array(AudioEventSchema).readonly()), method(object({ deviceId: number() }), array(EventKindDescriptorSchema).readonly()), method(object({ deviceIds: array(number()).min(1).max(200) }), array(EventKindsForDeviceSchema).readonly()), method(object({
17521
- deviceId: number(),
17522
- since: number().optional(),
17523
- until: number().optional(),
17524
- kinds: array(string()).optional(),
17525
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
17526
- }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
17527
- deviceId: number(),
17528
- since: number(),
17529
- until: number(),
17530
- bucketMs: number().int().positive()
17531
- }), array(object({
17532
- bucketStart: number(),
17533
- motion: number().int(),
17534
- object: number().int(),
17535
- audio: number().int()
17536
- })).readonly()), method(object({
17537
- deviceId: number(),
17538
- cutoffMs: number()
17539
- }), object({
17540
- motion: number().int(),
17541
- object: number().int(),
17542
- audio: number().int()
17543
- }), {
17544
- kind: "mutation",
17545
- auth: "admin"
17546
- }), method(object({
17547
- deviceId: number(),
17548
- cutoffMs: number()
17549
- }), TrackCascadeCountsSchema, {
17550
- kind: "mutation",
17551
- auth: "admin"
17552
- }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
17553
- kind: "mutation",
17554
- auth: "admin"
17555
- }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
17556
- kind: "mutation",
17557
- auth: "admin"
17558
- }), method(object({
17559
- deviceId: number(),
17560
- trackIds: array(string()).min(1)
17561
- }), object({
17562
- deleted: number().int(),
17563
- failed: array(string()).readonly()
17564
- }), {
17565
- kind: "mutation",
17566
- auth: "admin"
17567
- }), method(object({
17568
- /** Log/audit scope only — the trackId is globally unique on its own. */
17569
- deviceId: number(),
17274
+ var TrackFlagFields = {
17275
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
17276
+ * `'staging'`. */
17277
+ markForTrain: boolean().optional(),
17278
+ /** Operator marked this track for diagnostic attention. */
17279
+ debug: boolean().optional(),
17280
+ /** Operator favourited this track. Pins it against pruning. */
17281
+ favourited: boolean().optional()
17282
+ };
17283
+ /**
17284
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17285
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17286
+ * write patch, and the status is not something the toggle sets — it is what the
17287
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17288
+ * always present on a persisted row (the column default materialises `'none'`).
17289
+ */
17290
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17291
+ /**
17292
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17293
+ * one flag can never clear the other — the toggles are independent and are
17294
+ * driven from three surfaces that do not know about each other.
17295
+ */
17296
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
17297
+ /**
17298
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
17299
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
17300
+ * mutation result without a re-fetch.
17301
+ */
17302
+ var TrackFlagsSchema = object({
17570
17303
  trackId: string(),
17571
- flags: TrackFlagsPatchSchema
17572
- }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
17573
- kind: "query",
17574
- auth: "admin"
17575
- }), method(object({
17576
- olderThanMs: number(),
17577
- reason: OpsLogReasonSchema.optional()
17578
- }), EventPruneCountsSchema, {
17579
- kind: "mutation",
17580
- auth: "admin"
17581
- }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
17582
- kind: "mutation",
17583
- auth: "admin"
17584
- }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
17585
- kind: "mutation",
17586
- auth: "admin"
17587
- }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
17588
- kind: "mutation",
17589
- auth: "admin"
17590
- }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
17591
- kind: "mutation",
17592
- auth: "admin"
17593
- }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
17594
- kind: "mutation",
17595
- auth: "admin"
17596
- }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17597
- kind: "mutation",
17598
- auth: "admin"
17599
- }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
17600
- kind: "mutation",
17601
- auth: "admin"
17602
- }), method(object({}), array(RelocateJobSchema).readonly(), {
17603
- kind: "query",
17604
- auth: "admin"
17605
- }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
17606
- kind: "mutation",
17607
- auth: "admin"
17608
- }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
17609
- kind: "query",
17610
- auth: "admin"
17611
- }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
17612
- kind: "query",
17613
- auth: "admin"
17614
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17615
- kind: "query",
17616
- auth: "admin"
17617
- }), method(object({
17618
- /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
17619
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
17620
- * route it at one camera's owner, and "every camera" would stop being
17621
- * expressible at all. */
17622
- deviceIds: array(number()).optional(),
17623
- limit: number().int().min(1).max(500).optional()
17624
- }), array(RetrainTrackSchema).readonly(), {
17625
- kind: "query",
17626
- auth: "admin"
17627
- }), method(object({ trackId: string() }), RetrainFrameListSchema, {
17628
- kind: "query",
17629
- auth: "admin"
17630
- }), method(object({
17304
+ markForTrain: boolean(),
17305
+ debug: boolean(),
17306
+ favourited: boolean(),
17307
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
17308
+ * a track row) because this shape is only ever produced by the write body,
17309
+ * which always knows it — and a surface that has just written needs to render
17310
+ * `trained` without a re-fetch. */
17311
+ retrainStatus: RetrainStatusSchema
17312
+ });
17313
+ union([literal(1), literal(2)]);
17314
+ /**
17315
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
17316
+ * the step and model that produced it — which is what makes the write rule
17317
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17318
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17319
+ *
17320
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17321
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17322
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
17323
+ * that value has no provenance, and the write rule lets ANY properly-attributed
17324
+ * write of the same tier replace it regardless of score.
17325
+ */
17326
+ var LabelAttributionSchema = object({
17327
+ stepId: string(),
17328
+ modelId: string().optional(),
17329
+ decidedAt: number(),
17330
+ /**
17331
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
17332
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17333
+ *
17334
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
17335
+ * notification rule authored on "Gianluca" stopped matching the moment the
17336
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
17337
+ * the thing that does not move, so it is what a rule matches on
17338
+ * (`NcConditions.identities`) and the text is what a human is shown.
17339
+ *
17340
+ * Absent when the label names no gallery row — a plate the OCR read but no
17341
+ * vehicle claims, a sub-class, a species, any tier-1 value.
17342
+ */
17343
+ identityId: string().optional()
17344
+ });
17345
+ /**
17346
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17347
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17348
+ * track and its events always answer the same question the same way.
17349
+ *
17350
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
17351
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17352
+ * is tier 2, and each carries its own score + attribution.
17353
+ *
17354
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17355
+ * finest thing known. Before 4g the single `label` column held the finest
17356
+ * value, so a consumer that has not been updated reads the tier-1 slot and
17357
+ * shows nothing on a species-only row; that is why the migration puts every
17358
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17359
+ * and why the read surfaces were changed in the same train.
17360
+ *
17361
+ * **Writing it.** The slots are independent, which is the whole point: a
17362
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17363
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
17364
+ * higher score wins. One rule, one implementation — see
17365
+ * `pipeline/label-tier.ts` in addon-post-analysis.
17366
+ */
17367
+ var TieredLabelFields = {
17368
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
17369
+ label: string().optional(),
17370
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
17371
+ labelScore: number().optional(),
17372
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17373
+ labelMeta: LabelAttributionSchema.optional(),
17374
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
17375
+ subLabel: string().optional(),
17376
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
17377
+ subLabelScore: number().optional(),
17378
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17379
+ subLabelMeta: LabelAttributionSchema.optional()
17380
+ };
17381
+ /** Per-camera slice of a training-export estimate. */
17382
+ var TrainingExportDeviceTotalsSchema = object({
17631
17383
  deviceId: number(),
17384
+ tracks: number().int(),
17385
+ files: number().int(),
17386
+ bytes: number().int()
17387
+ });
17388
+ /**
17389
+ * What a training export WOULD contain. Computed from media index rows only —
17390
+ * no blob is read to produce this.
17391
+ */
17392
+ var TrainingExportSummarySchema = object({
17393
+ generatedAt: number(),
17394
+ trackCount: number().int(),
17395
+ fileCount: number().int(),
17396
+ byteCount: number().int(),
17397
+ /** More marked tracks exist than a single pass carries. */
17398
+ truncated: boolean(),
17399
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
17400
+ });
17401
+ var TrackSchema = object({
17632
17402
  trackId: string(),
17633
- mediaKeys: array(string()).min(1)
17634
- }), RetrainFrameSelectionSchema, {
17635
- kind: "mutation",
17636
- auth: "admin"
17637
- }), method(object({
17638
17403
  deviceId: number(),
17639
- trackId: string(),
17640
- frameId: string()
17641
- }), object({
17642
- removed: boolean(),
17643
- removedAnnotations: number().int()
17644
- }), {
17645
- kind: "mutation",
17646
- auth: "admin"
17647
- }), method(object({ frameId: string() }), object({
17404
+ className: string(),
17405
+ ...TieredLabelFields,
17406
+ producingDeviceName: string().optional(),
17407
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
17408
+ source: TrackSourceSchema.optional(),
17409
+ firstSeen: number(),
17410
+ lastSeen: number(),
17411
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
17412
+ positions: array(TrackPositionSchema).readonly(),
17413
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17414
+ * saveThumbnails policy). */
17415
+ snapshots: array(TrackSnapshotSchema).readonly(),
17416
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
17417
+ zonesVisited: array(string()).readonly(),
17418
+ /**
17419
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17420
+ * `zones` capability.
17421
+ *
17422
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17423
+ * and no card can render — so every free-text search surface was structurally
17424
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17425
+ * just returned nothing. Resolving here rather than in each client keeps ONE
17426
+ * derivation and costs the clients no extra call (the `zones` cap is
17427
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
17428
+ * surface built to avoid exactly that).
17429
+ *
17430
+ * Resolved, never invented: a zone deleted since the track was written has no
17431
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17432
+ * two are not positionally aligned. Absent when the track visited no zone, or
17433
+ * when the zone catalogue could not be read.
17434
+ */
17435
+ zoneNames: array(string()).readonly().optional(),
17436
+ /** Deduplicated set of detector classes observed for this track over its
17437
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
17438
+ * legacy rows written before class accumulation shipped. */
17439
+ classes: array(string()).readonly().optional(),
17440
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17441
+ totalDistance: number(),
17442
+ state: TrackStateSchema,
17443
+ active: boolean(),
17444
+ /** Deterministic key-event importance score in [0,1] (server-computed at
17445
+ * track expiry, recomputed on late label). Absent on legacy rows written
17446
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
17447
+ importance: number().optional(),
17448
+ /** Id of the track's highest-confidence ObjectEvent (its representative
17449
+ * "best" frame). Absent when the track produced no object events. */
17450
+ bestEventId: string().optional(),
17451
+ /** Tag of the importance sub-signal that dominated the score
17452
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
17453
+ importanceReason: string().optional(),
17454
+ /** Audio-classification labels heard on the camera during the track's
17455
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
17456
+ * Absent on legacy rows / tracks with no confident audio. */
17457
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17458
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17459
+ * Populated from the persisted envelope columns on historical reads;
17460
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17461
+ envelope: TrackEnvelopeSchema.optional(),
17462
+ /**
17463
+ * A face DETECTOR found a face on this track — nothing more. It says the
17464
+ * detail plane produced a `face` detail; it does NOT say the face was
17465
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
17466
+ * enabled. Set once and never cleared.
17467
+ *
17468
+ * **This exists so "face present but not recognised" is expressible.** A
17469
+ * recognised identity lands in `subLabel` (attributed to the face chain via
17470
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17471
+ * and a track with no face at all were byte-identical on the wire and no
17472
+ * surface could tell them apart. The read is `hasFace === true && subLabel
17473
+ * === undefined`.
17474
+ *
17475
+ * **Absent ≠ false.** Every row written before the column existed omits it,
17476
+ * and so does every server that predates the field — a consumer must test
17477
+ * `=== true` and render nothing otherwise, never infer "no face".
17478
+ */
17479
+ hasFace: boolean().optional(),
17480
+ /**
17481
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
17482
+ * face an operator could ASSIGN to an identity.
17483
+ *
17484
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17485
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
17486
+ * branch, before every gate, and means no more than "a face detector produced
17487
+ * a face detail". This one is stamped at the single moment the gallery row
17488
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17489
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17490
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
17491
+ * the crop-store drop. Everything between the detector and that insert can
17492
+ * legitimately refuse the face, so a flag written any earlier promises the
17493
+ * operator something to assign and delivers nothing.
17494
+ *
17495
+ * **Independent of recognition.** A face collected but never auto-matched is
17496
+ * still assignable — it is in fact the face an operator most wants to reach —
17497
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17498
+ * `subLabel`; this says only that the raw material exists.
17499
+ *
17500
+ * **Set once, never cleared.** A track that produced a gallery row produced
17501
+ * one; deleting the row later is the gallery's business, not this flag's.
17502
+ *
17503
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17504
+ * before the column omits it, and so does every server that predates the
17505
+ * field. A consumer must test `=== true` and render nothing otherwise —
17506
+ * never infer "no assignable face".
17507
+ */
17508
+ hasEmbeddedFace: boolean().optional(),
17509
+ /**
17510
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
17511
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17512
+ * so the passage is tracked once and as a VEHICLE.
17513
+ *
17514
+ * It exists because the fold's record was dishonest. D34 and the code both
17515
+ * said "the person is not lost — it is reported so both entities stay on the
17516
+ * record"; in fact the pair went into a per-processor RAM field behind an
17517
+ * accessor nobody called, and every durable surface said `vehicle`, full
17518
+ * stop. This is the composition note that makes the row true.
17519
+ *
17520
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
17521
+ * person" is not an answer to "what is this" — both label tiers would refuse
17522
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
17523
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17524
+ * and a `person` rule still does not fire for someone cycling past.
17525
+ *
17526
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17527
+ * the column, and every hub that predates the field, omits it. Test
17528
+ * `=== true` and render nothing otherwise — never infer "no rider".
17529
+ */
17530
+ hasRider: boolean().optional(),
17531
+ ...TrackFlagFields,
17532
+ ...TrackRetrainFields
17533
+ });
17534
+ var BaseEventFields = {
17535
+ id: string(),
17536
+ deviceId: number(),
17537
+ timestamp: number()
17538
+ };
17539
+ var MotionEventSchema = object({
17540
+ ...BaseEventFields,
17541
+ kind: literal("motion"),
17542
+ regionCount: number(),
17543
+ /** Heavy JSON array — omitted in slim projection. */
17544
+ regions: array(object({
17545
+ bbox: BoundingBoxSchema,
17546
+ pixelCount: number(),
17547
+ intensity: number()
17548
+ })).readonly().optional(),
17549
+ /** Omitted in slim projection. */
17550
+ frameWidth: number().optional(),
17551
+ /** Omitted in slim projection. */
17552
+ frameHeight: number().optional(),
17553
+ /** Populated by B5 (recording playback URL for this event). */
17554
+ mediaUrl: string().optional()
17555
+ });
17556
+ /**
17557
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
17558
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
17559
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
17560
+ * tracking, per-kind persistence) but stay distinguishable so consumers
17561
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17562
+ * Absent on legacy rows ⇒ treat as `pipeline`.
17563
+ */
17564
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17565
+ /**
17566
+ * The confirmed zone crossing that produced an object event. Present ONLY on
17567
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17568
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17569
+ * appearance event carry none, so a rule asking for a direction fails closed
17570
+ * on them.
17571
+ *
17572
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17573
+ * into its own event, so a frame in which a track enters A while leaving B
17574
+ * produces two events with two directions — never one ambiguous row.
17575
+ *
17576
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17577
+ * membership the box has NOW, and by definition it no longer contains the zone
17578
+ * that was just left. Without the id here, a zone-scoped rule could never match
17579
+ * the exit it asked for.
17580
+ */
17581
+ var ZoneCrossingSchema = object({
17582
+ direction: _enum(["enter", "exit"]),
17583
+ /** Admin zone id crossed. */
17584
+ zoneId: string(),
17585
+ /** Zone display name at crossing time (falls back to the id). */
17586
+ zoneName: string().optional()
17587
+ });
17588
+ var ObjectEventSchema = object({
17589
+ ...BaseEventFields,
17590
+ kind: literal("object"),
17591
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
17592
+ source: DetectionSourceSchema.optional(),
17593
+ /**
17594
+ * Inference-frame id shared by every object event emitted from the SAME frame
17595
+ * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
17596
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
17597
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
17598
+ * Optional for backward-compat with pre-existing rows / the slim projection
17599
+ * includes it (it is light). Absent on rows written before this field.
17600
+ */
17601
+ frameId: string().optional(),
17602
+ /** Omitted in slim projection. */
17603
+ trackId: string().optional(),
17604
+ className: string(),
17605
+ ...TieredLabelFields,
17606
+ /** Omitted in slim projection. */
17607
+ confidence: number().optional(),
17608
+ /** Heavy JSON — omitted in slim projection. */
17609
+ bbox: BoundingBoxSchema.optional(),
17610
+ /** Heavy JSON — omitted in slim projection. */
17611
+ zones: array(string()).readonly().optional(),
17612
+ /** Omitted in slim projection. */
17613
+ state: TrackStateSchema.optional(),
17614
+ /**
17615
+ * The zone crossing this event IS, when it is one. Absent on every other
17616
+ * event kind (movement state, appearance, package) — see
17617
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
17618
+ */
17619
+ zoneCrossing: ZoneCrossingSchema.optional(),
17620
+ /** Detection-frame dimensions in pixels — let consumers normalize the
17621
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
17622
+ frameWidth: number().optional(),
17623
+ frameHeight: number().optional(),
17624
+ /** MediaStore key for the crop attached to this event (if any). */
17625
+ mediaKey: string().optional(),
17626
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
17627
+ * best-detection full frame). Resolve via the event-media data-plane
17628
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
17629
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
17630
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
17631
+ keyFrameMediaKey: string().optional(),
17632
+ /** Populated by B5 (recording playback URL for this event). */
17633
+ mediaUrl: string().optional(),
17634
+ /** The parent track's key-event importance [0,1], propagated to every object
17635
+ * event of the track (so an event row can be sorted by importance without a
17636
+ * track join). Absent on legacy rows / before the track was scored. */
17637
+ importance: number().optional()
17638
+ });
17639
+ var AudioEventSchema = object({
17640
+ ...BaseEventFields,
17641
+ kind: literal("audio"),
17642
+ rms: number(),
17643
+ dbfs: number(),
17644
+ classification: object({
17645
+ className: string(),
17646
+ originalClass: string().optional(),
17647
+ score: number()
17648
+ }).optional(),
17649
+ /** Populated by B5 (recording playback URL for this event). */
17650
+ mediaUrl: string().optional()
17651
+ });
17652
+ var MediaFileKindEnum = _enum([
17653
+ "crop",
17654
+ "thumbnail",
17655
+ "snapshot",
17656
+ "firstFrame",
17657
+ "lastFrame",
17658
+ "fullFrame",
17659
+ "fullFrameBoxed",
17660
+ "faceCrop",
17661
+ "plateCrop",
17662
+ "keyFrame",
17663
+ "keyFrameSmall",
17664
+ "thumbnailSmall"
17665
+ ]);
17666
+ var MediaFileSchema = object({
17667
+ key: string(),
17668
+ kind: MediaFileKindEnum,
17648
17669
  base64: string(),
17649
- width: number().int(),
17650
- height: number().int()
17651
- }), {
17652
- kind: "query",
17653
- auth: "admin"
17654
- }), method(object({
17655
- deviceId: number(),
17656
- trackId: string(),
17657
- frameId: string(),
17658
- subject: RetrainAssistSubjectSchema,
17659
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
17660
- nodeId: string().optional()
17661
- }), RetrainAssistResultSchema, {
17662
- kind: "mutation",
17663
- auth: "admin"
17664
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
17665
- kind: "query",
17666
- auth: "admin"
17667
- }), method(object({
17668
- deviceId: number(),
17670
+ sizeBytes: number(),
17671
+ timestamp: number()
17672
+ });
17673
+ /**
17674
+ * One media row WITHOUT its bytes.
17675
+ *
17676
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17677
+ * 140 s track), and a client that renders tiles from the media data plane needs
17678
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
17679
+ * with an immutable cache, instead of all at once inside a tRPC response that
17680
+ * blocks the whole view.
17681
+ *
17682
+ * `sizeBytes` is carried because it is what lets a client decide between the
17683
+ * stored blob and a `?variant=thumb` rendering without fetching either.
17684
+ */
17685
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17686
+ /**
17687
+ * The MACRO tier of an annotation — a CLOSED set.
17688
+ *
17689
+ * This is what the exported detector predicts, so a typo here is a new class
17690
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
17691
+ * the whole point of the page is teaching the model things it does not know
17692
+ * yet, and constraining that vocabulary would make it useless.
17693
+ *
17694
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
17695
+ * `subLabel` is one of these values, in any casing, because once `person`
17696
+ * exists in both tiers "every person box" stops being answerable without
17697
+ * knowing every string anyone ever typed — and the damage is retroactive.
17698
+ */
17699
+ var RetrainMacroClassSchema = _enum([
17700
+ "person",
17701
+ "vehicle",
17702
+ "animal",
17703
+ "package",
17704
+ "face",
17705
+ "plate"
17706
+ ]);
17707
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17708
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17709
+ /** Did a human draw this box, or did the assist propose it? */
17710
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17711
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17712
+ var RetrainBboxSchema = object({
17713
+ x: number(),
17714
+ y: number(),
17715
+ w: number(),
17716
+ h: number()
17717
+ });
17718
+ /**
17719
+ * One annotated subject.
17720
+ *
17721
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17722
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17723
+ * derived from it at export and never stored — storing them is how one feature
17724
+ * space ends up holding two crops of the same subject (D52).
17725
+ */
17726
+ var RetrainAnnotationSchema = object({
17727
+ id: string(),
17669
17728
  trackId: string(),
17670
- frameId: string(),
17671
- annotations: array(RetrainAnnotationDraftSchema)
17672
- }), array(RetrainAnnotationSchema).readonly(), {
17673
- kind: "mutation",
17674
- auth: "admin"
17675
- }), method(object({
17676
- deviceId: number(),
17677
- trackId: string()
17678
- }), RetrainTransitionResultSchema, {
17679
- kind: "mutation",
17680
- auth: "admin"
17681
- }), method(object({
17682
17729
  deviceId: number(),
17683
- trackId: string()
17684
- }), RetrainTransitionResultSchema, {
17685
- kind: "mutation",
17686
- auth: "admin"
17687
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
17688
- kind: "query",
17689
- auth: "admin"
17690
- }), method(object({
17691
- eventId: string(),
17692
- kind: MediaFileKindEnum.optional(),
17693
- deviceId: number()
17694
- }), array(MediaFileSchema).readonly()), method(object({
17695
- trackId: string(),
17696
- kinds: array(MediaFileKindEnum).optional(),
17697
- deviceId: number()
17698
- }), array(MediaFileSchema).readonly()), method(object({
17730
+ /** The COPY in retrain storage — never the source track's media key. */
17731
+ mediaKey: string(),
17732
+ bbox: RetrainBboxSchema,
17733
+ macroClass: RetrainMacroClassSchema,
17734
+ label: string().optional(),
17735
+ subLabel: string().optional(),
17736
+ kind: RetrainAnnotationKindSchema,
17737
+ source: RetrainAnnotationSourceSchema,
17738
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
17739
+ assistModelId: string().optional(),
17740
+ assistScore: number().optional(),
17741
+ exportedInBatch: string().optional(),
17742
+ createdAt: number()
17743
+ });
17744
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17745
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17746
+ id: true,
17747
+ trackId: true,
17748
+ deviceId: true,
17749
+ mediaKey: true,
17750
+ createdAt: true,
17751
+ exportedInBatch: true
17752
+ });
17753
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17754
+ var RetrainTrackSchema = object({
17699
17755
  trackId: string(),
17700
- deviceId: number()
17701
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
17702
- kind: "mutation",
17703
- auth: "admin"
17704
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
17705
- kind: "mutation",
17706
- auth: "admin"
17707
- }), method(object({}), RebuildStatusSchema), object({
17708
17756
  deviceId: number(),
17757
+ className: string(),
17758
+ label: string().optional(),
17759
+ firstSeen: number(),
17760
+ lastSeen: number(),
17761
+ /** How many frames the dataset already holds from this track. */
17762
+ frameCount: number().int(),
17763
+ /** How many subjects have been annotated on those frames. `0` with
17764
+ * `frameCount: 0` is exactly "staging, still to work". */
17765
+ annotationCount: number().int()
17766
+ });
17767
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
17768
+ var RetrainFrameCandidateSchema = object({
17769
+ mediaKey: string(),
17770
+ kind: MediaFileKindEnum,
17709
17771
  timestamp: number(),
17710
- frameWidth: number(),
17711
- frameHeight: number(),
17712
- detections: array(OverlayDetectionSchema).readonly()
17713
- }), object({
17714
- deviceId: number(),
17715
- trackId: string(),
17716
- className: string()
17717
- }), object({
17772
+ sizeBytes: number().int(),
17773
+ /** A copy of this original already exists — selecting it is free and cannot
17774
+ * fail, whatever became of the original. */
17775
+ copied: boolean()
17776
+ });
17777
+ /** A frame the dataset OWNS: bytes copied at selection time. */
17778
+ var RetrainFrameSchema = object({
17779
+ frameId: string(),
17718
17780
  deviceId: number(),
17719
17781
  trackId: string(),
17720
- className: string(),
17721
- durationMs: number()
17722
- }), object({
17723
- deviceId: number(),
17724
- kind: EventKindSchema,
17725
- eventId: string(),
17726
- timestamp: number()
17782
+ /** Provenance only. It may already point at nothing — that is expected. */
17783
+ sourceMediaKey: string(),
17784
+ sourceKind: MediaFileKindEnum,
17785
+ sizeBytes: number().int(),
17786
+ width: number().int(),
17787
+ height: number().int(),
17788
+ copiedAt: number()
17727
17789
  });
17728
- /**
17729
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
17730
- * within the frame, so the executor can re-cut a leaf child ROI at native
17731
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
17732
- */
17733
- var NativeCropRefSchema = object({
17734
- /** Handle keying the retained native surface (node-pinned to its owner). */
17735
- handle: FrameHandleSchema,
17736
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
17737
- cropFrameSpace: object({
17738
- x: number(),
17739
- y: number(),
17740
- w: number(),
17741
- h: number()
17742
- })
17790
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17791
+ var RetrainCopyRefusalSchema = _enum([
17792
+ "source-missing",
17793
+ "unreadable-image",
17794
+ "write-failed"
17795
+ ]);
17796
+ var RetrainFrameSelectionSchema = object({
17797
+ copied: array(RetrainFrameSchema).readonly(),
17798
+ refused: array(object({
17799
+ sourceMediaKey: string(),
17800
+ reason: RetrainCopyRefusalSchema
17801
+ })).readonly()
17743
17802
  });
17744
- object({
17745
- crop: object({
17746
- left: number(),
17747
- top: number(),
17748
- width: number().positive(),
17749
- height: number().positive()
17750
- }).optional(),
17751
- content: object({
17752
- width: number().int().positive(),
17753
- height: number().int().positive()
17754
- }),
17755
- fit: _enum(["stretch", "contain"]),
17756
- format: _enum([
17757
- "rgb",
17758
- "gray",
17759
- "jpeg"
17760
- ])
17803
+ var RetrainFrameListSchema = object({
17804
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
17805
+ copies: array(RetrainFrameSchema).readonly(),
17806
+ /** What the page pre-selects — the native key frame when one survives. */
17807
+ autoPickMediaKey: string().optional()
17761
17808
  });
17809
+ /** What the operator asked the assist to look for. */
17810
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17811
+ kind: literal("package"),
17812
+ zone: RetrainBboxSchema.optional()
17813
+ }), object({
17814
+ kind: literal("objects"),
17815
+ modelId: string(),
17816
+ minScore: number().optional()
17817
+ })]);
17762
17818
  /**
17763
- * Process-local frame identity. It is serializable so it can ride an in-process
17764
- * capability call, but `registryId` deliberately prevents resolution in any
17765
- * other process or execution group.
17819
+ * The assist's answer — a discriminated union, because "the model saw nothing"
17820
+ * and "this node cannot run that model" lead to different next moves and a
17821
+ * nullable result cannot tell them apart.
17766
17822
  */
17767
- var FrameRefSchema = object({
17768
- registryId: string().min(1),
17769
- id: string().min(1),
17770
- width: number().int().positive(),
17771
- height: number().int().positive(),
17772
- format: _enum(["rgb", "gray"]),
17773
- timestamp: number(),
17774
- capturedAt: number().optional()
17823
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17824
+ kind: literal("proposed"),
17825
+ modelId: string(),
17826
+ stepId: string(),
17827
+ minScore: number(),
17828
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17829
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
17830
+ /** Returned by the runner but removed by the threshold. */
17831
+ belowThreshold: number().int()
17832
+ }), object({
17833
+ kind: literal("refused"),
17834
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17835
+ reason: string(),
17836
+ detail: string().optional()
17837
+ })]);
17838
+ /** The outcome of a lifecycle move owned by the retrain page. */
17839
+ var RetrainTransitionResultSchema = object({
17840
+ trackId: string(),
17841
+ /** Where the track ended up, whatever happened. */
17842
+ retrainStatus: RetrainStatusSchema,
17843
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17844
+ changed: boolean(),
17845
+ reason: _enum([
17846
+ "unknown-track",
17847
+ "no-frames-copied",
17848
+ "not-staging",
17849
+ "not-trained",
17850
+ "unchanged"
17851
+ ]).optional()
17775
17852
  });
17776
- var ModelFormatSchema$1 = _enum([
17777
- "onnx",
17778
- "coreml",
17779
- "openvino",
17780
- "tflite",
17781
- "pt",
17782
- "gguf"
17783
- ]);
17784
- var PipelineSlotSchema = _enum([
17785
- "detector",
17786
- "cropper",
17787
- "classifier",
17788
- "refiner",
17789
- "audio-classifier"
17790
- ]);
17791
- var PipelineEngineChoiceSchema = object({
17792
- runtime: _enum(["node", "python"]),
17793
- backend: string(),
17794
- format: ModelFormatSchema$1,
17795
- device: string().optional()
17853
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17854
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
17855
+ var DeviceEventQueryInput = object({
17856
+ deviceId: number(),
17857
+ since: number().optional(),
17858
+ until: number().optional(),
17859
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17860
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17861
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17862
+ * exact behaviour. Callers may omit this field — the store defaults to
17863
+ * `full` when not provided. */
17864
+ projection: _enum(["full", "slim"]).optional()
17796
17865
  });
17797
- var AvailableEngineSchema = object({
17798
- engine: PipelineEngineChoiceSchema,
17799
- devices: array(object({
17800
- id: string(),
17801
- label: string(),
17802
- description: string().optional()
17803
- })).readonly(),
17804
- defaultDevice: string()
17866
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17867
+ var RecentTracksQueryInput = object({
17868
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17869
+ deviceIds: array(number()),
17870
+ /** Window lower bound on `lastSeen` (inclusive). */
17871
+ since: number().optional(),
17872
+ /** Window upper bound on `lastSeen` (inclusive). */
17873
+ until: number().optional(),
17874
+ /** Page size. Default 200, max 1000. */
17875
+ limit: number().int().min(1).max(1e3).default(200),
17876
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
17877
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
17878
+ cursor: string().optional(),
17879
+ /** See {@link TrackProjectionSchema}. Default `full`. */
17880
+ projection: TrackProjectionSchema.optional(),
17881
+ /** Include stationary-promoted rows (parked objects). Default false: the
17882
+ * feed lists passages; parking records live on the stationary registry. */
17883
+ includeStationary: boolean().optional()
17805
17884
  });
17806
- var PipelineDefaultStepSchema = lazy(() => object({
17807
- addonId: string(),
17808
- addonName: string(),
17809
- slot: PipelineSlotSchema,
17810
- inputClasses: array(string()).readonly(),
17811
- outputClasses: array(string()).readonly(),
17812
- enabled: boolean(),
17813
- modelId: string(),
17814
- children: array(PipelineDefaultStepSchema).readonly(),
17815
- group: string().optional(),
17816
- settings: record(string(), unknown()).optional()
17817
- }));
17818
- var PipelineTemplateStepSchema = lazy(() => object({
17819
- addonId: string(),
17820
- enabled: boolean(),
17821
- modelId: string(),
17822
- children: array(PipelineTemplateStepSchema).readonly(),
17823
- settings: record(string(), unknown()).optional()
17824
- }));
17825
- var PipelineTemplateSchema$1 = object({
17826
- id: string(),
17827
- name: string(),
17828
- createdAt: string(),
17829
- updatedAt: string(),
17830
- engine: PipelineEngineChoiceSchema,
17831
- steps: array(PipelineTemplateStepSchema).readonly()
17885
+ var RecentTracksPageSchema = object({
17886
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17887
+ tracks: array(TrackSchema).readonly(),
17888
+ /** Cursor for the next page, or null when this page is the last. */
17889
+ nextCursor: string().nullable()
17832
17890
  });
17833
- var PipelineModelOptionSchema = object({
17891
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
17892
+ var LIST_GROUPS_MAX_LIMIT = 100;
17893
+ var AnalyticsGroupRecordSchema = object({
17834
17894
  id: string(),
17835
- name: string(),
17836
- formats: record(string(), object({
17837
- downloaded: boolean(),
17838
- sizeMB: number()
17839
- })),
17840
- group: ModelVariantGroupSchema.optional(),
17841
- legacy: boolean().optional(),
17842
- provider: ModelProviderIdSchema.optional()
17895
+ deviceId: number().int(),
17896
+ openedAt: number().int(),
17897
+ closedAt: number().int(),
17898
+ timestamp: number().int(),
17899
+ memberCount: number().int(),
17900
+ memberTrackIds: array(string()).readonly(),
17901
+ className: string(),
17902
+ classes: array(string()).readonly(),
17903
+ /** Relative event-media path, or null when the group has no picture yet. */
17904
+ mediaUrl: string().nullable(),
17905
+ singleton: boolean()
17843
17906
  });
17844
- var ConfigFieldBridge = custom();
17845
- var PipelineAddonSchemaSchema = object({
17846
- id: string(),
17847
- name: string(),
17848
- slot: PipelineSlotSchema,
17849
- inputClasses: array(string()).readonly(),
17850
- outputClasses: array(string()).readonly(),
17851
- childSlots: array(PipelineSlotSchema).readonly(),
17852
- models: array(PipelineModelOptionSchema).readonly(),
17853
- defaultModelId: string(),
17854
- defaultModelIdByFormat: record(string(), string()).optional(),
17855
- enabledByDefault: boolean().optional(),
17856
- backfillIntoExistingOverrides: boolean().optional(),
17857
- defaultConfidence: number(),
17858
- group: string().optional(),
17859
- configSchema: array(ConfigFieldBridge).readonly().optional()
17907
+ var AnalyticsGroupMemberSchema = object({
17908
+ trackId: string(),
17909
+ deviceId: number().int(),
17910
+ className: string(),
17911
+ firstSeen: number().int(),
17912
+ lastSeen: number().int(),
17913
+ mediaUrl: string().nullable()
17860
17914
  });
17861
- var PipelineSlotSchemaSchema = object({
17862
- id: PipelineSlotSchema,
17863
- label: string(),
17864
- priority: number(),
17865
- parentSlot: PipelineSlotSchema.nullable(),
17866
- addons: array(PipelineAddonSchemaSchema).readonly()
17915
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17916
+ var ListGroupsQueryInput = object({
17917
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17918
+ deviceIds: array(number()),
17919
+ /** Window lower bound on `closedAt` (inclusive). */
17920
+ since: number().optional(),
17921
+ /** Window upper bound on `openedAt` (inclusive). */
17922
+ until: number().optional(),
17923
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17924
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
17925
+ cursor: string().optional()
17867
17926
  });
17868
- var PipelineSchemaSchema = object({
17869
- availableEngines: array(AvailableEngineSchema).readonly(),
17870
- selectedEngine: PipelineEngineChoiceSchema,
17871
- slots: array(PipelineSlotSchemaSchema).readonly()
17927
+ var ListGroupsPageSchema = object({
17928
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
17929
+ nextCursor: string().nullable()
17872
17930
  });
17873
- var EngineProvisioningSchema = object({
17874
- runtimeId: _enum([
17875
- "onnx",
17876
- "openvino",
17877
- "coreml",
17878
- "edgetpu"
17879
- ]).nullable(),
17880
- device: string().nullable(),
17881
- state: _enum([
17882
- "idle",
17883
- "installing",
17884
- "verifying",
17885
- "ready",
17886
- "failed"
17887
- ]),
17888
- progress: number().optional(),
17889
- error: string().optional(),
17890
- nextRetryAt: number().optional(),
17891
- /**
17892
- * Gate A (config-correctness gate at engine change): human-readable
17893
- * config issues surfaced EAGERLY when the node's engine changes — model
17894
- * substitutions ("chose X, running Y") and zero-build steps ("no model
17895
- * has a <format> build"). Additive/optional: informational only, never
17896
- * enforced here — `assertEngineReady` (readiness) still gates inference.
17897
- * Absent/empty when the node-default tree resolves cleanly.
17898
- */
17899
- configIssues: array(string()).optional()
17931
+ var KeyEventQueryInput = object({
17932
+ deviceId: number(),
17933
+ /** Window lower bound (track firstSeen ≥ since). */
17934
+ since: number(),
17935
+ /** Window upper bound (track firstSeen ≤ until). */
17936
+ until: number(),
17937
+ limit: number().int().min(1).max(200).default(50),
17938
+ /** Drop tracks scoring below this importance. */
17939
+ minImportance: number().min(0).max(1).optional(),
17940
+ /** Restrict to a single class (e.g. 'person'). */
17941
+ classFilter: string().optional()
17900
17942
  });
17901
- var PipelineStepInputSchema = lazy(() => object({
17902
- addonId: string(),
17903
- modelId: string().optional(),
17904
- enabled: boolean().default(true),
17905
- children: array(PipelineStepInputSchema).optional(),
17906
- settings: record(string(), unknown()).optional(),
17907
- jumpDeviceKey: string().optional()
17908
- }));
17909
- var ModelSubstitutionSchema = object({
17910
- addonId: string(),
17911
- chosen: string(),
17912
- running: string(),
17913
- format: string()
17943
+ var KeyEventSchema = object({
17944
+ /** The representative event id (the track's best ObjectEvent, else its trackId). */
17945
+ id: string(),
17946
+ trackId: string(),
17947
+ /** Track start time (firstSeen). */
17948
+ timestamp: number(),
17949
+ className: string(),
17950
+ ...TieredLabelFields,
17951
+ importance: number(),
17952
+ /** Highest-confidence ObjectEvent id for the track (empty when none). */
17953
+ bestEventId: string(),
17954
+ /** Track lifetime in ms (lastSeen - firstSeen). */
17955
+ windowMs: number().optional(),
17956
+ ...TrackFlagFields,
17957
+ ...TrackRetrainFields
17914
17958
  });
17915
- var PipelineValidationIssueSchema = object({
17916
- addonId: string(),
17917
- kind: _enum(["unknown-addon", "no-format-build"]),
17918
- detail: string()
17959
+ object({
17960
+ trackId: string(),
17961
+ className: string(),
17962
+ confidence: number(),
17963
+ bbox: BoundingBoxSchema,
17964
+ zones: array(string()).readonly(),
17965
+ state: TrackStateSchema
17919
17966
  });
17920
- var PipelineValidationResultSchema = object({
17921
- ok: boolean(),
17922
- issues: array(PipelineValidationIssueSchema).readonly(),
17923
- substitutions: array(ModelSubstitutionSchema).readonly(),
17924
- /** The node's `currentEngine.format` this validation ran against. */
17925
- format: string()
17967
+ var OverlayDetectionSchema = looseObject({
17968
+ id: string(),
17969
+ kind: _enum(["first-level", "detail"]),
17970
+ macroClass: string(),
17971
+ score: number(),
17972
+ bbox: object({
17973
+ x: number(),
17974
+ y: number(),
17975
+ width: number(),
17976
+ height: number()
17977
+ }),
17978
+ labels: array(looseObject({
17979
+ label: string(),
17980
+ score: number()
17981
+ })).readonly(),
17982
+ parentId: string().optional()
17983
+ });
17984
+ var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
17985
+ var SearchObjectEventsInput = object({
17986
+ text: string(),
17987
+ deviceId: number().optional(),
17988
+ since: number().optional(),
17989
+ until: number().optional(),
17990
+ classFilter: string().optional(),
17991
+ limit: number().default(50),
17992
+ minScore: number().min(0).max(1).default(.2)
17993
+ });
17994
+ var TrackCascadeCountsSchema = object({
17995
+ /** Persisted track roots deleted (authoritative). */
17996
+ tracks: number().int(),
17997
+ /** Object events removed with their tracks (best-effort; see note above). */
17998
+ events: number().int(),
17999
+ /** Track/face/plate-owned media removed (best-effort). Never identity media. */
18000
+ media: number().int(),
18001
+ /** Unassigned (non-enrolled) face reads removed (best-effort). */
18002
+ faces: number().int(),
18003
+ /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
18004
+ plates: number().int(),
18005
+ /** Per-track CLIP search vectors removed (best-effort). */
18006
+ embeddings: number().int(),
18007
+ /** Group membership + group rows removed with their last member (best-effort). */
18008
+ groups: number().int()
17926
18009
  });
17927
- var ReferenceImageEntrySchema = object({
17928
- filename: string(),
17929
- stepIds: array(string()).readonly().optional()
18010
+ /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
18011
+ var DiskReconcileCountsSchema = object({
18012
+ mediaDropped: number().int(),
18013
+ tracks: number().int(),
18014
+ events: number().int()
17930
18015
  });
17931
- var ReferenceImageBodySchema = object({
17932
- base64: string(),
17933
- filename: string()
18016
+ /** Event-store footprint for one camera. */
18017
+ var EventStoreDeviceFootprintSchema = object({
18018
+ deviceId: number(),
18019
+ /** Persisted event rows (motion + object + audio) for the camera. */
18020
+ rows: number().int(),
18021
+ /** Event-owned media bytes on disk for the camera. */
18022
+ bytes: number().int()
17934
18023
  });
17935
- var ReferenceAudioEntrySchema = object({
17936
- filename: string(),
17937
- sizeKb: number()
18024
+ /** Aggregate event-store footprint: global totals + per-camera breakdown. */
18025
+ var EventStoreFootprintSchema = object({
18026
+ totalRows: number().int(),
18027
+ totalBytes: number().int(),
18028
+ devices: array(EventStoreDeviceFootprintSchema).readonly()
17938
18029
  });
17939
- var ReferenceAudioBodySchema = object({ base64: string() });
17940
- var AudioBackendSchema = object({
17941
- id: string(),
17942
- name: string(),
17943
- description: string(),
17944
- available: boolean(),
18030
+ /** Per-kind counts returned by the event-prune / device-delete mutations. */
18031
+ var EventPruneCountsSchema = object({
18032
+ motion: number().int(),
18033
+ object: number().int(),
18034
+ audio: number().int()
18035
+ });
18036
+ /**
18037
+ * Re-embed stored tracks from their key frames.
18038
+ *
18039
+ * The reason this is an operator-callable method and not a migration script:
18040
+ * every knob that decides what a vector MEANS — encoder model, crop margin,
18041
+ * squaring — is only changeable if the existing vectors can be regenerated.
18042
+ * Mixing feature spaces in one index makes cosine scores incomparable, and the
18043
+ * symptom is a quality regression with no visible cause.
18044
+ */
18045
+ var RebuildObjectEmbeddingsInput = object({
18046
+ /** Restrict to one camera. Omit for the whole fleet. */
18047
+ deviceId: number().optional(),
18048
+ since: number().optional(),
18049
+ until: number().optional(),
18050
+ /** Stop after this many tracks; the result reports whether more remain. */
18051
+ maxTracks: number().int().positive().optional(),
17945
18052
  /**
17946
- * Raw classifier labels this backend can emit (e.g. YAMNet's
17947
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
17948
- * the benchmark UI to populate the `enabledMicroClasses` filter
17949
- * specific to the selected backend without a separate fetch.
18053
+ * Run every embedding on THIS node instead of round-robining the fleet.
18054
+ *
18055
+ * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
18056
+ * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
18057
+ * calling it that would pin the rebuild REQUEST itself to that node — the
18058
+ * rebuild orchestration lives on the hub, and only the per-track step runs
18059
+ * remotely. This field is data; the per-track pin is applied inside.
18060
+ *
18061
+ * Absent ⇒ round-robin over every online node whose runner can serve the
18062
+ * pinned model.
17950
18063
  */
17951
- rawLabels: array(string()).readonly().optional()
17952
- });
17953
- var AudioCapabilitiesSchema = object({
17954
- activeBackend: string(),
17955
- availableBackends: array(AudioBackendSchema).readonly(),
17956
- sampleRate: number(),
17957
- chunkDurationMs: number()
17958
- });
17959
- var DownloadModelResultSchema = object({
17960
- filePath: string(),
17961
- sizeMB: number(),
17962
- durationMs: number()
18064
+ executeOnNodeId: string().optional(),
18065
+ /**
18066
+ * Milliseconds to wait between tracks; omit for the built-in default, `0` to
18067
+ * run flat out.
18068
+ *
18069
+ * A rebuild is bulk maintenance on hub-main's single thread. Measured
18070
+ * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
18071
+ * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
18072
+ * force is logged at start and finish so a deliberately slow pass reads
18073
+ * differently from a stalled one.
18074
+ */
18075
+ pacingMs: number().int().nonnegative().optional()
17963
18076
  });
17964
18077
  /**
17965
- * Wrapper carrying a single test run's result. Replaces the legacy
17966
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
17967
- * canonical `AudioResult` from the Phase 6 output rework: one
17968
- * `AudioDetection` per class above `minScore`, top-N candidates in
17969
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
17970
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
17971
- * benchmark UI can still report a clean failure when the classifier
17972
- * cap isn't available.
18078
+ * Result of emptying the CLIP index.
18079
+ *
18080
+ * The clean slate before a policy change: a new crop margin or encoder model
18081
+ * leaves two feature spaces in one index whose cosine scores are not
18082
+ * comparable, so wiping and rebuilding is the only way to be sure every vector
18083
+ * means the same thing.
17973
18084
  */
17974
- var AudioTestResultSchema = object({
17975
- success: boolean(),
17976
- error: string().optional(),
17977
- frame: custom().optional()
18085
+ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
18086
+ /**
18087
+ * Acknowledgement that a rebuild STARTED.
18088
+ *
18089
+ * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
18090
+ * runs detached and this returns immediately. Waiting for it made the client
18091
+ * time out while the work carried on server-side, which is the worst of both:
18092
+ * no result and no way to know it was still going. Poll
18093
+ * `getObjectEmbeddingRebuildStatus` for progress.
18094
+ */
18095
+ var RebuildObjectEmbeddingsResultSchema = object({
18096
+ started: boolean(),
18097
+ /** True when a pass was already running; the new request is ignored. */
18098
+ alreadyRunning: boolean()
17978
18099
  });
17979
- var PipelineConfigBridge = custom();
17980
- var ConfigUISchemaBridge = custom();
17981
- var ConfigUISchemaNullableBridge = custom();
17982
- var InferenceCapabilitiesBridge = custom();
17983
- var ModelAvailabilityListBridge = custom();
17984
- var PipelineRunResultBridge = custom();
17985
- method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
17986
- modelId: string(),
17987
- settings: record(string(), unknown()).readonly()
17988
- }))), method(object({ steps: record(string(), object({
17989
- modelId: string(),
17990
- settings: record(string(), unknown()).readonly()
17991
- })) }), object({ success: literal(true) }), {
18100
+ var RebuildStatusSchema = object({
18101
+ running: boolean(),
18102
+ scanned: number(),
18103
+ rebuilt: number(),
18104
+ /** Tracks whose key frame is gone — nothing to re-embed from. */
18105
+ missingKeyFrame: number(),
18106
+ /** Tracks with no usable detection box. */
18107
+ missingBbox: number(),
18108
+ /**
18109
+ * Tracks an executing node REFUSED rather than broke on — an unreadable key
18110
+ * frame, a step that threw. Separate from `failed` because the remedy is
18111
+ * different, and because a whole camera silently contributing zero vectors
18112
+ * is the shape of failure a rebuild must never hide.
18113
+ */
18114
+ notRunnable: number(),
18115
+ /**
18116
+ * The pass stopped because NO node could serve the pinned model.
18117
+ *
18118
+ * Distinct from `notRunnable` on purpose: that one says "this track was
18119
+ * refused", this one says "the cluster cannot do this work at all" — every
18120
+ * candidate node either lacks the `clip-embedding` step, lacks a build of the
18121
+ * pinned model for its engine format, or dropped out. The remedy is a model /
18122
+ * engine change, not a per-camera one. Non-zero here always comes with
18123
+ * `complete: false`.
18124
+ */
18125
+ noCapableNode: number(),
18126
+ failed: number(),
18127
+ /** Set once a pass ends: true only when EVERYTHING was covered. */
18128
+ complete: boolean().nullable(),
18129
+ startedAtMs: number().nullable(),
18130
+ finishedAtMs: number().nullable(),
18131
+ /** Present when the pass ended by throwing. */
18132
+ error: string().nullable()
18133
+ });
18134
+ var ReplayFrameInputSchema = object({
18135
+ timestamp: number(),
18136
+ frame: PipelineRunResultBridge
18137
+ });
18138
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
18139
+ className: string(),
18140
+ firstSeenMs: number(),
18141
+ lastSeenMs: number(),
18142
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
18143
+ * frame — a representative box for the diff's `(className, window, IoU)`
18144
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
18145
+ * trajectory production's `Track.positions` keeps. */
18146
+ bbox: BoundingBoxSchema,
18147
+ /** How many of the input frames this track matched a real detection on
18148
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
18149
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
18150
+ framesMatched: number().int()
18151
+ })).readonly() });
18152
+ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
18153
+ deviceId: number(),
18154
+ trackId: string()
18155
+ }), TrackSchema.nullable()), method(object({
18156
+ deviceId: number(),
18157
+ since: number().optional(),
18158
+ until: number().optional(),
18159
+ limit: number().optional(),
18160
+ /** Spatial filter — only tracks whose trajectory intersects the zone
18161
+ * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
18162
+ * envelope columns, then precisely tested per position. Tracks with
18163
+ * an unknown envelope (no frame dims at persist time) always match. */
18164
+ zone: TrackZoneFilterSchema.optional(),
18165
+ /** See {@link TrackProjectionSchema}. Default `full` (backward
18166
+ * compatible — omitting the field keeps today's exact behaviour). */
18167
+ projection: TrackProjectionSchema.optional(),
18168
+ /** Include stationary-promoted rows (parked objects handed to the
18169
+ * stationary registry). Default false: the timeline lists passages,
18170
+ * not parking records (operator decision, 2026-08-15). */
18171
+ includeStationary: boolean().optional()
18172
+ }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
18173
+ deviceId: number(),
18174
+ groupId: string().min(1)
18175
+ }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
18176
+ kind: "mutation",
18177
+ auth: "admin"
18178
+ }), method(DeviceEventQueryInput, array(MotionEventSchema).readonly()), method(ObjectEventQueryInput, array(ObjectEventSchema).readonly()), method(DeviceEventQueryInput, array(AudioEventSchema).readonly()), method(object({ deviceId: number() }), array(EventKindDescriptorSchema).readonly()), method(object({ deviceIds: array(number()).min(1).max(200) }), array(EventKindsForDeviceSchema).readonly()), method(object({
18179
+ deviceId: number(),
18180
+ since: number().optional(),
18181
+ until: number().optional(),
18182
+ kinds: array(string()).optional(),
18183
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
18184
+ }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
18185
+ deviceId: number(),
18186
+ since: number(),
18187
+ until: number(),
18188
+ bucketMs: number().int().positive()
18189
+ }), array(object({
18190
+ bucketStart: number(),
18191
+ motion: number().int(),
18192
+ object: number().int(),
18193
+ audio: number().int()
18194
+ })).readonly()), method(object({
18195
+ deviceId: number(),
18196
+ cutoffMs: number()
18197
+ }), object({
18198
+ motion: number().int(),
18199
+ object: number().int(),
18200
+ audio: number().int()
18201
+ }), {
18202
+ kind: "mutation",
18203
+ auth: "admin"
18204
+ }), method(object({
18205
+ deviceId: number(),
18206
+ cutoffMs: number()
18207
+ }), TrackCascadeCountsSchema, {
18208
+ kind: "mutation",
18209
+ auth: "admin"
18210
+ }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
18211
+ kind: "mutation",
18212
+ auth: "admin"
18213
+ }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
18214
+ kind: "mutation",
18215
+ auth: "admin"
18216
+ }), method(object({
18217
+ deviceId: number(),
18218
+ trackIds: array(string()).min(1)
18219
+ }), object({
18220
+ deleted: number().int(),
18221
+ failed: array(string()).readonly()
18222
+ }), {
18223
+ kind: "mutation",
18224
+ auth: "admin"
18225
+ }), method(object({
18226
+ /** Log/audit scope only — the trackId is globally unique on its own. */
18227
+ deviceId: number(),
18228
+ trackId: string(),
18229
+ flags: TrackFlagsPatchSchema
18230
+ }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
18231
+ kind: "query",
18232
+ auth: "admin"
18233
+ }), method(object({
18234
+ olderThanMs: number(),
18235
+ reason: OpsLogReasonSchema.optional()
18236
+ }), EventPruneCountsSchema, {
17992
18237
  kind: "mutation",
17993
18238
  auth: "admin"
17994
- }), method(object({ nodeId: string() }), object({
17995
- success: literal(true),
17996
- clearedDevices: number()
17997
- }), {
18239
+ }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
17998
18240
  kind: "mutation",
17999
18241
  auth: "admin"
18000
- }), method(_void(), PipelineSchemaSchema), method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()), method(_void(), PipelineConfigBridge), method(_void(), ConfigUISchemaBridge), method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema), method(_void(), array(PipelineTemplateSchema$1).readonly()), method(object({
18001
- name: string(),
18002
- steps: array(PipelineTemplateStepSchema).readonly(),
18003
- engine: PipelineEngineChoiceSchema
18004
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
18005
- id: string(),
18006
- name: string().optional(),
18007
- steps: array(PipelineTemplateStepSchema).readonly().optional()
18008
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
18009
- addonId: string(),
18010
- modelId: string(),
18011
- format: ModelFormatSchema$1
18012
- }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
18013
- addonId: string(),
18014
- modelId: string(),
18015
- format: ModelFormatSchema$1
18016
- }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
18017
- engine: PipelineEngineChoiceSchema.optional(),
18018
- steps: array(PipelineStepInputSchema).min(1),
18019
- frame: FrameInputSchema.optional(),
18020
- /**
18021
- * Process-local lazy frame. Valid only when caller and provider resolve
18022
- * in the same execution-group process; split/cross-node callers use
18023
- * `frame`/`image` inline compatibility instead.
18024
- */
18025
- frameRef: FrameRefSchema.optional(),
18026
- /**
18027
- * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
18028
- * the decoded pixels live in. One more member of the one-of
18029
- * frame/frameHandle/image/imageBase64/referenceImage group.
18030
- */
18031
- frameHandle: FrameHandleSchema.optional(),
18032
- imageBase64: string().optional(),
18033
- /**
18034
- * Binary JPEG bytes — preferred over `imageBase64` on internal
18035
- * hops (hub → forked worker via Moleculer MsgPack) because it
18036
- * skips the 33% base64 overhead + the per-call base64 decode on
18037
- * the detection-pipeline worker. Callers can pass either; exactly
18038
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
18039
- */
18040
- image: _instanceof(Uint8Array).optional(),
18041
- referenceImage: string().optional(),
18042
- deviceId: number().optional(),
18043
- sessionId: string().optional(),
18044
- /**
18045
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
18046
- * reference-image, and detail-subtree calls. 'frame' is the live
18047
- * per-frame dispatch: ONLY root-plane steps run; crop children
18048
- * (inputClasses ≠ null) are skipped and served per-track via
18049
- * pipelineRunner.runDetailSubtree (two-plane design).
18050
- */
18051
- plane: _enum(["full", "frame"]).optional(),
18052
- /**
18053
- * Inference-device selector (Phase 2 multi-device). Format
18054
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
18055
- * Omitted ⇒ the runner's default device (current single-engine
18056
- * behaviour). Selects WHICH device pool of the node runs the call.
18057
- */
18058
- deviceKey: string().optional(),
18059
- /**
18060
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
18061
- * when the parent crop was resolved from the frame's retained NATIVE
18062
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
18063
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
18064
- * resolution from that surface — the SAME quality path faces already
18065
- * had — instead of the downscaled parent tile. `handle` keys the native
18066
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
18067
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
18068
- * the executor's crop-normalized child ROI back into frame-normalized
18069
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
18070
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
18071
- * (today's behaviour on the fallback path).
18072
- */
18073
- nativeCropRef: NativeCropRefSchema.optional()
18074
- }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
18075
- engine: PipelineEngineChoiceSchema.optional(),
18076
- steps: array(PipelineStepInputSchema).min(1),
18077
- frames: array(FrameInputSchema).min(1).max(255),
18078
- deviceId: number().optional(),
18079
- sessionId: string().optional(),
18080
- /**
18081
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
18082
- * the batch to the Python pool's bench preprocess cache
18083
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
18084
- * preprocessed ONCE and every later inference is a pure-inference cache
18085
- * hit — the sustained-throughput run measures inference, not
18086
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
18087
- * full preprocess every call, correct). Fresh per sustained run;
18088
- * released via `uncacheFrame`.
18089
- */
18090
- frameId: number().int().nonnegative().optional(),
18091
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
18092
- deviceKey: string().optional()
18093
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
18094
- data: _instanceof(Uint8Array),
18095
- width: number().int().positive(),
18096
- height: number().int().positive(),
18097
- format: _enum([
18098
- "rgb",
18099
- "bgr",
18100
- "gray"
18101
- ])
18242
+ }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
18243
+ kind: "mutation",
18244
+ auth: "admin"
18245
+ }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
18246
+ kind: "mutation",
18247
+ auth: "admin"
18248
+ }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
18249
+ kind: "mutation",
18250
+ auth: "admin"
18251
+ }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
18252
+ kind: "mutation",
18253
+ auth: "admin"
18254
+ }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18255
+ kind: "mutation",
18256
+ auth: "admin"
18257
+ }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
18258
+ kind: "mutation",
18259
+ auth: "admin"
18260
+ }), method(object({}), array(RelocateJobSchema).readonly(), {
18261
+ kind: "query",
18262
+ auth: "admin"
18263
+ }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18264
+ kind: "mutation",
18265
+ auth: "admin"
18266
+ }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
18267
+ kind: "query",
18268
+ auth: "admin"
18269
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
18270
+ kind: "query",
18271
+ auth: "admin"
18272
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18273
+ kind: "query",
18274
+ auth: "admin"
18275
+ }), method(object({
18276
+ /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
18277
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
18278
+ * route it at one camera's owner, and "every camera" would stop being
18279
+ * expressible at all. */
18280
+ deviceIds: array(number()).optional(),
18281
+ limit: number().int().min(1).max(500).optional()
18282
+ }), array(RetrainTrackSchema).readonly(), {
18283
+ kind: "query",
18284
+ auth: "admin"
18285
+ }), method(object({ trackId: string() }), RetrainFrameListSchema, {
18286
+ kind: "query",
18287
+ auth: "admin"
18288
+ }), method(object({
18289
+ deviceId: number(),
18290
+ trackId: string(),
18291
+ mediaKeys: array(string()).min(1)
18292
+ }), RetrainFrameSelectionSchema, {
18293
+ kind: "mutation",
18294
+ auth: "admin"
18295
+ }), method(object({
18296
+ deviceId: number(),
18297
+ trackId: string(),
18298
+ frameId: string()
18102
18299
  }), object({
18103
- frameId: number(),
18104
- width: number(),
18105
- height: number()
18106
- }), { kind: "mutation" }), method(object({
18107
- stepId: string(),
18108
- frameId: number().int()
18109
- }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
18110
- batchMode: string(),
18111
- windowMs: number(),
18112
- maxBatchSize: number(),
18113
- concurrency: number()
18114
- })), method(_void(), array(object({
18115
- engineKey: string(),
18116
- engine: PipelineEngineChoiceSchema,
18117
- modelsLoaded: array(string()).readonly(),
18118
- inUseByCameras: array(number()).readonly(),
18119
- /**
18120
- * Origin of this resident factory.
18121
- * - `runtime` — main camera-serving engine (no idle TTL).
18122
- * - `warm-override` — benchmark/test override held in the warm
18123
- * cache; auto-disposed after the idle TTL.
18124
- * - `device-pool` — a concurrent per-device pool (Phase 2
18125
- * multi-device, keyed by `deviceKey`) resolved
18126
- * via `resolveDeviceFactory`. Runs alongside the
18127
- * `runtime` engine on a DIFFERENT accelerator
18128
- * (NPU / iGPU / Coral) — this is how the
18129
- * Engines tab shows all pools running at once.
18130
- */
18131
- kind: _enum([
18132
- "runtime",
18133
- "warm-override",
18134
- "device-pool"
18135
- ]),
18136
- /** Native pid of the underlying Python pool (null when no pool). */
18137
- poolPid: number().nullable(),
18138
- /** ms since this factory was last used (null when not warm-tracked). */
18139
- idleMs: number().nullable(),
18140
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
18141
- idleTtlMs: number().nullable()
18142
- })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
18300
+ removed: boolean(),
18301
+ removedAnnotations: number().int()
18302
+ }), {
18303
+ kind: "mutation",
18304
+ auth: "admin"
18305
+ }), method(object({ frameId: string() }), object({
18306
+ base64: string(),
18307
+ width: number().int(),
18308
+ height: number().int()
18309
+ }), {
18310
+ kind: "query",
18311
+ auth: "admin"
18312
+ }), method(object({
18313
+ deviceId: number(),
18314
+ trackId: string(),
18315
+ frameId: string(),
18316
+ subject: RetrainAssistSubjectSchema,
18317
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
18318
+ nodeId: string().optional()
18319
+ }), RetrainAssistResultSchema, {
18320
+ kind: "mutation",
18321
+ auth: "admin"
18322
+ }), method(object({
18323
+ deviceId: number(),
18324
+ source: DetectionSourceSchema,
18325
+ zones: array(ZoneSchema).readonly().optional(),
18326
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
18327
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
18328
+ frames: array(ReplayFrameInputSchema).min(1)
18329
+ }), RunReplayFrameProcessorResultSchema, {
18330
+ kind: "mutation",
18331
+ auth: "admin"
18332
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
18333
+ kind: "query",
18334
+ auth: "admin"
18335
+ }), method(object({
18336
+ deviceId: number(),
18337
+ trackId: string(),
18338
+ frameId: string(),
18339
+ annotations: array(RetrainAnnotationDraftSchema)
18340
+ }), array(RetrainAnnotationSchema).readonly(), {
18341
+ kind: "mutation",
18342
+ auth: "admin"
18343
+ }), method(object({
18344
+ deviceId: number(),
18345
+ trackId: string()
18346
+ }), RetrainTransitionResultSchema, {
18347
+ kind: "mutation",
18348
+ auth: "admin"
18349
+ }), method(object({
18350
+ deviceId: number(),
18351
+ trackId: string()
18352
+ }), RetrainTransitionResultSchema, {
18143
18353
  kind: "mutation",
18144
18354
  auth: "admin"
18355
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18356
+ kind: "query",
18357
+ auth: "admin"
18145
18358
  }), method(object({
18146
- engine: PipelineEngineChoiceSchema,
18147
- force: boolean().optional()
18148
- }), object({
18149
- success: boolean(),
18150
- reason: string().optional()
18151
- }), {
18359
+ eventId: string(),
18360
+ kind: MediaFileKindEnum.optional(),
18361
+ deviceId: number()
18362
+ }), array(MediaFileSchema).readonly()), method(object({
18363
+ trackId: string(),
18364
+ kinds: array(MediaFileKindEnum).optional(),
18365
+ deviceId: number()
18366
+ }), array(MediaFileSchema).readonly()), method(object({
18367
+ trackId: string(),
18368
+ deviceId: number()
18369
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18152
18370
  kind: "mutation",
18153
18371
  auth: "admin"
18154
- }), method(_void(), array(ReferenceImageEntrySchema).readonly()), method(object({ filename: string() }), ReferenceImageBodySchema.nullable()), method(_void(), array(ReferenceAudioEntrySchema).readonly()), method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()), method(_void(), AudioCapabilitiesSchema), method(object({
18155
- addonId: string(),
18156
- modelId: string(),
18157
- filename: string().optional(),
18158
- settings: record(string(), unknown()).optional()
18159
- }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
18372
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18373
+ kind: "mutation",
18374
+ auth: "admin"
18375
+ }), method(object({}), RebuildStatusSchema), object({
18376
+ deviceId: number(),
18377
+ timestamp: number(),
18378
+ frameWidth: number(),
18379
+ frameHeight: number(),
18380
+ detections: array(OverlayDetectionSchema).readonly()
18381
+ }), object({
18382
+ deviceId: number(),
18383
+ trackId: string(),
18384
+ className: string()
18385
+ }), object({
18386
+ deviceId: number(),
18387
+ trackId: string(),
18388
+ className: string(),
18389
+ durationMs: number()
18390
+ }), object({
18391
+ deviceId: number(),
18392
+ kind: EventKindSchema,
18393
+ eventId: string(),
18394
+ timestamp: number()
18395
+ });
18160
18396
  object({
18161
18397
  activeCameras: number(),
18162
18398
  throttledCameras: number(),
@@ -18182,106 +18418,6 @@ var CameraMetricsSchema = object({
18182
18418
  });
18183
18419
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
18184
18420
  /**
18185
- * Zone — pure geometry + identity. NO filtering behaviour.
18186
- *
18187
- * Zones describe **where** in the frame the operator wants to flag
18188
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
18189
- * each pipeline stage uses them. Splitting the two means a single
18190
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
18191
- * a detection-include rule on `['car']`, and an occupancy aggregate
18192
- * — without three duplicated polygons.
18193
- *
18194
- * Owned by the orchestrator addon (provider) and mirrored into the
18195
- * `zones` device-state slice on every mutation. Consumers
18196
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
18197
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
18198
- * mirror with `onChanged`).
18199
- *
18200
- * Coordinates are normalised fractions of the frame (0–1) so zones
18201
- * survive resolution changes and stream profile switches.
18202
- *
18203
- * `kind` discriminates between full polygons (closed regions used
18204
- * for intrusion / occupancy filters) and tripwires (open 2-point
18205
- * line segments used for cross events). Onboard / firmware-reported
18206
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
18207
- * task list.
18208
- */
18209
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
18210
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
18211
- var PolygonPointSchema = object({
18212
- x: number(),
18213
- y: number()
18214
- });
18215
- /** A camera detection zone — pure geometry/identity. */
18216
- var ZoneSchema = object({
18217
- id: string(),
18218
- name: string(),
18219
- kind: ZoneKindEnum.default("polygon"),
18220
- /** Polygon vertices, fraction of frame (0–1). */
18221
- polygon: array(PolygonPointSchema).readonly(),
18222
- /** Visual color for UI rendering. */
18223
- color: string().default("#3b82f6")
18224
- });
18225
- /**
18226
- * Zones capability — per-camera CRUD over polygon detection zones.
18227
- *
18228
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
18229
- * to per-device settings and mirrors into the `zones` device-state
18230
- * slice on every mutation, so downstream consumers can subscribe via
18231
- * `dev.state.zones.onChanged`.
18232
- *
18233
- * The cap surface only handles geometry + identity; filtering
18234
- * behaviour (per-class, include/exclude, threshold) lives in the
18235
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
18236
- * `capabilities/schemas/zone-rule.js`.
18237
- */
18238
- var zonesCapability = {
18239
- name: "zones",
18240
- scope: "device",
18241
- mode: "singleton",
18242
- deviceTypes: [DeviceType.Camera],
18243
- methods: {
18244
- listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
18245
- addZone: method(object({
18246
- deviceId: number(),
18247
- zone: ZoneSchema
18248
- }), _void(), {
18249
- kind: "mutation",
18250
- auth: "admin"
18251
- }),
18252
- removeZone: method(object({
18253
- deviceId: number(),
18254
- zoneId: string()
18255
- }), _void(), {
18256
- kind: "mutation",
18257
- auth: "admin"
18258
- }),
18259
- updateZone: method(object({
18260
- deviceId: number(),
18261
- zone: ZoneSchema
18262
- }), _void(), {
18263
- kind: "mutation",
18264
- auth: "admin"
18265
- })
18266
- },
18267
- /**
18268
- * Runtime-state slice — the live zone catalogue mirrored by the
18269
- * orchestrator on every CRUD mutation. Consumers read via
18270
- * `device.state.zones.value` / `.watch(...)` without round-tripping
18271
- * the cap, and the codegen DeviceProxy auto-wires the reactive
18272
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
18273
- * (e.g. zone groupings) can sit alongside the polygon list.
18274
- */
18275
- runtimeState: object({ zones: array(ZoneSchema).readonly() }),
18276
- /**
18277
- * Runtime-state durability: **restored** — written only on operator mutation, so a camera that never had one has nothing to re-derive from. This is the slice `zone-mirror-hydration.ts` exists to paper over.
18278
- *
18279
- * See `RuntimeStateDurability`. Enforced by
18280
- * `scripts/check-runtime-state-durability.ts`.
18281
- */
18282
- durability: "restored"
18283
- };
18284
- /**
18285
18421
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
18286
18422
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
18287
18423
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -27600,92 +27736,6 @@ var sceneMonitorCapability = {
27600
27736
  durability: "session"
27601
27737
  };
27602
27738
  /**
27603
- * Per-stage gating mode applied to the zones a rule references.
27604
- *
27605
- * - `include`: the rule contributes to a **whitelist** for its stage.
27606
- * When at least one `include` rule fires for a stage, only entities
27607
- * inside one of those zones pass that stage.
27608
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
27609
- * Entities inside one of those zones are dropped at that stage.
27610
- *
27611
- * `monitor`-style observation (count without filtering) is not a rule
27612
- * mode — zones without any matching rule are observed naturally by
27613
- * `zone-analytics` (live snapshot + history), so an "I just want to
27614
- * count, not filter" use case needs no rule at all.
27615
- */
27616
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
27617
- /**
27618
- * Per-consumer rule that references existing zones (geometry) and
27619
- * defines how a specific pipeline stage should treat them. Each
27620
- * consumer addon owns its own `ZoneRule[]` array in its per-device
27621
- * settings:
27622
- *
27623
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
27624
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
27625
- * - future: notification rules, audio gating, etc.
27626
- *
27627
- * One rule applies to N zones (`zoneIds[]`) so the operator can
27628
- * express "ignore motion in ALL of {garden, street}" with a single
27629
- * rule. `classFilter` narrows the rule to specific object classes —
27630
- * "drop person detections in the street, but keep cars" is one
27631
- * `exclude` rule with `classFilter: ['person']`.
27632
- *
27633
- * `enabled` is a soft toggle — the operator can keep the rule
27634
- * configured but inert without deleting it.
27635
- */
27636
- var ZoneRuleSchema = object({
27637
- /** Stable rule id — survives edits, used by the UI for diffing. */
27638
- id: string(),
27639
- /** Optional human-readable label rendered in the rule editor. */
27640
- name: string().optional(),
27641
- /** Zones this rule targets. The rule's `mode` applies to ALL
27642
- * listed zones (OR-set: a detection in any one of them counts).
27643
- * At least one zone id required — a rule with no targets is a
27644
- * configuration mistake and the form validator rejects it. */
27645
- zoneIds: array(string()).min(1).readonly(),
27646
- mode: ZoneRuleModeEnum,
27647
- /**
27648
- * Class names this rule applies to. Empty / undefined ⇒ rule
27649
- * applies to every class. Class strings match the `macroClass`
27650
- * field on detections (e.g. `person`, `car`, `dog`).
27651
- */
27652
- classFilter: array(string()).readonly().optional(),
27653
- /**
27654
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
27655
- * required to consider an entity "in the zone". Defaults to the
27656
- * consumer's stage default when omitted. Kept for back-compat with
27657
- * existing per-rule overrides; new operators pick the value via
27658
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
27659
- * set, the lower-level engine reads it as a 0–1 fraction.
27660
- */
27661
- overlapThreshold: number().min(0).max(1).optional(),
27662
- /**
27663
- * Operator-friendly version of `overlapThreshold` — the percentage
27664
- * of the detection's bbox that must lie inside the zone for the
27665
- * rule to match. Documented default is 85%; the engine substitutes
27666
- * that when the field is omitted (kept optional so existing rules
27667
- * stored without it stay valid).
27668
- *
27669
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
27670
- * rule, the engine prefers `bboxInclusionPct` because it's the
27671
- * field exposed in the UI. Internally both feed the same gate.
27672
- */
27673
- bboxInclusionPct: number().min(0).max(100).optional(),
27674
- /**
27675
- * When `true` and a detection has a segmentation mask, use the
27676
- * mask for overlap instead of the bbox. Detection-stage only;
27677
- * motion rules ignore this field.
27678
- */
27679
- preferMask: boolean().optional(),
27680
- /**
27681
- * Soft-toggle: `false` disables the rule without deleting it.
27682
- * Defaults to `true` so operators creating a rule via the UI
27683
- * see it active immediately.
27684
- */
27685
- enabled: boolean().default(true)
27686
- });
27687
- array(ZoneRuleSchema).readonly();
27688
- /**
27689
27739
  * Script-runner cap. Models HA `script.*` entities on
27690
27740
  * `DeviceType.Script`. A Script is a pre-recorded action sequence
27691
27741
  * that can be invoked imperatively — optionally with a variables
@@ -33622,6 +33672,12 @@ Object.freeze({
33622
33672
  addonId: null,
33623
33673
  access: "create"
33624
33674
  },
33675
+ "pipelineAnalytics.runReplayFrameProcessor": {
33676
+ capName: "pipeline-analytics",
33677
+ capScope: "device",
33678
+ addonId: null,
33679
+ access: "create"
33680
+ },
33625
33681
  "pipelineAnalytics.saveRetrainAnnotations": {
33626
33682
  capName: "pipeline-analytics",
33627
33683
  capScope: "device",
@@ -33754,6 +33810,12 @@ Object.freeze({
33754
33810
  addonId: null,
33755
33811
  access: "view"
33756
33812
  },
33813
+ "pipelineExecutor.getInferenceDeviceHealth": {
33814
+ capName: "pipeline-executor",
33815
+ capScope: "system",
33816
+ addonId: null,
33817
+ access: "view"
33818
+ },
33757
33819
  "pipelineExecutor.getOrchestratorConfigSchema": {
33758
33820
  capName: "pipeline-executor",
33759
33821
  capScope: "system",
@@ -33826,6 +33888,12 @@ Object.freeze({
33826
33888
  addonId: null,
33827
33889
  access: "view"
33828
33890
  },
33891
+ "pipelineExecutor.rearmInferenceDevice": {
33892
+ capName: "pipeline-executor",
33893
+ capScope: "system",
33894
+ addonId: null,
33895
+ access: "create"
33896
+ },
33829
33897
  "pipelineExecutor.runAudioTest": {
33830
33898
  capName: "pipeline-executor",
33831
33899
  capScope: "system",
@@ -37074,6 +37142,11 @@ Object.freeze({
37074
37142
  form: "single",
37075
37143
  optional: false
37076
37144
  }],
37145
+ "pipelineAnalytics.runReplayFrameProcessor": [{
37146
+ name: "deviceId",
37147
+ form: "single",
37148
+ optional: false
37149
+ }],
37077
37150
  "pipelineAnalytics.saveRetrainAnnotations": [{
37078
37151
  name: "deviceId",
37079
37152
  form: "single",