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