@camstack/addon-provider-homematic 1.2.30 → 1.2.31

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