@camstack/addon-provider-gree 0.2.28 → 0.2.29

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