@camstack/addon-provider-unifi 0.2.29 → 0.2.30

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