@camstack/addon-provider-gree 0.2.28 → 0.2.29

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