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