@camstack/addon-provider-hikvision 1.2.36 → 1.2.37

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