@camstack/addon-notifiers 1.2.33 → 1.2.34

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