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