@camstack/addon-provider-petkit 0.2.29 → 0.2.30

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
@@ -17468,1760 +17468,1996 @@ var OauthIntegrationDescriptorSchema = object({
17468
17468
  });
17469
17469
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
17470
17470
  /**
17471
- * pipeline-analytics device-scoped wrapper cap. Refines raw
17472
- * per-frame detections emitted by the pipeline runner into tracked
17473
- * objects, per-kind event collections (motion / object / audio), and
17474
- * persisted media. Owns the post-detection domain end-to-end:
17475
- *
17476
- * runner emits PipelineInferenceResult
17477
- * ↓ (event bus)
17478
- * pipeline-analytics subscriber
17479
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
17480
- * → three DB collections (one per kind), one FS media tree, one
17481
- * unified event emitter (FrameTracked + TrackStarted/Ended +
17482
- * DetectionEvent on bus)
17483
- *
17484
- * Pure subscriber model. No `processFrame` cap method — the runner
17485
- * already publishes the raw frame on the bus. The cap surface is
17486
- * only QUERIES + per-device settings, bound on/off via
17487
- * `device-manager.setWrapperActive`. `defaultActive: true` because
17488
- * every camera with a detection pipeline wants its raw detections
17489
- * refined; operators opt out per-device via BindingsTab when needed.
17490
- *
17491
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
17492
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
17471
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
17472
+ * within the frame, so the executor can re-cut a leaf child ROI at native
17473
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
17493
17474
  */
17494
- var TrackStateSchema = _enum([
17495
- "new",
17496
- "entered",
17497
- "left",
17498
- "moving",
17499
- "idle"
17500
- ]);
17501
- var EventKindSchema = _enum([
17502
- "motion",
17503
- "object",
17504
- "audio"
17505
- ]);
17475
+ var NativeCropRefSchema = object({
17476
+ /** Handle keying the retained native surface (node-pinned to its owner). */
17477
+ handle: FrameHandleSchema,
17478
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
17479
+ cropFrameSpace: object({
17480
+ x: number(),
17481
+ y: number(),
17482
+ w: number(),
17483
+ h: number()
17484
+ })
17485
+ });
17486
+ object({
17487
+ crop: object({
17488
+ left: number(),
17489
+ top: number(),
17490
+ width: number().positive(),
17491
+ height: number().positive()
17492
+ }).optional(),
17493
+ content: object({
17494
+ width: number().int().positive(),
17495
+ height: number().int().positive()
17496
+ }),
17497
+ fit: _enum(["stretch", "contain"]),
17498
+ format: _enum([
17499
+ "rgb",
17500
+ "gray",
17501
+ "jpeg"
17502
+ ])
17503
+ });
17506
17504
  /**
17507
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
17508
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
17509
- * of the camera frame (top-left origin), matching the drawing-plane editor.
17505
+ * Process-local frame identity. It is serializable so it can ride an in-process
17506
+ * capability call, but `registryId` deliberately prevents resolution in any
17507
+ * other process or execution group.
17510
17508
  */
17511
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
17512
- /** Closed icon vocabulary so clients render a known glyph per kind. */
17513
- var EventKindIconSchema = _enum([
17514
- "motion",
17515
- "audio",
17516
- "person",
17517
- "vehicle",
17518
- "animal",
17519
- "door",
17520
- "pir",
17521
- "smoke",
17522
- "water",
17523
- "button",
17524
- "package",
17525
- "generic"
17509
+ var FrameRefSchema = object({
17510
+ registryId: string().min(1),
17511
+ id: string().min(1),
17512
+ width: number().int().positive(),
17513
+ height: number().int().positive(),
17514
+ format: _enum(["rgb", "gray"]),
17515
+ timestamp: number(),
17516
+ capturedAt: number().optional()
17517
+ });
17518
+ var ModelFormatSchema$1 = _enum([
17519
+ "onnx",
17520
+ "coreml",
17521
+ "openvino",
17522
+ "tflite",
17523
+ "pt",
17524
+ "gguf"
17526
17525
  ]);
17527
- var EventKindCategorySchema = _enum([
17528
- "motion",
17529
- "audio",
17530
- "detection",
17531
- "sensor",
17532
- "control",
17533
- "custom",
17534
- "package"
17526
+ var PipelineSlotSchema = _enum([
17527
+ "detector",
17528
+ "cropper",
17529
+ "classifier",
17530
+ "refiner",
17531
+ "audio-classifier"
17535
17532
  ]);
17536
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
17537
- var EventKindLevelSchema = _enum(["macro", "sub"]);
17538
- var EventKindDescriptorSchema = object({
17539
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
17540
- kind: string(),
17541
- /** i18n key resolved on the UI side; `label` is the English fallback. */
17542
- labelKey: string(),
17543
- /** English fallback label (kept for clients that don't translate). */
17544
- label: string(),
17545
- /** Hex color for timeline/legend rendering. */
17546
- color: string(),
17547
- /** Dictionary id → lucide component on the UI side. */
17548
- iconId: string(),
17549
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
17550
- icon: EventKindIconSchema,
17551
- category: EventKindCategorySchema,
17552
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
17553
- parentKind: string().nullable(),
17554
- /** Derived from `parentKind`, explicit for the client tree. */
17555
- level: EventKindLevelSchema,
17556
- /** Which cap + device contributes this kind. For built-ins the camera
17557
- * itself; for sensor kinds the LINKED source device. */
17558
- source: object({
17559
- capName: string(),
17560
- deviceId: number()
17561
- })
17533
+ var PipelineEngineChoiceSchema = object({
17534
+ runtime: _enum(["node", "python"]),
17535
+ backend: string(),
17536
+ format: ModelFormatSchema$1,
17537
+ device: string().optional()
17562
17538
  });
17563
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
17564
- var EventKindsForDeviceSchema = object({
17565
- deviceId: number(),
17566
- kinds: array(EventKindDescriptorSchema).readonly()
17539
+ var AvailableEngineSchema = object({
17540
+ engine: PipelineEngineChoiceSchema,
17541
+ devices: array(object({
17542
+ id: string(),
17543
+ label: string(),
17544
+ description: string().optional()
17545
+ })).readonly(),
17546
+ defaultDevice: string()
17567
17547
  });
17568
- var SensorEventSchema = object({
17548
+ var PipelineDefaultStepSchema = lazy(() => object({
17549
+ addonId: string(),
17550
+ addonName: string(),
17551
+ slot: PipelineSlotSchema,
17552
+ inputClasses: array(string()).readonly(),
17553
+ outputClasses: array(string()).readonly(),
17554
+ enabled: boolean(),
17555
+ modelId: string(),
17556
+ children: array(PipelineDefaultStepSchema).readonly(),
17557
+ group: string().optional(),
17558
+ settings: record(string(), unknown()).optional()
17559
+ }));
17560
+ var PipelineTemplateStepSchema = lazy(() => object({
17561
+ addonId: string(),
17562
+ enabled: boolean(),
17563
+ modelId: string(),
17564
+ children: array(PipelineTemplateStepSchema).readonly(),
17565
+ settings: record(string(), unknown()).optional()
17566
+ }));
17567
+ var PipelineTemplateSchema$1 = object({
17569
17568
  id: string(),
17570
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
17571
- * yields N rows, one per camera). */
17572
- deviceId: number(),
17573
- /** The linked sensor device whose state changed. */
17574
- sourceDeviceId: number(),
17575
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
17576
- kind: string(),
17577
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
17578
- value: record(string(), unknown()).nullable(),
17579
- timestamp: number()
17569
+ name: string(),
17570
+ createdAt: string(),
17571
+ updatedAt: string(),
17572
+ engine: PipelineEngineChoiceSchema,
17573
+ steps: array(PipelineTemplateStepSchema).readonly()
17580
17574
  });
17581
- var TrackPositionSchema = object({
17582
- x: number(),
17583
- y: number(),
17584
- timestamp: number(),
17585
- bbox: BoundingBoxSchema
17575
+ var PipelineModelOptionSchema = object({
17576
+ id: string(),
17577
+ name: string(),
17578
+ formats: record(string(), object({
17579
+ downloaded: boolean(),
17580
+ sizeMB: number()
17581
+ })),
17582
+ group: ModelVariantGroupSchema.optional(),
17583
+ legacy: boolean().optional(),
17584
+ provider: ModelProviderIdSchema.optional()
17586
17585
  });
17587
- var TrackSnapshotSchema = object({
17588
- timestamp: number(),
17589
- position: TrackPositionSchema,
17590
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
17591
- mediaKey: string()
17586
+ var ConfigFieldBridge = custom();
17587
+ var PipelineAddonSchemaSchema = object({
17588
+ id: string(),
17589
+ name: string(),
17590
+ slot: PipelineSlotSchema,
17591
+ inputClasses: array(string()).readonly(),
17592
+ outputClasses: array(string()).readonly(),
17593
+ childSlots: array(PipelineSlotSchema).readonly(),
17594
+ models: array(PipelineModelOptionSchema).readonly(),
17595
+ defaultModelId: string(),
17596
+ defaultModelIdByFormat: record(string(), string()).optional(),
17597
+ enabledByDefault: boolean().optional(),
17598
+ backfillIntoExistingOverrides: boolean().optional(),
17599
+ defaultConfidence: number(),
17600
+ group: string().optional(),
17601
+ configSchema: array(ConfigFieldBridge).readonly().optional()
17592
17602
  });
17593
- /**
17594
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
17595
- * divided by the track's detection-frame dims), computed at persist time.
17596
- * Absent when the frame dims were unknown when the track was persisted
17597
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
17598
- */
17599
- var TrackEnvelopeSchema = object({
17600
- minX: number(),
17601
- minY: number(),
17602
- maxX: number(),
17603
- maxY: number()
17603
+ var PipelineSlotSchemaSchema = object({
17604
+ id: PipelineSlotSchema,
17605
+ label: string(),
17606
+ priority: number(),
17607
+ parentSlot: PipelineSlotSchema.nullable(),
17608
+ addons: array(PipelineAddonSchemaSchema).readonly()
17604
17609
  });
17605
- /**
17606
- * Row projection for track list queries. `full` (default) returns the
17607
- * complete Track including the frame-rate `positions[]` history and the
17608
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
17609
- * keeps every scalar the list surfaces actually render (ids, class(es),
17610
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
17611
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
17612
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
17613
- * `getTrack`. Mirrors the event-store `projection` convention
17614
- * (`getObjectEvents` et al.).
17615
- */
17616
- var TrackProjectionSchema = _enum(["full", "slim"]);
17617
- /**
17618
- * One audio-classification label heard on the track's camera while the
17619
- * track was alive, aggregated per label. An "episode" is one persisted
17620
- * audio event (the confident-classification path: score ≥ the device's
17621
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
17622
- * one 32 ms inference chunk, so counts stay human-scaled.
17623
- */
17624
- var TrackAudioLabelSchema = object({
17625
- label: string(),
17626
- /** Highest classification score observed across the label's episodes. */
17627
- peakScore: number(),
17628
- /** Number of coalesced audio-event episodes carrying this label. */
17629
- count: number(),
17630
- firstAt: number(),
17631
- lastAt: number()
17610
+ var PipelineSchemaSchema = object({
17611
+ availableEngines: array(AvailableEngineSchema).readonly(),
17612
+ selectedEngine: PipelineEngineChoiceSchema,
17613
+ slots: array(PipelineSlotSchemaSchema).readonly()
17632
17614
  });
17633
- /**
17634
- * How a track was produced. `pipeline` (default / absent) = the spatial
17635
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17636
- * no positions, a single snapshot, and no bbox trajectory at all:
17637
- *
17638
- * - `sensor` — a linked sensor/control device state change.
17639
- * - `audio` — an audio event on the camera itself that was anomalous for
17640
- * THAT camera, loud, and heard while nothing visual was happening (D62).
17641
- *
17642
- * The spatial subsystems (tracker association, occupancy count, re-id /
17643
- * embedding, resurrection) MUST skip every synthetic source. Test for that
17644
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17645
- * check silently readmits every source added after it was written.
17646
- */
17647
- var TrackSourceSchema = _enum([
17648
- "pipeline",
17649
- "sensor",
17650
- "audio"
17651
- ]);
17652
- /**
17653
- * Where a track sits in the RETRAIN lifecycle (D81).
17654
- *
17655
- * - `none` never marked, or un-marked. Evictable.
17656
- * - `staging`the operator wants this track as training material and has not
17657
- * finished with it. **This is the only state retention holds**: the track and
17658
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
17659
- * the device's age window.
17660
- * - `trained` — the retrain page has taken what it needed. The frames it chose
17661
- * were COPIED into the retrain dataset at selection time, so the dataset no
17662
- * longer depends on the track's media and the track becomes EVICTABLE again.
17663
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17664
- * a deliberate action of the retrain page, not a side effect of a checkbox.
17665
- *
17666
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17667
- * the store's filter language has only positive equality and `whereIn` — no
17668
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17669
- * would make the entire pre-column history immortal in one deploy.
17670
- */
17671
- var RetrainStatusSchema = _enum([
17672
- "none",
17673
- "staging",
17674
- "trained"
17675
- ]);
17676
- /**
17677
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
17678
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17679
- * so the two surfaces cannot drift.
17680
- *
17681
- * **Absent ≠ false.** A track that has never been touched omits the field; an
17682
- * explicitly un-flagged track carries `false`. Legacy rows written before the
17683
- * columns existed read as absent, and a consumer that needs a boolean should say
17684
- * `flag === true`, not `flag !== false`.
17685
- *
17686
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17687
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17688
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17689
- * `trained` track reports `false` while refusing both writes. The boolean is
17690
- * kept because three surfaces drive a toggle off it; anything that needs to tell
17691
- * "never marked" from "already trained" must read `retrainStatus`.
17692
- *
17693
- * `debug` does NOT pin; it is attention, not durability.
17694
- *
17695
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17696
- * A favourited track is skipped by retention the same way `staging` is, but
17697
- * it does not enter `none|staging|trained` and has no staging budget.
17698
- */
17699
- var TrackFlagFields = {
17700
- /** Operator marked this track as training material — i.e. `retrainStatus` is
17701
- * `'staging'`. */
17702
- markForTrain: boolean().optional(),
17703
- /** Operator marked this track for diagnostic attention. */
17704
- debug: boolean().optional(),
17705
- /** Operator favourited this track. Pins it against pruning. */
17706
- favourited: boolean().optional()
17707
- };
17708
- /**
17709
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17710
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17711
- * write patch, and the status is not something the toggle sets — it is what the
17712
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17713
- * always present on a persisted row (the column default materialises `'none'`).
17714
- */
17715
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17716
- /**
17717
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17718
- * one flag can never clear the other — the toggles are independent and are
17719
- * driven from three surfaces that do not know about each other.
17720
- */
17721
- var TrackFlagsPatchSchema = object(TrackFlagFields);
17722
- /**
17723
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
17724
- * collapses to `false`) so a caller can drive a toggle's checked state off the
17725
- * mutation result without a re-fetch.
17726
- */
17727
- var TrackFlagsSchema = object({
17728
- trackId: string(),
17729
- markForTrain: boolean(),
17730
- debug: boolean(),
17731
- favourited: boolean(),
17732
- /** The lifecycle state the boolean was derived from. Required here (unlike on
17733
- * a track row) because this shape is only ever produced by the write body,
17734
- * which always knows it — and a surface that has just written needs to render
17735
- * `trained` without a re-fetch. */
17736
- retrainStatus: RetrainStatusSchema
17615
+ var EngineProvisioningSchema = object({
17616
+ runtimeId: _enum([
17617
+ "onnx",
17618
+ "openvino",
17619
+ "coreml",
17620
+ "edgetpu"
17621
+ ]).nullable(),
17622
+ device: string().nullable(),
17623
+ state: _enum([
17624
+ "idle",
17625
+ "installing",
17626
+ "verifying",
17627
+ "ready",
17628
+ "failed"
17629
+ ]),
17630
+ progress: number().optional(),
17631
+ error: string().optional(),
17632
+ nextRetryAt: number().optional(),
17633
+ /**
17634
+ * Gate A (config-correctness gate at engine change): human-readable
17635
+ * config issues surfaced EAGERLY when the node's engine changes — model
17636
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
17637
+ * has a <format> build"). Additive/optional: informational only, never
17638
+ * enforced here `assertEngineReady` (readiness) still gates inference.
17639
+ * Absent/empty when the node-default tree resolves cleanly.
17640
+ */
17641
+ configIssues: array(string()).optional()
17737
17642
  });
17738
- union([literal(1), literal(2)]);
17739
- /**
17740
- * WHO decided a label, and when. Carried per tier so a value can be traced to
17741
- * the step and model that produced it — which is what makes the write rule
17742
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17743
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17744
- *
17745
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17746
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17747
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
17748
- * that value has no provenance, and the write rule lets ANY properly-attributed
17749
- * write of the same tier replace it regardless of score.
17750
- */
17751
- var LabelAttributionSchema = object({
17752
- stepId: string(),
17643
+ var PipelineStepInputSchema = lazy(() => object({
17644
+ addonId: string(),
17753
17645
  modelId: string().optional(),
17754
- decidedAt: number(),
17646
+ enabled: boolean().default(true),
17647
+ children: array(PipelineStepInputSchema).optional(),
17648
+ settings: record(string(), unknown()).optional(),
17649
+ jumpDeviceKey: string().optional()
17650
+ }));
17651
+ var ModelSubstitutionSchema = object({
17652
+ addonId: string(),
17653
+ chosen: string(),
17654
+ running: string(),
17655
+ format: string()
17656
+ });
17657
+ var PipelineValidationIssueSchema = object({
17658
+ addonId: string(),
17659
+ kind: _enum(["unknown-addon", "no-format-build"]),
17660
+ detail: string()
17661
+ });
17662
+ var PipelineValidationResultSchema = object({
17663
+ ok: boolean(),
17664
+ issues: array(PipelineValidationIssueSchema).readonly(),
17665
+ substitutions: array(ModelSubstitutionSchema).readonly(),
17666
+ /** The node's `currentEngine.format` this validation ran against. */
17667
+ format: string()
17668
+ });
17669
+ var ReferenceImageEntrySchema = object({
17670
+ filename: string(),
17671
+ stepIds: array(string()).readonly().optional()
17672
+ });
17673
+ var ReferenceImageBodySchema = object({
17674
+ base64: string(),
17675
+ filename: string()
17676
+ });
17677
+ var ReferenceAudioEntrySchema = object({
17678
+ filename: string(),
17679
+ sizeKb: number()
17680
+ });
17681
+ var ReferenceAudioBodySchema = object({ base64: string() });
17682
+ var AudioBackendSchema = object({
17683
+ id: string(),
17684
+ name: string(),
17685
+ description: string(),
17686
+ available: boolean(),
17755
17687
  /**
17756
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
17757
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17758
- *
17759
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
17760
- * notification rule authored on "Gianluca" stopped matching the moment the
17761
- * operator fixed the spelling in the gallery, and nothing said so. The id is
17762
- * the thing that does not move, so it is what a rule matches on
17763
- * (`NcConditions.identities`) and the text is what a human is shown.
17764
- *
17765
- * Absent when the label names no gallery row — a plate the OCR read but no
17766
- * vehicle claims, a sub-class, a species, any tier-1 value.
17688
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
17689
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
17690
+ * the benchmark UI to populate the `enabledMicroClasses` filter
17691
+ * specific to the selected backend without a separate fetch.
17767
17692
  */
17768
- identityId: string().optional()
17693
+ rawLabels: array(string()).readonly().optional()
17694
+ });
17695
+ var AudioCapabilitiesSchema = object({
17696
+ activeBackend: string(),
17697
+ availableBackends: array(AudioBackendSchema).readonly(),
17698
+ sampleRate: number(),
17699
+ chunkDurationMs: number()
17700
+ });
17701
+ var DownloadModelResultSchema = object({
17702
+ filePath: string(),
17703
+ sizeMB: number(),
17704
+ durationMs: number()
17769
17705
  });
17770
17706
  /**
17771
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17772
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17773
- * track and its events always answer the same question the same way.
17774
- *
17775
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
17776
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17777
- * is tier 2, and each carries its own score + attribution.
17778
- *
17779
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17780
- * finest thing known. Before 4g the single `label` column held the finest
17781
- * value, so a consumer that has not been updated reads the tier-1 slot and
17782
- * shows nothing on a species-only row; that is why the migration puts every
17783
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17784
- * and why the read surfaces were changed in the same train.
17785
- *
17786
- * **Writing it.** The slots are independent, which is the whole point: a
17787
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17788
- * migratorius`), so fineness cannot regress by construction. Within a tier the
17789
- * higher score wins. One rule, one implementation — see
17790
- * `pipeline/label-tier.ts` in addon-post-analysis.
17791
- */
17792
- var TieredLabelFields = {
17793
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
17794
- label: string().optional(),
17795
- /** Confidence of the tier-1 value, as reported by the deciding step. */
17796
- labelScore: number().optional(),
17797
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17798
- labelMeta: LabelAttributionSchema.optional(),
17799
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
17800
- subLabel: string().optional(),
17801
- /** Confidence of the tier-2 value, as reported by the deciding step. */
17802
- subLabelScore: number().optional(),
17803
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17804
- subLabelMeta: LabelAttributionSchema.optional()
17805
- };
17806
- /** Per-camera slice of a training-export estimate. */
17807
- var TrainingExportDeviceTotalsSchema = object({
17808
- deviceId: number(),
17809
- tracks: number().int(),
17810
- files: number().int(),
17811
- bytes: number().int()
17812
- });
17813
- /**
17814
- * What a training export WOULD contain. Computed from media index rows only —
17815
- * no blob is read to produce this.
17707
+ * Wrapper carrying a single test run's result. Replaces the legacy
17708
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
17709
+ * canonical `AudioResult` from the Phase 6 output rework: one
17710
+ * `AudioDetection` per class above `minScore`, top-N candidates in
17711
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
17712
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
17713
+ * benchmark UI can still report a clean failure when the classifier
17714
+ * cap isn't available.
17816
17715
  */
17817
- var TrainingExportSummarySchema = object({
17818
- generatedAt: number(),
17819
- trackCount: number().int(),
17820
- fileCount: number().int(),
17821
- byteCount: number().int(),
17822
- /** More marked tracks exist than a single pass carries. */
17823
- truncated: boolean(),
17824
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
17716
+ var AudioTestResultSchema = object({
17717
+ success: boolean(),
17718
+ error: string().optional(),
17719
+ frame: custom().optional()
17825
17720
  });
17826
- var TrackSchema = object({
17827
- trackId: string(),
17828
- deviceId: number(),
17829
- className: string(),
17830
- ...TieredLabelFields,
17831
- producingDeviceName: string().optional(),
17832
- /** Track provenance. Absent `pipeline` (legacy rows). */
17833
- source: TrackSourceSchema.optional(),
17834
- firstSeen: number(),
17835
- lastSeen: number(),
17836
- /** Frame-rate position history (subject to maxPositionHistory cap). */
17837
- positions: array(TrackPositionSchema).readonly(),
17838
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17839
- * saveThumbnails policy). */
17840
- snapshots: array(TrackSnapshotSchema).readonly(),
17841
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
17842
- zonesVisited: array(string()).readonly(),
17721
+ var PipelineConfigBridge = custom();
17722
+ var ConfigUISchemaBridge = custom();
17723
+ var ConfigUISchemaNullableBridge = custom();
17724
+ var InferenceCapabilitiesBridge = custom();
17725
+ var ModelAvailabilityListBridge = custom();
17726
+ var PipelineRunResultBridge = custom();
17727
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
17728
+ modelId: string(),
17729
+ settings: record(string(), unknown()).readonly()
17730
+ }))), method(object({ steps: record(string(), object({
17731
+ modelId: string(),
17732
+ settings: record(string(), unknown()).readonly()
17733
+ })) }), object({ success: literal(true) }), {
17734
+ kind: "mutation",
17735
+ auth: "admin"
17736
+ }), method(object({ nodeId: string() }), object({
17737
+ success: literal(true),
17738
+ clearedDevices: number()
17739
+ }), {
17740
+ kind: "mutation",
17741
+ auth: "admin"
17742
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
17743
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
17744
+ deviceKey: string(),
17843
17745
  /**
17844
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17845
- * `zones` capability.
17846
- *
17847
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17848
- * and no card can render — so every free-text search surface was structurally
17849
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17850
- * just returned nothing. Resolving here rather than in each client keeps ONE
17851
- * derivation and costs the clients no extra call (the `zones` cap is
17852
- * per-device, so a client-side resolve would be a per-camera fan-out on a
17853
- * surface built to avoid exactly that).
17854
- *
17855
- * Resolved, never invented: a zone deleted since the track was written has no
17856
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17857
- * two are not positionally aligned. Absent when the track visited no zone, or
17858
- * when the zone catalogue could not be read.
17746
+ * `failed` the per-device restart budget is exhausted; no pool
17747
+ * will be spawned until an operator re-arms it or the runner
17748
+ * respawns. `backoff` — under budget, waiting out the backoff (or
17749
+ * a cached pool observed dead and not yet condemned).
17859
17750
  */
17860
- zoneNames: array(string()).readonly().optional(),
17861
- /** Deduplicated set of detector classes observed for this track over its
17862
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
17863
- * legacy rows written before class accumulation shipped. */
17864
- classes: array(string()).readonly().optional(),
17865
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17866
- totalDistance: number(),
17867
- state: TrackStateSchema,
17868
- active: boolean(),
17869
- /** Deterministic key-event importance score in [0,1] (server-computed at
17870
- * track expiry, recomputed on late label). Absent on legacy rows written
17871
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
17872
- importance: number().optional(),
17873
- /** Id of the track's highest-confidence ObjectEvent (its representative
17874
- * "best" frame). Absent when the track produced no object events. */
17875
- bestEventId: string().optional(),
17876
- /** Tag of the importance sub-signal that dominated the score
17877
- * (identity|dwell|proximity|class|confidence|travel|zone). */
17878
- importanceReason: string().optional(),
17879
- /** Audio-classification labels heard on the camera during the track's
17880
- * life (score ≥ device `classificationMinScore`), aggregated per label.
17881
- * Absent on legacy rows / tracks with no confident audio. */
17882
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17883
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17884
- * Populated from the persisted envelope columns on historical reads;
17885
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17886
- envelope: TrackEnvelopeSchema.optional(),
17751
+ state: _enum(["failed", "backoff"]),
17752
+ /** Epoch ms of the death that produced this state. */
17753
+ since: number(),
17754
+ /** Pool deaths inside the current window. */
17755
+ deaths: number(),
17756
+ /** The last death's message. */
17757
+ lastError: string()
17758
+ })).readonly() })), method(object({
17759
+ nodeId: string(),
17760
+ deviceKey: string()
17761
+ }), object({ rearmed: boolean() }), {
17762
+ kind: "mutation",
17763
+ auth: "admin"
17764
+ }), 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({
17765
+ name: string(),
17766
+ steps: array(PipelineTemplateStepSchema).readonly(),
17767
+ engine: PipelineEngineChoiceSchema
17768
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
17769
+ id: string(),
17770
+ name: string().optional(),
17771
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
17772
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
17773
+ addonId: string(),
17774
+ modelId: string(),
17775
+ format: ModelFormatSchema$1
17776
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
17777
+ addonId: string(),
17778
+ modelId: string(),
17779
+ format: ModelFormatSchema$1
17780
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
17781
+ engine: PipelineEngineChoiceSchema.optional(),
17782
+ steps: array(PipelineStepInputSchema).min(1),
17783
+ frame: FrameInputSchema.optional(),
17887
17784
  /**
17888
- * A face DETECTOR found a face on this track — nothing more. It says the
17889
- * detail plane produced a `face` detail; it does NOT say the face was
17890
- * embedded, matched, above `minFacePx`, or that the recognizer was even
17891
- * enabled. Set once and never cleared.
17892
- *
17893
- * **This exists so "face present but not recognised" is expressible.** A
17894
- * recognised identity lands in `subLabel` (attributed to the face chain via
17895
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17896
- * and a track with no face at all were byte-identical on the wire and no
17897
- * surface could tell them apart. The read is `hasFace === true && subLabel
17898
- * === undefined`.
17899
- *
17900
- * **Absent ≠ false.** Every row written before the column existed omits it,
17901
- * and so does every server that predates the field — a consumer must test
17902
- * `=== true` and render nothing otherwise, never infer "no face".
17785
+ * Process-local lazy frame. Valid only when caller and provider resolve
17786
+ * in the same execution-group process; split/cross-node callers use
17787
+ * `frame`/`image` inline compatibility instead.
17903
17788
  */
17904
- hasFace: boolean().optional(),
17789
+ frameRef: FrameRefSchema.optional(),
17905
17790
  /**
17906
- * This track has a face row IN THE GALLERY: a crop **and** an embedding a
17907
- * face an operator could ASSIGN to an identity.
17908
- *
17909
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17910
- * because the two disagree. `hasFace` is stamped at the TOP of the face
17911
- * branch, before every gate, and means no more than "a face detector produced
17912
- * a face detail". This one is stamped at the single moment the gallery row
17913
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17914
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17915
- * candidate gate, the imageless-track drop (no crop was ever captured) and
17916
- * the crop-store drop. Everything between the detector and that insert can
17917
- * legitimately refuse the face, so a flag written any earlier promises the
17918
- * operator something to assign and delivers nothing.
17919
- *
17920
- * **Independent of recognition.** A face collected but never auto-matched is
17921
- * still assignable — it is in fact the face an operator most wants to reach —
17922
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17923
- * `subLabel`; this says only that the raw material exists.
17924
- *
17925
- * **Set once, never cleared.** A track that produced a gallery row produced
17926
- * one; deleting the row later is the gallery's business, not this flag's.
17927
- *
17928
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17929
- * before the column omits it, and so does every server that predates the
17930
- * field. A consumer must test `=== true` and render nothing otherwise —
17931
- * never infer "no assignable face".
17791
+ * CB5 shm passthrough a `FrameHandle` naming the same ring slot
17792
+ * the decoded pixels live in. One more member of the one-of
17793
+ * frame/frameHandle/image/imageBase64/referenceImage group.
17932
17794
  */
17933
- hasEmbeddedFace: boolean().optional(),
17795
+ frameHandle: FrameHandleSchema.optional(),
17796
+ imageBase64: string().optional(),
17934
17797
  /**
17935
- * This subject CONTAINS a folded rider a person the rider-pairing step
17936
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17937
- * so the passage is tracked once and as a VEHICLE.
17938
- *
17939
- * It exists because the fold's record was dishonest. D34 and the code both
17940
- * said "the person is not lost — it is reported so both entities stay on the
17941
- * record"; in fact the pair went into a per-processor RAM field behind an
17942
- * accessor nobody called, and every durable surface said `vehicle`, full
17943
- * stop. This is the composition note that makes the row true.
17944
- *
17945
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
17946
- * person" is not an answer to "what is this" — both label tiers would refuse
17947
- * a macro token anyway (D89), and correctly. Nothing here changes what the
17948
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17949
- * and a `person` rule still does not fire for someone cycling past.
17950
- *
17951
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17952
- * the column, and every hub that predates the field, omits it. Test
17953
- * `=== true` and render nothing otherwise — never infer "no rider".
17798
+ * Binary JPEG bytespreferred over `imageBase64` on internal
17799
+ * hops (hub forked worker via Moleculer MsgPack) because it
17800
+ * skips the 33% base64 overhead + the per-call base64 decode on
17801
+ * the detection-pipeline worker. Callers can pass either; exactly
17802
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
17954
17803
  */
17955
- hasRider: boolean().optional(),
17956
- ...TrackFlagFields,
17957
- ...TrackRetrainFields
17958
- });
17959
- var BaseEventFields = {
17960
- id: string(),
17961
- deviceId: number(),
17962
- timestamp: number()
17963
- };
17964
- var MotionEventSchema = object({
17965
- ...BaseEventFields,
17966
- kind: literal("motion"),
17967
- regionCount: number(),
17968
- /** Heavy JSON array omitted in slim projection. */
17969
- regions: array(object({
17970
- bbox: BoundingBoxSchema,
17971
- pixelCount: number(),
17972
- intensity: number()
17973
- })).readonly().optional(),
17974
- /** Omitted in slim projection. */
17975
- frameWidth: number().optional(),
17976
- /** Omitted in slim projection. */
17977
- frameHeight: number().optional(),
17978
- /** Populated by B5 (recording playback URL for this event). */
17979
- mediaUrl: string().optional()
17980
- });
17804
+ image: _instanceof(Uint8Array).optional(),
17805
+ referenceImage: string().optional(),
17806
+ deviceId: number().optional(),
17807
+ sessionId: string().optional(),
17808
+ /**
17809
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
17810
+ * reference-image, and detail-subtree calls. 'frame' is the live
17811
+ * per-frame dispatch: ONLY root-plane steps run; crop children
17812
+ * (inputClasses ≠ null) are skipped and served per-track via
17813
+ * pipelineRunner.runDetailSubtree (two-plane design).
17814
+ */
17815
+ plane: _enum(["full", "frame"]).optional(),
17816
+ /**
17817
+ * Inference-device selector (Phase 2 multi-device). Format
17818
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
17819
+ * Omitted ⇒ the runner's default device (current single-engine
17820
+ * behaviour). Selects WHICH device pool of the node runs the call.
17821
+ */
17822
+ deviceKey: string().optional(),
17823
+ /**
17824
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
17825
+ * when the parent crop was resolved from the frame's retained NATIVE
17826
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
17827
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
17828
+ * resolution from that surface — the SAME quality path faces already
17829
+ * had — instead of the downscaled parent tile. `handle` keys the native
17830
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
17831
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
17832
+ * the executor's crop-normalized child ROI back into frame-normalized
17833
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
17834
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
17835
+ * (today's behaviour on the fallback path).
17836
+ */
17837
+ nativeCropRef: NativeCropRefSchema.optional()
17838
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
17839
+ engine: PipelineEngineChoiceSchema.optional(),
17840
+ steps: array(PipelineStepInputSchema).min(1),
17841
+ frames: array(FrameInputSchema).min(1).max(255),
17842
+ deviceId: number().optional(),
17843
+ sessionId: string().optional(),
17844
+ /**
17845
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
17846
+ * the batch to the Python pool's bench preprocess cache
17847
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
17848
+ * preprocessed ONCE and every later inference is a pure-inference cache
17849
+ * hit — the sustained-throughput run measures inference, not
17850
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
17851
+ * full preprocess every call, correct). Fresh per sustained run;
17852
+ * released via `uncacheFrame`.
17853
+ */
17854
+ frameId: number().int().nonnegative().optional(),
17855
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
17856
+ deviceKey: string().optional()
17857
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
17858
+ data: _instanceof(Uint8Array),
17859
+ width: number().int().positive(),
17860
+ height: number().int().positive(),
17861
+ format: _enum([
17862
+ "rgb",
17863
+ "bgr",
17864
+ "gray"
17865
+ ])
17866
+ }), object({
17867
+ frameId: number(),
17868
+ width: number(),
17869
+ height: number()
17870
+ }), { kind: "mutation" }), method(object({
17871
+ stepId: string(),
17872
+ frameId: number().int()
17873
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
17874
+ batchMode: string(),
17875
+ windowMs: number(),
17876
+ maxBatchSize: number(),
17877
+ concurrency: number()
17878
+ })), method(_void(), array(object({
17879
+ engineKey: string(),
17880
+ engine: PipelineEngineChoiceSchema,
17881
+ modelsLoaded: array(string()).readonly(),
17882
+ inUseByCameras: array(number()).readonly(),
17883
+ /**
17884
+ * Origin of this resident factory.
17885
+ * - `runtime` — main camera-serving engine (no idle TTL).
17886
+ * - `warm-override` — benchmark/test override held in the warm
17887
+ * cache; auto-disposed after the idle TTL.
17888
+ * - `device-pool` — a concurrent per-device pool (Phase 2
17889
+ * multi-device, keyed by `deviceKey`) resolved
17890
+ * via `resolveDeviceFactory`. Runs alongside the
17891
+ * `runtime` engine on a DIFFERENT accelerator
17892
+ * (NPU / iGPU / Coral) — this is how the
17893
+ * Engines tab shows all pools running at once.
17894
+ */
17895
+ kind: _enum([
17896
+ "runtime",
17897
+ "warm-override",
17898
+ "device-pool"
17899
+ ]),
17900
+ /** Native pid of the underlying Python pool (null when no pool). */
17901
+ poolPid: number().nullable(),
17902
+ /** ms since this factory was last used (null when not warm-tracked). */
17903
+ idleMs: number().nullable(),
17904
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
17905
+ idleTtlMs: number().nullable()
17906
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
17907
+ kind: "mutation",
17908
+ auth: "admin"
17909
+ }), method(object({
17910
+ engine: PipelineEngineChoiceSchema,
17911
+ force: boolean().optional()
17912
+ }), object({
17913
+ success: boolean(),
17914
+ reason: string().optional()
17915
+ }), {
17916
+ kind: "mutation",
17917
+ auth: "admin"
17918
+ }), 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({
17919
+ addonId: string(),
17920
+ modelId: string(),
17921
+ filename: string().optional(),
17922
+ settings: record(string(), unknown()).optional()
17923
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
17981
17924
  /**
17982
- * Which detection SOURCE produced an object event. `pipeline` = the ML
17983
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
17984
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
17985
- * tracking, per-kind persistence) but stay distinguishable so consumers
17986
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17987
- * Absent on legacy rows treat as `pipeline`.
17925
+ * Per-stage gating mode applied to the zones a rule references.
17926
+ *
17927
+ * - `include`: the rule contributes to a **whitelist** for its stage.
17928
+ * When at least one `include` rule fires for a stage, only entities
17929
+ * inside one of those zones pass that stage.
17930
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
17931
+ * Entities inside one of those zones are dropped at that stage.
17932
+ *
17933
+ * `monitor`-style observation (count without filtering) is not a rule
17934
+ * mode — zones without any matching rule are observed naturally by
17935
+ * `zone-analytics` (live snapshot + history), so an "I just want to
17936
+ * count, not filter" use case needs no rule at all.
17988
17937
  */
17989
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17938
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
17990
17939
  /**
17991
- * The confirmed zone crossing that produced an object event. Present ONLY on
17992
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17993
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17994
- * appearance event carry none, so a rule asking for a direction fails closed
17995
- * on them.
17940
+ * Per-consumer rule that references existing zones (geometry) and
17941
+ * defines how a specific pipeline stage should treat them. Each
17942
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
17943
+ * settings:
17996
17944
  *
17997
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17998
- * into its own event, so a frame in which a track enters A while leaving B
17999
- * produces two events with two directions — never one ambiguous row.
17945
+ * - `addon-motion-wasm` `motionZoneRules: ZoneRule[]` (motion stage)
17946
+ * - `addon-detection-pipeline` `detectionZoneRules: ZoneRule[]` (detection stage)
17947
+ * - future: notification rules, audio gating, etc.
18000
17948
  *
18001
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
18002
- * membership the box has NOW, and by definition it no longer contains the zone
18003
- * that was just left. Without the id here, a zone-scoped rule could never match
18004
- * the exit it asked for.
17949
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
17950
+ * express "ignore motion in ALL of {garden, street}" with a single
17951
+ * rule. `classFilter` narrows the rule to specific object classes
17952
+ * "drop person detections in the street, but keep cars" is one
17953
+ * `exclude` rule with `classFilter: ['person']`.
17954
+ *
17955
+ * `enabled` is a soft toggle — the operator can keep the rule
17956
+ * configured but inert without deleting it.
18005
17957
  */
18006
- var ZoneCrossingSchema = object({
18007
- direction: _enum(["enter", "exit"]),
18008
- /** Admin zone id crossed. */
18009
- zoneId: string(),
18010
- /** Zone display name at crossing time (falls back to the id). */
18011
- zoneName: string().optional()
18012
- });
18013
- var ObjectEventSchema = object({
18014
- ...BaseEventFields,
18015
- kind: literal("object"),
18016
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
18017
- source: DetectionSourceSchema.optional(),
17958
+ var ZoneRuleSchema = object({
17959
+ /** Stable rule id — survives edits, used by the UI for diffing. */
17960
+ id: string(),
17961
+ /** Optional human-readable label rendered in the rule editor. */
17962
+ name: string().optional(),
17963
+ /** Zones this rule targets. The rule's `mode` applies to ALL
17964
+ * listed zones (OR-set: a detection in any one of them counts).
17965
+ * At least one zone id required — a rule with no targets is a
17966
+ * configuration mistake and the form validator rejects it. */
17967
+ zoneIds: array(string()).min(1).readonly(),
17968
+ mode: ZoneRuleModeEnum,
18018
17969
  /**
18019
- * Inference-frame id shared by every object event emitted from the SAME frame
18020
- * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
18021
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
18022
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
18023
- * Optional for backward-compat with pre-existing rows / the slim projection
18024
- * includes it (it is light). Absent on rows written before this field.
17970
+ * Class names this rule applies to. Empty / undefined rule
17971
+ * applies to every class. Class strings match the `macroClass`
17972
+ * field on detections (e.g. `person`, `car`, `dog`).
18025
17973
  */
18026
- frameId: string().optional(),
18027
- /** Omitted in slim projection. */
18028
- trackId: string().optional(),
18029
- className: string(),
18030
- ...TieredLabelFields,
18031
- /** Omitted in slim projection. */
18032
- confidence: number().optional(),
18033
- /** Heavy JSON — omitted in slim projection. */
18034
- bbox: BoundingBoxSchema.optional(),
18035
- /** Heavy JSON — omitted in slim projection. */
18036
- zones: array(string()).readonly().optional(),
18037
- /** Omitted in slim projection. */
18038
- state: TrackStateSchema.optional(),
17974
+ classFilter: array(string()).readonly().optional(),
18039
17975
  /**
18040
- * The zone crossing this event IS, when it is one. Absent on every other
18041
- * event kind (movement state, appearance, package) see
18042
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
17976
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
17977
+ * required to consider an entity "in the zone". Defaults to the
17978
+ * consumer's stage default when omitted. Kept for back-compat with
17979
+ * existing per-rule overrides; new operators pick the value via
17980
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
17981
+ * set, the lower-level engine reads it as a 0–1 fraction.
18043
17982
  */
18044
- zoneCrossing: ZoneCrossingSchema.optional(),
18045
- /** Detection-frame dimensions in pixels — let consumers normalize the
18046
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
18047
- frameWidth: number().optional(),
18048
- frameHeight: number().optional(),
18049
- /** MediaStore key for the crop attached to this event (if any). */
18050
- mediaKey: string().optional(),
18051
- /** Design B: MediaStore key of the track's native-resolution key frame (the
18052
- * best-detection full frame). Resolve via the event-media data-plane
18053
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
18054
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
18055
- * sources — consumers fall back to `mediaKey` (the tight crop). */
18056
- keyFrameMediaKey: string().optional(),
18057
- /** Populated by B5 (recording playback URL for this event). */
18058
- mediaUrl: string().optional(),
18059
- /** The parent track's key-event importance [0,1], propagated to every object
18060
- * event of the track (so an event row can be sorted by importance without a
18061
- * track join). Absent on legacy rows / before the track was scored. */
18062
- importance: number().optional()
18063
- });
18064
- var AudioEventSchema = object({
18065
- ...BaseEventFields,
18066
- kind: literal("audio"),
18067
- rms: number(),
18068
- dbfs: number(),
18069
- classification: object({
18070
- className: string(),
18071
- originalClass: string().optional(),
18072
- score: number()
18073
- }).optional(),
18074
- /** Populated by B5 (recording playback URL for this event). */
18075
- mediaUrl: string().optional()
17983
+ overlapThreshold: number().min(0).max(1).optional(),
17984
+ /**
17985
+ * Operator-friendly version of `overlapThreshold` the percentage
17986
+ * of the detection's bbox that must lie inside the zone for the
17987
+ * rule to match. Documented default is 85%; the engine substitutes
17988
+ * that when the field is omitted (kept optional so existing rules
17989
+ * stored without it stay valid).
17990
+ *
17991
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
17992
+ * rule, the engine prefers `bboxInclusionPct` because it's the
17993
+ * field exposed in the UI. Internally both feed the same gate.
17994
+ */
17995
+ bboxInclusionPct: number().min(0).max(100).optional(),
17996
+ /**
17997
+ * When `true` and a detection has a segmentation mask, use the
17998
+ * mask for overlap instead of the bbox. Detection-stage only;
17999
+ * motion rules ignore this field.
18000
+ */
18001
+ preferMask: boolean().optional(),
18002
+ /**
18003
+ * Soft-toggle: `false` disables the rule without deleting it.
18004
+ * Defaults to `true` so operators creating a rule via the UI
18005
+ * see it active immediately.
18006
+ */
18007
+ enabled: boolean().default(true)
18076
18008
  });
18077
- var MediaFileKindEnum = _enum([
18078
- "crop",
18079
- "thumbnail",
18080
- "snapshot",
18081
- "firstFrame",
18082
- "lastFrame",
18083
- "fullFrame",
18084
- "fullFrameBoxed",
18085
- "faceCrop",
18086
- "plateCrop",
18087
- "keyFrame",
18088
- "keyFrameSmall",
18089
- "thumbnailSmall"
18090
- ]);
18091
- var MediaFileSchema = object({
18092
- key: string(),
18093
- kind: MediaFileKindEnum,
18094
- base64: string(),
18095
- sizeBytes: number(),
18096
- timestamp: number()
18009
+ array(ZoneRuleSchema).readonly();
18010
+ /**
18011
+ * Zone — pure geometry + identity. NO filtering behaviour.
18012
+ *
18013
+ * Zones describe **where** in the frame the operator wants to flag
18014
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
18015
+ * each pipeline stage uses them. Splitting the two means a single
18016
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
18017
+ * a detection-include rule on `['car']`, and an occupancy aggregate
18018
+ * — without three duplicated polygons.
18019
+ *
18020
+ * Owned by the orchestrator addon (provider) and mirrored into the
18021
+ * `zones` device-state slice on every mutation. Consumers
18022
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
18023
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
18024
+ * mirror with `onChanged`).
18025
+ *
18026
+ * Coordinates are normalised fractions of the frame (0–1) so zones
18027
+ * survive resolution changes and stream profile switches.
18028
+ *
18029
+ * `kind` discriminates between full polygons (closed regions used
18030
+ * for intrusion / occupancy filters) and tripwires (open 2-point
18031
+ * line segments used for cross events). Onboard / firmware-reported
18032
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
18033
+ * task list.
18034
+ */
18035
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
18036
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
18037
+ var PolygonPointSchema = object({
18038
+ x: number(),
18039
+ y: number()
18040
+ });
18041
+ /** A camera detection zone — pure geometry/identity. */
18042
+ var ZoneSchema = object({
18043
+ id: string(),
18044
+ name: string(),
18045
+ kind: ZoneKindEnum.default("polygon"),
18046
+ /** Polygon vertices, fraction of frame (0–1). */
18047
+ polygon: array(PolygonPointSchema).readonly(),
18048
+ /** Visual color for UI rendering. */
18049
+ color: string().default("#3b82f6")
18097
18050
  });
18098
18051
  /**
18099
- * One media row WITHOUT its bytes.
18052
+ * Zones capability per-camera CRUD over polygon detection zones.
18100
18053
  *
18101
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
18102
- * 140 s track), and a client that renders tiles from the media data plane needs
18103
- * to know only WHAT EXISTS the bytes then arrive per tile, lazily, over HTTP
18104
- * with an immutable cache, instead of all at once inside a tRPC response that
18105
- * blocks the whole view.
18054
+ * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
18055
+ * to per-device settings and mirrors into the `zones` device-state
18056
+ * slice on every mutation, so downstream consumers can subscribe via
18057
+ * `dev.state.zones.onChanged`.
18106
18058
  *
18107
- * `sizeBytes` is carried because it is what lets a client decide between the
18108
- * stored blob and a `?variant=thumb` rendering without fetching either.
18059
+ * The cap surface only handles geometry + identity; filtering
18060
+ * behaviour (per-class, include/exclude, threshold) lives in the
18061
+ * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
18062
+ * `capabilities/schemas/zone-rule.js`.
18109
18063
  */
18110
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
18064
+ var zonesCapability = {
18065
+ name: "zones",
18066
+ scope: "device",
18067
+ mode: "singleton",
18068
+ deviceTypes: [DeviceType.Camera],
18069
+ methods: {
18070
+ listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
18071
+ addZone: method(object({
18072
+ deviceId: number(),
18073
+ zone: ZoneSchema
18074
+ }), _void(), {
18075
+ kind: "mutation",
18076
+ auth: "admin"
18077
+ }),
18078
+ removeZone: method(object({
18079
+ deviceId: number(),
18080
+ zoneId: string()
18081
+ }), _void(), {
18082
+ kind: "mutation",
18083
+ auth: "admin"
18084
+ }),
18085
+ updateZone: method(object({
18086
+ deviceId: number(),
18087
+ zone: ZoneSchema
18088
+ }), _void(), {
18089
+ kind: "mutation",
18090
+ auth: "admin"
18091
+ })
18092
+ },
18093
+ /**
18094
+ * Runtime-state slice — the live zone catalogue mirrored by the
18095
+ * orchestrator on every CRUD mutation. Consumers read via
18096
+ * `device.state.zones.value` / `.watch(...)` without round-tripping
18097
+ * the cap, and the codegen DeviceProxy auto-wires the reactive
18098
+ * handle. Slice shape is `{ zones: Zone[] }` so future extensions
18099
+ * (e.g. zone groupings) can sit alongside the polygon list.
18100
+ */
18101
+ runtimeState: object({ zones: array(ZoneSchema).readonly() }),
18102
+ /**
18103
+ * 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.
18104
+ *
18105
+ * See `RuntimeStateDurability`. Enforced by
18106
+ * `scripts/check-runtime-state-durability.ts`.
18107
+ */
18108
+ durability: "restored"
18109
+ };
18111
18110
  /**
18112
- * The MACRO tier of an annotation — a CLOSED set.
18111
+ * pipeline-analytics device-scoped wrapper cap. Refines raw
18112
+ * per-frame detections emitted by the pipeline runner into tracked
18113
+ * objects, per-kind event collections (motion / object / audio), and
18114
+ * persisted media. Owns the post-detection domain end-to-end:
18113
18115
  *
18114
- * This is what the exported detector predicts, so a typo here is a new class
18115
- * with one example in it. `label` and `subLabel` are open strings by contrast:
18116
- * the whole point of the page is teaching the model things it does not know
18117
- * yet, and constraining that vocabulary would make it useless.
18116
+ * runner emits PipelineInferenceResult
18117
+ * (event bus)
18118
+ * pipeline-analytics subscriber
18119
+ * SORT tracker + zone engine + state analyzer + event emitter
18120
+ * → three DB collections (one per kind), one FS media tree, one
18121
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
18122
+ * DetectionEvent on bus)
18118
18123
  *
18119
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
18120
- * `subLabel` is one of these values, in any casing, because once `person`
18121
- * exists in both tiers "every person box" stops being answerable without
18122
- * knowing every string anyone ever typed — and the damage is retroactive.
18124
+ * Pure subscriber model. No `processFrame` cap method the runner
18125
+ * already publishes the raw frame on the bus. The cap surface is
18126
+ * only QUERIES + per-device settings, bound on/off via
18127
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
18128
+ * every camera with a detection pipeline wants its raw detections
18129
+ * refined; operators opt out per-device via BindingsTab when needed.
18130
+ *
18131
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
18132
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
18123
18133
  */
18124
- var RetrainMacroClassSchema = _enum([
18134
+ var TrackStateSchema = _enum([
18135
+ "new",
18136
+ "entered",
18137
+ "left",
18138
+ "moving",
18139
+ "idle"
18140
+ ]);
18141
+ var EventKindSchema = _enum([
18142
+ "motion",
18143
+ "object",
18144
+ "audio"
18145
+ ]);
18146
+ /**
18147
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
18148
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
18149
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
18150
+ */
18151
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
18152
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
18153
+ var EventKindIconSchema = _enum([
18154
+ "motion",
18155
+ "audio",
18125
18156
  "person",
18126
18157
  "vehicle",
18127
18158
  "animal",
18159
+ "door",
18160
+ "pir",
18161
+ "smoke",
18162
+ "water",
18163
+ "button",
18128
18164
  "package",
18129
- "face",
18130
- "plate"
18165
+ "generic"
18131
18166
  ]);
18132
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
18133
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
18134
- /** Did a human draw this box, or did the assist propose it? */
18135
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
18136
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
18137
- var RetrainBboxSchema = object({
18138
- x: number(),
18139
- y: number(),
18140
- w: number(),
18141
- h: number()
18167
+ var EventKindCategorySchema = _enum([
18168
+ "motion",
18169
+ "audio",
18170
+ "detection",
18171
+ "sensor",
18172
+ "control",
18173
+ "custom",
18174
+ "package"
18175
+ ]);
18176
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
18177
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
18178
+ var EventKindDescriptorSchema = object({
18179
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
18180
+ kind: string(),
18181
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
18182
+ labelKey: string(),
18183
+ /** English fallback label (kept for clients that don't translate). */
18184
+ label: string(),
18185
+ /** Hex color for timeline/legend rendering. */
18186
+ color: string(),
18187
+ /** Dictionary id → lucide component on the UI side. */
18188
+ iconId: string(),
18189
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
18190
+ icon: EventKindIconSchema,
18191
+ category: EventKindCategorySchema,
18192
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
18193
+ parentKind: string().nullable(),
18194
+ /** Derived from `parentKind`, explicit for the client tree. */
18195
+ level: EventKindLevelSchema,
18196
+ /** Which cap + device contributes this kind. For built-ins the camera
18197
+ * itself; for sensor kinds the LINKED source device. */
18198
+ source: object({
18199
+ capName: string(),
18200
+ deviceId: number()
18201
+ })
18142
18202
  });
18143
- /**
18144
- * One annotated subject.
18145
- *
18146
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
18147
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
18148
- * derived from it at export and never stored — storing them is how one feature
18149
- * space ends up holding two crops of the same subject (D52).
18150
- */
18151
- var RetrainAnnotationSchema = object({
18152
- id: string(),
18153
- trackId: string(),
18203
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
18204
+ var EventKindsForDeviceSchema = object({
18154
18205
  deviceId: number(),
18155
- /** The COPY in retrain storage — never the source track's media key. */
18156
- mediaKey: string(),
18157
- bbox: RetrainBboxSchema,
18158
- macroClass: RetrainMacroClassSchema,
18159
- label: string().optional(),
18160
- subLabel: string().optional(),
18161
- kind: RetrainAnnotationKindSchema,
18162
- source: RetrainAnnotationSourceSchema,
18163
- /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
18164
- assistModelId: string().optional(),
18165
- assistScore: number().optional(),
18166
- exportedInBatch: string().optional(),
18167
- createdAt: number()
18168
- });
18169
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
18170
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
18171
- id: true,
18172
- trackId: true,
18173
- deviceId: true,
18174
- mediaKey: true,
18175
- createdAt: true,
18176
- exportedInBatch: true
18206
+ kinds: array(EventKindDescriptorSchema).readonly()
18177
18207
  });
18178
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
18179
- var RetrainTrackSchema = object({
18180
- trackId: string(),
18208
+ var SensorEventSchema = object({
18209
+ id: string(),
18210
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
18211
+ * yields N rows, one per camera). */
18181
18212
  deviceId: number(),
18182
- className: string(),
18183
- label: string().optional(),
18184
- firstSeen: number(),
18185
- lastSeen: number(),
18186
- /** How many frames the dataset already holds from this track. */
18187
- frameCount: number().int(),
18188
- /** How many subjects have been annotated on those frames. `0` with
18189
- * `frameCount: 0` is exactly "staging, still to work". */
18190
- annotationCount: number().int()
18213
+ /** The linked sensor device whose state changed. */
18214
+ sourceDeviceId: number(),
18215
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
18216
+ kind: string(),
18217
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
18218
+ value: record(string(), unknown()).nullable(),
18219
+ timestamp: number()
18191
18220
  });
18192
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
18193
- var RetrainFrameCandidateSchema = object({
18194
- mediaKey: string(),
18195
- kind: MediaFileKindEnum,
18221
+ var TrackPositionSchema = object({
18222
+ x: number(),
18223
+ y: number(),
18196
18224
  timestamp: number(),
18197
- sizeBytes: number().int(),
18198
- /** A copy of this original already exists — selecting it is free and cannot
18199
- * fail, whatever became of the original. */
18200
- copied: boolean()
18201
- });
18202
- /** A frame the dataset OWNS: bytes copied at selection time. */
18203
- var RetrainFrameSchema = object({
18204
- frameId: string(),
18205
- deviceId: number(),
18206
- trackId: string(),
18207
- /** Provenance only. It may already point at nothing — that is expected. */
18208
- sourceMediaKey: string(),
18209
- sourceKind: MediaFileKindEnum,
18210
- sizeBytes: number().int(),
18211
- width: number().int(),
18212
- height: number().int(),
18213
- copiedAt: number()
18214
- });
18215
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
18216
- var RetrainCopyRefusalSchema = _enum([
18217
- "source-missing",
18218
- "unreadable-image",
18219
- "write-failed"
18220
- ]);
18221
- var RetrainFrameSelectionSchema = object({
18222
- copied: array(RetrainFrameSchema).readonly(),
18223
- refused: array(object({
18224
- sourceMediaKey: string(),
18225
- reason: RetrainCopyRefusalSchema
18226
- })).readonly()
18225
+ bbox: BoundingBoxSchema
18227
18226
  });
18228
- var RetrainFrameListSchema = object({
18229
- candidates: array(RetrainFrameCandidateSchema).readonly(),
18230
- copies: array(RetrainFrameSchema).readonly(),
18231
- /** What the page pre-selects the native key frame when one survives. */
18232
- autoPickMediaKey: string().optional()
18227
+ var TrackSnapshotSchema = object({
18228
+ timestamp: number(),
18229
+ position: TrackPositionSchema,
18230
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
18231
+ mediaKey: string()
18233
18232
  });
18234
- /** What the operator asked the assist to look for. */
18235
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
18236
- kind: literal("package"),
18237
- zone: RetrainBboxSchema.optional()
18238
- }), object({
18239
- kind: literal("objects"),
18240
- modelId: string(),
18241
- minScore: number().optional()
18242
- })]);
18243
18233
  /**
18244
- * The assist's answer a discriminated union, because "the model saw nothing"
18245
- * and "this node cannot run that model" lead to different next moves and a
18246
- * nullable result cannot tell them apart.
18234
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
18235
+ * divided by the track's detection-frame dims), computed at persist time.
18236
+ * Absent when the frame dims were unknown when the track was persisted
18237
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
18247
18238
  */
18248
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
18249
- kind: literal("proposed"),
18250
- modelId: string(),
18251
- stepId: string(),
18252
- minScore: number(),
18253
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
18254
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
18255
- /** Returned by the runner but removed by the threshold. */
18256
- belowThreshold: number().int()
18257
- }), object({
18258
- kind: literal("refused"),
18259
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
18260
- reason: string(),
18261
- detail: string().optional()
18262
- })]);
18263
- /** The outcome of a lifecycle move owned by the retrain page. */
18264
- var RetrainTransitionResultSchema = object({
18265
- trackId: string(),
18266
- /** Where the track ended up, whatever happened. */
18267
- retrainStatus: RetrainStatusSchema,
18268
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
18269
- changed: boolean(),
18270
- reason: _enum([
18271
- "unknown-track",
18272
- "no-frames-copied",
18273
- "not-staging",
18274
- "not-trained",
18275
- "unchanged"
18276
- ]).optional()
18277
- });
18278
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
18279
- var MAX_EVENT_QUERY_LIMIT = 5e3;
18280
- var DeviceEventQueryInput = object({
18281
- deviceId: number(),
18282
- since: number().optional(),
18283
- until: number().optional(),
18284
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
18285
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
18286
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
18287
- * exact behaviour. Callers may omit this field — the store defaults to
18288
- * `full` when not provided. */
18289
- projection: _enum(["full", "slim"]).optional()
18290
- });
18291
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
18292
- var RecentTracksQueryInput = object({
18293
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
18294
- deviceIds: array(number()),
18295
- /** Window lower bound on `lastSeen` (inclusive). */
18296
- since: number().optional(),
18297
- /** Window upper bound on `lastSeen` (inclusive). */
18298
- until: number().optional(),
18299
- /** Page size. Default 200, max 1000. */
18300
- limit: number().int().min(1).max(1e3).default(200),
18301
- /** Opaque continuation cursor from a previous page's `nextCursor`.
18302
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
18303
- cursor: string().optional(),
18304
- /** See {@link TrackProjectionSchema}. Default `full`. */
18305
- projection: TrackProjectionSchema.optional(),
18306
- /** Include stationary-promoted rows (parked objects). Default false: the
18307
- * feed lists passages; parking records live on the stationary registry. */
18308
- includeStationary: boolean().optional()
18309
- });
18310
- var RecentTracksPageSchema = object({
18311
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
18312
- tracks: array(TrackSchema).readonly(),
18313
- /** Cursor for the next page, or null when this page is the last. */
18314
- nextCursor: string().nullable()
18315
- });
18316
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
18317
- var LIST_GROUPS_MAX_LIMIT = 100;
18318
- var AnalyticsGroupRecordSchema = object({
18319
- id: string(),
18320
- deviceId: number().int(),
18321
- openedAt: number().int(),
18322
- closedAt: number().int(),
18323
- timestamp: number().int(),
18324
- memberCount: number().int(),
18325
- memberTrackIds: array(string()).readonly(),
18326
- className: string(),
18327
- classes: array(string()).readonly(),
18328
- /** Relative event-media path, or null when the group has no picture yet. */
18329
- mediaUrl: string().nullable(),
18330
- singleton: boolean()
18239
+ var TrackEnvelopeSchema = object({
18240
+ minX: number(),
18241
+ minY: number(),
18242
+ maxX: number(),
18243
+ maxY: number()
18331
18244
  });
18332
- var AnalyticsGroupMemberSchema = object({
18333
- trackId: string(),
18334
- deviceId: number().int(),
18335
- className: string(),
18336
- firstSeen: number().int(),
18337
- lastSeen: number().int(),
18338
- mediaUrl: string().nullable()
18339
- });
18340
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
18341
- var ListGroupsQueryInput = object({
18342
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
18343
- deviceIds: array(number()),
18344
- /** Window lower bound on `closedAt` (inclusive). */
18345
- since: number().optional(),
18346
- /** Window upper bound on `openedAt` (inclusive). */
18347
- until: number().optional(),
18348
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
18349
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
18350
- cursor: string().optional()
18351
- });
18352
- var ListGroupsPageSchema = object({
18353
- groups: array(AnalyticsGroupRecordSchema).readonly(),
18354
- nextCursor: string().nullable()
18355
- });
18356
- var KeyEventQueryInput = object({
18357
- deviceId: number(),
18358
- /** Window lower bound (track firstSeen ≥ since). */
18359
- since: number(),
18360
- /** Window upper bound (track firstSeen ≤ until). */
18361
- until: number(),
18362
- limit: number().int().min(1).max(200).default(50),
18363
- /** Drop tracks scoring below this importance. */
18364
- minImportance: number().min(0).max(1).optional(),
18365
- /** Restrict to a single class (e.g. 'person'). */
18366
- classFilter: string().optional()
18367
- });
18368
- var KeyEventSchema = object({
18369
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
18370
- id: string(),
18371
- trackId: string(),
18372
- /** Track start time (firstSeen). */
18373
- timestamp: number(),
18374
- className: string(),
18375
- ...TieredLabelFields,
18376
- importance: number(),
18377
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
18378
- bestEventId: string(),
18379
- /** Track lifetime in ms (lastSeen - firstSeen). */
18380
- windowMs: number().optional(),
18381
- ...TrackFlagFields,
18382
- ...TrackRetrainFields
18383
- });
18384
- object({
18385
- trackId: string(),
18386
- className: string(),
18387
- confidence: number(),
18388
- bbox: BoundingBoxSchema,
18389
- zones: array(string()).readonly(),
18390
- state: TrackStateSchema
18391
- });
18392
- var OverlayDetectionSchema = looseObject({
18393
- id: string(),
18394
- kind: _enum(["first-level", "detail"]),
18395
- macroClass: string(),
18396
- score: number(),
18397
- bbox: object({
18398
- x: number(),
18399
- y: number(),
18400
- width: number(),
18401
- height: number()
18402
- }),
18403
- labels: array(looseObject({
18404
- label: string(),
18405
- score: number()
18406
- })).readonly(),
18407
- parentId: string().optional()
18408
- });
18409
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
18410
- var SearchObjectEventsInput = object({
18411
- text: string(),
18412
- deviceId: number().optional(),
18413
- since: number().optional(),
18414
- until: number().optional(),
18415
- classFilter: string().optional(),
18416
- limit: number().default(50),
18417
- minScore: number().min(0).max(1).default(.2)
18418
- });
18419
- var TrackCascadeCountsSchema = object({
18420
- /** Persisted track roots deleted (authoritative). */
18421
- tracks: number().int(),
18422
- /** Object events removed with their tracks (best-effort; see note above). */
18423
- events: number().int(),
18424
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
18425
- media: number().int(),
18426
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
18427
- faces: number().int(),
18428
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
18429
- plates: number().int(),
18430
- /** Per-track CLIP search vectors removed (best-effort). */
18431
- embeddings: number().int(),
18432
- /** Group membership + group rows removed with their last member (best-effort). */
18433
- groups: number().int()
18434
- });
18435
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
18436
- var DiskReconcileCountsSchema = object({
18437
- mediaDropped: number().int(),
18438
- tracks: number().int(),
18439
- events: number().int()
18440
- });
18441
- /** Event-store footprint for one camera. */
18442
- var EventStoreDeviceFootprintSchema = object({
18443
- deviceId: number(),
18444
- /** Persisted event rows (motion + object + audio) for the camera. */
18445
- rows: number().int(),
18446
- /** Event-owned media bytes on disk for the camera. */
18447
- bytes: number().int()
18448
- });
18449
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
18450
- var EventStoreFootprintSchema = object({
18451
- totalRows: number().int(),
18452
- totalBytes: number().int(),
18453
- devices: array(EventStoreDeviceFootprintSchema).readonly()
18454
- });
18455
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
18456
- var EventPruneCountsSchema = object({
18457
- motion: number().int(),
18458
- object: number().int(),
18459
- audio: number().int()
18245
+ /**
18246
+ * Row projection for track list queries. `full` (default) returns the
18247
+ * complete Track including the frame-rate `positions[]` history and the
18248
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
18249
+ * keeps every scalar the list surfaces actually render (ids, class(es),
18250
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
18251
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
18252
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
18253
+ * `getTrack`. Mirrors the event-store `projection` convention
18254
+ * (`getObjectEvents` et al.).
18255
+ */
18256
+ var TrackProjectionSchema = _enum(["full", "slim"]);
18257
+ /**
18258
+ * One audio-classification label heard on the track's camera while the
18259
+ * track was alive, aggregated per label. An "episode" is one persisted
18260
+ * audio event (the confident-classification path: score ≥ the device's
18261
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
18262
+ * one 32 ms inference chunk, so counts stay human-scaled.
18263
+ */
18264
+ var TrackAudioLabelSchema = object({
18265
+ label: string(),
18266
+ /** Highest classification score observed across the label's episodes. */
18267
+ peakScore: number(),
18268
+ /** Number of coalesced audio-event episodes carrying this label. */
18269
+ count: number(),
18270
+ firstAt: number(),
18271
+ lastAt: number()
18460
18272
  });
18461
18273
  /**
18462
- * Re-embed stored tracks from their key frames.
18274
+ * How a track was produced. `pipeline` (default / absent) = the spatial
18275
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
18276
+ * no positions, a single snapshot, and no bbox trajectory at all:
18463
18277
  *
18464
- * The reason this is an operator-callable method and not a migration script:
18465
- * every knob that decides what a vector MEANS encoder model, crop margin,
18466
- * squaring is only changeable if the existing vectors can be regenerated.
18467
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
18468
- * symptom is a quality regression with no visible cause.
18278
+ * - `sensor` a linked sensor/control device state change.
18279
+ * - `audio` an audio event on the camera itself that was anomalous for
18280
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
18281
+ *
18282
+ * The spatial subsystems (tracker association, occupancy count, re-id /
18283
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
18284
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
18285
+ * check silently readmits every source added after it was written.
18469
18286
  */
18470
- var RebuildObjectEmbeddingsInput = object({
18471
- /** Restrict to one camera. Omit for the whole fleet. */
18472
- deviceId: number().optional(),
18473
- since: number().optional(),
18474
- until: number().optional(),
18475
- /** Stop after this many tracks; the result reports whether more remain. */
18476
- maxTracks: number().int().positive().optional(),
18477
- /**
18478
- * Run every embedding on THIS node instead of round-robining the fleet.
18479
- *
18480
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
18481
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
18482
- * calling it that would pin the rebuild REQUEST itself to that node — the
18483
- * rebuild orchestration lives on the hub, and only the per-track step runs
18484
- * remotely. This field is data; the per-track pin is applied inside.
18485
- *
18486
- * Absent ⇒ round-robin over every online node whose runner can serve the
18487
- * pinned model.
18488
- */
18489
- executeOnNodeId: string().optional(),
18490
- /**
18491
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
18492
- * run flat out.
18493
- *
18494
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
18495
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
18496
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
18497
- * force is logged at start and finish so a deliberately slow pass reads
18498
- * differently from a stalled one.
18499
- */
18500
- pacingMs: number().int().nonnegative().optional()
18501
- });
18287
+ var TrackSourceSchema = _enum([
18288
+ "pipeline",
18289
+ "sensor",
18290
+ "audio"
18291
+ ]);
18502
18292
  /**
18503
- * Result of emptying the CLIP index.
18293
+ * Where a track sits in the RETRAIN lifecycle (D81).
18504
18294
  *
18505
- * The clean slate before a policy change: a new crop margin or encoder model
18506
- * leaves two feature spaces in one index whose cosine scores are not
18507
- * comparable, so wiping and rebuilding is the only way to be sure every vector
18508
- * means the same thing.
18295
+ * - `none` never marked, or un-marked. Evictable.
18296
+ * - `staging` the operator wants this track as training material and has not
18297
+ * finished with it. **This is the only state retention holds**: the track and
18298
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
18299
+ * the device's age window.
18300
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
18301
+ * were COPIED into the retrain dataset at selection time, so the dataset no
18302
+ * longer depends on the track's media and the track becomes EVICTABLE again.
18303
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
18304
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
18305
+ *
18306
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
18307
+ * the store's filter language has only positive equality and `whereIn` — no
18308
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
18309
+ * would make the entire pre-column history immortal in one deploy.
18509
18310
  */
18510
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
18311
+ var RetrainStatusSchema = _enum([
18312
+ "none",
18313
+ "staging",
18314
+ "trained"
18315
+ ]);
18511
18316
  /**
18512
- * Acknowledgement that a rebuild STARTED.
18317
+ * Per-track OPERATOR flags set by hand from the admin UI or the viewer, never
18318
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
18319
+ * so the two surfaces cannot drift.
18513
18320
  *
18514
- * The pass costs ~1s per track 45 minutes for a 2,600-track fleet so it
18515
- * runs detached and this returns immediately. Waiting for it made the client
18516
- * time out while the work carried on server-side, which is the worst of both:
18517
- * no result and no way to know it was still going. Poll
18518
- * `getObjectEmbeddingRebuildStatus` for progress.
18321
+ * **Absent false.** A track that has never been touched omits the field; an
18322
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
18323
+ * columns existed read as absent, and a consumer that needs a boolean should say
18324
+ * `flag === true`, not `flag !== false`.
18325
+ *
18326
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
18327
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
18328
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
18329
+ * `trained` track reports `false` while refusing both writes. The boolean is
18330
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
18331
+ * "never marked" from "already trained" must read `retrainStatus`.
18332
+ *
18333
+ * `debug` does NOT pin; it is attention, not durability.
18334
+ *
18335
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
18336
+ * A favourited track is skipped by retention the same way `staging` is, but
18337
+ * it does not enter `none|staging|trained` and has no staging budget.
18519
18338
  */
18520
- var RebuildObjectEmbeddingsResultSchema = object({
18521
- started: boolean(),
18522
- /** True when a pass was already running; the new request is ignored. */
18523
- alreadyRunning: boolean()
18524
- });
18525
- var RebuildStatusSchema = object({
18526
- running: boolean(),
18527
- scanned: number(),
18528
- rebuilt: number(),
18529
- /** Tracks whose key frame is gone — nothing to re-embed from. */
18530
- missingKeyFrame: number(),
18531
- /** Tracks with no usable detection box. */
18532
- missingBbox: number(),
18533
- /**
18534
- * Tracks an executing node REFUSED rather than broke on an unreadable key
18535
- * frame, a step that threw. Separate from `failed` because the remedy is
18536
- * different, and because a whole camera silently contributing zero vectors
18537
- * is the shape of failure a rebuild must never hide.
18538
- */
18539
- notRunnable: number(),
18540
- /**
18541
- * The pass stopped because NO node could serve the pinned model.
18542
- *
18543
- * Distinct from `notRunnable` on purpose: that one says "this track was
18544
- * refused", this one says "the cluster cannot do this work at all" — every
18545
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
18546
- * pinned model for its engine format, or dropped out. The remedy is a model /
18547
- * engine change, not a per-camera one. Non-zero here always comes with
18548
- * `complete: false`.
18549
- */
18550
- noCapableNode: number(),
18551
- failed: number(),
18552
- /** Set once a pass ends: true only when EVERYTHING was covered. */
18553
- complete: boolean().nullable(),
18554
- startedAtMs: number().nullable(),
18555
- finishedAtMs: number().nullable(),
18556
- /** Present when the pass ended by throwing. */
18557
- error: string().nullable()
18558
- });
18559
- DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
18560
- deviceId: number(),
18561
- trackId: string()
18562
- }), TrackSchema.nullable()), method(object({
18563
- deviceId: number(),
18564
- since: number().optional(),
18565
- until: number().optional(),
18566
- limit: number().optional(),
18567
- /** Spatial filter — only tracks whose trajectory intersects the zone
18568
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
18569
- * envelope columns, then precisely tested per position. Tracks with
18570
- * an unknown envelope (no frame dims at persist time) always match. */
18571
- zone: TrackZoneFilterSchema.optional(),
18572
- /** See {@link TrackProjectionSchema}. Default `full` (backward
18573
- * compatible — omitting the field keeps today's exact behaviour). */
18574
- projection: TrackProjectionSchema.optional(),
18575
- /** Include stationary-promoted rows (parked objects handed to the
18576
- * stationary registry). Default false: the timeline lists passages,
18577
- * not parking records (operator decision, 2026-08-15). */
18578
- includeStationary: boolean().optional()
18579
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
18580
- deviceId: number(),
18581
- groupId: string().min(1)
18582
- }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
18583
- kind: "mutation",
18584
- auth: "admin"
18585
- }), 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({
18586
- deviceId: number(),
18587
- since: number().optional(),
18588
- until: number().optional(),
18589
- kinds: array(string()).optional(),
18590
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
18591
- }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
18592
- deviceId: number(),
18593
- since: number(),
18594
- until: number(),
18595
- bucketMs: number().int().positive()
18596
- }), array(object({
18597
- bucketStart: number(),
18598
- motion: number().int(),
18599
- object: number().int(),
18600
- audio: number().int()
18601
- })).readonly()), method(object({
18602
- deviceId: number(),
18603
- cutoffMs: number()
18604
- }), object({
18605
- motion: number().int(),
18606
- object: number().int(),
18607
- audio: number().int()
18608
- }), {
18609
- kind: "mutation",
18610
- auth: "admin"
18611
- }), method(object({
18612
- deviceId: number(),
18613
- cutoffMs: number()
18614
- }), TrackCascadeCountsSchema, {
18615
- kind: "mutation",
18616
- auth: "admin"
18617
- }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
18618
- kind: "mutation",
18619
- auth: "admin"
18620
- }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
18621
- kind: "mutation",
18622
- auth: "admin"
18623
- }), method(object({
18624
- deviceId: number(),
18625
- trackIds: array(string()).min(1)
18626
- }), object({
18627
- deleted: number().int(),
18628
- failed: array(string()).readonly()
18629
- }), {
18630
- kind: "mutation",
18631
- auth: "admin"
18632
- }), method(object({
18633
- /** Log/audit scope only — the trackId is globally unique on its own. */
18634
- deviceId: number(),
18339
+ var TrackFlagFields = {
18340
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
18341
+ * `'staging'`. */
18342
+ markForTrain: boolean().optional(),
18343
+ /** Operator marked this track for diagnostic attention. */
18344
+ debug: boolean().optional(),
18345
+ /** Operator favourited this track. Pins it against pruning. */
18346
+ favourited: boolean().optional()
18347
+ };
18348
+ /**
18349
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
18350
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
18351
+ * write patch, and the status is not something the toggle sets — it is what the
18352
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
18353
+ * always present on a persisted row (the column default materialises `'none'`).
18354
+ */
18355
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
18356
+ /**
18357
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
18358
+ * one flag can never clear the other — the toggles are independent and are
18359
+ * driven from three surfaces that do not know about each other.
18360
+ */
18361
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
18362
+ /**
18363
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
18364
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
18365
+ * mutation result without a re-fetch.
18366
+ */
18367
+ var TrackFlagsSchema = object({
18635
18368
  trackId: string(),
18636
- flags: TrackFlagsPatchSchema
18637
- }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
18638
- kind: "query",
18639
- auth: "admin"
18640
- }), method(object({
18641
- olderThanMs: number(),
18642
- reason: OpsLogReasonSchema.optional()
18643
- }), EventPruneCountsSchema, {
18644
- kind: "mutation",
18645
- auth: "admin"
18646
- }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
18647
- kind: "mutation",
18648
- auth: "admin"
18649
- }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
18650
- kind: "mutation",
18651
- auth: "admin"
18652
- }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
18653
- kind: "mutation",
18654
- auth: "admin"
18655
- }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
18656
- kind: "mutation",
18657
- auth: "admin"
18658
- }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
18659
- kind: "mutation",
18660
- auth: "admin"
18661
- }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18662
- kind: "mutation",
18663
- auth: "admin"
18664
- }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
18665
- kind: "mutation",
18666
- auth: "admin"
18667
- }), method(object({}), array(RelocateJobSchema).readonly(), {
18668
- kind: "query",
18669
- auth: "admin"
18670
- }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18671
- kind: "mutation",
18672
- auth: "admin"
18673
- }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
18674
- kind: "query",
18675
- auth: "admin"
18676
- }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
18677
- kind: "query",
18678
- auth: "admin"
18679
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18680
- kind: "query",
18681
- auth: "admin"
18682
- }), method(object({
18683
- /** Empty every camera that has staging tracks. A LIST, not a single
18684
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
18685
- * route it at one camera's owner, and "every camera" would stop being
18686
- * expressible at all. */
18687
- deviceIds: array(number()).optional(),
18688
- limit: number().int().min(1).max(500).optional()
18689
- }), array(RetrainTrackSchema).readonly(), {
18690
- kind: "query",
18691
- auth: "admin"
18692
- }), method(object({ trackId: string() }), RetrainFrameListSchema, {
18693
- kind: "query",
18694
- auth: "admin"
18695
- }), method(object({
18369
+ markForTrain: boolean(),
18370
+ debug: boolean(),
18371
+ favourited: boolean(),
18372
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
18373
+ * a track row) because this shape is only ever produced by the write body,
18374
+ * which always knows it — and a surface that has just written needs to render
18375
+ * `trained` without a re-fetch. */
18376
+ retrainStatus: RetrainStatusSchema
18377
+ });
18378
+ union([literal(1), literal(2)]);
18379
+ /**
18380
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
18381
+ * the step and model that produced it — which is what makes the write rule
18382
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
18383
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
18384
+ *
18385
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
18386
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
18387
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
18388
+ * that value has no provenance, and the write rule lets ANY properly-attributed
18389
+ * write of the same tier replace it regardless of score.
18390
+ */
18391
+ var LabelAttributionSchema = object({
18392
+ stepId: string(),
18393
+ modelId: string().optional(),
18394
+ decidedAt: number(),
18395
+ /**
18396
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
18397
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
18398
+ *
18399
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
18400
+ * notification rule authored on "Gianluca" stopped matching the moment the
18401
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
18402
+ * the thing that does not move, so it is what a rule matches on
18403
+ * (`NcConditions.identities`) and the text is what a human is shown.
18404
+ *
18405
+ * Absent when the label names no gallery row — a plate the OCR read but no
18406
+ * vehicle claims, a sub-class, a species, any tier-1 value.
18407
+ */
18408
+ identityId: string().optional()
18409
+ });
18410
+ /**
18411
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
18412
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
18413
+ * track and its events always answer the same question the same way.
18414
+ *
18415
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
18416
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
18417
+ * is tier 2, and each carries its own score + attribution.
18418
+ *
18419
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
18420
+ * finest thing known. Before 4g the single `label` column held the finest
18421
+ * value, so a consumer that has not been updated reads the tier-1 slot and
18422
+ * shows nothing on a species-only row; that is why the migration puts every
18423
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
18424
+ * and why the read surfaces were changed in the same train.
18425
+ *
18426
+ * **Writing it.** The slots are independent, which is the whole point: a
18427
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
18428
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
18429
+ * higher score wins. One rule, one implementation — see
18430
+ * `pipeline/label-tier.ts` in addon-post-analysis.
18431
+ */
18432
+ var TieredLabelFields = {
18433
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
18434
+ label: string().optional(),
18435
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
18436
+ labelScore: number().optional(),
18437
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
18438
+ labelMeta: LabelAttributionSchema.optional(),
18439
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
18440
+ subLabel: string().optional(),
18441
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
18442
+ subLabelScore: number().optional(),
18443
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
18444
+ subLabelMeta: LabelAttributionSchema.optional()
18445
+ };
18446
+ /** Per-camera slice of a training-export estimate. */
18447
+ var TrainingExportDeviceTotalsSchema = object({
18696
18448
  deviceId: number(),
18449
+ tracks: number().int(),
18450
+ files: number().int(),
18451
+ bytes: number().int()
18452
+ });
18453
+ /**
18454
+ * What a training export WOULD contain. Computed from media index rows only —
18455
+ * no blob is read to produce this.
18456
+ */
18457
+ var TrainingExportSummarySchema = object({
18458
+ generatedAt: number(),
18459
+ trackCount: number().int(),
18460
+ fileCount: number().int(),
18461
+ byteCount: number().int(),
18462
+ /** More marked tracks exist than a single pass carries. */
18463
+ truncated: boolean(),
18464
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
18465
+ });
18466
+ var TrackSchema = object({
18697
18467
  trackId: string(),
18698
- mediaKeys: array(string()).min(1)
18699
- }), RetrainFrameSelectionSchema, {
18700
- kind: "mutation",
18701
- auth: "admin"
18702
- }), method(object({
18703
18468
  deviceId: number(),
18704
- trackId: string(),
18705
- frameId: string()
18706
- }), object({
18707
- removed: boolean(),
18708
- removedAnnotations: number().int()
18709
- }), {
18710
- kind: "mutation",
18711
- auth: "admin"
18712
- }), method(object({ frameId: string() }), object({
18469
+ className: string(),
18470
+ ...TieredLabelFields,
18471
+ producingDeviceName: string().optional(),
18472
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
18473
+ source: TrackSourceSchema.optional(),
18474
+ firstSeen: number(),
18475
+ lastSeen: number(),
18476
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
18477
+ positions: array(TrackPositionSchema).readonly(),
18478
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
18479
+ * saveThumbnails policy). */
18480
+ snapshots: array(TrackSnapshotSchema).readonly(),
18481
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
18482
+ zonesVisited: array(string()).readonly(),
18483
+ /**
18484
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
18485
+ * `zones` capability.
18486
+ *
18487
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
18488
+ * and no card can render — so every free-text search surface was structurally
18489
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
18490
+ * just returned nothing. Resolving here rather than in each client keeps ONE
18491
+ * derivation and costs the clients no extra call (the `zones` cap is
18492
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
18493
+ * surface built to avoid exactly that).
18494
+ *
18495
+ * Resolved, never invented: a zone deleted since the track was written has no
18496
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
18497
+ * two are not positionally aligned. Absent when the track visited no zone, or
18498
+ * when the zone catalogue could not be read.
18499
+ */
18500
+ zoneNames: array(string()).readonly().optional(),
18501
+ /** Deduplicated set of detector classes observed for this track over its
18502
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
18503
+ * legacy rows written before class accumulation shipped. */
18504
+ classes: array(string()).readonly().optional(),
18505
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
18506
+ totalDistance: number(),
18507
+ state: TrackStateSchema,
18508
+ active: boolean(),
18509
+ /** Deterministic key-event importance score in [0,1] (server-computed at
18510
+ * track expiry, recomputed on late label). Absent on legacy rows written
18511
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
18512
+ importance: number().optional(),
18513
+ /** Id of the track's highest-confidence ObjectEvent (its representative
18514
+ * "best" frame). Absent when the track produced no object events. */
18515
+ bestEventId: string().optional(),
18516
+ /** Tag of the importance sub-signal that dominated the score
18517
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
18518
+ importanceReason: string().optional(),
18519
+ /** Audio-classification labels heard on the camera during the track's
18520
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
18521
+ * Absent on legacy rows / tracks with no confident audio. */
18522
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
18523
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
18524
+ * Populated from the persisted envelope columns on historical reads;
18525
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
18526
+ envelope: TrackEnvelopeSchema.optional(),
18527
+ /**
18528
+ * A face DETECTOR found a face on this track — nothing more. It says the
18529
+ * detail plane produced a `face` detail; it does NOT say the face was
18530
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
18531
+ * enabled. Set once and never cleared.
18532
+ *
18533
+ * **This exists so "face present but not recognised" is expressible.** A
18534
+ * recognised identity lands in `subLabel` (attributed to the face chain via
18535
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
18536
+ * and a track with no face at all were byte-identical on the wire and no
18537
+ * surface could tell them apart. The read is `hasFace === true && subLabel
18538
+ * === undefined`.
18539
+ *
18540
+ * **Absent ≠ false.** Every row written before the column existed omits it,
18541
+ * and so does every server that predates the field — a consumer must test
18542
+ * `=== true` and render nothing otherwise, never infer "no face".
18543
+ */
18544
+ hasFace: boolean().optional(),
18545
+ /**
18546
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
18547
+ * face an operator could ASSIGN to an identity.
18548
+ *
18549
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
18550
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
18551
+ * branch, before every gate, and means no more than "a face detector produced
18552
+ * a face detail". This one is stamped at the single moment the gallery row
18553
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
18554
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
18555
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
18556
+ * the crop-store drop. Everything between the detector and that insert can
18557
+ * legitimately refuse the face, so a flag written any earlier promises the
18558
+ * operator something to assign and delivers nothing.
18559
+ *
18560
+ * **Independent of recognition.** A face collected but never auto-matched is
18561
+ * still assignable — it is in fact the face an operator most wants to reach —
18562
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
18563
+ * `subLabel`; this says only that the raw material exists.
18564
+ *
18565
+ * **Set once, never cleared.** A track that produced a gallery row produced
18566
+ * one; deleting the row later is the gallery's business, not this flag's.
18567
+ *
18568
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
18569
+ * before the column omits it, and so does every server that predates the
18570
+ * field. A consumer must test `=== true` and render nothing otherwise —
18571
+ * never infer "no assignable face".
18572
+ */
18573
+ hasEmbeddedFace: boolean().optional(),
18574
+ /**
18575
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
18576
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
18577
+ * so the passage is tracked once and as a VEHICLE.
18578
+ *
18579
+ * It exists because the fold's record was dishonest. D34 and the code both
18580
+ * said "the person is not lost — it is reported so both entities stay on the
18581
+ * record"; in fact the pair went into a per-processor RAM field behind an
18582
+ * accessor nobody called, and every durable surface said `vehicle`, full
18583
+ * stop. This is the composition note that makes the row true.
18584
+ *
18585
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
18586
+ * person" is not an answer to "what is this" — both label tiers would refuse
18587
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
18588
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
18589
+ * and a `person` rule still does not fire for someone cycling past.
18590
+ *
18591
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
18592
+ * the column, and every hub that predates the field, omits it. Test
18593
+ * `=== true` and render nothing otherwise — never infer "no rider".
18594
+ */
18595
+ hasRider: boolean().optional(),
18596
+ ...TrackFlagFields,
18597
+ ...TrackRetrainFields
18598
+ });
18599
+ var BaseEventFields = {
18600
+ id: string(),
18601
+ deviceId: number(),
18602
+ timestamp: number()
18603
+ };
18604
+ var MotionEventSchema = object({
18605
+ ...BaseEventFields,
18606
+ kind: literal("motion"),
18607
+ regionCount: number(),
18608
+ /** Heavy JSON array — omitted in slim projection. */
18609
+ regions: array(object({
18610
+ bbox: BoundingBoxSchema,
18611
+ pixelCount: number(),
18612
+ intensity: number()
18613
+ })).readonly().optional(),
18614
+ /** Omitted in slim projection. */
18615
+ frameWidth: number().optional(),
18616
+ /** Omitted in slim projection. */
18617
+ frameHeight: number().optional(),
18618
+ /** Populated by B5 (recording playback URL for this event). */
18619
+ mediaUrl: string().optional()
18620
+ });
18621
+ /**
18622
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
18623
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
18624
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
18625
+ * tracking, per-kind persistence) but stay distinguishable so consumers
18626
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
18627
+ * Absent on legacy rows ⇒ treat as `pipeline`.
18628
+ */
18629
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
18630
+ /**
18631
+ * The confirmed zone crossing that produced an object event. Present ONLY on
18632
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
18633
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
18634
+ * appearance event carry none, so a rule asking for a direction fails closed
18635
+ * on them.
18636
+ *
18637
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
18638
+ * into its own event, so a frame in which a track enters A while leaving B
18639
+ * produces two events with two directions — never one ambiguous row.
18640
+ *
18641
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
18642
+ * membership the box has NOW, and by definition it no longer contains the zone
18643
+ * that was just left. Without the id here, a zone-scoped rule could never match
18644
+ * the exit it asked for.
18645
+ */
18646
+ var ZoneCrossingSchema = object({
18647
+ direction: _enum(["enter", "exit"]),
18648
+ /** Admin zone id crossed. */
18649
+ zoneId: string(),
18650
+ /** Zone display name at crossing time (falls back to the id). */
18651
+ zoneName: string().optional()
18652
+ });
18653
+ var ObjectEventSchema = object({
18654
+ ...BaseEventFields,
18655
+ kind: literal("object"),
18656
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
18657
+ source: DetectionSourceSchema.optional(),
18658
+ /**
18659
+ * Inference-frame id shared by every object event emitted from the SAME frame
18660
+ * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
18661
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
18662
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
18663
+ * Optional for backward-compat with pre-existing rows / the slim projection
18664
+ * includes it (it is light). Absent on rows written before this field.
18665
+ */
18666
+ frameId: string().optional(),
18667
+ /** Omitted in slim projection. */
18668
+ trackId: string().optional(),
18669
+ className: string(),
18670
+ ...TieredLabelFields,
18671
+ /** Omitted in slim projection. */
18672
+ confidence: number().optional(),
18673
+ /** Heavy JSON — omitted in slim projection. */
18674
+ bbox: BoundingBoxSchema.optional(),
18675
+ /** Heavy JSON — omitted in slim projection. */
18676
+ zones: array(string()).readonly().optional(),
18677
+ /** Omitted in slim projection. */
18678
+ state: TrackStateSchema.optional(),
18679
+ /**
18680
+ * The zone crossing this event IS, when it is one. Absent on every other
18681
+ * event kind (movement state, appearance, package) — see
18682
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
18683
+ */
18684
+ zoneCrossing: ZoneCrossingSchema.optional(),
18685
+ /** Detection-frame dimensions in pixels — let consumers normalize the
18686
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
18687
+ frameWidth: number().optional(),
18688
+ frameHeight: number().optional(),
18689
+ /** MediaStore key for the crop attached to this event (if any). */
18690
+ mediaKey: string().optional(),
18691
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
18692
+ * best-detection full frame). Resolve via the event-media data-plane
18693
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
18694
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
18695
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
18696
+ keyFrameMediaKey: string().optional(),
18697
+ /** Populated by B5 (recording playback URL for this event). */
18698
+ mediaUrl: string().optional(),
18699
+ /** The parent track's key-event importance [0,1], propagated to every object
18700
+ * event of the track (so an event row can be sorted by importance without a
18701
+ * track join). Absent on legacy rows / before the track was scored. */
18702
+ importance: number().optional()
18703
+ });
18704
+ var AudioEventSchema = object({
18705
+ ...BaseEventFields,
18706
+ kind: literal("audio"),
18707
+ rms: number(),
18708
+ dbfs: number(),
18709
+ classification: object({
18710
+ className: string(),
18711
+ originalClass: string().optional(),
18712
+ score: number()
18713
+ }).optional(),
18714
+ /** Populated by B5 (recording playback URL for this event). */
18715
+ mediaUrl: string().optional()
18716
+ });
18717
+ var MediaFileKindEnum = _enum([
18718
+ "crop",
18719
+ "thumbnail",
18720
+ "snapshot",
18721
+ "firstFrame",
18722
+ "lastFrame",
18723
+ "fullFrame",
18724
+ "fullFrameBoxed",
18725
+ "faceCrop",
18726
+ "plateCrop",
18727
+ "keyFrame",
18728
+ "keyFrameSmall",
18729
+ "thumbnailSmall"
18730
+ ]);
18731
+ var MediaFileSchema = object({
18732
+ key: string(),
18733
+ kind: MediaFileKindEnum,
18713
18734
  base64: string(),
18714
- width: number().int(),
18715
- height: number().int()
18716
- }), {
18717
- kind: "query",
18718
- auth: "admin"
18719
- }), method(object({
18720
- deviceId: number(),
18721
- trackId: string(),
18722
- frameId: string(),
18723
- subject: RetrainAssistSubjectSchema,
18724
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
18725
- nodeId: string().optional()
18726
- }), RetrainAssistResultSchema, {
18727
- kind: "mutation",
18728
- auth: "admin"
18729
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
18730
- kind: "query",
18731
- auth: "admin"
18732
- }), method(object({
18733
- deviceId: number(),
18735
+ sizeBytes: number(),
18736
+ timestamp: number()
18737
+ });
18738
+ /**
18739
+ * One media row WITHOUT its bytes.
18740
+ *
18741
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
18742
+ * 140 s track), and a client that renders tiles from the media data plane needs
18743
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
18744
+ * with an immutable cache, instead of all at once inside a tRPC response that
18745
+ * blocks the whole view.
18746
+ *
18747
+ * `sizeBytes` is carried because it is what lets a client decide between the
18748
+ * stored blob and a `?variant=thumb` rendering without fetching either.
18749
+ */
18750
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
18751
+ /**
18752
+ * The MACRO tier of an annotation — a CLOSED set.
18753
+ *
18754
+ * This is what the exported detector predicts, so a typo here is a new class
18755
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
18756
+ * the whole point of the page is teaching the model things it does not know
18757
+ * yet, and constraining that vocabulary would make it useless.
18758
+ *
18759
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
18760
+ * `subLabel` is one of these values, in any casing, because once `person`
18761
+ * exists in both tiers "every person box" stops being answerable without
18762
+ * knowing every string anyone ever typed — and the damage is retroactive.
18763
+ */
18764
+ var RetrainMacroClassSchema = _enum([
18765
+ "person",
18766
+ "vehicle",
18767
+ "animal",
18768
+ "package",
18769
+ "face",
18770
+ "plate"
18771
+ ]);
18772
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
18773
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
18774
+ /** Did a human draw this box, or did the assist propose it? */
18775
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
18776
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
18777
+ var RetrainBboxSchema = object({
18778
+ x: number(),
18779
+ y: number(),
18780
+ w: number(),
18781
+ h: number()
18782
+ });
18783
+ /**
18784
+ * One annotated subject.
18785
+ *
18786
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
18787
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
18788
+ * derived from it at export and never stored — storing them is how one feature
18789
+ * space ends up holding two crops of the same subject (D52).
18790
+ */
18791
+ var RetrainAnnotationSchema = object({
18792
+ id: string(),
18734
18793
  trackId: string(),
18735
- frameId: string(),
18736
- annotations: array(RetrainAnnotationDraftSchema)
18737
- }), array(RetrainAnnotationSchema).readonly(), {
18738
- kind: "mutation",
18739
- auth: "admin"
18740
- }), method(object({
18741
- deviceId: number(),
18742
- trackId: string()
18743
- }), RetrainTransitionResultSchema, {
18744
- kind: "mutation",
18745
- auth: "admin"
18746
- }), method(object({
18747
18794
  deviceId: number(),
18748
- trackId: string()
18749
- }), RetrainTransitionResultSchema, {
18750
- kind: "mutation",
18751
- auth: "admin"
18752
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18753
- kind: "query",
18754
- auth: "admin"
18755
- }), method(object({
18756
- eventId: string(),
18757
- kind: MediaFileKindEnum.optional(),
18758
- deviceId: number()
18759
- }), array(MediaFileSchema).readonly()), method(object({
18760
- trackId: string(),
18761
- kinds: array(MediaFileKindEnum).optional(),
18762
- deviceId: number()
18763
- }), array(MediaFileSchema).readonly()), method(object({
18795
+ /** The COPY in retrain storage — never the source track's media key. */
18796
+ mediaKey: string(),
18797
+ bbox: RetrainBboxSchema,
18798
+ macroClass: RetrainMacroClassSchema,
18799
+ label: string().optional(),
18800
+ subLabel: string().optional(),
18801
+ kind: RetrainAnnotationKindSchema,
18802
+ source: RetrainAnnotationSourceSchema,
18803
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
18804
+ assistModelId: string().optional(),
18805
+ assistScore: number().optional(),
18806
+ exportedInBatch: string().optional(),
18807
+ createdAt: number()
18808
+ });
18809
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
18810
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
18811
+ id: true,
18812
+ trackId: true,
18813
+ deviceId: true,
18814
+ mediaKey: true,
18815
+ createdAt: true,
18816
+ exportedInBatch: true
18817
+ });
18818
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
18819
+ var RetrainTrackSchema = object({
18764
18820
  trackId: string(),
18765
- deviceId: number()
18766
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18767
- kind: "mutation",
18768
- auth: "admin"
18769
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18770
- kind: "mutation",
18771
- auth: "admin"
18772
- }), method(object({}), RebuildStatusSchema), object({
18773
18821
  deviceId: number(),
18822
+ className: string(),
18823
+ label: string().optional(),
18824
+ firstSeen: number(),
18825
+ lastSeen: number(),
18826
+ /** How many frames the dataset already holds from this track. */
18827
+ frameCount: number().int(),
18828
+ /** How many subjects have been annotated on those frames. `0` with
18829
+ * `frameCount: 0` is exactly "staging, still to work". */
18830
+ annotationCount: number().int()
18831
+ });
18832
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
18833
+ var RetrainFrameCandidateSchema = object({
18834
+ mediaKey: string(),
18835
+ kind: MediaFileKindEnum,
18774
18836
  timestamp: number(),
18775
- frameWidth: number(),
18776
- frameHeight: number(),
18777
- detections: array(OverlayDetectionSchema).readonly()
18778
- }), object({
18779
- deviceId: number(),
18780
- trackId: string(),
18781
- className: string()
18782
- }), object({
18837
+ sizeBytes: number().int(),
18838
+ /** A copy of this original already exists — selecting it is free and cannot
18839
+ * fail, whatever became of the original. */
18840
+ copied: boolean()
18841
+ });
18842
+ /** A frame the dataset OWNS: bytes copied at selection time. */
18843
+ var RetrainFrameSchema = object({
18844
+ frameId: string(),
18783
18845
  deviceId: number(),
18784
18846
  trackId: string(),
18785
- className: string(),
18786
- durationMs: number()
18787
- }), object({
18788
- deviceId: number(),
18789
- kind: EventKindSchema,
18790
- eventId: string(),
18791
- timestamp: number()
18847
+ /** Provenance only. It may already point at nothing — that is expected. */
18848
+ sourceMediaKey: string(),
18849
+ sourceKind: MediaFileKindEnum,
18850
+ sizeBytes: number().int(),
18851
+ width: number().int(),
18852
+ height: number().int(),
18853
+ copiedAt: number()
18792
18854
  });
18793
- /**
18794
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
18795
- * within the frame, so the executor can re-cut a leaf child ROI at native
18796
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
18797
- */
18798
- var NativeCropRefSchema = object({
18799
- /** Handle keying the retained native surface (node-pinned to its owner). */
18800
- handle: FrameHandleSchema,
18801
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
18802
- cropFrameSpace: object({
18803
- x: number(),
18804
- y: number(),
18805
- w: number(),
18806
- h: number()
18807
- })
18855
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
18856
+ var RetrainCopyRefusalSchema = _enum([
18857
+ "source-missing",
18858
+ "unreadable-image",
18859
+ "write-failed"
18860
+ ]);
18861
+ var RetrainFrameSelectionSchema = object({
18862
+ copied: array(RetrainFrameSchema).readonly(),
18863
+ refused: array(object({
18864
+ sourceMediaKey: string(),
18865
+ reason: RetrainCopyRefusalSchema
18866
+ })).readonly()
18808
18867
  });
18809
- object({
18810
- crop: object({
18811
- left: number(),
18812
- top: number(),
18813
- width: number().positive(),
18814
- height: number().positive()
18815
- }).optional(),
18816
- content: object({
18817
- width: number().int().positive(),
18818
- height: number().int().positive()
18819
- }),
18820
- fit: _enum(["stretch", "contain"]),
18821
- format: _enum([
18822
- "rgb",
18823
- "gray",
18824
- "jpeg"
18825
- ])
18868
+ var RetrainFrameListSchema = object({
18869
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
18870
+ copies: array(RetrainFrameSchema).readonly(),
18871
+ /** What the page pre-selects — the native key frame when one survives. */
18872
+ autoPickMediaKey: string().optional()
18826
18873
  });
18874
+ /** What the operator asked the assist to look for. */
18875
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
18876
+ kind: literal("package"),
18877
+ zone: RetrainBboxSchema.optional()
18878
+ }), object({
18879
+ kind: literal("objects"),
18880
+ modelId: string(),
18881
+ minScore: number().optional()
18882
+ })]);
18827
18883
  /**
18828
- * Process-local frame identity. It is serializable so it can ride an in-process
18829
- * capability call, but `registryId` deliberately prevents resolution in any
18830
- * other process or execution group.
18884
+ * The assist's answer a discriminated union, because "the model saw nothing"
18885
+ * and "this node cannot run that model" lead to different next moves and a
18886
+ * nullable result cannot tell them apart.
18831
18887
  */
18832
- var FrameRefSchema = object({
18833
- registryId: string().min(1),
18834
- id: string().min(1),
18835
- width: number().int().positive(),
18836
- height: number().int().positive(),
18837
- format: _enum(["rgb", "gray"]),
18838
- timestamp: number(),
18839
- capturedAt: number().optional()
18888
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
18889
+ kind: literal("proposed"),
18890
+ modelId: string(),
18891
+ stepId: string(),
18892
+ minScore: number(),
18893
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
18894
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
18895
+ /** Returned by the runner but removed by the threshold. */
18896
+ belowThreshold: number().int()
18897
+ }), object({
18898
+ kind: literal("refused"),
18899
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
18900
+ reason: string(),
18901
+ detail: string().optional()
18902
+ })]);
18903
+ /** The outcome of a lifecycle move owned by the retrain page. */
18904
+ var RetrainTransitionResultSchema = object({
18905
+ trackId: string(),
18906
+ /** Where the track ended up, whatever happened. */
18907
+ retrainStatus: RetrainStatusSchema,
18908
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
18909
+ changed: boolean(),
18910
+ reason: _enum([
18911
+ "unknown-track",
18912
+ "no-frames-copied",
18913
+ "not-staging",
18914
+ "not-trained",
18915
+ "unchanged"
18916
+ ]).optional()
18840
18917
  });
18841
- var ModelFormatSchema$1 = _enum([
18842
- "onnx",
18843
- "coreml",
18844
- "openvino",
18845
- "tflite",
18846
- "pt",
18847
- "gguf"
18848
- ]);
18849
- var PipelineSlotSchema = _enum([
18850
- "detector",
18851
- "cropper",
18852
- "classifier",
18853
- "refiner",
18854
- "audio-classifier"
18855
- ]);
18856
- var PipelineEngineChoiceSchema = object({
18857
- runtime: _enum(["node", "python"]),
18858
- backend: string(),
18859
- format: ModelFormatSchema$1,
18860
- device: string().optional()
18918
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
18919
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
18920
+ var DeviceEventQueryInput = object({
18921
+ deviceId: number(),
18922
+ since: number().optional(),
18923
+ until: number().optional(),
18924
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
18925
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
18926
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
18927
+ * exact behaviour. Callers may omit this field — the store defaults to
18928
+ * `full` when not provided. */
18929
+ projection: _enum(["full", "slim"]).optional()
18861
18930
  });
18862
- var AvailableEngineSchema = object({
18863
- engine: PipelineEngineChoiceSchema,
18864
- devices: array(object({
18865
- id: string(),
18866
- label: string(),
18867
- description: string().optional()
18868
- })).readonly(),
18869
- defaultDevice: string()
18931
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
18932
+ var RecentTracksQueryInput = object({
18933
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
18934
+ deviceIds: array(number()),
18935
+ /** Window lower bound on `lastSeen` (inclusive). */
18936
+ since: number().optional(),
18937
+ /** Window upper bound on `lastSeen` (inclusive). */
18938
+ until: number().optional(),
18939
+ /** Page size. Default 200, max 1000. */
18940
+ limit: number().int().min(1).max(1e3).default(200),
18941
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
18942
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
18943
+ cursor: string().optional(),
18944
+ /** See {@link TrackProjectionSchema}. Default `full`. */
18945
+ projection: TrackProjectionSchema.optional(),
18946
+ /** Include stationary-promoted rows (parked objects). Default false: the
18947
+ * feed lists passages; parking records live on the stationary registry. */
18948
+ includeStationary: boolean().optional()
18870
18949
  });
18871
- var PipelineDefaultStepSchema = lazy(() => object({
18872
- addonId: string(),
18873
- addonName: string(),
18874
- slot: PipelineSlotSchema,
18875
- inputClasses: array(string()).readonly(),
18876
- outputClasses: array(string()).readonly(),
18877
- enabled: boolean(),
18878
- modelId: string(),
18879
- children: array(PipelineDefaultStepSchema).readonly(),
18880
- group: string().optional(),
18881
- settings: record(string(), unknown()).optional()
18882
- }));
18883
- var PipelineTemplateStepSchema = lazy(() => object({
18884
- addonId: string(),
18885
- enabled: boolean(),
18886
- modelId: string(),
18887
- children: array(PipelineTemplateStepSchema).readonly(),
18888
- settings: record(string(), unknown()).optional()
18889
- }));
18890
- var PipelineTemplateSchema$1 = object({
18891
- id: string(),
18892
- name: string(),
18893
- createdAt: string(),
18894
- updatedAt: string(),
18895
- engine: PipelineEngineChoiceSchema,
18896
- steps: array(PipelineTemplateStepSchema).readonly()
18950
+ var RecentTracksPageSchema = object({
18951
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
18952
+ tracks: array(TrackSchema).readonly(),
18953
+ /** Cursor for the next page, or null when this page is the last. */
18954
+ nextCursor: string().nullable()
18897
18955
  });
18898
- var PipelineModelOptionSchema = object({
18956
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
18957
+ var LIST_GROUPS_MAX_LIMIT = 100;
18958
+ var AnalyticsGroupRecordSchema = object({
18899
18959
  id: string(),
18900
- name: string(),
18901
- formats: record(string(), object({
18902
- downloaded: boolean(),
18903
- sizeMB: number()
18904
- })),
18905
- group: ModelVariantGroupSchema.optional(),
18906
- legacy: boolean().optional(),
18907
- provider: ModelProviderIdSchema.optional()
18960
+ deviceId: number().int(),
18961
+ openedAt: number().int(),
18962
+ closedAt: number().int(),
18963
+ timestamp: number().int(),
18964
+ memberCount: number().int(),
18965
+ memberTrackIds: array(string()).readonly(),
18966
+ className: string(),
18967
+ classes: array(string()).readonly(),
18968
+ /** Relative event-media path, or null when the group has no picture yet. */
18969
+ mediaUrl: string().nullable(),
18970
+ singleton: boolean()
18908
18971
  });
18909
- var ConfigFieldBridge = custom();
18910
- var PipelineAddonSchemaSchema = object({
18911
- id: string(),
18912
- name: string(),
18913
- slot: PipelineSlotSchema,
18914
- inputClasses: array(string()).readonly(),
18915
- outputClasses: array(string()).readonly(),
18916
- childSlots: array(PipelineSlotSchema).readonly(),
18917
- models: array(PipelineModelOptionSchema).readonly(),
18918
- defaultModelId: string(),
18919
- defaultModelIdByFormat: record(string(), string()).optional(),
18920
- enabledByDefault: boolean().optional(),
18921
- backfillIntoExistingOverrides: boolean().optional(),
18922
- defaultConfidence: number(),
18923
- group: string().optional(),
18924
- configSchema: array(ConfigFieldBridge).readonly().optional()
18972
+ var AnalyticsGroupMemberSchema = object({
18973
+ trackId: string(),
18974
+ deviceId: number().int(),
18975
+ className: string(),
18976
+ firstSeen: number().int(),
18977
+ lastSeen: number().int(),
18978
+ mediaUrl: string().nullable()
18925
18979
  });
18926
- var PipelineSlotSchemaSchema = object({
18927
- id: PipelineSlotSchema,
18928
- label: string(),
18929
- priority: number(),
18930
- parentSlot: PipelineSlotSchema.nullable(),
18931
- addons: array(PipelineAddonSchemaSchema).readonly()
18980
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
18981
+ var ListGroupsQueryInput = object({
18982
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
18983
+ deviceIds: array(number()),
18984
+ /** Window lower bound on `closedAt` (inclusive). */
18985
+ since: number().optional(),
18986
+ /** Window upper bound on `openedAt` (inclusive). */
18987
+ until: number().optional(),
18988
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
18989
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
18990
+ cursor: string().optional()
18932
18991
  });
18933
- var PipelineSchemaSchema = object({
18934
- availableEngines: array(AvailableEngineSchema).readonly(),
18935
- selectedEngine: PipelineEngineChoiceSchema,
18936
- slots: array(PipelineSlotSchemaSchema).readonly()
18992
+ var ListGroupsPageSchema = object({
18993
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
18994
+ nextCursor: string().nullable()
18937
18995
  });
18938
- var EngineProvisioningSchema = object({
18939
- runtimeId: _enum([
18940
- "onnx",
18941
- "openvino",
18942
- "coreml",
18943
- "edgetpu"
18944
- ]).nullable(),
18945
- device: string().nullable(),
18946
- state: _enum([
18947
- "idle",
18948
- "installing",
18949
- "verifying",
18950
- "ready",
18951
- "failed"
18952
- ]),
18953
- progress: number().optional(),
18954
- error: string().optional(),
18955
- nextRetryAt: number().optional(),
18956
- /**
18957
- * Gate A (config-correctness gate at engine change): human-readable
18958
- * config issues surfaced EAGERLY when the node's engine changes — model
18959
- * substitutions ("chose X, running Y") and zero-build steps ("no model
18960
- * has a <format> build"). Additive/optional: informational only, never
18961
- * enforced here — `assertEngineReady` (readiness) still gates inference.
18962
- * Absent/empty when the node-default tree resolves cleanly.
18963
- */
18964
- configIssues: array(string()).optional()
18996
+ var KeyEventQueryInput = object({
18997
+ deviceId: number(),
18998
+ /** Window lower bound (track firstSeen ≥ since). */
18999
+ since: number(),
19000
+ /** Window upper bound (track firstSeen ≤ until). */
19001
+ until: number(),
19002
+ limit: number().int().min(1).max(200).default(50),
19003
+ /** Drop tracks scoring below this importance. */
19004
+ minImportance: number().min(0).max(1).optional(),
19005
+ /** Restrict to a single class (e.g. 'person'). */
19006
+ classFilter: string().optional()
18965
19007
  });
18966
- var PipelineStepInputSchema = lazy(() => object({
18967
- addonId: string(),
18968
- modelId: string().optional(),
18969
- enabled: boolean().default(true),
18970
- children: array(PipelineStepInputSchema).optional(),
18971
- settings: record(string(), unknown()).optional(),
18972
- jumpDeviceKey: string().optional()
18973
- }));
18974
- var ModelSubstitutionSchema = object({
18975
- addonId: string(),
18976
- chosen: string(),
18977
- running: string(),
18978
- format: string()
19008
+ var KeyEventSchema = object({
19009
+ /** The representative event id (the track's best ObjectEvent, else its trackId). */
19010
+ id: string(),
19011
+ trackId: string(),
19012
+ /** Track start time (firstSeen). */
19013
+ timestamp: number(),
19014
+ className: string(),
19015
+ ...TieredLabelFields,
19016
+ importance: number(),
19017
+ /** Highest-confidence ObjectEvent id for the track (empty when none). */
19018
+ bestEventId: string(),
19019
+ /** Track lifetime in ms (lastSeen - firstSeen). */
19020
+ windowMs: number().optional(),
19021
+ ...TrackFlagFields,
19022
+ ...TrackRetrainFields
18979
19023
  });
18980
- var PipelineValidationIssueSchema = object({
18981
- addonId: string(),
18982
- kind: _enum(["unknown-addon", "no-format-build"]),
18983
- detail: string()
19024
+ object({
19025
+ trackId: string(),
19026
+ className: string(),
19027
+ confidence: number(),
19028
+ bbox: BoundingBoxSchema,
19029
+ zones: array(string()).readonly(),
19030
+ state: TrackStateSchema
18984
19031
  });
18985
- var PipelineValidationResultSchema = object({
18986
- ok: boolean(),
18987
- issues: array(PipelineValidationIssueSchema).readonly(),
18988
- substitutions: array(ModelSubstitutionSchema).readonly(),
18989
- /** The node's `currentEngine.format` this validation ran against. */
18990
- format: string()
19032
+ var OverlayDetectionSchema = looseObject({
19033
+ id: string(),
19034
+ kind: _enum(["first-level", "detail"]),
19035
+ macroClass: string(),
19036
+ score: number(),
19037
+ bbox: object({
19038
+ x: number(),
19039
+ y: number(),
19040
+ width: number(),
19041
+ height: number()
19042
+ }),
19043
+ labels: array(looseObject({
19044
+ label: string(),
19045
+ score: number()
19046
+ })).readonly(),
19047
+ parentId: string().optional()
19048
+ });
19049
+ var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
19050
+ var SearchObjectEventsInput = object({
19051
+ text: string(),
19052
+ deviceId: number().optional(),
19053
+ since: number().optional(),
19054
+ until: number().optional(),
19055
+ classFilter: string().optional(),
19056
+ limit: number().default(50),
19057
+ minScore: number().min(0).max(1).default(.2)
19058
+ });
19059
+ var TrackCascadeCountsSchema = object({
19060
+ /** Persisted track roots deleted (authoritative). */
19061
+ tracks: number().int(),
19062
+ /** Object events removed with their tracks (best-effort; see note above). */
19063
+ events: number().int(),
19064
+ /** Track/face/plate-owned media removed (best-effort). Never identity media. */
19065
+ media: number().int(),
19066
+ /** Unassigned (non-enrolled) face reads removed (best-effort). */
19067
+ faces: number().int(),
19068
+ /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
19069
+ plates: number().int(),
19070
+ /** Per-track CLIP search vectors removed (best-effort). */
19071
+ embeddings: number().int(),
19072
+ /** Group membership + group rows removed with their last member (best-effort). */
19073
+ groups: number().int()
18991
19074
  });
18992
- var ReferenceImageEntrySchema = object({
18993
- filename: string(),
18994
- stepIds: array(string()).readonly().optional()
19075
+ /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
19076
+ var DiskReconcileCountsSchema = object({
19077
+ mediaDropped: number().int(),
19078
+ tracks: number().int(),
19079
+ events: number().int()
18995
19080
  });
18996
- var ReferenceImageBodySchema = object({
18997
- base64: string(),
18998
- filename: string()
19081
+ /** Event-store footprint for one camera. */
19082
+ var EventStoreDeviceFootprintSchema = object({
19083
+ deviceId: number(),
19084
+ /** Persisted event rows (motion + object + audio) for the camera. */
19085
+ rows: number().int(),
19086
+ /** Event-owned media bytes on disk for the camera. */
19087
+ bytes: number().int()
18999
19088
  });
19000
- var ReferenceAudioEntrySchema = object({
19001
- filename: string(),
19002
- sizeKb: number()
19089
+ /** Aggregate event-store footprint: global totals + per-camera breakdown. */
19090
+ var EventStoreFootprintSchema = object({
19091
+ totalRows: number().int(),
19092
+ totalBytes: number().int(),
19093
+ devices: array(EventStoreDeviceFootprintSchema).readonly()
19003
19094
  });
19004
- var ReferenceAudioBodySchema = object({ base64: string() });
19005
- var AudioBackendSchema = object({
19006
- id: string(),
19007
- name: string(),
19008
- description: string(),
19009
- available: boolean(),
19095
+ /** Per-kind counts returned by the event-prune / device-delete mutations. */
19096
+ var EventPruneCountsSchema = object({
19097
+ motion: number().int(),
19098
+ object: number().int(),
19099
+ audio: number().int()
19100
+ });
19101
+ /**
19102
+ * Re-embed stored tracks from their key frames.
19103
+ *
19104
+ * The reason this is an operator-callable method and not a migration script:
19105
+ * every knob that decides what a vector MEANS — encoder model, crop margin,
19106
+ * squaring — is only changeable if the existing vectors can be regenerated.
19107
+ * Mixing feature spaces in one index makes cosine scores incomparable, and the
19108
+ * symptom is a quality regression with no visible cause.
19109
+ */
19110
+ var RebuildObjectEmbeddingsInput = object({
19111
+ /** Restrict to one camera. Omit for the whole fleet. */
19112
+ deviceId: number().optional(),
19113
+ since: number().optional(),
19114
+ until: number().optional(),
19115
+ /** Stop after this many tracks; the result reports whether more remain. */
19116
+ maxTracks: number().int().positive().optional(),
19010
19117
  /**
19011
- * Raw classifier labels this backend can emit (e.g. YAMNet's
19012
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
19013
- * the benchmark UI to populate the `enabledMicroClasses` filter
19014
- * specific to the selected backend without a separate fetch.
19118
+ * Run every embedding on THIS node instead of round-robining the fleet.
19119
+ *
19120
+ * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
19121
+ * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
19122
+ * calling it that would pin the rebuild REQUEST itself to that node — the
19123
+ * rebuild orchestration lives on the hub, and only the per-track step runs
19124
+ * remotely. This field is data; the per-track pin is applied inside.
19125
+ *
19126
+ * Absent ⇒ round-robin over every online node whose runner can serve the
19127
+ * pinned model.
19015
19128
  */
19016
- rawLabels: array(string()).readonly().optional()
19017
- });
19018
- var AudioCapabilitiesSchema = object({
19019
- activeBackend: string(),
19020
- availableBackends: array(AudioBackendSchema).readonly(),
19021
- sampleRate: number(),
19022
- chunkDurationMs: number()
19023
- });
19024
- var DownloadModelResultSchema = object({
19025
- filePath: string(),
19026
- sizeMB: number(),
19027
- durationMs: number()
19129
+ executeOnNodeId: string().optional(),
19130
+ /**
19131
+ * Milliseconds to wait between tracks; omit for the built-in default, `0` to
19132
+ * run flat out.
19133
+ *
19134
+ * A rebuild is bulk maintenance on hub-main's single thread. Measured
19135
+ * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
19136
+ * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
19137
+ * force is logged at start and finish so a deliberately slow pass reads
19138
+ * differently from a stalled one.
19139
+ */
19140
+ pacingMs: number().int().nonnegative().optional()
19028
19141
  });
19029
19142
  /**
19030
- * Wrapper carrying a single test run's result. Replaces the legacy
19031
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
19032
- * canonical `AudioResult` from the Phase 6 output rework: one
19033
- * `AudioDetection` per class above `minScore`, top-N candidates in
19034
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
19035
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
19036
- * benchmark UI can still report a clean failure when the classifier
19037
- * cap isn't available.
19143
+ * Result of emptying the CLIP index.
19144
+ *
19145
+ * The clean slate before a policy change: a new crop margin or encoder model
19146
+ * leaves two feature spaces in one index whose cosine scores are not
19147
+ * comparable, so wiping and rebuilding is the only way to be sure every vector
19148
+ * means the same thing.
19038
19149
  */
19039
- var AudioTestResultSchema = object({
19040
- success: boolean(),
19041
- error: string().optional(),
19042
- frame: custom().optional()
19150
+ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
19151
+ /**
19152
+ * Acknowledgement that a rebuild STARTED.
19153
+ *
19154
+ * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
19155
+ * runs detached and this returns immediately. Waiting for it made the client
19156
+ * time out while the work carried on server-side, which is the worst of both:
19157
+ * no result and no way to know it was still going. Poll
19158
+ * `getObjectEmbeddingRebuildStatus` for progress.
19159
+ */
19160
+ var RebuildObjectEmbeddingsResultSchema = object({
19161
+ started: boolean(),
19162
+ /** True when a pass was already running; the new request is ignored. */
19163
+ alreadyRunning: boolean()
19043
19164
  });
19044
- var PipelineConfigBridge = custom();
19045
- var ConfigUISchemaBridge = custom();
19046
- var ConfigUISchemaNullableBridge = custom();
19047
- var InferenceCapabilitiesBridge = custom();
19048
- var ModelAvailabilityListBridge = custom();
19049
- var PipelineRunResultBridge = custom();
19050
- method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
19051
- modelId: string(),
19052
- settings: record(string(), unknown()).readonly()
19053
- }))), method(object({ steps: record(string(), object({
19054
- modelId: string(),
19055
- settings: record(string(), unknown()).readonly()
19056
- })) }), object({ success: literal(true) }), {
19165
+ var RebuildStatusSchema = object({
19166
+ running: boolean(),
19167
+ scanned: number(),
19168
+ rebuilt: number(),
19169
+ /** Tracks whose key frame is gone — nothing to re-embed from. */
19170
+ missingKeyFrame: number(),
19171
+ /** Tracks with no usable detection box. */
19172
+ missingBbox: number(),
19173
+ /**
19174
+ * Tracks an executing node REFUSED rather than broke on — an unreadable key
19175
+ * frame, a step that threw. Separate from `failed` because the remedy is
19176
+ * different, and because a whole camera silently contributing zero vectors
19177
+ * is the shape of failure a rebuild must never hide.
19178
+ */
19179
+ notRunnable: number(),
19180
+ /**
19181
+ * The pass stopped because NO node could serve the pinned model.
19182
+ *
19183
+ * Distinct from `notRunnable` on purpose: that one says "this track was
19184
+ * refused", this one says "the cluster cannot do this work at all" — every
19185
+ * candidate node either lacks the `clip-embedding` step, lacks a build of the
19186
+ * pinned model for its engine format, or dropped out. The remedy is a model /
19187
+ * engine change, not a per-camera one. Non-zero here always comes with
19188
+ * `complete: false`.
19189
+ */
19190
+ noCapableNode: number(),
19191
+ failed: number(),
19192
+ /** Set once a pass ends: true only when EVERYTHING was covered. */
19193
+ complete: boolean().nullable(),
19194
+ startedAtMs: number().nullable(),
19195
+ finishedAtMs: number().nullable(),
19196
+ /** Present when the pass ended by throwing. */
19197
+ error: string().nullable()
19198
+ });
19199
+ var ReplayFrameInputSchema = object({
19200
+ timestamp: number(),
19201
+ frame: PipelineRunResultBridge
19202
+ });
19203
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
19204
+ className: string(),
19205
+ firstSeenMs: number(),
19206
+ lastSeenMs: number(),
19207
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
19208
+ * frame — a representative box for the diff's `(className, window, IoU)`
19209
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
19210
+ * trajectory production's `Track.positions` keeps. */
19211
+ bbox: BoundingBoxSchema,
19212
+ /** How many of the input frames this track matched a real detection on
19213
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
19214
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
19215
+ framesMatched: number().int()
19216
+ })).readonly() });
19217
+ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
19218
+ deviceId: number(),
19219
+ trackId: string()
19220
+ }), TrackSchema.nullable()), method(object({
19221
+ deviceId: number(),
19222
+ since: number().optional(),
19223
+ until: number().optional(),
19224
+ limit: number().optional(),
19225
+ /** Spatial filter — only tracks whose trajectory intersects the zone
19226
+ * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
19227
+ * envelope columns, then precisely tested per position. Tracks with
19228
+ * an unknown envelope (no frame dims at persist time) always match. */
19229
+ zone: TrackZoneFilterSchema.optional(),
19230
+ /** See {@link TrackProjectionSchema}. Default `full` (backward
19231
+ * compatible — omitting the field keeps today's exact behaviour). */
19232
+ projection: TrackProjectionSchema.optional(),
19233
+ /** Include stationary-promoted rows (parked objects handed to the
19234
+ * stationary registry). Default false: the timeline lists passages,
19235
+ * not parking records (operator decision, 2026-08-15). */
19236
+ includeStationary: boolean().optional()
19237
+ }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
19238
+ deviceId: number(),
19239
+ groupId: string().min(1)
19240
+ }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
19241
+ kind: "mutation",
19242
+ auth: "admin"
19243
+ }), 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({
19244
+ deviceId: number(),
19245
+ since: number().optional(),
19246
+ until: number().optional(),
19247
+ kinds: array(string()).optional(),
19248
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
19249
+ }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
19250
+ deviceId: number(),
19251
+ since: number(),
19252
+ until: number(),
19253
+ bucketMs: number().int().positive()
19254
+ }), array(object({
19255
+ bucketStart: number(),
19256
+ motion: number().int(),
19257
+ object: number().int(),
19258
+ audio: number().int()
19259
+ })).readonly()), method(object({
19260
+ deviceId: number(),
19261
+ cutoffMs: number()
19262
+ }), object({
19263
+ motion: number().int(),
19264
+ object: number().int(),
19265
+ audio: number().int()
19266
+ }), {
19267
+ kind: "mutation",
19268
+ auth: "admin"
19269
+ }), method(object({
19270
+ deviceId: number(),
19271
+ cutoffMs: number()
19272
+ }), TrackCascadeCountsSchema, {
19273
+ kind: "mutation",
19274
+ auth: "admin"
19275
+ }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
19276
+ kind: "mutation",
19277
+ auth: "admin"
19278
+ }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
19279
+ kind: "mutation",
19280
+ auth: "admin"
19281
+ }), method(object({
19282
+ deviceId: number(),
19283
+ trackIds: array(string()).min(1)
19284
+ }), object({
19285
+ deleted: number().int(),
19286
+ failed: array(string()).readonly()
19287
+ }), {
19288
+ kind: "mutation",
19289
+ auth: "admin"
19290
+ }), method(object({
19291
+ /** Log/audit scope only — the trackId is globally unique on its own. */
19292
+ deviceId: number(),
19293
+ trackId: string(),
19294
+ flags: TrackFlagsPatchSchema
19295
+ }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
19296
+ kind: "query",
19297
+ auth: "admin"
19298
+ }), method(object({
19299
+ olderThanMs: number(),
19300
+ reason: OpsLogReasonSchema.optional()
19301
+ }), EventPruneCountsSchema, {
19057
19302
  kind: "mutation",
19058
19303
  auth: "admin"
19059
- }), method(object({ nodeId: string() }), object({
19060
- success: literal(true),
19061
- clearedDevices: number()
19062
- }), {
19304
+ }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
19063
19305
  kind: "mutation",
19064
19306
  auth: "admin"
19065
- }), 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({
19066
- name: string(),
19067
- steps: array(PipelineTemplateStepSchema).readonly(),
19068
- engine: PipelineEngineChoiceSchema
19069
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
19070
- id: string(),
19071
- name: string().optional(),
19072
- steps: array(PipelineTemplateStepSchema).readonly().optional()
19073
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
19074
- addonId: string(),
19075
- modelId: string(),
19076
- format: ModelFormatSchema$1
19077
- }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
19078
- addonId: string(),
19079
- modelId: string(),
19080
- format: ModelFormatSchema$1
19081
- }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
19082
- engine: PipelineEngineChoiceSchema.optional(),
19083
- steps: array(PipelineStepInputSchema).min(1),
19084
- frame: FrameInputSchema.optional(),
19085
- /**
19086
- * Process-local lazy frame. Valid only when caller and provider resolve
19087
- * in the same execution-group process; split/cross-node callers use
19088
- * `frame`/`image` inline compatibility instead.
19089
- */
19090
- frameRef: FrameRefSchema.optional(),
19091
- /**
19092
- * CB5 shm passthrough a `FrameHandle` naming the same ring slot
19093
- * the decoded pixels live in. One more member of the one-of
19094
- * frame/frameHandle/image/imageBase64/referenceImage group.
19095
- */
19096
- frameHandle: FrameHandleSchema.optional(),
19097
- imageBase64: string().optional(),
19098
- /**
19099
- * Binary JPEG bytes preferred over `imageBase64` on internal
19100
- * hops (hub forked worker via Moleculer MsgPack) because it
19101
- * skips the 33% base64 overhead + the per-call base64 decode on
19102
- * the detection-pipeline worker. Callers can pass either; exactly
19103
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
19104
- */
19105
- image: _instanceof(Uint8Array).optional(),
19106
- referenceImage: string().optional(),
19107
- deviceId: number().optional(),
19108
- sessionId: string().optional(),
19109
- /**
19110
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
19111
- * reference-image, and detail-subtree calls. 'frame' is the live
19112
- * per-frame dispatch: ONLY root-plane steps run; crop children
19113
- * (inputClasses ≠ null) are skipped and served per-track via
19114
- * pipelineRunner.runDetailSubtree (two-plane design).
19115
- */
19116
- plane: _enum(["full", "frame"]).optional(),
19117
- /**
19118
- * Inference-device selector (Phase 2 multi-device). Format
19119
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
19120
- * Omitted ⇒ the runner's default device (current single-engine
19121
- * behaviour). Selects WHICH device pool of the node runs the call.
19122
- */
19123
- deviceKey: string().optional(),
19124
- /**
19125
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
19126
- * when the parent crop was resolved from the frame's retained NATIVE
19127
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
19128
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
19129
- * resolution from that surface — the SAME quality path faces already
19130
- * had — instead of the downscaled parent tile. `handle` keys the native
19131
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
19132
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
19133
- * the executor's crop-normalized child ROI back into frame-normalized
19134
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
19135
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
19136
- * (today's behaviour on the fallback path).
19137
- */
19138
- nativeCropRef: NativeCropRefSchema.optional()
19139
- }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
19140
- engine: PipelineEngineChoiceSchema.optional(),
19141
- steps: array(PipelineStepInputSchema).min(1),
19142
- frames: array(FrameInputSchema).min(1).max(255),
19143
- deviceId: number().optional(),
19144
- sessionId: string().optional(),
19145
- /**
19146
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
19147
- * the batch to the Python pool's bench preprocess cache
19148
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
19149
- * preprocessed ONCE and every later inference is a pure-inference cache
19150
- * hit — the sustained-throughput run measures inference, not
19151
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
19152
- * full preprocess every call, correct). Fresh per sustained run;
19153
- * released via `uncacheFrame`.
19154
- */
19155
- frameId: number().int().nonnegative().optional(),
19156
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
19157
- deviceKey: string().optional()
19158
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
19159
- data: _instanceof(Uint8Array),
19160
- width: number().int().positive(),
19161
- height: number().int().positive(),
19162
- format: _enum([
19163
- "rgb",
19164
- "bgr",
19165
- "gray"
19166
- ])
19307
+ }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
19308
+ kind: "mutation",
19309
+ auth: "admin"
19310
+ }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
19311
+ kind: "mutation",
19312
+ auth: "admin"
19313
+ }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
19314
+ kind: "mutation",
19315
+ auth: "admin"
19316
+ }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
19317
+ kind: "mutation",
19318
+ auth: "admin"
19319
+ }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
19320
+ kind: "mutation",
19321
+ auth: "admin"
19322
+ }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
19323
+ kind: "mutation",
19324
+ auth: "admin"
19325
+ }), method(object({}), array(RelocateJobSchema).readonly(), {
19326
+ kind: "query",
19327
+ auth: "admin"
19328
+ }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
19329
+ kind: "mutation",
19330
+ auth: "admin"
19331
+ }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
19332
+ kind: "query",
19333
+ auth: "admin"
19334
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
19335
+ kind: "query",
19336
+ auth: "admin"
19337
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
19338
+ kind: "query",
19339
+ auth: "admin"
19340
+ }), method(object({
19341
+ /** Empty every camera that has staging tracks. A LIST, not a single
19342
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
19343
+ * route it at one camera's owner, and "every camera" would stop being
19344
+ * expressible at all. */
19345
+ deviceIds: array(number()).optional(),
19346
+ limit: number().int().min(1).max(500).optional()
19347
+ }), array(RetrainTrackSchema).readonly(), {
19348
+ kind: "query",
19349
+ auth: "admin"
19350
+ }), method(object({ trackId: string() }), RetrainFrameListSchema, {
19351
+ kind: "query",
19352
+ auth: "admin"
19353
+ }), method(object({
19354
+ deviceId: number(),
19355
+ trackId: string(),
19356
+ mediaKeys: array(string()).min(1)
19357
+ }), RetrainFrameSelectionSchema, {
19358
+ kind: "mutation",
19359
+ auth: "admin"
19360
+ }), method(object({
19361
+ deviceId: number(),
19362
+ trackId: string(),
19363
+ frameId: string()
19167
19364
  }), object({
19168
- frameId: number(),
19169
- width: number(),
19170
- height: number()
19171
- }), { kind: "mutation" }), method(object({
19172
- stepId: string(),
19173
- frameId: number().int()
19174
- }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
19175
- batchMode: string(),
19176
- windowMs: number(),
19177
- maxBatchSize: number(),
19178
- concurrency: number()
19179
- })), method(_void(), array(object({
19180
- engineKey: string(),
19181
- engine: PipelineEngineChoiceSchema,
19182
- modelsLoaded: array(string()).readonly(),
19183
- inUseByCameras: array(number()).readonly(),
19184
- /**
19185
- * Origin of this resident factory.
19186
- * - `runtime` — main camera-serving engine (no idle TTL).
19187
- * - `warm-override` — benchmark/test override held in the warm
19188
- * cache; auto-disposed after the idle TTL.
19189
- * - `device-pool` — a concurrent per-device pool (Phase 2
19190
- * multi-device, keyed by `deviceKey`) resolved
19191
- * via `resolveDeviceFactory`. Runs alongside the
19192
- * `runtime` engine on a DIFFERENT accelerator
19193
- * (NPU / iGPU / Coral) — this is how the
19194
- * Engines tab shows all pools running at once.
19195
- */
19196
- kind: _enum([
19197
- "runtime",
19198
- "warm-override",
19199
- "device-pool"
19200
- ]),
19201
- /** Native pid of the underlying Python pool (null when no pool). */
19202
- poolPid: number().nullable(),
19203
- /** ms since this factory was last used (null when not warm-tracked). */
19204
- idleMs: number().nullable(),
19205
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
19206
- idleTtlMs: number().nullable()
19207
- })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
19365
+ removed: boolean(),
19366
+ removedAnnotations: number().int()
19367
+ }), {
19368
+ kind: "mutation",
19369
+ auth: "admin"
19370
+ }), method(object({ frameId: string() }), object({
19371
+ base64: string(),
19372
+ width: number().int(),
19373
+ height: number().int()
19374
+ }), {
19375
+ kind: "query",
19376
+ auth: "admin"
19377
+ }), method(object({
19378
+ deviceId: number(),
19379
+ trackId: string(),
19380
+ frameId: string(),
19381
+ subject: RetrainAssistSubjectSchema,
19382
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
19383
+ nodeId: string().optional()
19384
+ }), RetrainAssistResultSchema, {
19385
+ kind: "mutation",
19386
+ auth: "admin"
19387
+ }), method(object({
19388
+ deviceId: number(),
19389
+ source: DetectionSourceSchema,
19390
+ zones: array(ZoneSchema).readonly().optional(),
19391
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
19392
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
19393
+ frames: array(ReplayFrameInputSchema).min(1)
19394
+ }), RunReplayFrameProcessorResultSchema, {
19395
+ kind: "mutation",
19396
+ auth: "admin"
19397
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
19398
+ kind: "query",
19399
+ auth: "admin"
19400
+ }), method(object({
19401
+ deviceId: number(),
19402
+ trackId: string(),
19403
+ frameId: string(),
19404
+ annotations: array(RetrainAnnotationDraftSchema)
19405
+ }), array(RetrainAnnotationSchema).readonly(), {
19406
+ kind: "mutation",
19407
+ auth: "admin"
19408
+ }), method(object({
19409
+ deviceId: number(),
19410
+ trackId: string()
19411
+ }), RetrainTransitionResultSchema, {
19412
+ kind: "mutation",
19413
+ auth: "admin"
19414
+ }), method(object({
19415
+ deviceId: number(),
19416
+ trackId: string()
19417
+ }), RetrainTransitionResultSchema, {
19208
19418
  kind: "mutation",
19209
19419
  auth: "admin"
19420
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
19421
+ kind: "query",
19422
+ auth: "admin"
19210
19423
  }), method(object({
19211
- engine: PipelineEngineChoiceSchema,
19212
- force: boolean().optional()
19213
- }), object({
19214
- success: boolean(),
19215
- reason: string().optional()
19216
- }), {
19424
+ eventId: string(),
19425
+ kind: MediaFileKindEnum.optional(),
19426
+ deviceId: number()
19427
+ }), array(MediaFileSchema).readonly()), method(object({
19428
+ trackId: string(),
19429
+ kinds: array(MediaFileKindEnum).optional(),
19430
+ deviceId: number()
19431
+ }), array(MediaFileSchema).readonly()), method(object({
19432
+ trackId: string(),
19433
+ deviceId: number()
19434
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
19217
19435
  kind: "mutation",
19218
19436
  auth: "admin"
19219
- }), 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({
19220
- addonId: string(),
19221
- modelId: string(),
19222
- filename: string().optional(),
19223
- settings: record(string(), unknown()).optional()
19224
- }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
19437
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
19438
+ kind: "mutation",
19439
+ auth: "admin"
19440
+ }), method(object({}), RebuildStatusSchema), object({
19441
+ deviceId: number(),
19442
+ timestamp: number(),
19443
+ frameWidth: number(),
19444
+ frameHeight: number(),
19445
+ detections: array(OverlayDetectionSchema).readonly()
19446
+ }), object({
19447
+ deviceId: number(),
19448
+ trackId: string(),
19449
+ className: string()
19450
+ }), object({
19451
+ deviceId: number(),
19452
+ trackId: string(),
19453
+ className: string(),
19454
+ durationMs: number()
19455
+ }), object({
19456
+ deviceId: number(),
19457
+ kind: EventKindSchema,
19458
+ eventId: string(),
19459
+ timestamp: number()
19460
+ });
19225
19461
  object({
19226
19462
  activeCameras: number(),
19227
19463
  throttledCameras: number(),
@@ -19247,106 +19483,6 @@ var CameraMetricsSchema = object({
19247
19483
  });
19248
19484
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
19249
19485
  /**
19250
- * Zone — pure geometry + identity. NO filtering behaviour.
19251
- *
19252
- * Zones describe **where** in the frame the operator wants to flag
19253
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
19254
- * each pipeline stage uses them. Splitting the two means a single
19255
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
19256
- * a detection-include rule on `['car']`, and an occupancy aggregate
19257
- * — without three duplicated polygons.
19258
- *
19259
- * Owned by the orchestrator addon (provider) and mirrored into the
19260
- * `zones` device-state slice on every mutation. Consumers
19261
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
19262
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
19263
- * mirror with `onChanged`).
19264
- *
19265
- * Coordinates are normalised fractions of the frame (0–1) so zones
19266
- * survive resolution changes and stream profile switches.
19267
- *
19268
- * `kind` discriminates between full polygons (closed regions used
19269
- * for intrusion / occupancy filters) and tripwires (open 2-point
19270
- * line segments used for cross events). Onboard / firmware-reported
19271
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
19272
- * task list.
19273
- */
19274
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
19275
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
19276
- var PolygonPointSchema = object({
19277
- x: number(),
19278
- y: number()
19279
- });
19280
- /** A camera detection zone — pure geometry/identity. */
19281
- var ZoneSchema = object({
19282
- id: string(),
19283
- name: string(),
19284
- kind: ZoneKindEnum.default("polygon"),
19285
- /** Polygon vertices, fraction of frame (0–1). */
19286
- polygon: array(PolygonPointSchema).readonly(),
19287
- /** Visual color for UI rendering. */
19288
- color: string().default("#3b82f6")
19289
- });
19290
- /**
19291
- * Zones capability — per-camera CRUD over polygon detection zones.
19292
- *
19293
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
19294
- * to per-device settings and mirrors into the `zones` device-state
19295
- * slice on every mutation, so downstream consumers can subscribe via
19296
- * `dev.state.zones.onChanged`.
19297
- *
19298
- * The cap surface only handles geometry + identity; filtering
19299
- * behaviour (per-class, include/exclude, threshold) lives in the
19300
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
19301
- * `capabilities/schemas/zone-rule.js`.
19302
- */
19303
- var zonesCapability = {
19304
- name: "zones",
19305
- scope: "device",
19306
- mode: "singleton",
19307
- deviceTypes: [DeviceType.Camera],
19308
- methods: {
19309
- listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
19310
- addZone: method(object({
19311
- deviceId: number(),
19312
- zone: ZoneSchema
19313
- }), _void(), {
19314
- kind: "mutation",
19315
- auth: "admin"
19316
- }),
19317
- removeZone: method(object({
19318
- deviceId: number(),
19319
- zoneId: string()
19320
- }), _void(), {
19321
- kind: "mutation",
19322
- auth: "admin"
19323
- }),
19324
- updateZone: method(object({
19325
- deviceId: number(),
19326
- zone: ZoneSchema
19327
- }), _void(), {
19328
- kind: "mutation",
19329
- auth: "admin"
19330
- })
19331
- },
19332
- /**
19333
- * Runtime-state slice — the live zone catalogue mirrored by the
19334
- * orchestrator on every CRUD mutation. Consumers read via
19335
- * `device.state.zones.value` / `.watch(...)` without round-tripping
19336
- * the cap, and the codegen DeviceProxy auto-wires the reactive
19337
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
19338
- * (e.g. zone groupings) can sit alongside the polygon list.
19339
- */
19340
- runtimeState: object({ zones: array(ZoneSchema).readonly() }),
19341
- /**
19342
- * 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.
19343
- *
19344
- * See `RuntimeStateDurability`. Enforced by
19345
- * `scripts/check-runtime-state-durability.ts`.
19346
- */
19347
- durability: "restored"
19348
- };
19349
- /**
19350
19486
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
19351
19487
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
19352
19488
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -28665,92 +28801,6 @@ var sceneMonitorCapability = {
28665
28801
  durability: "session"
28666
28802
  };
28667
28803
  /**
28668
- * Per-stage gating mode applied to the zones a rule references.
28669
- *
28670
- * - `include`: the rule contributes to a **whitelist** for its stage.
28671
- * When at least one `include` rule fires for a stage, only entities
28672
- * inside one of those zones pass that stage.
28673
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
28674
- * Entities inside one of those zones are dropped at that stage.
28675
- *
28676
- * `monitor`-style observation (count without filtering) is not a rule
28677
- * mode — zones without any matching rule are observed naturally by
28678
- * `zone-analytics` (live snapshot + history), so an "I just want to
28679
- * count, not filter" use case needs no rule at all.
28680
- */
28681
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
28682
- /**
28683
- * Per-consumer rule that references existing zones (geometry) and
28684
- * defines how a specific pipeline stage should treat them. Each
28685
- * consumer addon owns its own `ZoneRule[]` array in its per-device
28686
- * settings:
28687
- *
28688
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
28689
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
28690
- * - future: notification rules, audio gating, etc.
28691
- *
28692
- * One rule applies to N zones (`zoneIds[]`) so the operator can
28693
- * express "ignore motion in ALL of {garden, street}" with a single
28694
- * rule. `classFilter` narrows the rule to specific object classes —
28695
- * "drop person detections in the street, but keep cars" is one
28696
- * `exclude` rule with `classFilter: ['person']`.
28697
- *
28698
- * `enabled` is a soft toggle — the operator can keep the rule
28699
- * configured but inert without deleting it.
28700
- */
28701
- var ZoneRuleSchema = object({
28702
- /** Stable rule id — survives edits, used by the UI for diffing. */
28703
- id: string(),
28704
- /** Optional human-readable label rendered in the rule editor. */
28705
- name: string().optional(),
28706
- /** Zones this rule targets. The rule's `mode` applies to ALL
28707
- * listed zones (OR-set: a detection in any one of them counts).
28708
- * At least one zone id required — a rule with no targets is a
28709
- * configuration mistake and the form validator rejects it. */
28710
- zoneIds: array(string()).min(1).readonly(),
28711
- mode: ZoneRuleModeEnum,
28712
- /**
28713
- * Class names this rule applies to. Empty / undefined ⇒ rule
28714
- * applies to every class. Class strings match the `macroClass`
28715
- * field on detections (e.g. `person`, `car`, `dog`).
28716
- */
28717
- classFilter: array(string()).readonly().optional(),
28718
- /**
28719
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
28720
- * required to consider an entity "in the zone". Defaults to the
28721
- * consumer's stage default when omitted. Kept for back-compat with
28722
- * existing per-rule overrides; new operators pick the value via
28723
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
28724
- * set, the lower-level engine reads it as a 0–1 fraction.
28725
- */
28726
- overlapThreshold: number().min(0).max(1).optional(),
28727
- /**
28728
- * Operator-friendly version of `overlapThreshold` — the percentage
28729
- * of the detection's bbox that must lie inside the zone for the
28730
- * rule to match. Documented default is 85%; the engine substitutes
28731
- * that when the field is omitted (kept optional so existing rules
28732
- * stored without it stay valid).
28733
- *
28734
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
28735
- * rule, the engine prefers `bboxInclusionPct` because it's the
28736
- * field exposed in the UI. Internally both feed the same gate.
28737
- */
28738
- bboxInclusionPct: number().min(0).max(100).optional(),
28739
- /**
28740
- * When `true` and a detection has a segmentation mask, use the
28741
- * mask for overlap instead of the bbox. Detection-stage only;
28742
- * motion rules ignore this field.
28743
- */
28744
- preferMask: boolean().optional(),
28745
- /**
28746
- * Soft-toggle: `false` disables the rule without deleting it.
28747
- * Defaults to `true` so operators creating a rule via the UI
28748
- * see it active immediately.
28749
- */
28750
- enabled: boolean().default(true)
28751
- });
28752
- array(ZoneRuleSchema).readonly();
28753
- /**
28754
28804
  * Script-runner cap. Models HA `script.*` entities on
28755
28805
  * `DeviceType.Script`. A Script is a pre-recorded action sequence
28756
28806
  * that can be invoked imperatively — optionally with a variables
@@ -34687,6 +34737,12 @@ Object.freeze({
34687
34737
  addonId: null,
34688
34738
  access: "create"
34689
34739
  },
34740
+ "pipelineAnalytics.runReplayFrameProcessor": {
34741
+ capName: "pipeline-analytics",
34742
+ capScope: "device",
34743
+ addonId: null,
34744
+ access: "create"
34745
+ },
34690
34746
  "pipelineAnalytics.saveRetrainAnnotations": {
34691
34747
  capName: "pipeline-analytics",
34692
34748
  capScope: "device",
@@ -34819,6 +34875,12 @@ Object.freeze({
34819
34875
  addonId: null,
34820
34876
  access: "view"
34821
34877
  },
34878
+ "pipelineExecutor.getInferenceDeviceHealth": {
34879
+ capName: "pipeline-executor",
34880
+ capScope: "system",
34881
+ addonId: null,
34882
+ access: "view"
34883
+ },
34822
34884
  "pipelineExecutor.getOrchestratorConfigSchema": {
34823
34885
  capName: "pipeline-executor",
34824
34886
  capScope: "system",
@@ -34891,6 +34953,12 @@ Object.freeze({
34891
34953
  addonId: null,
34892
34954
  access: "view"
34893
34955
  },
34956
+ "pipelineExecutor.rearmInferenceDevice": {
34957
+ capName: "pipeline-executor",
34958
+ capScope: "system",
34959
+ addonId: null,
34960
+ access: "create"
34961
+ },
34894
34962
  "pipelineExecutor.runAudioTest": {
34895
34963
  capName: "pipeline-executor",
34896
34964
  capScope: "system",
@@ -38139,6 +38207,11 @@ Object.freeze({
38139
38207
  form: "single",
38140
38208
  optional: false
38141
38209
  }],
38210
+ "pipelineAnalytics.runReplayFrameProcessor": [{
38211
+ name: "deviceId",
38212
+ form: "single",
38213
+ optional: false
38214
+ }],
38142
38215
  "pipelineAnalytics.saveRetrainAnnotations": [{
38143
38216
  name: "deviceId",
38144
38217
  form: "single",