@camstack/addon-import-alexa 0.2.28 → 0.2.29

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