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