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