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