@camstack/addon-provider-rademacher 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
@@ -17334,1760 +17334,1996 @@ var OauthIntegrationDescriptorSchema = object({
17334
17334
  });
17335
17335
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
17336
17336
  /**
17337
- * pipeline-analytics device-scoped wrapper cap. Refines raw
17338
- * per-frame detections emitted by the pipeline runner into tracked
17339
- * objects, per-kind event collections (motion / object / audio), and
17340
- * persisted media. Owns the post-detection domain end-to-end:
17341
- *
17342
- * runner emits PipelineInferenceResult
17343
- * ↓ (event bus)
17344
- * pipeline-analytics subscriber
17345
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
17346
- * → three DB collections (one per kind), one FS media tree, one
17347
- * unified event emitter (FrameTracked + TrackStarted/Ended +
17348
- * DetectionEvent on bus)
17349
- *
17350
- * Pure subscriber model. No `processFrame` cap method — the runner
17351
- * already publishes the raw frame on the bus. The cap surface is
17352
- * only QUERIES + per-device settings, bound on/off via
17353
- * `device-manager.setWrapperActive`. `defaultActive: true` because
17354
- * every camera with a detection pipeline wants its raw detections
17355
- * refined; operators opt out per-device via BindingsTab when needed.
17356
- *
17357
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
17358
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
17337
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
17338
+ * within the frame, so the executor can re-cut a leaf child ROI at native
17339
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
17359
17340
  */
17360
- var TrackStateSchema = _enum([
17361
- "new",
17362
- "entered",
17363
- "left",
17364
- "moving",
17365
- "idle"
17366
- ]);
17367
- var EventKindSchema = _enum([
17368
- "motion",
17369
- "object",
17370
- "audio"
17371
- ]);
17341
+ var NativeCropRefSchema = object({
17342
+ /** Handle keying the retained native surface (node-pinned to its owner). */
17343
+ handle: FrameHandleSchema,
17344
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
17345
+ cropFrameSpace: object({
17346
+ x: number(),
17347
+ y: number(),
17348
+ w: number(),
17349
+ h: number()
17350
+ })
17351
+ });
17352
+ object({
17353
+ crop: object({
17354
+ left: number(),
17355
+ top: number(),
17356
+ width: number().positive(),
17357
+ height: number().positive()
17358
+ }).optional(),
17359
+ content: object({
17360
+ width: number().int().positive(),
17361
+ height: number().int().positive()
17362
+ }),
17363
+ fit: _enum(["stretch", "contain"]),
17364
+ format: _enum([
17365
+ "rgb",
17366
+ "gray",
17367
+ "jpeg"
17368
+ ])
17369
+ });
17372
17370
  /**
17373
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
17374
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
17375
- * of the camera frame (top-left origin), matching the drawing-plane editor.
17371
+ * Process-local frame identity. It is serializable so it can ride an in-process
17372
+ * capability call, but `registryId` deliberately prevents resolution in any
17373
+ * other process or execution group.
17376
17374
  */
17377
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
17378
- /** Closed icon vocabulary so clients render a known glyph per kind. */
17379
- var EventKindIconSchema = _enum([
17380
- "motion",
17381
- "audio",
17382
- "person",
17383
- "vehicle",
17384
- "animal",
17385
- "door",
17386
- "pir",
17387
- "smoke",
17388
- "water",
17389
- "button",
17390
- "package",
17391
- "generic"
17375
+ var FrameRefSchema = object({
17376
+ registryId: string().min(1),
17377
+ id: string().min(1),
17378
+ width: number().int().positive(),
17379
+ height: number().int().positive(),
17380
+ format: _enum(["rgb", "gray"]),
17381
+ timestamp: number(),
17382
+ capturedAt: number().optional()
17383
+ });
17384
+ var ModelFormatSchema$1 = _enum([
17385
+ "onnx",
17386
+ "coreml",
17387
+ "openvino",
17388
+ "tflite",
17389
+ "pt",
17390
+ "gguf"
17392
17391
  ]);
17393
- var EventKindCategorySchema = _enum([
17394
- "motion",
17395
- "audio",
17396
- "detection",
17397
- "sensor",
17398
- "control",
17399
- "custom",
17400
- "package"
17392
+ var PipelineSlotSchema = _enum([
17393
+ "detector",
17394
+ "cropper",
17395
+ "classifier",
17396
+ "refiner",
17397
+ "audio-classifier"
17401
17398
  ]);
17402
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
17403
- var EventKindLevelSchema = _enum(["macro", "sub"]);
17404
- var EventKindDescriptorSchema = object({
17405
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
17406
- kind: string(),
17407
- /** i18n key resolved on the UI side; `label` is the English fallback. */
17408
- labelKey: string(),
17409
- /** English fallback label (kept for clients that don't translate). */
17410
- label: string(),
17411
- /** Hex color for timeline/legend rendering. */
17412
- color: string(),
17413
- /** Dictionary id → lucide component on the UI side. */
17414
- iconId: string(),
17415
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
17416
- icon: EventKindIconSchema,
17417
- category: EventKindCategorySchema,
17418
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
17419
- parentKind: string().nullable(),
17420
- /** Derived from `parentKind`, explicit for the client tree. */
17421
- level: EventKindLevelSchema,
17422
- /** Which cap + device contributes this kind. For built-ins the camera
17423
- * itself; for sensor kinds the LINKED source device. */
17424
- source: object({
17425
- capName: string(),
17426
- deviceId: number()
17427
- })
17399
+ var PipelineEngineChoiceSchema = object({
17400
+ runtime: _enum(["node", "python"]),
17401
+ backend: string(),
17402
+ format: ModelFormatSchema$1,
17403
+ device: string().optional()
17428
17404
  });
17429
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
17430
- var EventKindsForDeviceSchema = object({
17431
- deviceId: number(),
17432
- kinds: array(EventKindDescriptorSchema).readonly()
17405
+ var AvailableEngineSchema = object({
17406
+ engine: PipelineEngineChoiceSchema,
17407
+ devices: array(object({
17408
+ id: string(),
17409
+ label: string(),
17410
+ description: string().optional()
17411
+ })).readonly(),
17412
+ defaultDevice: string()
17433
17413
  });
17434
- var SensorEventSchema = object({
17414
+ var PipelineDefaultStepSchema = lazy(() => object({
17415
+ addonId: string(),
17416
+ addonName: string(),
17417
+ slot: PipelineSlotSchema,
17418
+ inputClasses: array(string()).readonly(),
17419
+ outputClasses: array(string()).readonly(),
17420
+ enabled: boolean(),
17421
+ modelId: string(),
17422
+ children: array(PipelineDefaultStepSchema).readonly(),
17423
+ group: string().optional(),
17424
+ settings: record(string(), unknown()).optional()
17425
+ }));
17426
+ var PipelineTemplateStepSchema = lazy(() => object({
17427
+ addonId: string(),
17428
+ enabled: boolean(),
17429
+ modelId: string(),
17430
+ children: array(PipelineTemplateStepSchema).readonly(),
17431
+ settings: record(string(), unknown()).optional()
17432
+ }));
17433
+ var PipelineTemplateSchema$1 = object({
17435
17434
  id: string(),
17436
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
17437
- * yields N rows, one per camera). */
17438
- deviceId: number(),
17439
- /** The linked sensor device whose state changed. */
17440
- sourceDeviceId: number(),
17441
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
17442
- kind: string(),
17443
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
17444
- value: record(string(), unknown()).nullable(),
17445
- timestamp: number()
17435
+ name: string(),
17436
+ createdAt: string(),
17437
+ updatedAt: string(),
17438
+ engine: PipelineEngineChoiceSchema,
17439
+ steps: array(PipelineTemplateStepSchema).readonly()
17446
17440
  });
17447
- var TrackPositionSchema = object({
17448
- x: number(),
17449
- y: number(),
17450
- timestamp: number(),
17451
- bbox: BoundingBoxSchema
17441
+ var PipelineModelOptionSchema = object({
17442
+ id: string(),
17443
+ name: string(),
17444
+ formats: record(string(), object({
17445
+ downloaded: boolean(),
17446
+ sizeMB: number()
17447
+ })),
17448
+ group: ModelVariantGroupSchema.optional(),
17449
+ legacy: boolean().optional(),
17450
+ provider: ModelProviderIdSchema.optional()
17452
17451
  });
17453
- var TrackSnapshotSchema = object({
17454
- timestamp: number(),
17455
- position: TrackPositionSchema,
17456
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
17457
- mediaKey: string()
17452
+ var ConfigFieldBridge = custom();
17453
+ var PipelineAddonSchemaSchema = object({
17454
+ id: string(),
17455
+ name: string(),
17456
+ slot: PipelineSlotSchema,
17457
+ inputClasses: array(string()).readonly(),
17458
+ outputClasses: array(string()).readonly(),
17459
+ childSlots: array(PipelineSlotSchema).readonly(),
17460
+ models: array(PipelineModelOptionSchema).readonly(),
17461
+ defaultModelId: string(),
17462
+ defaultModelIdByFormat: record(string(), string()).optional(),
17463
+ enabledByDefault: boolean().optional(),
17464
+ backfillIntoExistingOverrides: boolean().optional(),
17465
+ defaultConfidence: number(),
17466
+ group: string().optional(),
17467
+ configSchema: array(ConfigFieldBridge).readonly().optional()
17458
17468
  });
17459
- /**
17460
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
17461
- * divided by the track's detection-frame dims), computed at persist time.
17462
- * Absent when the frame dims were unknown when the track was persisted
17463
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
17464
- */
17465
- var TrackEnvelopeSchema = object({
17466
- minX: number(),
17467
- minY: number(),
17468
- maxX: number(),
17469
- maxY: number()
17469
+ var PipelineSlotSchemaSchema = object({
17470
+ id: PipelineSlotSchema,
17471
+ label: string(),
17472
+ priority: number(),
17473
+ parentSlot: PipelineSlotSchema.nullable(),
17474
+ addons: array(PipelineAddonSchemaSchema).readonly()
17470
17475
  });
17471
- /**
17472
- * Row projection for track list queries. `full` (default) returns the
17473
- * complete Track including the frame-rate `positions[]` history and the
17474
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
17475
- * keeps every scalar the list surfaces actually render (ids, class(es),
17476
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
17477
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
17478
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
17479
- * `getTrack`. Mirrors the event-store `projection` convention
17480
- * (`getObjectEvents` et al.).
17481
- */
17482
- var TrackProjectionSchema = _enum(["full", "slim"]);
17483
- /**
17484
- * One audio-classification label heard on the track's camera while the
17485
- * track was alive, aggregated per label. An "episode" is one persisted
17486
- * audio event (the confident-classification path: score ≥ the device's
17487
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
17488
- * one 32 ms inference chunk, so counts stay human-scaled.
17489
- */
17490
- var TrackAudioLabelSchema = object({
17491
- label: string(),
17492
- /** Highest classification score observed across the label's episodes. */
17493
- peakScore: number(),
17494
- /** Number of coalesced audio-event episodes carrying this label. */
17495
- count: number(),
17496
- firstAt: number(),
17497
- lastAt: number()
17476
+ var PipelineSchemaSchema = object({
17477
+ availableEngines: array(AvailableEngineSchema).readonly(),
17478
+ selectedEngine: PipelineEngineChoiceSchema,
17479
+ slots: array(PipelineSlotSchemaSchema).readonly()
17498
17480
  });
17499
- /**
17500
- * How a track was produced. `pipeline` (default / absent) = the spatial
17501
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17502
- * no positions, a single snapshot, and no bbox trajectory at all:
17503
- *
17504
- * - `sensor` — a linked sensor/control device state change.
17505
- * - `audio` — an audio event on the camera itself that was anomalous for
17506
- * THAT camera, loud, and heard while nothing visual was happening (D62).
17507
- *
17508
- * The spatial subsystems (tracker association, occupancy count, re-id /
17509
- * embedding, resurrection) MUST skip every synthetic source. Test for that
17510
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17511
- * check silently readmits every source added after it was written.
17512
- */
17513
- var TrackSourceSchema = _enum([
17514
- "pipeline",
17515
- "sensor",
17516
- "audio"
17517
- ]);
17518
- /**
17519
- * Where a track sits in the RETRAIN lifecycle (D81).
17520
- *
17521
- * - `none` never marked, or un-marked. Evictable.
17522
- * - `staging`the operator wants this track as training material and has not
17523
- * finished with it. **This is the only state retention holds**: the track and
17524
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
17525
- * the device's age window.
17526
- * - `trained` — the retrain page has taken what it needed. The frames it chose
17527
- * were COPIED into the retrain dataset at selection time, so the dataset no
17528
- * longer depends on the track's media and the track becomes EVICTABLE again.
17529
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17530
- * a deliberate action of the retrain page, not a side effect of a checkbox.
17531
- *
17532
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17533
- * the store's filter language has only positive equality and `whereIn` — no
17534
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17535
- * would make the entire pre-column history immortal in one deploy.
17536
- */
17537
- var RetrainStatusSchema = _enum([
17538
- "none",
17539
- "staging",
17540
- "trained"
17541
- ]);
17542
- /**
17543
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
17544
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17545
- * so the two surfaces cannot drift.
17546
- *
17547
- * **Absent ≠ false.** A track that has never been touched omits the field; an
17548
- * explicitly un-flagged track carries `false`. Legacy rows written before the
17549
- * columns existed read as absent, and a consumer that needs a boolean should say
17550
- * `flag === true`, not `flag !== false`.
17551
- *
17552
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17553
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17554
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17555
- * `trained` track reports `false` while refusing both writes. The boolean is
17556
- * kept because three surfaces drive a toggle off it; anything that needs to tell
17557
- * "never marked" from "already trained" must read `retrainStatus`.
17558
- *
17559
- * `debug` does NOT pin; it is attention, not durability.
17560
- *
17561
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17562
- * A favourited track is skipped by retention the same way `staging` is, but
17563
- * it does not enter `none|staging|trained` and has no staging budget.
17564
- */
17565
- var TrackFlagFields = {
17566
- /** Operator marked this track as training material — i.e. `retrainStatus` is
17567
- * `'staging'`. */
17568
- markForTrain: boolean().optional(),
17569
- /** Operator marked this track for diagnostic attention. */
17570
- debug: boolean().optional(),
17571
- /** Operator favourited this track. Pins it against pruning. */
17572
- favourited: boolean().optional()
17573
- };
17574
- /**
17575
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17576
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17577
- * write patch, and the status is not something the toggle sets — it is what the
17578
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17579
- * always present on a persisted row (the column default materialises `'none'`).
17580
- */
17581
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17582
- /**
17583
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17584
- * one flag can never clear the other — the toggles are independent and are
17585
- * driven from three surfaces that do not know about each other.
17586
- */
17587
- var TrackFlagsPatchSchema = object(TrackFlagFields);
17588
- /**
17589
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
17590
- * collapses to `false`) so a caller can drive a toggle's checked state off the
17591
- * mutation result without a re-fetch.
17592
- */
17593
- var TrackFlagsSchema = object({
17594
- trackId: string(),
17595
- markForTrain: boolean(),
17596
- debug: boolean(),
17597
- favourited: boolean(),
17598
- /** The lifecycle state the boolean was derived from. Required here (unlike on
17599
- * a track row) because this shape is only ever produced by the write body,
17600
- * which always knows it — and a surface that has just written needs to render
17601
- * `trained` without a re-fetch. */
17602
- retrainStatus: RetrainStatusSchema
17481
+ var EngineProvisioningSchema = object({
17482
+ runtimeId: _enum([
17483
+ "onnx",
17484
+ "openvino",
17485
+ "coreml",
17486
+ "edgetpu"
17487
+ ]).nullable(),
17488
+ device: string().nullable(),
17489
+ state: _enum([
17490
+ "idle",
17491
+ "installing",
17492
+ "verifying",
17493
+ "ready",
17494
+ "failed"
17495
+ ]),
17496
+ progress: number().optional(),
17497
+ error: string().optional(),
17498
+ nextRetryAt: number().optional(),
17499
+ /**
17500
+ * Gate A (config-correctness gate at engine change): human-readable
17501
+ * config issues surfaced EAGERLY when the node's engine changes — model
17502
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
17503
+ * has a <format> build"). Additive/optional: informational only, never
17504
+ * enforced here `assertEngineReady` (readiness) still gates inference.
17505
+ * Absent/empty when the node-default tree resolves cleanly.
17506
+ */
17507
+ configIssues: array(string()).optional()
17603
17508
  });
17604
- union([literal(1), literal(2)]);
17605
- /**
17606
- * WHO decided a label, and when. Carried per tier so a value can be traced to
17607
- * the step and model that produced it — which is what makes the write rule
17608
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17609
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17610
- *
17611
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17612
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17613
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
17614
- * that value has no provenance, and the write rule lets ANY properly-attributed
17615
- * write of the same tier replace it regardless of score.
17616
- */
17617
- var LabelAttributionSchema = object({
17618
- stepId: string(),
17509
+ var PipelineStepInputSchema = lazy(() => object({
17510
+ addonId: string(),
17619
17511
  modelId: string().optional(),
17620
- decidedAt: number(),
17512
+ enabled: boolean().default(true),
17513
+ children: array(PipelineStepInputSchema).optional(),
17514
+ settings: record(string(), unknown()).optional(),
17515
+ jumpDeviceKey: string().optional()
17516
+ }));
17517
+ var ModelSubstitutionSchema = object({
17518
+ addonId: string(),
17519
+ chosen: string(),
17520
+ running: string(),
17521
+ format: string()
17522
+ });
17523
+ var PipelineValidationIssueSchema = object({
17524
+ addonId: string(),
17525
+ kind: _enum(["unknown-addon", "no-format-build"]),
17526
+ detail: string()
17527
+ });
17528
+ var PipelineValidationResultSchema = object({
17529
+ ok: boolean(),
17530
+ issues: array(PipelineValidationIssueSchema).readonly(),
17531
+ substitutions: array(ModelSubstitutionSchema).readonly(),
17532
+ /** The node's `currentEngine.format` this validation ran against. */
17533
+ format: string()
17534
+ });
17535
+ var ReferenceImageEntrySchema = object({
17536
+ filename: string(),
17537
+ stepIds: array(string()).readonly().optional()
17538
+ });
17539
+ var ReferenceImageBodySchema = object({
17540
+ base64: string(),
17541
+ filename: string()
17542
+ });
17543
+ var ReferenceAudioEntrySchema = object({
17544
+ filename: string(),
17545
+ sizeKb: number()
17546
+ });
17547
+ var ReferenceAudioBodySchema = object({ base64: string() });
17548
+ var AudioBackendSchema = object({
17549
+ id: string(),
17550
+ name: string(),
17551
+ description: string(),
17552
+ available: boolean(),
17621
17553
  /**
17622
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
17623
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17624
- *
17625
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
17626
- * notification rule authored on "Gianluca" stopped matching the moment the
17627
- * operator fixed the spelling in the gallery, and nothing said so. The id is
17628
- * the thing that does not move, so it is what a rule matches on
17629
- * (`NcConditions.identities`) and the text is what a human is shown.
17630
- *
17631
- * Absent when the label names no gallery row — a plate the OCR read but no
17632
- * vehicle claims, a sub-class, a species, any tier-1 value.
17554
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
17555
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
17556
+ * the benchmark UI to populate the `enabledMicroClasses` filter
17557
+ * specific to the selected backend without a separate fetch.
17633
17558
  */
17634
- identityId: string().optional()
17559
+ rawLabels: array(string()).readonly().optional()
17560
+ });
17561
+ var AudioCapabilitiesSchema = object({
17562
+ activeBackend: string(),
17563
+ availableBackends: array(AudioBackendSchema).readonly(),
17564
+ sampleRate: number(),
17565
+ chunkDurationMs: number()
17566
+ });
17567
+ var DownloadModelResultSchema = object({
17568
+ filePath: string(),
17569
+ sizeMB: number(),
17570
+ durationMs: number()
17635
17571
  });
17636
17572
  /**
17637
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17638
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17639
- * track and its events always answer the same question the same way.
17640
- *
17641
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
17642
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17643
- * is tier 2, and each carries its own score + attribution.
17644
- *
17645
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17646
- * finest thing known. Before 4g the single `label` column held the finest
17647
- * value, so a consumer that has not been updated reads the tier-1 slot and
17648
- * shows nothing on a species-only row; that is why the migration puts every
17649
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17650
- * and why the read surfaces were changed in the same train.
17651
- *
17652
- * **Writing it.** The slots are independent, which is the whole point: a
17653
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17654
- * migratorius`), so fineness cannot regress by construction. Within a tier the
17655
- * higher score wins. One rule, one implementation — see
17656
- * `pipeline/label-tier.ts` in addon-post-analysis.
17657
- */
17658
- var TieredLabelFields = {
17659
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
17660
- label: string().optional(),
17661
- /** Confidence of the tier-1 value, as reported by the deciding step. */
17662
- labelScore: number().optional(),
17663
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17664
- labelMeta: LabelAttributionSchema.optional(),
17665
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
17666
- subLabel: string().optional(),
17667
- /** Confidence of the tier-2 value, as reported by the deciding step. */
17668
- subLabelScore: number().optional(),
17669
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17670
- subLabelMeta: LabelAttributionSchema.optional()
17671
- };
17672
- /** Per-camera slice of a training-export estimate. */
17673
- var TrainingExportDeviceTotalsSchema = object({
17674
- deviceId: number(),
17675
- tracks: number().int(),
17676
- files: number().int(),
17677
- bytes: number().int()
17678
- });
17679
- /**
17680
- * What a training export WOULD contain. Computed from media index rows only —
17681
- * no blob is read to produce this.
17573
+ * Wrapper carrying a single test run's result. Replaces the legacy
17574
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
17575
+ * canonical `AudioResult` from the Phase 6 output rework: one
17576
+ * `AudioDetection` per class above `minScore`, top-N candidates in
17577
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
17578
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
17579
+ * benchmark UI can still report a clean failure when the classifier
17580
+ * cap isn't available.
17682
17581
  */
17683
- var TrainingExportSummarySchema = object({
17684
- generatedAt: number(),
17685
- trackCount: number().int(),
17686
- fileCount: number().int(),
17687
- byteCount: number().int(),
17688
- /** More marked tracks exist than a single pass carries. */
17689
- truncated: boolean(),
17690
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
17582
+ var AudioTestResultSchema = object({
17583
+ success: boolean(),
17584
+ error: string().optional(),
17585
+ frame: custom().optional()
17691
17586
  });
17692
- var TrackSchema = object({
17693
- trackId: string(),
17694
- deviceId: number(),
17695
- className: string(),
17696
- ...TieredLabelFields,
17697
- producingDeviceName: string().optional(),
17698
- /** Track provenance. Absent `pipeline` (legacy rows). */
17699
- source: TrackSourceSchema.optional(),
17700
- firstSeen: number(),
17701
- lastSeen: number(),
17702
- /** Frame-rate position history (subject to maxPositionHistory cap). */
17703
- positions: array(TrackPositionSchema).readonly(),
17704
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17705
- * saveThumbnails policy). */
17706
- snapshots: array(TrackSnapshotSchema).readonly(),
17707
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
17708
- zonesVisited: array(string()).readonly(),
17587
+ var PipelineConfigBridge = custom();
17588
+ var ConfigUISchemaBridge = custom();
17589
+ var ConfigUISchemaNullableBridge = custom();
17590
+ var InferenceCapabilitiesBridge = custom();
17591
+ var ModelAvailabilityListBridge = custom();
17592
+ var PipelineRunResultBridge = custom();
17593
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
17594
+ modelId: string(),
17595
+ settings: record(string(), unknown()).readonly()
17596
+ }))), method(object({ steps: record(string(), object({
17597
+ modelId: string(),
17598
+ settings: record(string(), unknown()).readonly()
17599
+ })) }), object({ success: literal(true) }), {
17600
+ kind: "mutation",
17601
+ auth: "admin"
17602
+ }), method(object({ nodeId: string() }), object({
17603
+ success: literal(true),
17604
+ clearedDevices: number()
17605
+ }), {
17606
+ kind: "mutation",
17607
+ auth: "admin"
17608
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
17609
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
17610
+ deviceKey: string(),
17709
17611
  /**
17710
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17711
- * `zones` capability.
17712
- *
17713
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17714
- * and no card can render — so every free-text search surface was structurally
17715
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17716
- * just returned nothing. Resolving here rather than in each client keeps ONE
17717
- * derivation and costs the clients no extra call (the `zones` cap is
17718
- * per-device, so a client-side resolve would be a per-camera fan-out on a
17719
- * surface built to avoid exactly that).
17720
- *
17721
- * Resolved, never invented: a zone deleted since the track was written has no
17722
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17723
- * two are not positionally aligned. Absent when the track visited no zone, or
17724
- * when the zone catalogue could not be read.
17612
+ * `failed` the per-device restart budget is exhausted; no pool
17613
+ * will be spawned until an operator re-arms it or the runner
17614
+ * respawns. `backoff` — under budget, waiting out the backoff (or
17615
+ * a cached pool observed dead and not yet condemned).
17725
17616
  */
17726
- zoneNames: array(string()).readonly().optional(),
17727
- /** Deduplicated set of detector classes observed for this track over its
17728
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
17729
- * legacy rows written before class accumulation shipped. */
17730
- classes: array(string()).readonly().optional(),
17731
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17732
- totalDistance: number(),
17733
- state: TrackStateSchema,
17734
- active: boolean(),
17735
- /** Deterministic key-event importance score in [0,1] (server-computed at
17736
- * track expiry, recomputed on late label). Absent on legacy rows written
17737
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
17738
- importance: number().optional(),
17739
- /** Id of the track's highest-confidence ObjectEvent (its representative
17740
- * "best" frame). Absent when the track produced no object events. */
17741
- bestEventId: string().optional(),
17742
- /** Tag of the importance sub-signal that dominated the score
17743
- * (identity|dwell|proximity|class|confidence|travel|zone). */
17744
- importanceReason: string().optional(),
17745
- /** Audio-classification labels heard on the camera during the track's
17746
- * life (score ≥ device `classificationMinScore`), aggregated per label.
17747
- * Absent on legacy rows / tracks with no confident audio. */
17748
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17749
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17750
- * Populated from the persisted envelope columns on historical reads;
17751
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17752
- envelope: TrackEnvelopeSchema.optional(),
17617
+ state: _enum(["failed", "backoff"]),
17618
+ /** Epoch ms of the death that produced this state. */
17619
+ since: number(),
17620
+ /** Pool deaths inside the current window. */
17621
+ deaths: number(),
17622
+ /** The last death's message. */
17623
+ lastError: string()
17624
+ })).readonly() })), method(object({
17625
+ nodeId: string(),
17626
+ deviceKey: string()
17627
+ }), object({ rearmed: boolean() }), {
17628
+ kind: "mutation",
17629
+ auth: "admin"
17630
+ }), 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({
17631
+ name: string(),
17632
+ steps: array(PipelineTemplateStepSchema).readonly(),
17633
+ engine: PipelineEngineChoiceSchema
17634
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
17635
+ id: string(),
17636
+ name: string().optional(),
17637
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
17638
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
17639
+ addonId: string(),
17640
+ modelId: string(),
17641
+ format: ModelFormatSchema$1
17642
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
17643
+ addonId: string(),
17644
+ modelId: string(),
17645
+ format: ModelFormatSchema$1
17646
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
17647
+ engine: PipelineEngineChoiceSchema.optional(),
17648
+ steps: array(PipelineStepInputSchema).min(1),
17649
+ frame: FrameInputSchema.optional(),
17753
17650
  /**
17754
- * A face DETECTOR found a face on this track — nothing more. It says the
17755
- * detail plane produced a `face` detail; it does NOT say the face was
17756
- * embedded, matched, above `minFacePx`, or that the recognizer was even
17757
- * enabled. Set once and never cleared.
17758
- *
17759
- * **This exists so "face present but not recognised" is expressible.** A
17760
- * recognised identity lands in `subLabel` (attributed to the face chain via
17761
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17762
- * and a track with no face at all were byte-identical on the wire and no
17763
- * surface could tell them apart. The read is `hasFace === true && subLabel
17764
- * === undefined`.
17765
- *
17766
- * **Absent ≠ false.** Every row written before the column existed omits it,
17767
- * and so does every server that predates the field — a consumer must test
17768
- * `=== true` and render nothing otherwise, never infer "no face".
17651
+ * Process-local lazy frame. Valid only when caller and provider resolve
17652
+ * in the same execution-group process; split/cross-node callers use
17653
+ * `frame`/`image` inline compatibility instead.
17769
17654
  */
17770
- hasFace: boolean().optional(),
17655
+ frameRef: FrameRefSchema.optional(),
17771
17656
  /**
17772
- * This track has a face row IN THE GALLERY: a crop **and** an embedding a
17773
- * face an operator could ASSIGN to an identity.
17774
- *
17775
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17776
- * because the two disagree. `hasFace` is stamped at the TOP of the face
17777
- * branch, before every gate, and means no more than "a face detector produced
17778
- * a face detail". This one is stamped at the single moment the gallery row
17779
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17780
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17781
- * candidate gate, the imageless-track drop (no crop was ever captured) and
17782
- * the crop-store drop. Everything between the detector and that insert can
17783
- * legitimately refuse the face, so a flag written any earlier promises the
17784
- * operator something to assign and delivers nothing.
17785
- *
17786
- * **Independent of recognition.** A face collected but never auto-matched is
17787
- * still assignable — it is in fact the face an operator most wants to reach —
17788
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17789
- * `subLabel`; this says only that the raw material exists.
17790
- *
17791
- * **Set once, never cleared.** A track that produced a gallery row produced
17792
- * one; deleting the row later is the gallery's business, not this flag's.
17793
- *
17794
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17795
- * before the column omits it, and so does every server that predates the
17796
- * field. A consumer must test `=== true` and render nothing otherwise —
17797
- * never infer "no assignable face".
17657
+ * CB5 shm passthrough a `FrameHandle` naming the same ring slot
17658
+ * the decoded pixels live in. One more member of the one-of
17659
+ * frame/frameHandle/image/imageBase64/referenceImage group.
17798
17660
  */
17799
- hasEmbeddedFace: boolean().optional(),
17661
+ frameHandle: FrameHandleSchema.optional(),
17662
+ imageBase64: string().optional(),
17800
17663
  /**
17801
- * This subject CONTAINS a folded rider a person the rider-pairing step
17802
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17803
- * so the passage is tracked once and as a VEHICLE.
17804
- *
17805
- * It exists because the fold's record was dishonest. D34 and the code both
17806
- * said "the person is not lost — it is reported so both entities stay on the
17807
- * record"; in fact the pair went into a per-processor RAM field behind an
17808
- * accessor nobody called, and every durable surface said `vehicle`, full
17809
- * stop. This is the composition note that makes the row true.
17810
- *
17811
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
17812
- * person" is not an answer to "what is this" — both label tiers would refuse
17813
- * a macro token anyway (D89), and correctly. Nothing here changes what the
17814
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17815
- * and a `person` rule still does not fire for someone cycling past.
17816
- *
17817
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17818
- * the column, and every hub that predates the field, omits it. Test
17819
- * `=== true` and render nothing otherwise — never infer "no rider".
17664
+ * Binary JPEG bytespreferred over `imageBase64` on internal
17665
+ * hops (hub forked worker via Moleculer MsgPack) because it
17666
+ * skips the 33% base64 overhead + the per-call base64 decode on
17667
+ * the detection-pipeline worker. Callers can pass either; exactly
17668
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
17820
17669
  */
17821
- hasRider: boolean().optional(),
17822
- ...TrackFlagFields,
17823
- ...TrackRetrainFields
17824
- });
17825
- var BaseEventFields = {
17826
- id: string(),
17827
- deviceId: number(),
17828
- timestamp: number()
17829
- };
17830
- var MotionEventSchema = object({
17831
- ...BaseEventFields,
17832
- kind: literal("motion"),
17833
- regionCount: number(),
17834
- /** Heavy JSON array omitted in slim projection. */
17835
- regions: array(object({
17836
- bbox: BoundingBoxSchema,
17837
- pixelCount: number(),
17838
- intensity: number()
17839
- })).readonly().optional(),
17840
- /** Omitted in slim projection. */
17841
- frameWidth: number().optional(),
17842
- /** Omitted in slim projection. */
17843
- frameHeight: number().optional(),
17844
- /** Populated by B5 (recording playback URL for this event). */
17845
- mediaUrl: string().optional()
17846
- });
17670
+ image: _instanceof(Uint8Array).optional(),
17671
+ referenceImage: string().optional(),
17672
+ deviceId: number().optional(),
17673
+ sessionId: string().optional(),
17674
+ /**
17675
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
17676
+ * reference-image, and detail-subtree calls. 'frame' is the live
17677
+ * per-frame dispatch: ONLY root-plane steps run; crop children
17678
+ * (inputClasses ≠ null) are skipped and served per-track via
17679
+ * pipelineRunner.runDetailSubtree (two-plane design).
17680
+ */
17681
+ plane: _enum(["full", "frame"]).optional(),
17682
+ /**
17683
+ * Inference-device selector (Phase 2 multi-device). Format
17684
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
17685
+ * Omitted ⇒ the runner's default device (current single-engine
17686
+ * behaviour). Selects WHICH device pool of the node runs the call.
17687
+ */
17688
+ deviceKey: string().optional(),
17689
+ /**
17690
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
17691
+ * when the parent crop was resolved from the frame's retained NATIVE
17692
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
17693
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
17694
+ * resolution from that surface — the SAME quality path faces already
17695
+ * had — instead of the downscaled parent tile. `handle` keys the native
17696
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
17697
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
17698
+ * the executor's crop-normalized child ROI back into frame-normalized
17699
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
17700
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
17701
+ * (today's behaviour on the fallback path).
17702
+ */
17703
+ nativeCropRef: NativeCropRefSchema.optional()
17704
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
17705
+ engine: PipelineEngineChoiceSchema.optional(),
17706
+ steps: array(PipelineStepInputSchema).min(1),
17707
+ frames: array(FrameInputSchema).min(1).max(255),
17708
+ deviceId: number().optional(),
17709
+ sessionId: string().optional(),
17710
+ /**
17711
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
17712
+ * the batch to the Python pool's bench preprocess cache
17713
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
17714
+ * preprocessed ONCE and every later inference is a pure-inference cache
17715
+ * hit — the sustained-throughput run measures inference, not
17716
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
17717
+ * full preprocess every call, correct). Fresh per sustained run;
17718
+ * released via `uncacheFrame`.
17719
+ */
17720
+ frameId: number().int().nonnegative().optional(),
17721
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
17722
+ deviceKey: string().optional()
17723
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
17724
+ data: _instanceof(Uint8Array),
17725
+ width: number().int().positive(),
17726
+ height: number().int().positive(),
17727
+ format: _enum([
17728
+ "rgb",
17729
+ "bgr",
17730
+ "gray"
17731
+ ])
17732
+ }), object({
17733
+ frameId: number(),
17734
+ width: number(),
17735
+ height: number()
17736
+ }), { kind: "mutation" }), method(object({
17737
+ stepId: string(),
17738
+ frameId: number().int()
17739
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
17740
+ batchMode: string(),
17741
+ windowMs: number(),
17742
+ maxBatchSize: number(),
17743
+ concurrency: number()
17744
+ })), method(_void(), array(object({
17745
+ engineKey: string(),
17746
+ engine: PipelineEngineChoiceSchema,
17747
+ modelsLoaded: array(string()).readonly(),
17748
+ inUseByCameras: array(number()).readonly(),
17749
+ /**
17750
+ * Origin of this resident factory.
17751
+ * - `runtime` — main camera-serving engine (no idle TTL).
17752
+ * - `warm-override` — benchmark/test override held in the warm
17753
+ * cache; auto-disposed after the idle TTL.
17754
+ * - `device-pool` — a concurrent per-device pool (Phase 2
17755
+ * multi-device, keyed by `deviceKey`) resolved
17756
+ * via `resolveDeviceFactory`. Runs alongside the
17757
+ * `runtime` engine on a DIFFERENT accelerator
17758
+ * (NPU / iGPU / Coral) — this is how the
17759
+ * Engines tab shows all pools running at once.
17760
+ */
17761
+ kind: _enum([
17762
+ "runtime",
17763
+ "warm-override",
17764
+ "device-pool"
17765
+ ]),
17766
+ /** Native pid of the underlying Python pool (null when no pool). */
17767
+ poolPid: number().nullable(),
17768
+ /** ms since this factory was last used (null when not warm-tracked). */
17769
+ idleMs: number().nullable(),
17770
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
17771
+ idleTtlMs: number().nullable()
17772
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
17773
+ kind: "mutation",
17774
+ auth: "admin"
17775
+ }), method(object({
17776
+ engine: PipelineEngineChoiceSchema,
17777
+ force: boolean().optional()
17778
+ }), object({
17779
+ success: boolean(),
17780
+ reason: string().optional()
17781
+ }), {
17782
+ kind: "mutation",
17783
+ auth: "admin"
17784
+ }), 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({
17785
+ addonId: string(),
17786
+ modelId: string(),
17787
+ filename: string().optional(),
17788
+ settings: record(string(), unknown()).optional()
17789
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
17847
17790
  /**
17848
- * Which detection SOURCE produced an object event. `pipeline` = the ML
17849
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
17850
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
17851
- * tracking, per-kind persistence) but stay distinguishable so consumers
17852
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17853
- * Absent on legacy rows treat as `pipeline`.
17791
+ * Per-stage gating mode applied to the zones a rule references.
17792
+ *
17793
+ * - `include`: the rule contributes to a **whitelist** for its stage.
17794
+ * When at least one `include` rule fires for a stage, only entities
17795
+ * inside one of those zones pass that stage.
17796
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
17797
+ * Entities inside one of those zones are dropped at that stage.
17798
+ *
17799
+ * `monitor`-style observation (count without filtering) is not a rule
17800
+ * mode — zones without any matching rule are observed naturally by
17801
+ * `zone-analytics` (live snapshot + history), so an "I just want to
17802
+ * count, not filter" use case needs no rule at all.
17854
17803
  */
17855
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17804
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
17856
17805
  /**
17857
- * The confirmed zone crossing that produced an object event. Present ONLY on
17858
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17859
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17860
- * appearance event carry none, so a rule asking for a direction fails closed
17861
- * on them.
17806
+ * Per-consumer rule that references existing zones (geometry) and
17807
+ * defines how a specific pipeline stage should treat them. Each
17808
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
17809
+ * settings:
17862
17810
  *
17863
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17864
- * into its own event, so a frame in which a track enters A while leaving B
17865
- * produces two events with two directions — never one ambiguous row.
17811
+ * - `addon-motion-wasm` `motionZoneRules: ZoneRule[]` (motion stage)
17812
+ * - `addon-detection-pipeline` `detectionZoneRules: ZoneRule[]` (detection stage)
17813
+ * - future: notification rules, audio gating, etc.
17866
17814
  *
17867
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17868
- * membership the box has NOW, and by definition it no longer contains the zone
17869
- * that was just left. Without the id here, a zone-scoped rule could never match
17870
- * the exit it asked for.
17815
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
17816
+ * express "ignore motion in ALL of {garden, street}" with a single
17817
+ * rule. `classFilter` narrows the rule to specific object classes
17818
+ * "drop person detections in the street, but keep cars" is one
17819
+ * `exclude` rule with `classFilter: ['person']`.
17820
+ *
17821
+ * `enabled` is a soft toggle — the operator can keep the rule
17822
+ * configured but inert without deleting it.
17871
17823
  */
17872
- var ZoneCrossingSchema = object({
17873
- direction: _enum(["enter", "exit"]),
17874
- /** Admin zone id crossed. */
17875
- zoneId: string(),
17876
- /** Zone display name at crossing time (falls back to the id). */
17877
- zoneName: string().optional()
17878
- });
17879
- var ObjectEventSchema = object({
17880
- ...BaseEventFields,
17881
- kind: literal("object"),
17882
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
17883
- source: DetectionSourceSchema.optional(),
17824
+ var ZoneRuleSchema = object({
17825
+ /** Stable rule id — survives edits, used by the UI for diffing. */
17826
+ id: string(),
17827
+ /** Optional human-readable label rendered in the rule editor. */
17828
+ name: string().optional(),
17829
+ /** Zones this rule targets. The rule's `mode` applies to ALL
17830
+ * listed zones (OR-set: a detection in any one of them counts).
17831
+ * At least one zone id required — a rule with no targets is a
17832
+ * configuration mistake and the form validator rejects it. */
17833
+ zoneIds: array(string()).min(1).readonly(),
17834
+ mode: ZoneRuleModeEnum,
17884
17835
  /**
17885
- * Inference-frame id shared by every object event emitted from the SAME frame
17886
- * the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
17887
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
17888
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
17889
- * Optional for backward-compat with pre-existing rows / the slim projection
17890
- * includes it (it is light). Absent on rows written before this field.
17836
+ * Class names this rule applies to. Empty / undefined rule
17837
+ * applies to every class. Class strings match the `macroClass`
17838
+ * field on detections (e.g. `person`, `car`, `dog`).
17891
17839
  */
17892
- frameId: string().optional(),
17893
- /** Omitted in slim projection. */
17894
- trackId: string().optional(),
17895
- className: string(),
17896
- ...TieredLabelFields,
17897
- /** Omitted in slim projection. */
17898
- confidence: number().optional(),
17899
- /** Heavy JSON — omitted in slim projection. */
17900
- bbox: BoundingBoxSchema.optional(),
17901
- /** Heavy JSON — omitted in slim projection. */
17902
- zones: array(string()).readonly().optional(),
17903
- /** Omitted in slim projection. */
17904
- state: TrackStateSchema.optional(),
17840
+ classFilter: array(string()).readonly().optional(),
17905
17841
  /**
17906
- * The zone crossing this event IS, when it is one. Absent on every other
17907
- * event kind (movement state, appearance, package) see
17908
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
17842
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
17843
+ * required to consider an entity "in the zone". Defaults to the
17844
+ * consumer's stage default when omitted. Kept for back-compat with
17845
+ * existing per-rule overrides; new operators pick the value via
17846
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
17847
+ * set, the lower-level engine reads it as a 0–1 fraction.
17909
17848
  */
17910
- zoneCrossing: ZoneCrossingSchema.optional(),
17911
- /** Detection-frame dimensions in pixels — let consumers normalize the
17912
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
17913
- frameWidth: number().optional(),
17914
- frameHeight: number().optional(),
17915
- /** MediaStore key for the crop attached to this event (if any). */
17916
- mediaKey: string().optional(),
17917
- /** Design B: MediaStore key of the track's native-resolution key frame (the
17918
- * best-detection full frame). Resolve via the event-media data-plane
17919
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
17920
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
17921
- * sources — consumers fall back to `mediaKey` (the tight crop). */
17922
- keyFrameMediaKey: string().optional(),
17923
- /** Populated by B5 (recording playback URL for this event). */
17924
- mediaUrl: string().optional(),
17925
- /** The parent track's key-event importance [0,1], propagated to every object
17926
- * event of the track (so an event row can be sorted by importance without a
17927
- * track join). Absent on legacy rows / before the track was scored. */
17928
- importance: number().optional()
17929
- });
17930
- var AudioEventSchema = object({
17931
- ...BaseEventFields,
17932
- kind: literal("audio"),
17933
- rms: number(),
17934
- dbfs: number(),
17935
- classification: object({
17936
- className: string(),
17937
- originalClass: string().optional(),
17938
- score: number()
17939
- }).optional(),
17940
- /** Populated by B5 (recording playback URL for this event). */
17941
- mediaUrl: string().optional()
17849
+ overlapThreshold: number().min(0).max(1).optional(),
17850
+ /**
17851
+ * Operator-friendly version of `overlapThreshold` the percentage
17852
+ * of the detection's bbox that must lie inside the zone for the
17853
+ * rule to match. Documented default is 85%; the engine substitutes
17854
+ * that when the field is omitted (kept optional so existing rules
17855
+ * stored without it stay valid).
17856
+ *
17857
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
17858
+ * rule, the engine prefers `bboxInclusionPct` because it's the
17859
+ * field exposed in the UI. Internally both feed the same gate.
17860
+ */
17861
+ bboxInclusionPct: number().min(0).max(100).optional(),
17862
+ /**
17863
+ * When `true` and a detection has a segmentation mask, use the
17864
+ * mask for overlap instead of the bbox. Detection-stage only;
17865
+ * motion rules ignore this field.
17866
+ */
17867
+ preferMask: boolean().optional(),
17868
+ /**
17869
+ * Soft-toggle: `false` disables the rule without deleting it.
17870
+ * Defaults to `true` so operators creating a rule via the UI
17871
+ * see it active immediately.
17872
+ */
17873
+ enabled: boolean().default(true)
17942
17874
  });
17943
- var MediaFileKindEnum = _enum([
17944
- "crop",
17945
- "thumbnail",
17946
- "snapshot",
17947
- "firstFrame",
17948
- "lastFrame",
17949
- "fullFrame",
17950
- "fullFrameBoxed",
17951
- "faceCrop",
17952
- "plateCrop",
17953
- "keyFrame",
17954
- "keyFrameSmall",
17955
- "thumbnailSmall"
17956
- ]);
17957
- var MediaFileSchema = object({
17958
- key: string(),
17959
- kind: MediaFileKindEnum,
17960
- base64: string(),
17961
- sizeBytes: number(),
17962
- timestamp: number()
17875
+ array(ZoneRuleSchema).readonly();
17876
+ /**
17877
+ * Zone — pure geometry + identity. NO filtering behaviour.
17878
+ *
17879
+ * Zones describe **where** in the frame the operator wants to flag
17880
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
17881
+ * each pipeline stage uses them. Splitting the two means a single
17882
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
17883
+ * a detection-include rule on `['car']`, and an occupancy aggregate
17884
+ * — without three duplicated polygons.
17885
+ *
17886
+ * Owned by the orchestrator addon (provider) and mirrored into the
17887
+ * `zones` device-state slice on every mutation. Consumers
17888
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
17889
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
17890
+ * mirror with `onChanged`).
17891
+ *
17892
+ * Coordinates are normalised fractions of the frame (0–1) so zones
17893
+ * survive resolution changes and stream profile switches.
17894
+ *
17895
+ * `kind` discriminates between full polygons (closed regions used
17896
+ * for intrusion / occupancy filters) and tripwires (open 2-point
17897
+ * line segments used for cross events). Onboard / firmware-reported
17898
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
17899
+ * task list.
17900
+ */
17901
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
17902
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
17903
+ var PolygonPointSchema = object({
17904
+ x: number(),
17905
+ y: number()
17906
+ });
17907
+ /** A camera detection zone — pure geometry/identity. */
17908
+ var ZoneSchema = object({
17909
+ id: string(),
17910
+ name: string(),
17911
+ kind: ZoneKindEnum.default("polygon"),
17912
+ /** Polygon vertices, fraction of frame (0–1). */
17913
+ polygon: array(PolygonPointSchema).readonly(),
17914
+ /** Visual color for UI rendering. */
17915
+ color: string().default("#3b82f6")
17963
17916
  });
17964
17917
  /**
17965
- * One media row WITHOUT its bytes.
17918
+ * Zones capability per-camera CRUD over polygon detection zones.
17966
17919
  *
17967
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17968
- * 140 s track), and a client that renders tiles from the media data plane needs
17969
- * to know only WHAT EXISTS the bytes then arrive per tile, lazily, over HTTP
17970
- * with an immutable cache, instead of all at once inside a tRPC response that
17971
- * blocks the whole view.
17920
+ * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
17921
+ * to per-device settings and mirrors into the `zones` device-state
17922
+ * slice on every mutation, so downstream consumers can subscribe via
17923
+ * `dev.state.zones.onChanged`.
17972
17924
  *
17973
- * `sizeBytes` is carried because it is what lets a client decide between the
17974
- * stored blob and a `?variant=thumb` rendering without fetching either.
17925
+ * The cap surface only handles geometry + identity; filtering
17926
+ * behaviour (per-class, include/exclude, threshold) lives in the
17927
+ * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
17928
+ * `capabilities/schemas/zone-rule.js`.
17975
17929
  */
17976
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17930
+ var zonesCapability = {
17931
+ name: "zones",
17932
+ scope: "device",
17933
+ mode: "singleton",
17934
+ deviceTypes: [DeviceType.Camera],
17935
+ methods: {
17936
+ listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
17937
+ addZone: method(object({
17938
+ deviceId: number(),
17939
+ zone: ZoneSchema
17940
+ }), _void(), {
17941
+ kind: "mutation",
17942
+ auth: "admin"
17943
+ }),
17944
+ removeZone: method(object({
17945
+ deviceId: number(),
17946
+ zoneId: string()
17947
+ }), _void(), {
17948
+ kind: "mutation",
17949
+ auth: "admin"
17950
+ }),
17951
+ updateZone: method(object({
17952
+ deviceId: number(),
17953
+ zone: ZoneSchema
17954
+ }), _void(), {
17955
+ kind: "mutation",
17956
+ auth: "admin"
17957
+ })
17958
+ },
17959
+ /**
17960
+ * Runtime-state slice — the live zone catalogue mirrored by the
17961
+ * orchestrator on every CRUD mutation. Consumers read via
17962
+ * `device.state.zones.value` / `.watch(...)` without round-tripping
17963
+ * the cap, and the codegen DeviceProxy auto-wires the reactive
17964
+ * handle. Slice shape is `{ zones: Zone[] }` so future extensions
17965
+ * (e.g. zone groupings) can sit alongside the polygon list.
17966
+ */
17967
+ runtimeState: object({ zones: array(ZoneSchema).readonly() }),
17968
+ /**
17969
+ * 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.
17970
+ *
17971
+ * See `RuntimeStateDurability`. Enforced by
17972
+ * `scripts/check-runtime-state-durability.ts`.
17973
+ */
17974
+ durability: "restored"
17975
+ };
17977
17976
  /**
17978
- * The MACRO tier of an annotation — a CLOSED set.
17977
+ * pipeline-analytics device-scoped wrapper cap. Refines raw
17978
+ * per-frame detections emitted by the pipeline runner into tracked
17979
+ * objects, per-kind event collections (motion / object / audio), and
17980
+ * persisted media. Owns the post-detection domain end-to-end:
17979
17981
  *
17980
- * This is what the exported detector predicts, so a typo here is a new class
17981
- * with one example in it. `label` and `subLabel` are open strings by contrast:
17982
- * the whole point of the page is teaching the model things it does not know
17983
- * yet, and constraining that vocabulary would make it useless.
17982
+ * runner emits PipelineInferenceResult
17983
+ * (event bus)
17984
+ * pipeline-analytics subscriber
17985
+ * SORT tracker + zone engine + state analyzer + event emitter
17986
+ * → three DB collections (one per kind), one FS media tree, one
17987
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
17988
+ * DetectionEvent on bus)
17984
17989
  *
17985
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
17986
- * `subLabel` is one of these values, in any casing, because once `person`
17987
- * exists in both tiers "every person box" stops being answerable without
17988
- * knowing every string anyone ever typed — and the damage is retroactive.
17990
+ * Pure subscriber model. No `processFrame` cap method the runner
17991
+ * already publishes the raw frame on the bus. The cap surface is
17992
+ * only QUERIES + per-device settings, bound on/off via
17993
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
17994
+ * every camera with a detection pipeline wants its raw detections
17995
+ * refined; operators opt out per-device via BindingsTab when needed.
17996
+ *
17997
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
17998
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
17989
17999
  */
17990
- var RetrainMacroClassSchema = _enum([
18000
+ var TrackStateSchema = _enum([
18001
+ "new",
18002
+ "entered",
18003
+ "left",
18004
+ "moving",
18005
+ "idle"
18006
+ ]);
18007
+ var EventKindSchema = _enum([
18008
+ "motion",
18009
+ "object",
18010
+ "audio"
18011
+ ]);
18012
+ /**
18013
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
18014
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
18015
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
18016
+ */
18017
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
18018
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
18019
+ var EventKindIconSchema = _enum([
18020
+ "motion",
18021
+ "audio",
17991
18022
  "person",
17992
18023
  "vehicle",
17993
18024
  "animal",
18025
+ "door",
18026
+ "pir",
18027
+ "smoke",
18028
+ "water",
18029
+ "button",
17994
18030
  "package",
17995
- "face",
17996
- "plate"
18031
+ "generic"
17997
18032
  ]);
17998
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17999
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
18000
- /** Did a human draw this box, or did the assist propose it? */
18001
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
18002
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
18003
- var RetrainBboxSchema = object({
18004
- x: number(),
18005
- y: number(),
18006
- w: number(),
18007
- h: number()
18033
+ var EventKindCategorySchema = _enum([
18034
+ "motion",
18035
+ "audio",
18036
+ "detection",
18037
+ "sensor",
18038
+ "control",
18039
+ "custom",
18040
+ "package"
18041
+ ]);
18042
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
18043
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
18044
+ var EventKindDescriptorSchema = object({
18045
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
18046
+ kind: string(),
18047
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
18048
+ labelKey: string(),
18049
+ /** English fallback label (kept for clients that don't translate). */
18050
+ label: string(),
18051
+ /** Hex color for timeline/legend rendering. */
18052
+ color: string(),
18053
+ /** Dictionary id → lucide component on the UI side. */
18054
+ iconId: string(),
18055
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
18056
+ icon: EventKindIconSchema,
18057
+ category: EventKindCategorySchema,
18058
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
18059
+ parentKind: string().nullable(),
18060
+ /** Derived from `parentKind`, explicit for the client tree. */
18061
+ level: EventKindLevelSchema,
18062
+ /** Which cap + device contributes this kind. For built-ins the camera
18063
+ * itself; for sensor kinds the LINKED source device. */
18064
+ source: object({
18065
+ capName: string(),
18066
+ deviceId: number()
18067
+ })
18008
18068
  });
18009
- /**
18010
- * One annotated subject.
18011
- *
18012
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
18013
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
18014
- * derived from it at export and never stored — storing them is how one feature
18015
- * space ends up holding two crops of the same subject (D52).
18016
- */
18017
- var RetrainAnnotationSchema = object({
18018
- id: string(),
18019
- trackId: string(),
18069
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
18070
+ var EventKindsForDeviceSchema = object({
18020
18071
  deviceId: number(),
18021
- /** The COPY in retrain storage — never the source track's media key. */
18022
- mediaKey: string(),
18023
- bbox: RetrainBboxSchema,
18024
- macroClass: RetrainMacroClassSchema,
18025
- label: string().optional(),
18026
- subLabel: string().optional(),
18027
- kind: RetrainAnnotationKindSchema,
18028
- source: RetrainAnnotationSourceSchema,
18029
- /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
18030
- assistModelId: string().optional(),
18031
- assistScore: number().optional(),
18032
- exportedInBatch: string().optional(),
18033
- createdAt: number()
18034
- });
18035
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
18036
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
18037
- id: true,
18038
- trackId: true,
18039
- deviceId: true,
18040
- mediaKey: true,
18041
- createdAt: true,
18042
- exportedInBatch: true
18072
+ kinds: array(EventKindDescriptorSchema).readonly()
18043
18073
  });
18044
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
18045
- var RetrainTrackSchema = object({
18046
- trackId: string(),
18074
+ var SensorEventSchema = object({
18075
+ id: string(),
18076
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
18077
+ * yields N rows, one per camera). */
18047
18078
  deviceId: number(),
18048
- className: string(),
18049
- label: string().optional(),
18050
- firstSeen: number(),
18051
- lastSeen: number(),
18052
- /** How many frames the dataset already holds from this track. */
18053
- frameCount: number().int(),
18054
- /** How many subjects have been annotated on those frames. `0` with
18055
- * `frameCount: 0` is exactly "staging, still to work". */
18056
- annotationCount: number().int()
18079
+ /** The linked sensor device whose state changed. */
18080
+ sourceDeviceId: number(),
18081
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
18082
+ kind: string(),
18083
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
18084
+ value: record(string(), unknown()).nullable(),
18085
+ timestamp: number()
18057
18086
  });
18058
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
18059
- var RetrainFrameCandidateSchema = object({
18060
- mediaKey: string(),
18061
- kind: MediaFileKindEnum,
18087
+ var TrackPositionSchema = object({
18088
+ x: number(),
18089
+ y: number(),
18062
18090
  timestamp: number(),
18063
- sizeBytes: number().int(),
18064
- /** A copy of this original already exists — selecting it is free and cannot
18065
- * fail, whatever became of the original. */
18066
- copied: boolean()
18067
- });
18068
- /** A frame the dataset OWNS: bytes copied at selection time. */
18069
- var RetrainFrameSchema = object({
18070
- frameId: string(),
18071
- deviceId: number(),
18072
- trackId: string(),
18073
- /** Provenance only. It may already point at nothing — that is expected. */
18074
- sourceMediaKey: string(),
18075
- sourceKind: MediaFileKindEnum,
18076
- sizeBytes: number().int(),
18077
- width: number().int(),
18078
- height: number().int(),
18079
- copiedAt: number()
18080
- });
18081
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
18082
- var RetrainCopyRefusalSchema = _enum([
18083
- "source-missing",
18084
- "unreadable-image",
18085
- "write-failed"
18086
- ]);
18087
- var RetrainFrameSelectionSchema = object({
18088
- copied: array(RetrainFrameSchema).readonly(),
18089
- refused: array(object({
18090
- sourceMediaKey: string(),
18091
- reason: RetrainCopyRefusalSchema
18092
- })).readonly()
18091
+ bbox: BoundingBoxSchema
18093
18092
  });
18094
- var RetrainFrameListSchema = object({
18095
- candidates: array(RetrainFrameCandidateSchema).readonly(),
18096
- copies: array(RetrainFrameSchema).readonly(),
18097
- /** What the page pre-selects the native key frame when one survives. */
18098
- autoPickMediaKey: string().optional()
18093
+ var TrackSnapshotSchema = object({
18094
+ timestamp: number(),
18095
+ position: TrackPositionSchema,
18096
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
18097
+ mediaKey: string()
18099
18098
  });
18100
- /** What the operator asked the assist to look for. */
18101
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
18102
- kind: literal("package"),
18103
- zone: RetrainBboxSchema.optional()
18104
- }), object({
18105
- kind: literal("objects"),
18106
- modelId: string(),
18107
- minScore: number().optional()
18108
- })]);
18109
18099
  /**
18110
- * The assist's answer a discriminated union, because "the model saw nothing"
18111
- * and "this node cannot run that model" lead to different next moves and a
18112
- * nullable result cannot tell them apart.
18100
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
18101
+ * divided by the track's detection-frame dims), computed at persist time.
18102
+ * Absent when the frame dims were unknown when the track was persisted
18103
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
18113
18104
  */
18114
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
18115
- kind: literal("proposed"),
18116
- modelId: string(),
18117
- stepId: string(),
18118
- minScore: number(),
18119
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
18120
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
18121
- /** Returned by the runner but removed by the threshold. */
18122
- belowThreshold: number().int()
18123
- }), object({
18124
- kind: literal("refused"),
18125
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
18126
- reason: string(),
18127
- detail: string().optional()
18128
- })]);
18129
- /** The outcome of a lifecycle move owned by the retrain page. */
18130
- var RetrainTransitionResultSchema = object({
18131
- trackId: string(),
18132
- /** Where the track ended up, whatever happened. */
18133
- retrainStatus: RetrainStatusSchema,
18134
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
18135
- changed: boolean(),
18136
- reason: _enum([
18137
- "unknown-track",
18138
- "no-frames-copied",
18139
- "not-staging",
18140
- "not-trained",
18141
- "unchanged"
18142
- ]).optional()
18143
- });
18144
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
18145
- var MAX_EVENT_QUERY_LIMIT = 5e3;
18146
- var DeviceEventQueryInput = object({
18147
- deviceId: number(),
18148
- since: number().optional(),
18149
- until: number().optional(),
18150
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
18151
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
18152
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
18153
- * exact behaviour. Callers may omit this field — the store defaults to
18154
- * `full` when not provided. */
18155
- projection: _enum(["full", "slim"]).optional()
18156
- });
18157
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
18158
- var RecentTracksQueryInput = object({
18159
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
18160
- deviceIds: array(number()),
18161
- /** Window lower bound on `lastSeen` (inclusive). */
18162
- since: number().optional(),
18163
- /** Window upper bound on `lastSeen` (inclusive). */
18164
- until: number().optional(),
18165
- /** Page size. Default 200, max 1000. */
18166
- limit: number().int().min(1).max(1e3).default(200),
18167
- /** Opaque continuation cursor from a previous page's `nextCursor`.
18168
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
18169
- cursor: string().optional(),
18170
- /** See {@link TrackProjectionSchema}. Default `full`. */
18171
- projection: TrackProjectionSchema.optional(),
18172
- /** Include stationary-promoted rows (parked objects). Default false: the
18173
- * feed lists passages; parking records live on the stationary registry. */
18174
- includeStationary: boolean().optional()
18175
- });
18176
- var RecentTracksPageSchema = object({
18177
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
18178
- tracks: array(TrackSchema).readonly(),
18179
- /** Cursor for the next page, or null when this page is the last. */
18180
- nextCursor: string().nullable()
18181
- });
18182
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
18183
- var LIST_GROUPS_MAX_LIMIT = 100;
18184
- var AnalyticsGroupRecordSchema = object({
18185
- id: string(),
18186
- deviceId: number().int(),
18187
- openedAt: number().int(),
18188
- closedAt: number().int(),
18189
- timestamp: number().int(),
18190
- memberCount: number().int(),
18191
- memberTrackIds: array(string()).readonly(),
18192
- className: string(),
18193
- classes: array(string()).readonly(),
18194
- /** Relative event-media path, or null when the group has no picture yet. */
18195
- mediaUrl: string().nullable(),
18196
- singleton: boolean()
18105
+ var TrackEnvelopeSchema = object({
18106
+ minX: number(),
18107
+ minY: number(),
18108
+ maxX: number(),
18109
+ maxY: number()
18197
18110
  });
18198
- var AnalyticsGroupMemberSchema = object({
18199
- trackId: string(),
18200
- deviceId: number().int(),
18201
- className: string(),
18202
- firstSeen: number().int(),
18203
- lastSeen: number().int(),
18204
- mediaUrl: string().nullable()
18205
- });
18206
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
18207
- var ListGroupsQueryInput = object({
18208
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
18209
- deviceIds: array(number()),
18210
- /** Window lower bound on `closedAt` (inclusive). */
18211
- since: number().optional(),
18212
- /** Window upper bound on `openedAt` (inclusive). */
18213
- until: number().optional(),
18214
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
18215
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
18216
- cursor: string().optional()
18217
- });
18218
- var ListGroupsPageSchema = object({
18219
- groups: array(AnalyticsGroupRecordSchema).readonly(),
18220
- nextCursor: string().nullable()
18221
- });
18222
- var KeyEventQueryInput = object({
18223
- deviceId: number(),
18224
- /** Window lower bound (track firstSeen ≥ since). */
18225
- since: number(),
18226
- /** Window upper bound (track firstSeen ≤ until). */
18227
- until: number(),
18228
- limit: number().int().min(1).max(200).default(50),
18229
- /** Drop tracks scoring below this importance. */
18230
- minImportance: number().min(0).max(1).optional(),
18231
- /** Restrict to a single class (e.g. 'person'). */
18232
- classFilter: string().optional()
18233
- });
18234
- var KeyEventSchema = object({
18235
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
18236
- id: string(),
18237
- trackId: string(),
18238
- /** Track start time (firstSeen). */
18239
- timestamp: number(),
18240
- className: string(),
18241
- ...TieredLabelFields,
18242
- importance: number(),
18243
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
18244
- bestEventId: string(),
18245
- /** Track lifetime in ms (lastSeen - firstSeen). */
18246
- windowMs: number().optional(),
18247
- ...TrackFlagFields,
18248
- ...TrackRetrainFields
18249
- });
18250
- object({
18251
- trackId: string(),
18252
- className: string(),
18253
- confidence: number(),
18254
- bbox: BoundingBoxSchema,
18255
- zones: array(string()).readonly(),
18256
- state: TrackStateSchema
18257
- });
18258
- var OverlayDetectionSchema = looseObject({
18259
- id: string(),
18260
- kind: _enum(["first-level", "detail"]),
18261
- macroClass: string(),
18262
- score: number(),
18263
- bbox: object({
18264
- x: number(),
18265
- y: number(),
18266
- width: number(),
18267
- height: number()
18268
- }),
18269
- labels: array(looseObject({
18270
- label: string(),
18271
- score: number()
18272
- })).readonly(),
18273
- parentId: string().optional()
18274
- });
18275
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
18276
- var SearchObjectEventsInput = object({
18277
- text: string(),
18278
- deviceId: number().optional(),
18279
- since: number().optional(),
18280
- until: number().optional(),
18281
- classFilter: string().optional(),
18282
- limit: number().default(50),
18283
- minScore: number().min(0).max(1).default(.2)
18284
- });
18285
- var TrackCascadeCountsSchema = object({
18286
- /** Persisted track roots deleted (authoritative). */
18287
- tracks: number().int(),
18288
- /** Object events removed with their tracks (best-effort; see note above). */
18289
- events: number().int(),
18290
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
18291
- media: number().int(),
18292
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
18293
- faces: number().int(),
18294
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
18295
- plates: number().int(),
18296
- /** Per-track CLIP search vectors removed (best-effort). */
18297
- embeddings: number().int(),
18298
- /** Group membership + group rows removed with their last member (best-effort). */
18299
- groups: number().int()
18300
- });
18301
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
18302
- var DiskReconcileCountsSchema = object({
18303
- mediaDropped: number().int(),
18304
- tracks: number().int(),
18305
- events: number().int()
18306
- });
18307
- /** Event-store footprint for one camera. */
18308
- var EventStoreDeviceFootprintSchema = object({
18309
- deviceId: number(),
18310
- /** Persisted event rows (motion + object + audio) for the camera. */
18311
- rows: number().int(),
18312
- /** Event-owned media bytes on disk for the camera. */
18313
- bytes: number().int()
18314
- });
18315
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
18316
- var EventStoreFootprintSchema = object({
18317
- totalRows: number().int(),
18318
- totalBytes: number().int(),
18319
- devices: array(EventStoreDeviceFootprintSchema).readonly()
18320
- });
18321
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
18322
- var EventPruneCountsSchema = object({
18323
- motion: number().int(),
18324
- object: number().int(),
18325
- audio: number().int()
18111
+ /**
18112
+ * Row projection for track list queries. `full` (default) returns the
18113
+ * complete Track including the frame-rate `positions[]` history and the
18114
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
18115
+ * keeps every scalar the list surfaces actually render (ids, class(es),
18116
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
18117
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
18118
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
18119
+ * `getTrack`. Mirrors the event-store `projection` convention
18120
+ * (`getObjectEvents` et al.).
18121
+ */
18122
+ var TrackProjectionSchema = _enum(["full", "slim"]);
18123
+ /**
18124
+ * One audio-classification label heard on the track's camera while the
18125
+ * track was alive, aggregated per label. An "episode" is one persisted
18126
+ * audio event (the confident-classification path: score ≥ the device's
18127
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
18128
+ * one 32 ms inference chunk, so counts stay human-scaled.
18129
+ */
18130
+ var TrackAudioLabelSchema = object({
18131
+ label: string(),
18132
+ /** Highest classification score observed across the label's episodes. */
18133
+ peakScore: number(),
18134
+ /** Number of coalesced audio-event episodes carrying this label. */
18135
+ count: number(),
18136
+ firstAt: number(),
18137
+ lastAt: number()
18326
18138
  });
18327
18139
  /**
18328
- * Re-embed stored tracks from their key frames.
18140
+ * How a track was produced. `pipeline` (default / absent) = the spatial
18141
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
18142
+ * no positions, a single snapshot, and no bbox trajectory at all:
18329
18143
  *
18330
- * The reason this is an operator-callable method and not a migration script:
18331
- * every knob that decides what a vector MEANS encoder model, crop margin,
18332
- * squaring is only changeable if the existing vectors can be regenerated.
18333
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
18334
- * symptom is a quality regression with no visible cause.
18144
+ * - `sensor` a linked sensor/control device state change.
18145
+ * - `audio` an audio event on the camera itself that was anomalous for
18146
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
18147
+ *
18148
+ * The spatial subsystems (tracker association, occupancy count, re-id /
18149
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
18150
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
18151
+ * check silently readmits every source added after it was written.
18335
18152
  */
18336
- var RebuildObjectEmbeddingsInput = object({
18337
- /** Restrict to one camera. Omit for the whole fleet. */
18338
- deviceId: number().optional(),
18339
- since: number().optional(),
18340
- until: number().optional(),
18341
- /** Stop after this many tracks; the result reports whether more remain. */
18342
- maxTracks: number().int().positive().optional(),
18343
- /**
18344
- * Run every embedding on THIS node instead of round-robining the fleet.
18345
- *
18346
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
18347
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
18348
- * calling it that would pin the rebuild REQUEST itself to that node — the
18349
- * rebuild orchestration lives on the hub, and only the per-track step runs
18350
- * remotely. This field is data; the per-track pin is applied inside.
18351
- *
18352
- * Absent ⇒ round-robin over every online node whose runner can serve the
18353
- * pinned model.
18354
- */
18355
- executeOnNodeId: string().optional(),
18356
- /**
18357
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
18358
- * run flat out.
18359
- *
18360
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
18361
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
18362
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
18363
- * force is logged at start and finish so a deliberately slow pass reads
18364
- * differently from a stalled one.
18365
- */
18366
- pacingMs: number().int().nonnegative().optional()
18367
- });
18153
+ var TrackSourceSchema = _enum([
18154
+ "pipeline",
18155
+ "sensor",
18156
+ "audio"
18157
+ ]);
18368
18158
  /**
18369
- * Result of emptying the CLIP index.
18159
+ * Where a track sits in the RETRAIN lifecycle (D81).
18370
18160
  *
18371
- * The clean slate before a policy change: a new crop margin or encoder model
18372
- * leaves two feature spaces in one index whose cosine scores are not
18373
- * comparable, so wiping and rebuilding is the only way to be sure every vector
18374
- * means the same thing.
18161
+ * - `none` never marked, or un-marked. Evictable.
18162
+ * - `staging` the operator wants this track as training material and has not
18163
+ * finished with it. **This is the only state retention holds**: the track and
18164
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
18165
+ * the device's age window.
18166
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
18167
+ * were COPIED into the retrain dataset at selection time, so the dataset no
18168
+ * longer depends on the track's media and the track becomes EVICTABLE again.
18169
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
18170
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
18171
+ *
18172
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
18173
+ * the store's filter language has only positive equality and `whereIn` — no
18174
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
18175
+ * would make the entire pre-column history immortal in one deploy.
18375
18176
  */
18376
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
18177
+ var RetrainStatusSchema = _enum([
18178
+ "none",
18179
+ "staging",
18180
+ "trained"
18181
+ ]);
18377
18182
  /**
18378
- * Acknowledgement that a rebuild STARTED.
18183
+ * Per-track OPERATOR flags set by hand from the admin UI or the viewer, never
18184
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
18185
+ * so the two surfaces cannot drift.
18379
18186
  *
18380
- * The pass costs ~1s per track 45 minutes for a 2,600-track fleet so it
18381
- * runs detached and this returns immediately. Waiting for it made the client
18382
- * time out while the work carried on server-side, which is the worst of both:
18383
- * no result and no way to know it was still going. Poll
18384
- * `getObjectEmbeddingRebuildStatus` for progress.
18187
+ * **Absent false.** A track that has never been touched omits the field; an
18188
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
18189
+ * columns existed read as absent, and a consumer that needs a boolean should say
18190
+ * `flag === true`, not `flag !== false`.
18191
+ *
18192
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
18193
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
18194
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
18195
+ * `trained` track reports `false` while refusing both writes. The boolean is
18196
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
18197
+ * "never marked" from "already trained" must read `retrainStatus`.
18198
+ *
18199
+ * `debug` does NOT pin; it is attention, not durability.
18200
+ *
18201
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
18202
+ * A favourited track is skipped by retention the same way `staging` is, but
18203
+ * it does not enter `none|staging|trained` and has no staging budget.
18385
18204
  */
18386
- var RebuildObjectEmbeddingsResultSchema = object({
18387
- started: boolean(),
18388
- /** True when a pass was already running; the new request is ignored. */
18389
- alreadyRunning: boolean()
18390
- });
18391
- var RebuildStatusSchema = object({
18392
- running: boolean(),
18393
- scanned: number(),
18394
- rebuilt: number(),
18395
- /** Tracks whose key frame is gone — nothing to re-embed from. */
18396
- missingKeyFrame: number(),
18397
- /** Tracks with no usable detection box. */
18398
- missingBbox: number(),
18399
- /**
18400
- * Tracks an executing node REFUSED rather than broke on an unreadable key
18401
- * frame, a step that threw. Separate from `failed` because the remedy is
18402
- * different, and because a whole camera silently contributing zero vectors
18403
- * is the shape of failure a rebuild must never hide.
18404
- */
18405
- notRunnable: number(),
18406
- /**
18407
- * The pass stopped because NO node could serve the pinned model.
18408
- *
18409
- * Distinct from `notRunnable` on purpose: that one says "this track was
18410
- * refused", this one says "the cluster cannot do this work at all" — every
18411
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
18412
- * pinned model for its engine format, or dropped out. The remedy is a model /
18413
- * engine change, not a per-camera one. Non-zero here always comes with
18414
- * `complete: false`.
18415
- */
18416
- noCapableNode: number(),
18417
- failed: number(),
18418
- /** Set once a pass ends: true only when EVERYTHING was covered. */
18419
- complete: boolean().nullable(),
18420
- startedAtMs: number().nullable(),
18421
- finishedAtMs: number().nullable(),
18422
- /** Present when the pass ended by throwing. */
18423
- error: string().nullable()
18424
- });
18425
- DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
18426
- deviceId: number(),
18427
- trackId: string()
18428
- }), TrackSchema.nullable()), method(object({
18429
- deviceId: number(),
18430
- since: number().optional(),
18431
- until: number().optional(),
18432
- limit: number().optional(),
18433
- /** Spatial filter — only tracks whose trajectory intersects the zone
18434
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
18435
- * envelope columns, then precisely tested per position. Tracks with
18436
- * an unknown envelope (no frame dims at persist time) always match. */
18437
- zone: TrackZoneFilterSchema.optional(),
18438
- /** See {@link TrackProjectionSchema}. Default `full` (backward
18439
- * compatible — omitting the field keeps today's exact behaviour). */
18440
- projection: TrackProjectionSchema.optional(),
18441
- /** Include stationary-promoted rows (parked objects handed to the
18442
- * stationary registry). Default false: the timeline lists passages,
18443
- * not parking records (operator decision, 2026-08-15). */
18444
- includeStationary: boolean().optional()
18445
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
18446
- deviceId: number(),
18447
- groupId: string().min(1)
18448
- }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
18449
- kind: "mutation",
18450
- auth: "admin"
18451
- }), 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({
18452
- deviceId: number(),
18453
- since: number().optional(),
18454
- until: number().optional(),
18455
- kinds: array(string()).optional(),
18456
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
18457
- }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
18458
- deviceId: number(),
18459
- since: number(),
18460
- until: number(),
18461
- bucketMs: number().int().positive()
18462
- }), array(object({
18463
- bucketStart: number(),
18464
- motion: number().int(),
18465
- object: number().int(),
18466
- audio: number().int()
18467
- })).readonly()), method(object({
18468
- deviceId: number(),
18469
- cutoffMs: number()
18470
- }), object({
18471
- motion: number().int(),
18472
- object: number().int(),
18473
- audio: number().int()
18474
- }), {
18475
- kind: "mutation",
18476
- auth: "admin"
18477
- }), method(object({
18478
- deviceId: number(),
18479
- cutoffMs: number()
18480
- }), TrackCascadeCountsSchema, {
18481
- kind: "mutation",
18482
- auth: "admin"
18483
- }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
18484
- kind: "mutation",
18485
- auth: "admin"
18486
- }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
18487
- kind: "mutation",
18488
- auth: "admin"
18489
- }), method(object({
18490
- deviceId: number(),
18491
- trackIds: array(string()).min(1)
18492
- }), object({
18493
- deleted: number().int(),
18494
- failed: array(string()).readonly()
18495
- }), {
18496
- kind: "mutation",
18497
- auth: "admin"
18498
- }), method(object({
18499
- /** Log/audit scope only — the trackId is globally unique on its own. */
18500
- deviceId: number(),
18205
+ var TrackFlagFields = {
18206
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
18207
+ * `'staging'`. */
18208
+ markForTrain: boolean().optional(),
18209
+ /** Operator marked this track for diagnostic attention. */
18210
+ debug: boolean().optional(),
18211
+ /** Operator favourited this track. Pins it against pruning. */
18212
+ favourited: boolean().optional()
18213
+ };
18214
+ /**
18215
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
18216
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
18217
+ * write patch, and the status is not something the toggle sets — it is what the
18218
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
18219
+ * always present on a persisted row (the column default materialises `'none'`).
18220
+ */
18221
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
18222
+ /**
18223
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
18224
+ * one flag can never clear the other — the toggles are independent and are
18225
+ * driven from three surfaces that do not know about each other.
18226
+ */
18227
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
18228
+ /**
18229
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
18230
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
18231
+ * mutation result without a re-fetch.
18232
+ */
18233
+ var TrackFlagsSchema = object({
18501
18234
  trackId: string(),
18502
- flags: TrackFlagsPatchSchema
18503
- }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
18504
- kind: "query",
18505
- auth: "admin"
18506
- }), method(object({
18507
- olderThanMs: number(),
18508
- reason: OpsLogReasonSchema.optional()
18509
- }), EventPruneCountsSchema, {
18510
- kind: "mutation",
18511
- auth: "admin"
18512
- }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
18513
- kind: "mutation",
18514
- auth: "admin"
18515
- }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
18516
- kind: "mutation",
18517
- auth: "admin"
18518
- }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
18519
- kind: "mutation",
18520
- auth: "admin"
18521
- }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
18522
- kind: "mutation",
18523
- auth: "admin"
18524
- }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
18525
- kind: "mutation",
18526
- auth: "admin"
18527
- }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18528
- kind: "mutation",
18529
- auth: "admin"
18530
- }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
18531
- kind: "mutation",
18532
- auth: "admin"
18533
- }), method(object({}), array(RelocateJobSchema).readonly(), {
18534
- kind: "query",
18535
- auth: "admin"
18536
- }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18537
- kind: "mutation",
18538
- auth: "admin"
18539
- }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
18540
- kind: "query",
18541
- auth: "admin"
18542
- }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
18543
- kind: "query",
18544
- auth: "admin"
18545
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18546
- kind: "query",
18547
- auth: "admin"
18548
- }), method(object({
18549
- /** Empty every camera that has staging tracks. A LIST, not a single
18550
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
18551
- * route it at one camera's owner, and "every camera" would stop being
18552
- * expressible at all. */
18553
- deviceIds: array(number()).optional(),
18554
- limit: number().int().min(1).max(500).optional()
18555
- }), array(RetrainTrackSchema).readonly(), {
18556
- kind: "query",
18557
- auth: "admin"
18558
- }), method(object({ trackId: string() }), RetrainFrameListSchema, {
18559
- kind: "query",
18560
- auth: "admin"
18561
- }), method(object({
18235
+ markForTrain: boolean(),
18236
+ debug: boolean(),
18237
+ favourited: boolean(),
18238
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
18239
+ * a track row) because this shape is only ever produced by the write body,
18240
+ * which always knows it — and a surface that has just written needs to render
18241
+ * `trained` without a re-fetch. */
18242
+ retrainStatus: RetrainStatusSchema
18243
+ });
18244
+ union([literal(1), literal(2)]);
18245
+ /**
18246
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
18247
+ * the step and model that produced it — which is what makes the write rule
18248
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
18249
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
18250
+ *
18251
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
18252
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
18253
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
18254
+ * that value has no provenance, and the write rule lets ANY properly-attributed
18255
+ * write of the same tier replace it regardless of score.
18256
+ */
18257
+ var LabelAttributionSchema = object({
18258
+ stepId: string(),
18259
+ modelId: string().optional(),
18260
+ decidedAt: number(),
18261
+ /**
18262
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
18263
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
18264
+ *
18265
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
18266
+ * notification rule authored on "Gianluca" stopped matching the moment the
18267
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
18268
+ * the thing that does not move, so it is what a rule matches on
18269
+ * (`NcConditions.identities`) and the text is what a human is shown.
18270
+ *
18271
+ * Absent when the label names no gallery row — a plate the OCR read but no
18272
+ * vehicle claims, a sub-class, a species, any tier-1 value.
18273
+ */
18274
+ identityId: string().optional()
18275
+ });
18276
+ /**
18277
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
18278
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
18279
+ * track and its events always answer the same question the same way.
18280
+ *
18281
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
18282
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
18283
+ * is tier 2, and each carries its own score + attribution.
18284
+ *
18285
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
18286
+ * finest thing known. Before 4g the single `label` column held the finest
18287
+ * value, so a consumer that has not been updated reads the tier-1 slot and
18288
+ * shows nothing on a species-only row; that is why the migration puts every
18289
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
18290
+ * and why the read surfaces were changed in the same train.
18291
+ *
18292
+ * **Writing it.** The slots are independent, which is the whole point: a
18293
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
18294
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
18295
+ * higher score wins. One rule, one implementation — see
18296
+ * `pipeline/label-tier.ts` in addon-post-analysis.
18297
+ */
18298
+ var TieredLabelFields = {
18299
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
18300
+ label: string().optional(),
18301
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
18302
+ labelScore: number().optional(),
18303
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
18304
+ labelMeta: LabelAttributionSchema.optional(),
18305
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
18306
+ subLabel: string().optional(),
18307
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
18308
+ subLabelScore: number().optional(),
18309
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
18310
+ subLabelMeta: LabelAttributionSchema.optional()
18311
+ };
18312
+ /** Per-camera slice of a training-export estimate. */
18313
+ var TrainingExportDeviceTotalsSchema = object({
18562
18314
  deviceId: number(),
18315
+ tracks: number().int(),
18316
+ files: number().int(),
18317
+ bytes: number().int()
18318
+ });
18319
+ /**
18320
+ * What a training export WOULD contain. Computed from media index rows only —
18321
+ * no blob is read to produce this.
18322
+ */
18323
+ var TrainingExportSummarySchema = object({
18324
+ generatedAt: number(),
18325
+ trackCount: number().int(),
18326
+ fileCount: number().int(),
18327
+ byteCount: number().int(),
18328
+ /** More marked tracks exist than a single pass carries. */
18329
+ truncated: boolean(),
18330
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
18331
+ });
18332
+ var TrackSchema = object({
18563
18333
  trackId: string(),
18564
- mediaKeys: array(string()).min(1)
18565
- }), RetrainFrameSelectionSchema, {
18566
- kind: "mutation",
18567
- auth: "admin"
18568
- }), method(object({
18569
18334
  deviceId: number(),
18570
- trackId: string(),
18571
- frameId: string()
18572
- }), object({
18573
- removed: boolean(),
18574
- removedAnnotations: number().int()
18575
- }), {
18576
- kind: "mutation",
18577
- auth: "admin"
18578
- }), method(object({ frameId: string() }), object({
18335
+ className: string(),
18336
+ ...TieredLabelFields,
18337
+ producingDeviceName: string().optional(),
18338
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
18339
+ source: TrackSourceSchema.optional(),
18340
+ firstSeen: number(),
18341
+ lastSeen: number(),
18342
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
18343
+ positions: array(TrackPositionSchema).readonly(),
18344
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
18345
+ * saveThumbnails policy). */
18346
+ snapshots: array(TrackSnapshotSchema).readonly(),
18347
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
18348
+ zonesVisited: array(string()).readonly(),
18349
+ /**
18350
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
18351
+ * `zones` capability.
18352
+ *
18353
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
18354
+ * and no card can render — so every free-text search surface was structurally
18355
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
18356
+ * just returned nothing. Resolving here rather than in each client keeps ONE
18357
+ * derivation and costs the clients no extra call (the `zones` cap is
18358
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
18359
+ * surface built to avoid exactly that).
18360
+ *
18361
+ * Resolved, never invented: a zone deleted since the track was written has no
18362
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
18363
+ * two are not positionally aligned. Absent when the track visited no zone, or
18364
+ * when the zone catalogue could not be read.
18365
+ */
18366
+ zoneNames: array(string()).readonly().optional(),
18367
+ /** Deduplicated set of detector classes observed for this track over its
18368
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
18369
+ * legacy rows written before class accumulation shipped. */
18370
+ classes: array(string()).readonly().optional(),
18371
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
18372
+ totalDistance: number(),
18373
+ state: TrackStateSchema,
18374
+ active: boolean(),
18375
+ /** Deterministic key-event importance score in [0,1] (server-computed at
18376
+ * track expiry, recomputed on late label). Absent on legacy rows written
18377
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
18378
+ importance: number().optional(),
18379
+ /** Id of the track's highest-confidence ObjectEvent (its representative
18380
+ * "best" frame). Absent when the track produced no object events. */
18381
+ bestEventId: string().optional(),
18382
+ /** Tag of the importance sub-signal that dominated the score
18383
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
18384
+ importanceReason: string().optional(),
18385
+ /** Audio-classification labels heard on the camera during the track's
18386
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
18387
+ * Absent on legacy rows / tracks with no confident audio. */
18388
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
18389
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
18390
+ * Populated from the persisted envelope columns on historical reads;
18391
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
18392
+ envelope: TrackEnvelopeSchema.optional(),
18393
+ /**
18394
+ * A face DETECTOR found a face on this track — nothing more. It says the
18395
+ * detail plane produced a `face` detail; it does NOT say the face was
18396
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
18397
+ * enabled. Set once and never cleared.
18398
+ *
18399
+ * **This exists so "face present but not recognised" is expressible.** A
18400
+ * recognised identity lands in `subLabel` (attributed to the face chain via
18401
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
18402
+ * and a track with no face at all were byte-identical on the wire and no
18403
+ * surface could tell them apart. The read is `hasFace === true && subLabel
18404
+ * === undefined`.
18405
+ *
18406
+ * **Absent ≠ false.** Every row written before the column existed omits it,
18407
+ * and so does every server that predates the field — a consumer must test
18408
+ * `=== true` and render nothing otherwise, never infer "no face".
18409
+ */
18410
+ hasFace: boolean().optional(),
18411
+ /**
18412
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
18413
+ * face an operator could ASSIGN to an identity.
18414
+ *
18415
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
18416
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
18417
+ * branch, before every gate, and means no more than "a face detector produced
18418
+ * a face detail". This one is stamped at the single moment the gallery row
18419
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
18420
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
18421
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
18422
+ * the crop-store drop. Everything between the detector and that insert can
18423
+ * legitimately refuse the face, so a flag written any earlier promises the
18424
+ * operator something to assign and delivers nothing.
18425
+ *
18426
+ * **Independent of recognition.** A face collected but never auto-matched is
18427
+ * still assignable — it is in fact the face an operator most wants to reach —
18428
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
18429
+ * `subLabel`; this says only that the raw material exists.
18430
+ *
18431
+ * **Set once, never cleared.** A track that produced a gallery row produced
18432
+ * one; deleting the row later is the gallery's business, not this flag's.
18433
+ *
18434
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
18435
+ * before the column omits it, and so does every server that predates the
18436
+ * field. A consumer must test `=== true` and render nothing otherwise —
18437
+ * never infer "no assignable face".
18438
+ */
18439
+ hasEmbeddedFace: boolean().optional(),
18440
+ /**
18441
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
18442
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
18443
+ * so the passage is tracked once and as a VEHICLE.
18444
+ *
18445
+ * It exists because the fold's record was dishonest. D34 and the code both
18446
+ * said "the person is not lost — it is reported so both entities stay on the
18447
+ * record"; in fact the pair went into a per-processor RAM field behind an
18448
+ * accessor nobody called, and every durable surface said `vehicle`, full
18449
+ * stop. This is the composition note that makes the row true.
18450
+ *
18451
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
18452
+ * person" is not an answer to "what is this" — both label tiers would refuse
18453
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
18454
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
18455
+ * and a `person` rule still does not fire for someone cycling past.
18456
+ *
18457
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
18458
+ * the column, and every hub that predates the field, omits it. Test
18459
+ * `=== true` and render nothing otherwise — never infer "no rider".
18460
+ */
18461
+ hasRider: boolean().optional(),
18462
+ ...TrackFlagFields,
18463
+ ...TrackRetrainFields
18464
+ });
18465
+ var BaseEventFields = {
18466
+ id: string(),
18467
+ deviceId: number(),
18468
+ timestamp: number()
18469
+ };
18470
+ var MotionEventSchema = object({
18471
+ ...BaseEventFields,
18472
+ kind: literal("motion"),
18473
+ regionCount: number(),
18474
+ /** Heavy JSON array — omitted in slim projection. */
18475
+ regions: array(object({
18476
+ bbox: BoundingBoxSchema,
18477
+ pixelCount: number(),
18478
+ intensity: number()
18479
+ })).readonly().optional(),
18480
+ /** Omitted in slim projection. */
18481
+ frameWidth: number().optional(),
18482
+ /** Omitted in slim projection. */
18483
+ frameHeight: number().optional(),
18484
+ /** Populated by B5 (recording playback URL for this event). */
18485
+ mediaUrl: string().optional()
18486
+ });
18487
+ /**
18488
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
18489
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
18490
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
18491
+ * tracking, per-kind persistence) but stay distinguishable so consumers
18492
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
18493
+ * Absent on legacy rows ⇒ treat as `pipeline`.
18494
+ */
18495
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
18496
+ /**
18497
+ * The confirmed zone crossing that produced an object event. Present ONLY on
18498
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
18499
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
18500
+ * appearance event carry none, so a rule asking for a direction fails closed
18501
+ * on them.
18502
+ *
18503
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
18504
+ * into its own event, so a frame in which a track enters A while leaving B
18505
+ * produces two events with two directions — never one ambiguous row.
18506
+ *
18507
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
18508
+ * membership the box has NOW, and by definition it no longer contains the zone
18509
+ * that was just left. Without the id here, a zone-scoped rule could never match
18510
+ * the exit it asked for.
18511
+ */
18512
+ var ZoneCrossingSchema = object({
18513
+ direction: _enum(["enter", "exit"]),
18514
+ /** Admin zone id crossed. */
18515
+ zoneId: string(),
18516
+ /** Zone display name at crossing time (falls back to the id). */
18517
+ zoneName: string().optional()
18518
+ });
18519
+ var ObjectEventSchema = object({
18520
+ ...BaseEventFields,
18521
+ kind: literal("object"),
18522
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
18523
+ source: DetectionSourceSchema.optional(),
18524
+ /**
18525
+ * Inference-frame id shared by every object event emitted from the SAME frame
18526
+ * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
18527
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
18528
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
18529
+ * Optional for backward-compat with pre-existing rows / the slim projection
18530
+ * includes it (it is light). Absent on rows written before this field.
18531
+ */
18532
+ frameId: string().optional(),
18533
+ /** Omitted in slim projection. */
18534
+ trackId: string().optional(),
18535
+ className: string(),
18536
+ ...TieredLabelFields,
18537
+ /** Omitted in slim projection. */
18538
+ confidence: number().optional(),
18539
+ /** Heavy JSON — omitted in slim projection. */
18540
+ bbox: BoundingBoxSchema.optional(),
18541
+ /** Heavy JSON — omitted in slim projection. */
18542
+ zones: array(string()).readonly().optional(),
18543
+ /** Omitted in slim projection. */
18544
+ state: TrackStateSchema.optional(),
18545
+ /**
18546
+ * The zone crossing this event IS, when it is one. Absent on every other
18547
+ * event kind (movement state, appearance, package) — see
18548
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
18549
+ */
18550
+ zoneCrossing: ZoneCrossingSchema.optional(),
18551
+ /** Detection-frame dimensions in pixels — let consumers normalize the
18552
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
18553
+ frameWidth: number().optional(),
18554
+ frameHeight: number().optional(),
18555
+ /** MediaStore key for the crop attached to this event (if any). */
18556
+ mediaKey: string().optional(),
18557
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
18558
+ * best-detection full frame). Resolve via the event-media data-plane
18559
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
18560
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
18561
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
18562
+ keyFrameMediaKey: string().optional(),
18563
+ /** Populated by B5 (recording playback URL for this event). */
18564
+ mediaUrl: string().optional(),
18565
+ /** The parent track's key-event importance [0,1], propagated to every object
18566
+ * event of the track (so an event row can be sorted by importance without a
18567
+ * track join). Absent on legacy rows / before the track was scored. */
18568
+ importance: number().optional()
18569
+ });
18570
+ var AudioEventSchema = object({
18571
+ ...BaseEventFields,
18572
+ kind: literal("audio"),
18573
+ rms: number(),
18574
+ dbfs: number(),
18575
+ classification: object({
18576
+ className: string(),
18577
+ originalClass: string().optional(),
18578
+ score: number()
18579
+ }).optional(),
18580
+ /** Populated by B5 (recording playback URL for this event). */
18581
+ mediaUrl: string().optional()
18582
+ });
18583
+ var MediaFileKindEnum = _enum([
18584
+ "crop",
18585
+ "thumbnail",
18586
+ "snapshot",
18587
+ "firstFrame",
18588
+ "lastFrame",
18589
+ "fullFrame",
18590
+ "fullFrameBoxed",
18591
+ "faceCrop",
18592
+ "plateCrop",
18593
+ "keyFrame",
18594
+ "keyFrameSmall",
18595
+ "thumbnailSmall"
18596
+ ]);
18597
+ var MediaFileSchema = object({
18598
+ key: string(),
18599
+ kind: MediaFileKindEnum,
18579
18600
  base64: string(),
18580
- width: number().int(),
18581
- height: number().int()
18582
- }), {
18583
- kind: "query",
18584
- auth: "admin"
18585
- }), method(object({
18586
- deviceId: number(),
18587
- trackId: string(),
18588
- frameId: string(),
18589
- subject: RetrainAssistSubjectSchema,
18590
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
18591
- nodeId: string().optional()
18592
- }), RetrainAssistResultSchema, {
18593
- kind: "mutation",
18594
- auth: "admin"
18595
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
18596
- kind: "query",
18597
- auth: "admin"
18598
- }), method(object({
18599
- deviceId: number(),
18601
+ sizeBytes: number(),
18602
+ timestamp: number()
18603
+ });
18604
+ /**
18605
+ * One media row WITHOUT its bytes.
18606
+ *
18607
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
18608
+ * 140 s track), and a client that renders tiles from the media data plane needs
18609
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
18610
+ * with an immutable cache, instead of all at once inside a tRPC response that
18611
+ * blocks the whole view.
18612
+ *
18613
+ * `sizeBytes` is carried because it is what lets a client decide between the
18614
+ * stored blob and a `?variant=thumb` rendering without fetching either.
18615
+ */
18616
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
18617
+ /**
18618
+ * The MACRO tier of an annotation — a CLOSED set.
18619
+ *
18620
+ * This is what the exported detector predicts, so a typo here is a new class
18621
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
18622
+ * the whole point of the page is teaching the model things it does not know
18623
+ * yet, and constraining that vocabulary would make it useless.
18624
+ *
18625
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
18626
+ * `subLabel` is one of these values, in any casing, because once `person`
18627
+ * exists in both tiers "every person box" stops being answerable without
18628
+ * knowing every string anyone ever typed — and the damage is retroactive.
18629
+ */
18630
+ var RetrainMacroClassSchema = _enum([
18631
+ "person",
18632
+ "vehicle",
18633
+ "animal",
18634
+ "package",
18635
+ "face",
18636
+ "plate"
18637
+ ]);
18638
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
18639
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
18640
+ /** Did a human draw this box, or did the assist propose it? */
18641
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
18642
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
18643
+ var RetrainBboxSchema = object({
18644
+ x: number(),
18645
+ y: number(),
18646
+ w: number(),
18647
+ h: number()
18648
+ });
18649
+ /**
18650
+ * One annotated subject.
18651
+ *
18652
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
18653
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
18654
+ * derived from it at export and never stored — storing them is how one feature
18655
+ * space ends up holding two crops of the same subject (D52).
18656
+ */
18657
+ var RetrainAnnotationSchema = object({
18658
+ id: string(),
18600
18659
  trackId: string(),
18601
- frameId: string(),
18602
- annotations: array(RetrainAnnotationDraftSchema)
18603
- }), array(RetrainAnnotationSchema).readonly(), {
18604
- kind: "mutation",
18605
- auth: "admin"
18606
- }), method(object({
18607
- deviceId: number(),
18608
- trackId: string()
18609
- }), RetrainTransitionResultSchema, {
18610
- kind: "mutation",
18611
- auth: "admin"
18612
- }), method(object({
18613
18660
  deviceId: number(),
18614
- trackId: string()
18615
- }), RetrainTransitionResultSchema, {
18616
- kind: "mutation",
18617
- auth: "admin"
18618
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18619
- kind: "query",
18620
- auth: "admin"
18621
- }), method(object({
18622
- eventId: string(),
18623
- kind: MediaFileKindEnum.optional(),
18624
- deviceId: number()
18625
- }), array(MediaFileSchema).readonly()), method(object({
18626
- trackId: string(),
18627
- kinds: array(MediaFileKindEnum).optional(),
18628
- deviceId: number()
18629
- }), array(MediaFileSchema).readonly()), method(object({
18661
+ /** The COPY in retrain storage — never the source track's media key. */
18662
+ mediaKey: string(),
18663
+ bbox: RetrainBboxSchema,
18664
+ macroClass: RetrainMacroClassSchema,
18665
+ label: string().optional(),
18666
+ subLabel: string().optional(),
18667
+ kind: RetrainAnnotationKindSchema,
18668
+ source: RetrainAnnotationSourceSchema,
18669
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
18670
+ assistModelId: string().optional(),
18671
+ assistScore: number().optional(),
18672
+ exportedInBatch: string().optional(),
18673
+ createdAt: number()
18674
+ });
18675
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
18676
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
18677
+ id: true,
18678
+ trackId: true,
18679
+ deviceId: true,
18680
+ mediaKey: true,
18681
+ createdAt: true,
18682
+ exportedInBatch: true
18683
+ });
18684
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
18685
+ var RetrainTrackSchema = object({
18630
18686
  trackId: string(),
18631
- deviceId: number()
18632
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18633
- kind: "mutation",
18634
- auth: "admin"
18635
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18636
- kind: "mutation",
18637
- auth: "admin"
18638
- }), method(object({}), RebuildStatusSchema), object({
18639
18687
  deviceId: number(),
18688
+ className: string(),
18689
+ label: string().optional(),
18690
+ firstSeen: number(),
18691
+ lastSeen: number(),
18692
+ /** How many frames the dataset already holds from this track. */
18693
+ frameCount: number().int(),
18694
+ /** How many subjects have been annotated on those frames. `0` with
18695
+ * `frameCount: 0` is exactly "staging, still to work". */
18696
+ annotationCount: number().int()
18697
+ });
18698
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
18699
+ var RetrainFrameCandidateSchema = object({
18700
+ mediaKey: string(),
18701
+ kind: MediaFileKindEnum,
18640
18702
  timestamp: number(),
18641
- frameWidth: number(),
18642
- frameHeight: number(),
18643
- detections: array(OverlayDetectionSchema).readonly()
18644
- }), object({
18645
- deviceId: number(),
18646
- trackId: string(),
18647
- className: string()
18648
- }), object({
18703
+ sizeBytes: number().int(),
18704
+ /** A copy of this original already exists — selecting it is free and cannot
18705
+ * fail, whatever became of the original. */
18706
+ copied: boolean()
18707
+ });
18708
+ /** A frame the dataset OWNS: bytes copied at selection time. */
18709
+ var RetrainFrameSchema = object({
18710
+ frameId: string(),
18649
18711
  deviceId: number(),
18650
18712
  trackId: string(),
18651
- className: string(),
18652
- durationMs: number()
18653
- }), object({
18654
- deviceId: number(),
18655
- kind: EventKindSchema,
18656
- eventId: string(),
18657
- timestamp: number()
18713
+ /** Provenance only. It may already point at nothing — that is expected. */
18714
+ sourceMediaKey: string(),
18715
+ sourceKind: MediaFileKindEnum,
18716
+ sizeBytes: number().int(),
18717
+ width: number().int(),
18718
+ height: number().int(),
18719
+ copiedAt: number()
18658
18720
  });
18659
- /**
18660
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
18661
- * within the frame, so the executor can re-cut a leaf child ROI at native
18662
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
18663
- */
18664
- var NativeCropRefSchema = object({
18665
- /** Handle keying the retained native surface (node-pinned to its owner). */
18666
- handle: FrameHandleSchema,
18667
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
18668
- cropFrameSpace: object({
18669
- x: number(),
18670
- y: number(),
18671
- w: number(),
18672
- h: number()
18673
- })
18721
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
18722
+ var RetrainCopyRefusalSchema = _enum([
18723
+ "source-missing",
18724
+ "unreadable-image",
18725
+ "write-failed"
18726
+ ]);
18727
+ var RetrainFrameSelectionSchema = object({
18728
+ copied: array(RetrainFrameSchema).readonly(),
18729
+ refused: array(object({
18730
+ sourceMediaKey: string(),
18731
+ reason: RetrainCopyRefusalSchema
18732
+ })).readonly()
18674
18733
  });
18675
- object({
18676
- crop: object({
18677
- left: number(),
18678
- top: number(),
18679
- width: number().positive(),
18680
- height: number().positive()
18681
- }).optional(),
18682
- content: object({
18683
- width: number().int().positive(),
18684
- height: number().int().positive()
18685
- }),
18686
- fit: _enum(["stretch", "contain"]),
18687
- format: _enum([
18688
- "rgb",
18689
- "gray",
18690
- "jpeg"
18691
- ])
18734
+ var RetrainFrameListSchema = object({
18735
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
18736
+ copies: array(RetrainFrameSchema).readonly(),
18737
+ /** What the page pre-selects — the native key frame when one survives. */
18738
+ autoPickMediaKey: string().optional()
18692
18739
  });
18740
+ /** What the operator asked the assist to look for. */
18741
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
18742
+ kind: literal("package"),
18743
+ zone: RetrainBboxSchema.optional()
18744
+ }), object({
18745
+ kind: literal("objects"),
18746
+ modelId: string(),
18747
+ minScore: number().optional()
18748
+ })]);
18693
18749
  /**
18694
- * Process-local frame identity. It is serializable so it can ride an in-process
18695
- * capability call, but `registryId` deliberately prevents resolution in any
18696
- * other process or execution group.
18750
+ * The assist's answer a discriminated union, because "the model saw nothing"
18751
+ * and "this node cannot run that model" lead to different next moves and a
18752
+ * nullable result cannot tell them apart.
18697
18753
  */
18698
- var FrameRefSchema = object({
18699
- registryId: string().min(1),
18700
- id: string().min(1),
18701
- width: number().int().positive(),
18702
- height: number().int().positive(),
18703
- format: _enum(["rgb", "gray"]),
18704
- timestamp: number(),
18705
- capturedAt: number().optional()
18754
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
18755
+ kind: literal("proposed"),
18756
+ modelId: string(),
18757
+ stepId: string(),
18758
+ minScore: number(),
18759
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
18760
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
18761
+ /** Returned by the runner but removed by the threshold. */
18762
+ belowThreshold: number().int()
18763
+ }), object({
18764
+ kind: literal("refused"),
18765
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
18766
+ reason: string(),
18767
+ detail: string().optional()
18768
+ })]);
18769
+ /** The outcome of a lifecycle move owned by the retrain page. */
18770
+ var RetrainTransitionResultSchema = object({
18771
+ trackId: string(),
18772
+ /** Where the track ended up, whatever happened. */
18773
+ retrainStatus: RetrainStatusSchema,
18774
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
18775
+ changed: boolean(),
18776
+ reason: _enum([
18777
+ "unknown-track",
18778
+ "no-frames-copied",
18779
+ "not-staging",
18780
+ "not-trained",
18781
+ "unchanged"
18782
+ ]).optional()
18706
18783
  });
18707
- var ModelFormatSchema$1 = _enum([
18708
- "onnx",
18709
- "coreml",
18710
- "openvino",
18711
- "tflite",
18712
- "pt",
18713
- "gguf"
18714
- ]);
18715
- var PipelineSlotSchema = _enum([
18716
- "detector",
18717
- "cropper",
18718
- "classifier",
18719
- "refiner",
18720
- "audio-classifier"
18721
- ]);
18722
- var PipelineEngineChoiceSchema = object({
18723
- runtime: _enum(["node", "python"]),
18724
- backend: string(),
18725
- format: ModelFormatSchema$1,
18726
- device: string().optional()
18784
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
18785
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
18786
+ var DeviceEventQueryInput = object({
18787
+ deviceId: number(),
18788
+ since: number().optional(),
18789
+ until: number().optional(),
18790
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
18791
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
18792
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
18793
+ * exact behaviour. Callers may omit this field — the store defaults to
18794
+ * `full` when not provided. */
18795
+ projection: _enum(["full", "slim"]).optional()
18727
18796
  });
18728
- var AvailableEngineSchema = object({
18729
- engine: PipelineEngineChoiceSchema,
18730
- devices: array(object({
18731
- id: string(),
18732
- label: string(),
18733
- description: string().optional()
18734
- })).readonly(),
18735
- defaultDevice: string()
18797
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
18798
+ var RecentTracksQueryInput = object({
18799
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
18800
+ deviceIds: array(number()),
18801
+ /** Window lower bound on `lastSeen` (inclusive). */
18802
+ since: number().optional(),
18803
+ /** Window upper bound on `lastSeen` (inclusive). */
18804
+ until: number().optional(),
18805
+ /** Page size. Default 200, max 1000. */
18806
+ limit: number().int().min(1).max(1e3).default(200),
18807
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
18808
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
18809
+ cursor: string().optional(),
18810
+ /** See {@link TrackProjectionSchema}. Default `full`. */
18811
+ projection: TrackProjectionSchema.optional(),
18812
+ /** Include stationary-promoted rows (parked objects). Default false: the
18813
+ * feed lists passages; parking records live on the stationary registry. */
18814
+ includeStationary: boolean().optional()
18736
18815
  });
18737
- var PipelineDefaultStepSchema = lazy(() => object({
18738
- addonId: string(),
18739
- addonName: string(),
18740
- slot: PipelineSlotSchema,
18741
- inputClasses: array(string()).readonly(),
18742
- outputClasses: array(string()).readonly(),
18743
- enabled: boolean(),
18744
- modelId: string(),
18745
- children: array(PipelineDefaultStepSchema).readonly(),
18746
- group: string().optional(),
18747
- settings: record(string(), unknown()).optional()
18748
- }));
18749
- var PipelineTemplateStepSchema = lazy(() => object({
18750
- addonId: string(),
18751
- enabled: boolean(),
18752
- modelId: string(),
18753
- children: array(PipelineTemplateStepSchema).readonly(),
18754
- settings: record(string(), unknown()).optional()
18755
- }));
18756
- var PipelineTemplateSchema$1 = object({
18757
- id: string(),
18758
- name: string(),
18759
- createdAt: string(),
18760
- updatedAt: string(),
18761
- engine: PipelineEngineChoiceSchema,
18762
- steps: array(PipelineTemplateStepSchema).readonly()
18816
+ var RecentTracksPageSchema = object({
18817
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
18818
+ tracks: array(TrackSchema).readonly(),
18819
+ /** Cursor for the next page, or null when this page is the last. */
18820
+ nextCursor: string().nullable()
18763
18821
  });
18764
- var PipelineModelOptionSchema = object({
18822
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
18823
+ var LIST_GROUPS_MAX_LIMIT = 100;
18824
+ var AnalyticsGroupRecordSchema = object({
18765
18825
  id: string(),
18766
- name: string(),
18767
- formats: record(string(), object({
18768
- downloaded: boolean(),
18769
- sizeMB: number()
18770
- })),
18771
- group: ModelVariantGroupSchema.optional(),
18772
- legacy: boolean().optional(),
18773
- provider: ModelProviderIdSchema.optional()
18826
+ deviceId: number().int(),
18827
+ openedAt: number().int(),
18828
+ closedAt: number().int(),
18829
+ timestamp: number().int(),
18830
+ memberCount: number().int(),
18831
+ memberTrackIds: array(string()).readonly(),
18832
+ className: string(),
18833
+ classes: array(string()).readonly(),
18834
+ /** Relative event-media path, or null when the group has no picture yet. */
18835
+ mediaUrl: string().nullable(),
18836
+ singleton: boolean()
18774
18837
  });
18775
- var ConfigFieldBridge = custom();
18776
- var PipelineAddonSchemaSchema = object({
18777
- id: string(),
18778
- name: string(),
18779
- slot: PipelineSlotSchema,
18780
- inputClasses: array(string()).readonly(),
18781
- outputClasses: array(string()).readonly(),
18782
- childSlots: array(PipelineSlotSchema).readonly(),
18783
- models: array(PipelineModelOptionSchema).readonly(),
18784
- defaultModelId: string(),
18785
- defaultModelIdByFormat: record(string(), string()).optional(),
18786
- enabledByDefault: boolean().optional(),
18787
- backfillIntoExistingOverrides: boolean().optional(),
18788
- defaultConfidence: number(),
18789
- group: string().optional(),
18790
- configSchema: array(ConfigFieldBridge).readonly().optional()
18838
+ var AnalyticsGroupMemberSchema = object({
18839
+ trackId: string(),
18840
+ deviceId: number().int(),
18841
+ className: string(),
18842
+ firstSeen: number().int(),
18843
+ lastSeen: number().int(),
18844
+ mediaUrl: string().nullable()
18791
18845
  });
18792
- var PipelineSlotSchemaSchema = object({
18793
- id: PipelineSlotSchema,
18794
- label: string(),
18795
- priority: number(),
18796
- parentSlot: PipelineSlotSchema.nullable(),
18797
- addons: array(PipelineAddonSchemaSchema).readonly()
18846
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
18847
+ var ListGroupsQueryInput = object({
18848
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
18849
+ deviceIds: array(number()),
18850
+ /** Window lower bound on `closedAt` (inclusive). */
18851
+ since: number().optional(),
18852
+ /** Window upper bound on `openedAt` (inclusive). */
18853
+ until: number().optional(),
18854
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
18855
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
18856
+ cursor: string().optional()
18798
18857
  });
18799
- var PipelineSchemaSchema = object({
18800
- availableEngines: array(AvailableEngineSchema).readonly(),
18801
- selectedEngine: PipelineEngineChoiceSchema,
18802
- slots: array(PipelineSlotSchemaSchema).readonly()
18858
+ var ListGroupsPageSchema = object({
18859
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
18860
+ nextCursor: string().nullable()
18803
18861
  });
18804
- var EngineProvisioningSchema = object({
18805
- runtimeId: _enum([
18806
- "onnx",
18807
- "openvino",
18808
- "coreml",
18809
- "edgetpu"
18810
- ]).nullable(),
18811
- device: string().nullable(),
18812
- state: _enum([
18813
- "idle",
18814
- "installing",
18815
- "verifying",
18816
- "ready",
18817
- "failed"
18818
- ]),
18819
- progress: number().optional(),
18820
- error: string().optional(),
18821
- nextRetryAt: number().optional(),
18822
- /**
18823
- * Gate A (config-correctness gate at engine change): human-readable
18824
- * config issues surfaced EAGERLY when the node's engine changes — model
18825
- * substitutions ("chose X, running Y") and zero-build steps ("no model
18826
- * has a <format> build"). Additive/optional: informational only, never
18827
- * enforced here — `assertEngineReady` (readiness) still gates inference.
18828
- * Absent/empty when the node-default tree resolves cleanly.
18829
- */
18830
- configIssues: array(string()).optional()
18862
+ var KeyEventQueryInput = object({
18863
+ deviceId: number(),
18864
+ /** Window lower bound (track firstSeen ≥ since). */
18865
+ since: number(),
18866
+ /** Window upper bound (track firstSeen ≤ until). */
18867
+ until: number(),
18868
+ limit: number().int().min(1).max(200).default(50),
18869
+ /** Drop tracks scoring below this importance. */
18870
+ minImportance: number().min(0).max(1).optional(),
18871
+ /** Restrict to a single class (e.g. 'person'). */
18872
+ classFilter: string().optional()
18831
18873
  });
18832
- var PipelineStepInputSchema = lazy(() => object({
18833
- addonId: string(),
18834
- modelId: string().optional(),
18835
- enabled: boolean().default(true),
18836
- children: array(PipelineStepInputSchema).optional(),
18837
- settings: record(string(), unknown()).optional(),
18838
- jumpDeviceKey: string().optional()
18839
- }));
18840
- var ModelSubstitutionSchema = object({
18841
- addonId: string(),
18842
- chosen: string(),
18843
- running: string(),
18844
- format: string()
18874
+ var KeyEventSchema = object({
18875
+ /** The representative event id (the track's best ObjectEvent, else its trackId). */
18876
+ id: string(),
18877
+ trackId: string(),
18878
+ /** Track start time (firstSeen). */
18879
+ timestamp: number(),
18880
+ className: string(),
18881
+ ...TieredLabelFields,
18882
+ importance: number(),
18883
+ /** Highest-confidence ObjectEvent id for the track (empty when none). */
18884
+ bestEventId: string(),
18885
+ /** Track lifetime in ms (lastSeen - firstSeen). */
18886
+ windowMs: number().optional(),
18887
+ ...TrackFlagFields,
18888
+ ...TrackRetrainFields
18845
18889
  });
18846
- var PipelineValidationIssueSchema = object({
18847
- addonId: string(),
18848
- kind: _enum(["unknown-addon", "no-format-build"]),
18849
- detail: string()
18890
+ object({
18891
+ trackId: string(),
18892
+ className: string(),
18893
+ confidence: number(),
18894
+ bbox: BoundingBoxSchema,
18895
+ zones: array(string()).readonly(),
18896
+ state: TrackStateSchema
18850
18897
  });
18851
- var PipelineValidationResultSchema = object({
18852
- ok: boolean(),
18853
- issues: array(PipelineValidationIssueSchema).readonly(),
18854
- substitutions: array(ModelSubstitutionSchema).readonly(),
18855
- /** The node's `currentEngine.format` this validation ran against. */
18856
- format: string()
18898
+ var OverlayDetectionSchema = looseObject({
18899
+ id: string(),
18900
+ kind: _enum(["first-level", "detail"]),
18901
+ macroClass: string(),
18902
+ score: number(),
18903
+ bbox: object({
18904
+ x: number(),
18905
+ y: number(),
18906
+ width: number(),
18907
+ height: number()
18908
+ }),
18909
+ labels: array(looseObject({
18910
+ label: string(),
18911
+ score: number()
18912
+ })).readonly(),
18913
+ parentId: string().optional()
18914
+ });
18915
+ var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
18916
+ var SearchObjectEventsInput = object({
18917
+ text: string(),
18918
+ deviceId: number().optional(),
18919
+ since: number().optional(),
18920
+ until: number().optional(),
18921
+ classFilter: string().optional(),
18922
+ limit: number().default(50),
18923
+ minScore: number().min(0).max(1).default(.2)
18924
+ });
18925
+ var TrackCascadeCountsSchema = object({
18926
+ /** Persisted track roots deleted (authoritative). */
18927
+ tracks: number().int(),
18928
+ /** Object events removed with their tracks (best-effort; see note above). */
18929
+ events: number().int(),
18930
+ /** Track/face/plate-owned media removed (best-effort). Never identity media. */
18931
+ media: number().int(),
18932
+ /** Unassigned (non-enrolled) face reads removed (best-effort). */
18933
+ faces: number().int(),
18934
+ /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
18935
+ plates: number().int(),
18936
+ /** Per-track CLIP search vectors removed (best-effort). */
18937
+ embeddings: number().int(),
18938
+ /** Group membership + group rows removed with their last member (best-effort). */
18939
+ groups: number().int()
18857
18940
  });
18858
- var ReferenceImageEntrySchema = object({
18859
- filename: string(),
18860
- stepIds: array(string()).readonly().optional()
18941
+ /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
18942
+ var DiskReconcileCountsSchema = object({
18943
+ mediaDropped: number().int(),
18944
+ tracks: number().int(),
18945
+ events: number().int()
18861
18946
  });
18862
- var ReferenceImageBodySchema = object({
18863
- base64: string(),
18864
- filename: string()
18947
+ /** Event-store footprint for one camera. */
18948
+ var EventStoreDeviceFootprintSchema = object({
18949
+ deviceId: number(),
18950
+ /** Persisted event rows (motion + object + audio) for the camera. */
18951
+ rows: number().int(),
18952
+ /** Event-owned media bytes on disk for the camera. */
18953
+ bytes: number().int()
18865
18954
  });
18866
- var ReferenceAudioEntrySchema = object({
18867
- filename: string(),
18868
- sizeKb: number()
18955
+ /** Aggregate event-store footprint: global totals + per-camera breakdown. */
18956
+ var EventStoreFootprintSchema = object({
18957
+ totalRows: number().int(),
18958
+ totalBytes: number().int(),
18959
+ devices: array(EventStoreDeviceFootprintSchema).readonly()
18869
18960
  });
18870
- var ReferenceAudioBodySchema = object({ base64: string() });
18871
- var AudioBackendSchema = object({
18872
- id: string(),
18873
- name: string(),
18874
- description: string(),
18875
- available: boolean(),
18961
+ /** Per-kind counts returned by the event-prune / device-delete mutations. */
18962
+ var EventPruneCountsSchema = object({
18963
+ motion: number().int(),
18964
+ object: number().int(),
18965
+ audio: number().int()
18966
+ });
18967
+ /**
18968
+ * Re-embed stored tracks from their key frames.
18969
+ *
18970
+ * The reason this is an operator-callable method and not a migration script:
18971
+ * every knob that decides what a vector MEANS — encoder model, crop margin,
18972
+ * squaring — is only changeable if the existing vectors can be regenerated.
18973
+ * Mixing feature spaces in one index makes cosine scores incomparable, and the
18974
+ * symptom is a quality regression with no visible cause.
18975
+ */
18976
+ var RebuildObjectEmbeddingsInput = object({
18977
+ /** Restrict to one camera. Omit for the whole fleet. */
18978
+ deviceId: number().optional(),
18979
+ since: number().optional(),
18980
+ until: number().optional(),
18981
+ /** Stop after this many tracks; the result reports whether more remain. */
18982
+ maxTracks: number().int().positive().optional(),
18876
18983
  /**
18877
- * Raw classifier labels this backend can emit (e.g. YAMNet's
18878
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
18879
- * the benchmark UI to populate the `enabledMicroClasses` filter
18880
- * specific to the selected backend without a separate fetch.
18984
+ * Run every embedding on THIS node instead of round-robining the fleet.
18985
+ *
18986
+ * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
18987
+ * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
18988
+ * calling it that would pin the rebuild REQUEST itself to that node — the
18989
+ * rebuild orchestration lives on the hub, and only the per-track step runs
18990
+ * remotely. This field is data; the per-track pin is applied inside.
18991
+ *
18992
+ * Absent ⇒ round-robin over every online node whose runner can serve the
18993
+ * pinned model.
18881
18994
  */
18882
- rawLabels: array(string()).readonly().optional()
18883
- });
18884
- var AudioCapabilitiesSchema = object({
18885
- activeBackend: string(),
18886
- availableBackends: array(AudioBackendSchema).readonly(),
18887
- sampleRate: number(),
18888
- chunkDurationMs: number()
18889
- });
18890
- var DownloadModelResultSchema = object({
18891
- filePath: string(),
18892
- sizeMB: number(),
18893
- durationMs: number()
18995
+ executeOnNodeId: string().optional(),
18996
+ /**
18997
+ * Milliseconds to wait between tracks; omit for the built-in default, `0` to
18998
+ * run flat out.
18999
+ *
19000
+ * A rebuild is bulk maintenance on hub-main's single thread. Measured
19001
+ * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
19002
+ * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
19003
+ * force is logged at start and finish so a deliberately slow pass reads
19004
+ * differently from a stalled one.
19005
+ */
19006
+ pacingMs: number().int().nonnegative().optional()
18894
19007
  });
18895
19008
  /**
18896
- * Wrapper carrying a single test run's result. Replaces the legacy
18897
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
18898
- * canonical `AudioResult` from the Phase 6 output rework: one
18899
- * `AudioDetection` per class above `minScore`, top-N candidates in
18900
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
18901
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
18902
- * benchmark UI can still report a clean failure when the classifier
18903
- * cap isn't available.
19009
+ * Result of emptying the CLIP index.
19010
+ *
19011
+ * The clean slate before a policy change: a new crop margin or encoder model
19012
+ * leaves two feature spaces in one index whose cosine scores are not
19013
+ * comparable, so wiping and rebuilding is the only way to be sure every vector
19014
+ * means the same thing.
18904
19015
  */
18905
- var AudioTestResultSchema = object({
18906
- success: boolean(),
18907
- error: string().optional(),
18908
- frame: custom().optional()
19016
+ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
19017
+ /**
19018
+ * Acknowledgement that a rebuild STARTED.
19019
+ *
19020
+ * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
19021
+ * runs detached and this returns immediately. Waiting for it made the client
19022
+ * time out while the work carried on server-side, which is the worst of both:
19023
+ * no result and no way to know it was still going. Poll
19024
+ * `getObjectEmbeddingRebuildStatus` for progress.
19025
+ */
19026
+ var RebuildObjectEmbeddingsResultSchema = object({
19027
+ started: boolean(),
19028
+ /** True when a pass was already running; the new request is ignored. */
19029
+ alreadyRunning: boolean()
18909
19030
  });
18910
- var PipelineConfigBridge = custom();
18911
- var ConfigUISchemaBridge = custom();
18912
- var ConfigUISchemaNullableBridge = custom();
18913
- var InferenceCapabilitiesBridge = custom();
18914
- var ModelAvailabilityListBridge = custom();
18915
- var PipelineRunResultBridge = custom();
18916
- method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
18917
- modelId: string(),
18918
- settings: record(string(), unknown()).readonly()
18919
- }))), method(object({ steps: record(string(), object({
18920
- modelId: string(),
18921
- settings: record(string(), unknown()).readonly()
18922
- })) }), object({ success: literal(true) }), {
19031
+ var RebuildStatusSchema = object({
19032
+ running: boolean(),
19033
+ scanned: number(),
19034
+ rebuilt: number(),
19035
+ /** Tracks whose key frame is gone — nothing to re-embed from. */
19036
+ missingKeyFrame: number(),
19037
+ /** Tracks with no usable detection box. */
19038
+ missingBbox: number(),
19039
+ /**
19040
+ * Tracks an executing node REFUSED rather than broke on — an unreadable key
19041
+ * frame, a step that threw. Separate from `failed` because the remedy is
19042
+ * different, and because a whole camera silently contributing zero vectors
19043
+ * is the shape of failure a rebuild must never hide.
19044
+ */
19045
+ notRunnable: number(),
19046
+ /**
19047
+ * The pass stopped because NO node could serve the pinned model.
19048
+ *
19049
+ * Distinct from `notRunnable` on purpose: that one says "this track was
19050
+ * refused", this one says "the cluster cannot do this work at all" — every
19051
+ * candidate node either lacks the `clip-embedding` step, lacks a build of the
19052
+ * pinned model for its engine format, or dropped out. The remedy is a model /
19053
+ * engine change, not a per-camera one. Non-zero here always comes with
19054
+ * `complete: false`.
19055
+ */
19056
+ noCapableNode: number(),
19057
+ failed: number(),
19058
+ /** Set once a pass ends: true only when EVERYTHING was covered. */
19059
+ complete: boolean().nullable(),
19060
+ startedAtMs: number().nullable(),
19061
+ finishedAtMs: number().nullable(),
19062
+ /** Present when the pass ended by throwing. */
19063
+ error: string().nullable()
19064
+ });
19065
+ var ReplayFrameInputSchema = object({
19066
+ timestamp: number(),
19067
+ frame: PipelineRunResultBridge
19068
+ });
19069
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
19070
+ className: string(),
19071
+ firstSeenMs: number(),
19072
+ lastSeenMs: number(),
19073
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
19074
+ * frame — a representative box for the diff's `(className, window, IoU)`
19075
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
19076
+ * trajectory production's `Track.positions` keeps. */
19077
+ bbox: BoundingBoxSchema,
19078
+ /** How many of the input frames this track matched a real detection on
19079
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
19080
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
19081
+ framesMatched: number().int()
19082
+ })).readonly() });
19083
+ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
19084
+ deviceId: number(),
19085
+ trackId: string()
19086
+ }), TrackSchema.nullable()), method(object({
19087
+ deviceId: number(),
19088
+ since: number().optional(),
19089
+ until: number().optional(),
19090
+ limit: number().optional(),
19091
+ /** Spatial filter — only tracks whose trajectory intersects the zone
19092
+ * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
19093
+ * envelope columns, then precisely tested per position. Tracks with
19094
+ * an unknown envelope (no frame dims at persist time) always match. */
19095
+ zone: TrackZoneFilterSchema.optional(),
19096
+ /** See {@link TrackProjectionSchema}. Default `full` (backward
19097
+ * compatible — omitting the field keeps today's exact behaviour). */
19098
+ projection: TrackProjectionSchema.optional(),
19099
+ /** Include stationary-promoted rows (parked objects handed to the
19100
+ * stationary registry). Default false: the timeline lists passages,
19101
+ * not parking records (operator decision, 2026-08-15). */
19102
+ includeStationary: boolean().optional()
19103
+ }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
19104
+ deviceId: number(),
19105
+ groupId: string().min(1)
19106
+ }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
19107
+ kind: "mutation",
19108
+ auth: "admin"
19109
+ }), 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({
19110
+ deviceId: number(),
19111
+ since: number().optional(),
19112
+ until: number().optional(),
19113
+ kinds: array(string()).optional(),
19114
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
19115
+ }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
19116
+ deviceId: number(),
19117
+ since: number(),
19118
+ until: number(),
19119
+ bucketMs: number().int().positive()
19120
+ }), array(object({
19121
+ bucketStart: number(),
19122
+ motion: number().int(),
19123
+ object: number().int(),
19124
+ audio: number().int()
19125
+ })).readonly()), method(object({
19126
+ deviceId: number(),
19127
+ cutoffMs: number()
19128
+ }), object({
19129
+ motion: number().int(),
19130
+ object: number().int(),
19131
+ audio: number().int()
19132
+ }), {
19133
+ kind: "mutation",
19134
+ auth: "admin"
19135
+ }), method(object({
19136
+ deviceId: number(),
19137
+ cutoffMs: number()
19138
+ }), TrackCascadeCountsSchema, {
19139
+ kind: "mutation",
19140
+ auth: "admin"
19141
+ }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
19142
+ kind: "mutation",
19143
+ auth: "admin"
19144
+ }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
19145
+ kind: "mutation",
19146
+ auth: "admin"
19147
+ }), method(object({
19148
+ deviceId: number(),
19149
+ trackIds: array(string()).min(1)
19150
+ }), object({
19151
+ deleted: number().int(),
19152
+ failed: array(string()).readonly()
19153
+ }), {
19154
+ kind: "mutation",
19155
+ auth: "admin"
19156
+ }), method(object({
19157
+ /** Log/audit scope only — the trackId is globally unique on its own. */
19158
+ deviceId: number(),
19159
+ trackId: string(),
19160
+ flags: TrackFlagsPatchSchema
19161
+ }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
19162
+ kind: "query",
19163
+ auth: "admin"
19164
+ }), method(object({
19165
+ olderThanMs: number(),
19166
+ reason: OpsLogReasonSchema.optional()
19167
+ }), EventPruneCountsSchema, {
18923
19168
  kind: "mutation",
18924
19169
  auth: "admin"
18925
- }), method(object({ nodeId: string() }), object({
18926
- success: literal(true),
18927
- clearedDevices: number()
18928
- }), {
19170
+ }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
18929
19171
  kind: "mutation",
18930
19172
  auth: "admin"
18931
- }), 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({
18932
- name: string(),
18933
- steps: array(PipelineTemplateStepSchema).readonly(),
18934
- engine: PipelineEngineChoiceSchema
18935
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
18936
- id: string(),
18937
- name: string().optional(),
18938
- steps: array(PipelineTemplateStepSchema).readonly().optional()
18939
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
18940
- addonId: string(),
18941
- modelId: string(),
18942
- format: ModelFormatSchema$1
18943
- }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
18944
- addonId: string(),
18945
- modelId: string(),
18946
- format: ModelFormatSchema$1
18947
- }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
18948
- engine: PipelineEngineChoiceSchema.optional(),
18949
- steps: array(PipelineStepInputSchema).min(1),
18950
- frame: FrameInputSchema.optional(),
18951
- /**
18952
- * Process-local lazy frame. Valid only when caller and provider resolve
18953
- * in the same execution-group process; split/cross-node callers use
18954
- * `frame`/`image` inline compatibility instead.
18955
- */
18956
- frameRef: FrameRefSchema.optional(),
18957
- /**
18958
- * CB5 shm passthrough a `FrameHandle` naming the same ring slot
18959
- * the decoded pixels live in. One more member of the one-of
18960
- * frame/frameHandle/image/imageBase64/referenceImage group.
18961
- */
18962
- frameHandle: FrameHandleSchema.optional(),
18963
- imageBase64: string().optional(),
18964
- /**
18965
- * Binary JPEG bytes preferred over `imageBase64` on internal
18966
- * hops (hub forked worker via Moleculer MsgPack) because it
18967
- * skips the 33% base64 overhead + the per-call base64 decode on
18968
- * the detection-pipeline worker. Callers can pass either; exactly
18969
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
18970
- */
18971
- image: _instanceof(Uint8Array).optional(),
18972
- referenceImage: string().optional(),
18973
- deviceId: number().optional(),
18974
- sessionId: string().optional(),
18975
- /**
18976
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
18977
- * reference-image, and detail-subtree calls. 'frame' is the live
18978
- * per-frame dispatch: ONLY root-plane steps run; crop children
18979
- * (inputClasses ≠ null) are skipped and served per-track via
18980
- * pipelineRunner.runDetailSubtree (two-plane design).
18981
- */
18982
- plane: _enum(["full", "frame"]).optional(),
18983
- /**
18984
- * Inference-device selector (Phase 2 multi-device). Format
18985
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
18986
- * Omitted ⇒ the runner's default device (current single-engine
18987
- * behaviour). Selects WHICH device pool of the node runs the call.
18988
- */
18989
- deviceKey: string().optional(),
18990
- /**
18991
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
18992
- * when the parent crop was resolved from the frame's retained NATIVE
18993
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
18994
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
18995
- * resolution from that surface — the SAME quality path faces already
18996
- * had — instead of the downscaled parent tile. `handle` keys the native
18997
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
18998
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
18999
- * the executor's crop-normalized child ROI back into frame-normalized
19000
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
19001
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
19002
- * (today's behaviour on the fallback path).
19003
- */
19004
- nativeCropRef: NativeCropRefSchema.optional()
19005
- }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
19006
- engine: PipelineEngineChoiceSchema.optional(),
19007
- steps: array(PipelineStepInputSchema).min(1),
19008
- frames: array(FrameInputSchema).min(1).max(255),
19009
- deviceId: number().optional(),
19010
- sessionId: string().optional(),
19011
- /**
19012
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
19013
- * the batch to the Python pool's bench preprocess cache
19014
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
19015
- * preprocessed ONCE and every later inference is a pure-inference cache
19016
- * hit — the sustained-throughput run measures inference, not
19017
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
19018
- * full preprocess every call, correct). Fresh per sustained run;
19019
- * released via `uncacheFrame`.
19020
- */
19021
- frameId: number().int().nonnegative().optional(),
19022
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
19023
- deviceKey: string().optional()
19024
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
19025
- data: _instanceof(Uint8Array),
19026
- width: number().int().positive(),
19027
- height: number().int().positive(),
19028
- format: _enum([
19029
- "rgb",
19030
- "bgr",
19031
- "gray"
19032
- ])
19173
+ }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
19174
+ kind: "mutation",
19175
+ auth: "admin"
19176
+ }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
19177
+ kind: "mutation",
19178
+ auth: "admin"
19179
+ }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
19180
+ kind: "mutation",
19181
+ auth: "admin"
19182
+ }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
19183
+ kind: "mutation",
19184
+ auth: "admin"
19185
+ }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
19186
+ kind: "mutation",
19187
+ auth: "admin"
19188
+ }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
19189
+ kind: "mutation",
19190
+ auth: "admin"
19191
+ }), method(object({}), array(RelocateJobSchema).readonly(), {
19192
+ kind: "query",
19193
+ auth: "admin"
19194
+ }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
19195
+ kind: "mutation",
19196
+ auth: "admin"
19197
+ }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
19198
+ kind: "query",
19199
+ auth: "admin"
19200
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
19201
+ kind: "query",
19202
+ auth: "admin"
19203
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
19204
+ kind: "query",
19205
+ auth: "admin"
19206
+ }), method(object({
19207
+ /** Empty every camera that has staging tracks. A LIST, not a single
19208
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
19209
+ * route it at one camera's owner, and "every camera" would stop being
19210
+ * expressible at all. */
19211
+ deviceIds: array(number()).optional(),
19212
+ limit: number().int().min(1).max(500).optional()
19213
+ }), array(RetrainTrackSchema).readonly(), {
19214
+ kind: "query",
19215
+ auth: "admin"
19216
+ }), method(object({ trackId: string() }), RetrainFrameListSchema, {
19217
+ kind: "query",
19218
+ auth: "admin"
19219
+ }), method(object({
19220
+ deviceId: number(),
19221
+ trackId: string(),
19222
+ mediaKeys: array(string()).min(1)
19223
+ }), RetrainFrameSelectionSchema, {
19224
+ kind: "mutation",
19225
+ auth: "admin"
19226
+ }), method(object({
19227
+ deviceId: number(),
19228
+ trackId: string(),
19229
+ frameId: string()
19033
19230
  }), object({
19034
- frameId: number(),
19035
- width: number(),
19036
- height: number()
19037
- }), { kind: "mutation" }), method(object({
19038
- stepId: string(),
19039
- frameId: number().int()
19040
- }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
19041
- batchMode: string(),
19042
- windowMs: number(),
19043
- maxBatchSize: number(),
19044
- concurrency: number()
19045
- })), method(_void(), array(object({
19046
- engineKey: string(),
19047
- engine: PipelineEngineChoiceSchema,
19048
- modelsLoaded: array(string()).readonly(),
19049
- inUseByCameras: array(number()).readonly(),
19050
- /**
19051
- * Origin of this resident factory.
19052
- * - `runtime` — main camera-serving engine (no idle TTL).
19053
- * - `warm-override` — benchmark/test override held in the warm
19054
- * cache; auto-disposed after the idle TTL.
19055
- * - `device-pool` — a concurrent per-device pool (Phase 2
19056
- * multi-device, keyed by `deviceKey`) resolved
19057
- * via `resolveDeviceFactory`. Runs alongside the
19058
- * `runtime` engine on a DIFFERENT accelerator
19059
- * (NPU / iGPU / Coral) — this is how the
19060
- * Engines tab shows all pools running at once.
19061
- */
19062
- kind: _enum([
19063
- "runtime",
19064
- "warm-override",
19065
- "device-pool"
19066
- ]),
19067
- /** Native pid of the underlying Python pool (null when no pool). */
19068
- poolPid: number().nullable(),
19069
- /** ms since this factory was last used (null when not warm-tracked). */
19070
- idleMs: number().nullable(),
19071
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
19072
- idleTtlMs: number().nullable()
19073
- })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
19231
+ removed: boolean(),
19232
+ removedAnnotations: number().int()
19233
+ }), {
19234
+ kind: "mutation",
19235
+ auth: "admin"
19236
+ }), method(object({ frameId: string() }), object({
19237
+ base64: string(),
19238
+ width: number().int(),
19239
+ height: number().int()
19240
+ }), {
19241
+ kind: "query",
19242
+ auth: "admin"
19243
+ }), method(object({
19244
+ deviceId: number(),
19245
+ trackId: string(),
19246
+ frameId: string(),
19247
+ subject: RetrainAssistSubjectSchema,
19248
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
19249
+ nodeId: string().optional()
19250
+ }), RetrainAssistResultSchema, {
19251
+ kind: "mutation",
19252
+ auth: "admin"
19253
+ }), method(object({
19254
+ deviceId: number(),
19255
+ source: DetectionSourceSchema,
19256
+ zones: array(ZoneSchema).readonly().optional(),
19257
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
19258
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
19259
+ frames: array(ReplayFrameInputSchema).min(1)
19260
+ }), RunReplayFrameProcessorResultSchema, {
19261
+ kind: "mutation",
19262
+ auth: "admin"
19263
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
19264
+ kind: "query",
19265
+ auth: "admin"
19266
+ }), method(object({
19267
+ deviceId: number(),
19268
+ trackId: string(),
19269
+ frameId: string(),
19270
+ annotations: array(RetrainAnnotationDraftSchema)
19271
+ }), array(RetrainAnnotationSchema).readonly(), {
19272
+ kind: "mutation",
19273
+ auth: "admin"
19274
+ }), method(object({
19275
+ deviceId: number(),
19276
+ trackId: string()
19277
+ }), RetrainTransitionResultSchema, {
19278
+ kind: "mutation",
19279
+ auth: "admin"
19280
+ }), method(object({
19281
+ deviceId: number(),
19282
+ trackId: string()
19283
+ }), RetrainTransitionResultSchema, {
19074
19284
  kind: "mutation",
19075
19285
  auth: "admin"
19286
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
19287
+ kind: "query",
19288
+ auth: "admin"
19076
19289
  }), method(object({
19077
- engine: PipelineEngineChoiceSchema,
19078
- force: boolean().optional()
19079
- }), object({
19080
- success: boolean(),
19081
- reason: string().optional()
19082
- }), {
19290
+ eventId: string(),
19291
+ kind: MediaFileKindEnum.optional(),
19292
+ deviceId: number()
19293
+ }), array(MediaFileSchema).readonly()), method(object({
19294
+ trackId: string(),
19295
+ kinds: array(MediaFileKindEnum).optional(),
19296
+ deviceId: number()
19297
+ }), array(MediaFileSchema).readonly()), method(object({
19298
+ trackId: string(),
19299
+ deviceId: number()
19300
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
19083
19301
  kind: "mutation",
19084
19302
  auth: "admin"
19085
- }), 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({
19086
- addonId: string(),
19087
- modelId: string(),
19088
- filename: string().optional(),
19089
- settings: record(string(), unknown()).optional()
19090
- }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
19303
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
19304
+ kind: "mutation",
19305
+ auth: "admin"
19306
+ }), method(object({}), RebuildStatusSchema), object({
19307
+ deviceId: number(),
19308
+ timestamp: number(),
19309
+ frameWidth: number(),
19310
+ frameHeight: number(),
19311
+ detections: array(OverlayDetectionSchema).readonly()
19312
+ }), object({
19313
+ deviceId: number(),
19314
+ trackId: string(),
19315
+ className: string()
19316
+ }), object({
19317
+ deviceId: number(),
19318
+ trackId: string(),
19319
+ className: string(),
19320
+ durationMs: number()
19321
+ }), object({
19322
+ deviceId: number(),
19323
+ kind: EventKindSchema,
19324
+ eventId: string(),
19325
+ timestamp: number()
19326
+ });
19091
19327
  object({
19092
19328
  activeCameras: number(),
19093
19329
  throttledCameras: number(),
@@ -19113,106 +19349,6 @@ var CameraMetricsSchema = object({
19113
19349
  });
19114
19350
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
19115
19351
  /**
19116
- * Zone — pure geometry + identity. NO filtering behaviour.
19117
- *
19118
- * Zones describe **where** in the frame the operator wants to flag
19119
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
19120
- * each pipeline stage uses them. Splitting the two means a single
19121
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
19122
- * a detection-include rule on `['car']`, and an occupancy aggregate
19123
- * — without three duplicated polygons.
19124
- *
19125
- * Owned by the orchestrator addon (provider) and mirrored into the
19126
- * `zones` device-state slice on every mutation. Consumers
19127
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
19128
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
19129
- * mirror with `onChanged`).
19130
- *
19131
- * Coordinates are normalised fractions of the frame (0–1) so zones
19132
- * survive resolution changes and stream profile switches.
19133
- *
19134
- * `kind` discriminates between full polygons (closed regions used
19135
- * for intrusion / occupancy filters) and tripwires (open 2-point
19136
- * line segments used for cross events). Onboard / firmware-reported
19137
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
19138
- * task list.
19139
- */
19140
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
19141
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
19142
- var PolygonPointSchema = object({
19143
- x: number(),
19144
- y: number()
19145
- });
19146
- /** A camera detection zone — pure geometry/identity. */
19147
- var ZoneSchema = object({
19148
- id: string(),
19149
- name: string(),
19150
- kind: ZoneKindEnum.default("polygon"),
19151
- /** Polygon vertices, fraction of frame (0–1). */
19152
- polygon: array(PolygonPointSchema).readonly(),
19153
- /** Visual color for UI rendering. */
19154
- color: string().default("#3b82f6")
19155
- });
19156
- /**
19157
- * Zones capability — per-camera CRUD over polygon detection zones.
19158
- *
19159
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
19160
- * to per-device settings and mirrors into the `zones` device-state
19161
- * slice on every mutation, so downstream consumers can subscribe via
19162
- * `dev.state.zones.onChanged`.
19163
- *
19164
- * The cap surface only handles geometry + identity; filtering
19165
- * behaviour (per-class, include/exclude, threshold) lives in the
19166
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
19167
- * `capabilities/schemas/zone-rule.js`.
19168
- */
19169
- var zonesCapability = {
19170
- name: "zones",
19171
- scope: "device",
19172
- mode: "singleton",
19173
- deviceTypes: [DeviceType.Camera],
19174
- methods: {
19175
- listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
19176
- addZone: method(object({
19177
- deviceId: number(),
19178
- zone: ZoneSchema
19179
- }), _void(), {
19180
- kind: "mutation",
19181
- auth: "admin"
19182
- }),
19183
- removeZone: method(object({
19184
- deviceId: number(),
19185
- zoneId: string()
19186
- }), _void(), {
19187
- kind: "mutation",
19188
- auth: "admin"
19189
- }),
19190
- updateZone: method(object({
19191
- deviceId: number(),
19192
- zone: ZoneSchema
19193
- }), _void(), {
19194
- kind: "mutation",
19195
- auth: "admin"
19196
- })
19197
- },
19198
- /**
19199
- * Runtime-state slice — the live zone catalogue mirrored by the
19200
- * orchestrator on every CRUD mutation. Consumers read via
19201
- * `device.state.zones.value` / `.watch(...)` without round-tripping
19202
- * the cap, and the codegen DeviceProxy auto-wires the reactive
19203
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
19204
- * (e.g. zone groupings) can sit alongside the polygon list.
19205
- */
19206
- runtimeState: object({ zones: array(ZoneSchema).readonly() }),
19207
- /**
19208
- * 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.
19209
- *
19210
- * See `RuntimeStateDurability`. Enforced by
19211
- * `scripts/check-runtime-state-durability.ts`.
19212
- */
19213
- durability: "restored"
19214
- };
19215
- /**
19216
19352
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
19217
19353
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
19218
19354
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -28523,92 +28659,6 @@ var sceneMonitorCapability = {
28523
28659
  durability: "session"
28524
28660
  };
28525
28661
  /**
28526
- * Per-stage gating mode applied to the zones a rule references.
28527
- *
28528
- * - `include`: the rule contributes to a **whitelist** for its stage.
28529
- * When at least one `include` rule fires for a stage, only entities
28530
- * inside one of those zones pass that stage.
28531
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
28532
- * Entities inside one of those zones are dropped at that stage.
28533
- *
28534
- * `monitor`-style observation (count without filtering) is not a rule
28535
- * mode — zones without any matching rule are observed naturally by
28536
- * `zone-analytics` (live snapshot + history), so an "I just want to
28537
- * count, not filter" use case needs no rule at all.
28538
- */
28539
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
28540
- /**
28541
- * Per-consumer rule that references existing zones (geometry) and
28542
- * defines how a specific pipeline stage should treat them. Each
28543
- * consumer addon owns its own `ZoneRule[]` array in its per-device
28544
- * settings:
28545
- *
28546
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
28547
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
28548
- * - future: notification rules, audio gating, etc.
28549
- *
28550
- * One rule applies to N zones (`zoneIds[]`) so the operator can
28551
- * express "ignore motion in ALL of {garden, street}" with a single
28552
- * rule. `classFilter` narrows the rule to specific object classes —
28553
- * "drop person detections in the street, but keep cars" is one
28554
- * `exclude` rule with `classFilter: ['person']`.
28555
- *
28556
- * `enabled` is a soft toggle — the operator can keep the rule
28557
- * configured but inert without deleting it.
28558
- */
28559
- var ZoneRuleSchema = object({
28560
- /** Stable rule id — survives edits, used by the UI for diffing. */
28561
- id: string(),
28562
- /** Optional human-readable label rendered in the rule editor. */
28563
- name: string().optional(),
28564
- /** Zones this rule targets. The rule's `mode` applies to ALL
28565
- * listed zones (OR-set: a detection in any one of them counts).
28566
- * At least one zone id required — a rule with no targets is a
28567
- * configuration mistake and the form validator rejects it. */
28568
- zoneIds: array(string()).min(1).readonly(),
28569
- mode: ZoneRuleModeEnum,
28570
- /**
28571
- * Class names this rule applies to. Empty / undefined ⇒ rule
28572
- * applies to every class. Class strings match the `macroClass`
28573
- * field on detections (e.g. `person`, `car`, `dog`).
28574
- */
28575
- classFilter: array(string()).readonly().optional(),
28576
- /**
28577
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
28578
- * required to consider an entity "in the zone". Defaults to the
28579
- * consumer's stage default when omitted. Kept for back-compat with
28580
- * existing per-rule overrides; new operators pick the value via
28581
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
28582
- * set, the lower-level engine reads it as a 0–1 fraction.
28583
- */
28584
- overlapThreshold: number().min(0).max(1).optional(),
28585
- /**
28586
- * Operator-friendly version of `overlapThreshold` — the percentage
28587
- * of the detection's bbox that must lie inside the zone for the
28588
- * rule to match. Documented default is 85%; the engine substitutes
28589
- * that when the field is omitted (kept optional so existing rules
28590
- * stored without it stay valid).
28591
- *
28592
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
28593
- * rule, the engine prefers `bboxInclusionPct` because it's the
28594
- * field exposed in the UI. Internally both feed the same gate.
28595
- */
28596
- bboxInclusionPct: number().min(0).max(100).optional(),
28597
- /**
28598
- * When `true` and a detection has a segmentation mask, use the
28599
- * mask for overlap instead of the bbox. Detection-stage only;
28600
- * motion rules ignore this field.
28601
- */
28602
- preferMask: boolean().optional(),
28603
- /**
28604
- * Soft-toggle: `false` disables the rule without deleting it.
28605
- * Defaults to `true` so operators creating a rule via the UI
28606
- * see it active immediately.
28607
- */
28608
- enabled: boolean().default(true)
28609
- });
28610
- array(ZoneRuleSchema).readonly();
28611
- /**
28612
28662
  * Script-runner cap. Models HA `script.*` entities on
28613
28663
  * `DeviceType.Script`. A Script is a pre-recorded action sequence
28614
28664
  * that can be invoked imperatively — optionally with a variables
@@ -34545,6 +34595,12 @@ Object.freeze({
34545
34595
  addonId: null,
34546
34596
  access: "create"
34547
34597
  },
34598
+ "pipelineAnalytics.runReplayFrameProcessor": {
34599
+ capName: "pipeline-analytics",
34600
+ capScope: "device",
34601
+ addonId: null,
34602
+ access: "create"
34603
+ },
34548
34604
  "pipelineAnalytics.saveRetrainAnnotations": {
34549
34605
  capName: "pipeline-analytics",
34550
34606
  capScope: "device",
@@ -34677,6 +34733,12 @@ Object.freeze({
34677
34733
  addonId: null,
34678
34734
  access: "view"
34679
34735
  },
34736
+ "pipelineExecutor.getInferenceDeviceHealth": {
34737
+ capName: "pipeline-executor",
34738
+ capScope: "system",
34739
+ addonId: null,
34740
+ access: "view"
34741
+ },
34680
34742
  "pipelineExecutor.getOrchestratorConfigSchema": {
34681
34743
  capName: "pipeline-executor",
34682
34744
  capScope: "system",
@@ -34749,6 +34811,12 @@ Object.freeze({
34749
34811
  addonId: null,
34750
34812
  access: "view"
34751
34813
  },
34814
+ "pipelineExecutor.rearmInferenceDevice": {
34815
+ capName: "pipeline-executor",
34816
+ capScope: "system",
34817
+ addonId: null,
34818
+ access: "create"
34819
+ },
34752
34820
  "pipelineExecutor.runAudioTest": {
34753
34821
  capName: "pipeline-executor",
34754
34822
  capScope: "system",
@@ -37997,6 +38065,11 @@ Object.freeze({
37997
38065
  form: "single",
37998
38066
  optional: false
37999
38067
  }],
38068
+ "pipelineAnalytics.runReplayFrameProcessor": [{
38069
+ name: "deviceId",
38070
+ form: "single",
38071
+ optional: false
38072
+ }],
38000
38073
  "pipelineAnalytics.saveRetrainAnnotations": [{
38001
38074
  name: "deviceId",
38002
38075
  form: "single",