@camstack/addon-provider-dreo 0.2.29 → 0.2.30

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