@camstack/addon-provider-tuya 0.2.29 → 0.2.30

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