@camstack/addon-provider-amcrest 0.2.30 → 0.2.31

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