@camstack/addon-provider-wyze 0.2.33 → 0.2.34

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