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