@camstack/addon-pipeline-orchestrator 1.2.109 → 1.2.110

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.
package/dist/index.js CHANGED
@@ -17002,1912 +17002,2180 @@ var OauthIntegrationDescriptorSchema = object({
17002
17002
  });
17003
17003
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
17004
17004
  /**
17005
- * pipeline-analytics device-scoped wrapper cap. Refines raw
17006
- * per-frame detections emitted by the pipeline runner into tracked
17007
- * objects, per-kind event collections (motion / object / audio), and
17008
- * persisted media. Owns the post-detection domain end-to-end:
17009
- *
17010
- * runner emits PipelineInferenceResult
17011
- * ↓ (event bus)
17012
- * pipeline-analytics subscriber
17013
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
17014
- * → three DB collections (one per kind), one FS media tree, one
17015
- * unified event emitter (FrameTracked + TrackStarted/Ended +
17016
- * DetectionEvent on bus)
17017
- *
17018
- * Pure subscriber model. No `processFrame` cap method — the runner
17019
- * already publishes the raw frame on the bus. The cap surface is
17020
- * only QUERIES + per-device settings, bound on/off via
17021
- * `device-manager.setWrapperActive`. `defaultActive: true` because
17022
- * every camera with a detection pipeline wants its raw detections
17023
- * refined; operators opt out per-device via BindingsTab when needed.
17024
- *
17025
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
17026
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
17005
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
17006
+ * within the frame, so the executor can re-cut a leaf child ROI at native
17007
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
17027
17008
  */
17028
- var TrackStateSchema = _enum([
17029
- "new",
17030
- "entered",
17031
- "left",
17032
- "moving",
17033
- "idle"
17034
- ]);
17035
- var EventKindSchema = _enum([
17036
- "motion",
17037
- "object",
17038
- "audio"
17039
- ]);
17009
+ var NativeCropRefSchema = object({
17010
+ /** Handle keying the retained native surface (node-pinned to its owner). */
17011
+ handle: FrameHandleSchema,
17012
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
17013
+ cropFrameSpace: object({
17014
+ x: number(),
17015
+ y: number(),
17016
+ w: number(),
17017
+ h: number()
17018
+ })
17019
+ });
17020
+ object({
17021
+ crop: object({
17022
+ left: number(),
17023
+ top: number(),
17024
+ width: number().positive(),
17025
+ height: number().positive()
17026
+ }).optional(),
17027
+ content: object({
17028
+ width: number().int().positive(),
17029
+ height: number().int().positive()
17030
+ }),
17031
+ fit: _enum(["stretch", "contain"]),
17032
+ format: _enum([
17033
+ "rgb",
17034
+ "gray",
17035
+ "jpeg"
17036
+ ])
17037
+ });
17040
17038
  /**
17041
- * Spatial filter for `listTracks` the rect + polygon variants of the shared
17042
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
17043
- * of the camera frame (top-left origin), matching the drawing-plane editor.
17039
+ * Process-local frame identity. It is serializable so it can ride an in-process
17040
+ * capability call, but `registryId` deliberately prevents resolution in any
17041
+ * other process or execution group.
17044
17042
  */
17045
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
17046
- /** Closed icon vocabulary so clients render a known glyph per kind. */
17047
- var EventKindIconSchema = _enum([
17048
- "motion",
17049
- "audio",
17050
- "person",
17051
- "vehicle",
17052
- "animal",
17053
- "door",
17054
- "pir",
17055
- "smoke",
17056
- "water",
17057
- "button",
17058
- "package",
17059
- "generic"
17043
+ var FrameRefSchema = object({
17044
+ registryId: string().min(1),
17045
+ id: string().min(1),
17046
+ width: number().int().positive(),
17047
+ height: number().int().positive(),
17048
+ format: _enum(["rgb", "gray"]),
17049
+ timestamp: number(),
17050
+ capturedAt: number().optional()
17051
+ });
17052
+ var ModelFormatSchema$1 = _enum([
17053
+ "onnx",
17054
+ "coreml",
17055
+ "openvino",
17056
+ "tflite",
17057
+ "pt",
17058
+ "gguf"
17060
17059
  ]);
17061
- var EventKindCategorySchema = _enum([
17062
- "motion",
17063
- "audio",
17064
- "detection",
17065
- "sensor",
17066
- "control",
17067
- "custom",
17068
- "package"
17060
+ var PipelineSlotSchema = _enum([
17061
+ "detector",
17062
+ "cropper",
17063
+ "classifier",
17064
+ "refiner",
17065
+ "audio-classifier"
17069
17066
  ]);
17070
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
17071
- var EventKindLevelSchema = _enum(["macro", "sub"]);
17072
- var EventKindDescriptorSchema = object({
17073
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
17074
- kind: string(),
17075
- /** i18n key resolved on the UI side; `label` is the English fallback. */
17076
- labelKey: string(),
17077
- /** English fallback label (kept for clients that don't translate). */
17078
- label: string(),
17079
- /** Hex color for timeline/legend rendering. */
17080
- color: string(),
17081
- /** Dictionary id → lucide component on the UI side. */
17082
- iconId: string(),
17083
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
17084
- icon: EventKindIconSchema,
17085
- category: EventKindCategorySchema,
17086
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
17087
- parentKind: string().nullable(),
17088
- /** Derived from `parentKind`, explicit for the client tree. */
17089
- level: EventKindLevelSchema,
17090
- /** Which cap + device contributes this kind. For built-ins the camera
17091
- * itself; for sensor kinds the LINKED source device. */
17092
- source: object({
17093
- capName: string(),
17094
- deviceId: number()
17095
- })
17067
+ var PipelineEngineChoiceSchema = object({
17068
+ runtime: _enum(["node", "python"]),
17069
+ backend: string(),
17070
+ format: ModelFormatSchema$1,
17071
+ device: string().optional()
17096
17072
  });
17097
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
17098
- var EventKindsForDeviceSchema = object({
17099
- deviceId: number(),
17100
- kinds: array(EventKindDescriptorSchema).readonly()
17073
+ var AvailableEngineSchema = object({
17074
+ engine: PipelineEngineChoiceSchema,
17075
+ devices: array(object({
17076
+ id: string(),
17077
+ label: string(),
17078
+ description: string().optional()
17079
+ })).readonly(),
17080
+ defaultDevice: string()
17101
17081
  });
17102
- var SensorEventSchema = object({
17082
+ var PipelineDefaultStepSchema = lazy(() => object({
17083
+ addonId: string(),
17084
+ addonName: string(),
17085
+ slot: PipelineSlotSchema,
17086
+ inputClasses: array(string()).readonly(),
17087
+ outputClasses: array(string()).readonly(),
17088
+ enabled: boolean(),
17089
+ modelId: string(),
17090
+ children: array(PipelineDefaultStepSchema).readonly(),
17091
+ group: string().optional(),
17092
+ settings: record(string(), unknown()).optional()
17093
+ }));
17094
+ var PipelineTemplateStepSchema = lazy(() => object({
17095
+ addonId: string(),
17096
+ enabled: boolean(),
17097
+ modelId: string(),
17098
+ children: array(PipelineTemplateStepSchema).readonly(),
17099
+ settings: record(string(), unknown()).optional()
17100
+ }));
17101
+ var PipelineTemplateSchema$1 = object({
17103
17102
  id: string(),
17104
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
17105
- * yields N rows, one per camera). */
17106
- deviceId: number(),
17107
- /** The linked sensor device whose state changed. */
17108
- sourceDeviceId: number(),
17109
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
17110
- kind: string(),
17111
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
17112
- value: record(string(), unknown()).nullable(),
17113
- timestamp: number()
17114
- });
17115
- var TrackPositionSchema = object({
17116
- x: number(),
17117
- y: number(),
17118
- timestamp: number(),
17119
- bbox: BoundingBoxSchema
17103
+ name: string(),
17104
+ createdAt: string(),
17105
+ updatedAt: string(),
17106
+ engine: PipelineEngineChoiceSchema,
17107
+ steps: array(PipelineTemplateStepSchema).readonly()
17120
17108
  });
17121
- var TrackSnapshotSchema = object({
17122
- timestamp: number(),
17123
- position: TrackPositionSchema,
17124
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
17125
- mediaKey: string()
17109
+ var PipelineModelOptionSchema = object({
17110
+ id: string(),
17111
+ name: string(),
17112
+ formats: record(string(), object({
17113
+ downloaded: boolean(),
17114
+ sizeMB: number()
17115
+ })),
17116
+ group: ModelVariantGroupSchema.optional(),
17117
+ legacy: boolean().optional(),
17118
+ provider: ModelProviderIdSchema.optional()
17126
17119
  });
17127
- /**
17128
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
17129
- * divided by the track's detection-frame dims), computed at persist time.
17130
- * Absent when the frame dims were unknown when the track was persisted
17131
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
17132
- */
17133
- var TrackEnvelopeSchema = object({
17134
- minX: number(),
17135
- minY: number(),
17136
- maxX: number(),
17137
- maxY: number()
17120
+ var ConfigFieldBridge = custom();
17121
+ var PipelineAddonSchemaSchema = object({
17122
+ id: string(),
17123
+ name: string(),
17124
+ slot: PipelineSlotSchema,
17125
+ inputClasses: array(string()).readonly(),
17126
+ outputClasses: array(string()).readonly(),
17127
+ childSlots: array(PipelineSlotSchema).readonly(),
17128
+ models: array(PipelineModelOptionSchema).readonly(),
17129
+ defaultModelId: string(),
17130
+ defaultModelIdByFormat: record(string(), string()).optional(),
17131
+ enabledByDefault: boolean().optional(),
17132
+ backfillIntoExistingOverrides: boolean().optional(),
17133
+ defaultConfidence: number(),
17134
+ group: string().optional(),
17135
+ configSchema: array(ConfigFieldBridge).readonly().optional()
17138
17136
  });
17139
- /**
17140
- * Row projection for track list queries. `full` (default) returns the
17141
- * complete Track including the frame-rate `positions[]` history and the
17142
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
17143
- * keeps every scalar the list surfaces actually render (ids, class(es),
17144
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
17145
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
17146
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
17147
- * `getTrack`. Mirrors the event-store `projection` convention
17148
- * (`getObjectEvents` et al.).
17149
- */
17150
- var TrackProjectionSchema = _enum(["full", "slim"]);
17151
- /**
17152
- * One audio-classification label heard on the track's camera while the
17153
- * track was alive, aggregated per label. An "episode" is one persisted
17154
- * audio event (the confident-classification path: score ≥ the device's
17155
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
17156
- * one 32 ms inference chunk, so counts stay human-scaled.
17157
- */
17158
- var TrackAudioLabelSchema = object({
17137
+ var PipelineSlotSchemaSchema = object({
17138
+ id: PipelineSlotSchema,
17159
17139
  label: string(),
17160
- /** Highest classification score observed across the label's episodes. */
17161
- peakScore: number(),
17162
- /** Number of coalesced audio-event episodes carrying this label. */
17163
- count: number(),
17164
- firstAt: number(),
17165
- lastAt: number()
17140
+ priority: number(),
17141
+ parentSlot: PipelineSlotSchema.nullable(),
17142
+ addons: array(PipelineAddonSchemaSchema).readonly()
17166
17143
  });
17167
- /**
17168
- * How a track was produced. `pipeline` (default / absent) = the spatial
17169
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
17170
- * no positions, a single snapshot, and no bbox trajectory at all:
17171
- *
17172
- * - `sensor` — a linked sensor/control device state change.
17173
- * - `audio` — an audio event on the camera itself that was anomalous for
17174
- * THAT camera, loud, and heard while nothing visual was happening (D62).
17175
- *
17176
- * The spatial subsystems (tracker association, occupancy count, re-id /
17177
- * embedding, resurrection) MUST skip every synthetic source. Test for that
17178
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
17179
- * check silently readmits every source added after it was written.
17180
- */
17181
- var TrackSourceSchema = _enum([
17182
- "pipeline",
17183
- "sensor",
17184
- "audio"
17185
- ]);
17186
- /**
17187
- * Where a track sits in the RETRAIN lifecycle (D81).
17188
- *
17189
- * - `none` — never marked, or un-marked. Evictable.
17190
- * - `staging` — the operator wants this track as training material and has not
17191
- * finished with it. **This is the only state retention holds**: the track and
17192
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
17193
- * the device's age window.
17194
- * - `trained` — the retrain page has taken what it needed. The frames it chose
17195
- * were COPIED into the retrain dataset at selection time, so the dataset no
17196
- * longer depends on the track's media and the track becomes EVICTABLE again.
17197
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
17198
- * a deliberate action of the retrain page, not a side effect of a checkbox.
17199
- *
17200
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
17201
- * the store's filter language has only positive equality and `whereIn` — no
17202
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
17203
- * would make the entire pre-column history immortal in one deploy.
17204
- */
17205
- var RetrainStatusSchema = _enum([
17206
- "none",
17207
- "staging",
17208
- "trained"
17209
- ]);
17210
- /**
17211
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
17212
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
17213
- * so the two surfaces cannot drift.
17214
- *
17215
- * **Absent ≠ false.** A track that has never been touched omits the field; an
17216
- * explicitly un-flagged track carries `false`. Legacy rows written before the
17217
- * columns existed read as absent, and a consumer that needs a boolean should say
17218
- * `flag === true`, not `flag !== false`.
17219
- *
17220
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
17221
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
17222
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
17223
- * `trained` track reports `false` while refusing both writes. The boolean is
17224
- * kept because three surfaces drive a toggle off it; anything that needs to tell
17225
- * "never marked" from "already trained" must read `retrainStatus`.
17226
- *
17227
- * `debug` does NOT pin; it is attention, not durability.
17228
- *
17229
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
17230
- * A favourited track is skipped by retention the same way `staging` is, but
17231
- * it does not enter `none|staging|trained` and has no staging budget.
17232
- */
17233
- var TrackFlagFields = {
17234
- /** Operator marked this track as training material — i.e. `retrainStatus` is
17235
- * `'staging'`. */
17236
- markForTrain: boolean().optional(),
17237
- /** Operator marked this track for diagnostic attention. */
17238
- debug: boolean().optional(),
17239
- /** Operator favourited this track. Pins it against pruning. */
17240
- favourited: boolean().optional()
17241
- };
17242
- /**
17243
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
17244
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
17245
- * write patch, and the status is not something the toggle sets — it is what the
17246
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
17247
- * always present on a persisted row (the column default materialises `'none'`).
17248
- */
17249
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
17250
- /**
17251
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
17252
- * one flag can never clear the other — the toggles are independent and are
17253
- * driven from three surfaces that do not know about each other.
17254
- */
17255
- var TrackFlagsPatchSchema = object(TrackFlagFields);
17256
- /**
17257
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
17258
- * collapses to `false`) so a caller can drive a toggle's checked state off the
17259
- * mutation result without a re-fetch.
17260
- */
17261
- var TrackFlagsSchema = object({
17262
- trackId: string(),
17263
- markForTrain: boolean(),
17264
- debug: boolean(),
17265
- favourited: boolean(),
17266
- /** The lifecycle state the boolean was derived from. Required here (unlike on
17267
- * a track row) because this shape is only ever produced by the write body,
17268
- * which always knows it — and a surface that has just written needs to render
17269
- * `trained` without a re-fetch. */
17270
- retrainStatus: RetrainStatusSchema
17144
+ var PipelineSchemaSchema = object({
17145
+ availableEngines: array(AvailableEngineSchema).readonly(),
17146
+ selectedEngine: PipelineEngineChoiceSchema,
17147
+ slots: array(PipelineSlotSchemaSchema).readonly()
17271
17148
  });
17272
- union([literal(1), literal(2)]);
17273
- /**
17274
- * WHO decided a label, and when. Carried per tier so a value can be traced to
17275
- * the step and model that produced it — which is what makes the write rule
17276
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
17277
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
17278
- *
17279
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
17280
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
17281
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
17282
- * that value has no provenance, and the write rule lets ANY properly-attributed
17283
- * write of the same tier replace it regardless of score.
17284
- */
17285
- var LabelAttributionSchema = object({
17286
- stepId: string(),
17287
- modelId: string().optional(),
17288
- decidedAt: number(),
17149
+ var EngineProvisioningSchema = object({
17150
+ runtimeId: _enum([
17151
+ "onnx",
17152
+ "openvino",
17153
+ "coreml",
17154
+ "edgetpu"
17155
+ ]).nullable(),
17156
+ device: string().nullable(),
17157
+ state: _enum([
17158
+ "idle",
17159
+ "installing",
17160
+ "verifying",
17161
+ "ready",
17162
+ "failed"
17163
+ ]),
17164
+ progress: number().optional(),
17165
+ error: string().optional(),
17166
+ nextRetryAt: number().optional(),
17289
17167
  /**
17290
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
17291
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
17292
- *
17293
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
17294
- * notification rule authored on "Gianluca" stopped matching the moment the
17295
- * operator fixed the spelling in the gallery, and nothing said so. The id is
17296
- * the thing that does not move, so it is what a rule matches on
17297
- * (`NcConditions.identities`) and the text is what a human is shown.
17298
- *
17299
- * Absent when the label names no gallery row — a plate the OCR read but no
17300
- * vehicle claims, a sub-class, a species, any tier-1 value.
17168
+ * Gate A (config-correctness gate at engine change): human-readable
17169
+ * config issues surfaced EAGERLY when the node's engine changes — model
17170
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
17171
+ * has a <format> build"). Additive/optional: informational only, never
17172
+ * enforced here `assertEngineReady` (readiness) still gates inference.
17173
+ * Absent/empty when the node-default tree resolves cleanly.
17301
17174
  */
17302
- identityId: string().optional()
17175
+ configIssues: array(string()).optional()
17303
17176
  });
17304
- /**
17305
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
17306
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
17307
- * track and its events always answer the same question the same way.
17308
- *
17309
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
17310
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
17311
- * is tier 2, and each carries its own score + attribution.
17312
- *
17313
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
17314
- * finest thing known. Before 4g the single `label` column held the finest
17315
- * value, so a consumer that has not been updated reads the tier-1 slot and
17316
- * shows nothing on a species-only row; that is why the migration puts every
17317
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
17318
- * and why the read surfaces were changed in the same train.
17319
- *
17320
- * **Writing it.** The slots are independent, which is the whole point: a
17321
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
17322
- * migratorius`), so fineness cannot regress by construction. Within a tier the
17323
- * higher score wins. One rule, one implementation — see
17324
- * `pipeline/label-tier.ts` in addon-post-analysis.
17325
- */
17326
- var TieredLabelFields = {
17327
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
17328
- label: string().optional(),
17329
- /** Confidence of the tier-1 value, as reported by the deciding step. */
17330
- labelScore: number().optional(),
17331
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
17332
- labelMeta: LabelAttributionSchema.optional(),
17333
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
17334
- subLabel: string().optional(),
17335
- /** Confidence of the tier-2 value, as reported by the deciding step. */
17336
- subLabelScore: number().optional(),
17337
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
17338
- subLabelMeta: LabelAttributionSchema.optional()
17339
- };
17340
- /** Per-camera slice of a training-export estimate. */
17341
- var TrainingExportDeviceTotalsSchema = object({
17342
- deviceId: number(),
17343
- tracks: number().int(),
17344
- files: number().int(),
17345
- bytes: number().int()
17177
+ var PipelineStepInputSchema = lazy(() => object({
17178
+ addonId: string(),
17179
+ modelId: string().optional(),
17180
+ enabled: boolean().default(true),
17181
+ children: array(PipelineStepInputSchema).optional(),
17182
+ settings: record(string(), unknown()).optional(),
17183
+ jumpDeviceKey: string().optional()
17184
+ }));
17185
+ var ModelSubstitutionSchema = object({
17186
+ addonId: string(),
17187
+ chosen: string(),
17188
+ running: string(),
17189
+ format: string()
17346
17190
  });
17347
- /**
17348
- * What a training export WOULD contain. Computed from media index rows only —
17349
- * no blob is read to produce this.
17350
- */
17351
- var TrainingExportSummarySchema = object({
17352
- generatedAt: number(),
17353
- trackCount: number().int(),
17354
- fileCount: number().int(),
17355
- byteCount: number().int(),
17356
- /** More marked tracks exist than a single pass carries. */
17357
- truncated: boolean(),
17358
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
17191
+ var PipelineValidationIssueSchema = object({
17192
+ addonId: string(),
17193
+ kind: _enum(["unknown-addon", "no-format-build"]),
17194
+ detail: string()
17359
17195
  });
17360
- var TrackSchema = object({
17361
- trackId: string(),
17362
- deviceId: number(),
17363
- className: string(),
17364
- ...TieredLabelFields,
17365
- producingDeviceName: string().optional(),
17366
- /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
17367
- source: TrackSourceSchema.optional(),
17368
- firstSeen: number(),
17369
- lastSeen: number(),
17370
- /** Frame-rate position history (subject to maxPositionHistory cap). */
17371
- positions: array(TrackPositionSchema).readonly(),
17372
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
17373
- * saveThumbnails policy). */
17374
- snapshots: array(TrackSnapshotSchema).readonly(),
17375
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
17376
- zonesVisited: array(string()).readonly(),
17377
- /**
17378
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
17379
- * `zones` capability.
17380
- *
17381
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
17382
- * and no card can render — so every free-text search surface was structurally
17383
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
17384
- * just returned nothing. Resolving here rather than in each client keeps ONE
17385
- * derivation and costs the clients no extra call (the `zones` cap is
17386
- * per-device, so a client-side resolve would be a per-camera fan-out on a
17387
- * surface built to avoid exactly that).
17388
- *
17389
- * Resolved, never invented: a zone deleted since the track was written has no
17390
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
17391
- * two are not positionally aligned. Absent when the track visited no zone, or
17392
- * when the zone catalogue could not be read.
17393
- */
17394
- zoneNames: array(string()).readonly().optional(),
17395
- /** Deduplicated set of detector classes observed for this track over its
17396
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
17397
- * legacy rows written before class accumulation shipped. */
17398
- classes: array(string()).readonly().optional(),
17399
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
17400
- totalDistance: number(),
17401
- state: TrackStateSchema,
17402
- active: boolean(),
17403
- /** Deterministic key-event importance score in [0,1] (server-computed at
17404
- * track expiry, recomputed on late label). Absent on legacy rows written
17405
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
17406
- importance: number().optional(),
17407
- /** Id of the track's highest-confidence ObjectEvent (its representative
17408
- * "best" frame). Absent when the track produced no object events. */
17409
- bestEventId: string().optional(),
17410
- /** Tag of the importance sub-signal that dominated the score
17411
- * (identity|dwell|proximity|class|confidence|travel|zone). */
17412
- importanceReason: string().optional(),
17413
- /** Audio-classification labels heard on the camera during the track's
17414
- * life (score ≥ device `classificationMinScore`), aggregated per label.
17415
- * Absent on legacy rows / tracks with no confident audio. */
17416
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
17417
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
17418
- * Populated from the persisted envelope columns on historical reads;
17419
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
17420
- envelope: TrackEnvelopeSchema.optional(),
17421
- /**
17422
- * A face DETECTOR found a face on this track — nothing more. It says the
17423
- * detail plane produced a `face` detail; it does NOT say the face was
17424
- * embedded, matched, above `minFacePx`, or that the recognizer was even
17425
- * enabled. Set once and never cleared.
17426
- *
17427
- * **This exists so "face present but not recognised" is expressible.** A
17428
- * recognised identity lands in `subLabel` (attributed to the face chain via
17429
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
17430
- * and a track with no face at all were byte-identical on the wire and no
17431
- * surface could tell them apart. The read is `hasFace === true && subLabel
17432
- * === undefined`.
17433
- *
17434
- * **Absent ≠ false.** Every row written before the column existed omits it,
17435
- * and so does every server that predates the field — a consumer must test
17436
- * `=== true` and render nothing otherwise, never infer "no face".
17437
- */
17438
- hasFace: boolean().optional(),
17439
- /**
17440
- * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
17441
- * face an operator could ASSIGN to an identity.
17442
- *
17443
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
17444
- * because the two disagree. `hasFace` is stamped at the TOP of the face
17445
- * branch, before every gate, and means no more than "a face detector produced
17446
- * a face detail". This one is stamped at the single moment the gallery row
17447
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
17448
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
17449
- * candidate gate, the imageless-track drop (no crop was ever captured) and
17450
- * the crop-store drop. Everything between the detector and that insert can
17451
- * legitimately refuse the face, so a flag written any earlier promises the
17452
- * operator something to assign and delivers nothing.
17453
- *
17454
- * **Independent of recognition.** A face collected but never auto-matched is
17455
- * still assignable — it is in fact the face an operator most wants to reach —
17456
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
17457
- * `subLabel`; this says only that the raw material exists.
17458
- *
17459
- * **Set once, never cleared.** A track that produced a gallery row produced
17460
- * one; deleting the row later is the gallery's business, not this flag's.
17461
- *
17462
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
17463
- * before the column omits it, and so does every server that predates the
17464
- * field. A consumer must test `=== true` and render nothing otherwise —
17465
- * never infer "no assignable face".
17466
- */
17467
- hasEmbeddedFace: boolean().optional(),
17468
- /**
17469
- * This subject CONTAINS a folded rider — a person the rider-pairing step
17470
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
17471
- * so the passage is tracked once and as a VEHICLE.
17472
- *
17473
- * It exists because the fold's record was dishonest. D34 and the code both
17474
- * said "the person is not lost — it is reported so both entities stay on the
17475
- * record"; in fact the pair went into a per-processor RAM field behind an
17476
- * accessor nobody called, and every durable surface said `vehicle`, full
17477
- * stop. This is the composition note that makes the row true.
17478
- *
17479
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
17480
- * person" is not an answer to "what is this" — both label tiers would refuse
17481
- * a macro token anyway (D89), and correctly. Nothing here changes what the
17482
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
17483
- * and a `person` rule still does not fire for someone cycling past.
17484
- *
17485
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
17486
- * the column, and every hub that predates the field, omits it. Test
17487
- * `=== true` and render nothing otherwise — never infer "no rider".
17488
- */
17489
- hasRider: boolean().optional(),
17490
- ...TrackFlagFields,
17491
- ...TrackRetrainFields
17196
+ var PipelineValidationResultSchema = object({
17197
+ ok: boolean(),
17198
+ issues: array(PipelineValidationIssueSchema).readonly(),
17199
+ substitutions: array(ModelSubstitutionSchema).readonly(),
17200
+ /** The node's `currentEngine.format` this validation ran against. */
17201
+ format: string()
17492
17202
  });
17493
- var BaseEventFields = {
17494
- id: string(),
17495
- deviceId: number(),
17496
- timestamp: number()
17497
- };
17498
- var MotionEventSchema = object({
17499
- ...BaseEventFields,
17500
- kind: literal("motion"),
17501
- regionCount: number(),
17502
- /** Heavy JSON array — omitted in slim projection. */
17503
- regions: array(object({
17504
- bbox: BoundingBoxSchema,
17505
- pixelCount: number(),
17506
- intensity: number()
17507
- })).readonly().optional(),
17508
- /** Omitted in slim projection. */
17509
- frameWidth: number().optional(),
17510
- /** Omitted in slim projection. */
17511
- frameHeight: number().optional(),
17512
- /** Populated by B5 (recording playback URL for this event). */
17513
- mediaUrl: string().optional()
17203
+ var ReferenceImageEntrySchema = object({
17204
+ filename: string(),
17205
+ stepIds: array(string()).readonly().optional()
17514
17206
  });
17515
- /**
17516
- * Which detection SOURCE produced an object event. `pipeline` = the ML
17517
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
17518
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
17519
- * tracking, per-kind persistence) but stay distinguishable so consumers
17520
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
17521
- * Absent on legacy rows ⇒ treat as `pipeline`.
17522
- */
17523
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
17524
- /**
17525
- * The confirmed zone crossing that produced an object event. Present ONLY on
17526
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
17527
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
17528
- * appearance event carry none, so a rule asking for a direction fails closed
17529
- * on them.
17530
- *
17531
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
17532
- * into its own event, so a frame in which a track enters A while leaving B
17533
- * produces two events with two directions — never one ambiguous row.
17534
- *
17535
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
17536
- * membership the box has NOW, and by definition it no longer contains the zone
17537
- * that was just left. Without the id here, a zone-scoped rule could never match
17538
- * the exit it asked for.
17539
- */
17540
- var ZoneCrossingSchema = object({
17541
- direction: _enum(["enter", "exit"]),
17542
- /** Admin zone id crossed. */
17543
- zoneId: string(),
17544
- /** Zone display name at crossing time (falls back to the id). */
17545
- zoneName: string().optional()
17207
+ var ReferenceImageBodySchema = object({
17208
+ base64: string(),
17209
+ filename: string()
17546
17210
  });
17547
- var ObjectEventSchema = object({
17548
- ...BaseEventFields,
17549
- kind: literal("object"),
17550
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
17551
- source: DetectionSourceSchema.optional(),
17552
- /**
17553
- * Inference-frame id shared by every object event emitted from the SAME frame
17554
- * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
17555
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
17556
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
17557
- * Optional for backward-compat with pre-existing rows / the slim projection
17558
- * includes it (it is light). Absent on rows written before this field.
17559
- */
17560
- frameId: string().optional(),
17561
- /** Omitted in slim projection. */
17562
- trackId: string().optional(),
17563
- className: string(),
17564
- ...TieredLabelFields,
17565
- /** Omitted in slim projection. */
17566
- confidence: number().optional(),
17567
- /** Heavy JSON — omitted in slim projection. */
17568
- bbox: BoundingBoxSchema.optional(),
17569
- /** Heavy JSON — omitted in slim projection. */
17570
- zones: array(string()).readonly().optional(),
17571
- /** Omitted in slim projection. */
17572
- state: TrackStateSchema.optional(),
17211
+ var ReferenceAudioEntrySchema = object({
17212
+ filename: string(),
17213
+ sizeKb: number()
17214
+ });
17215
+ var ReferenceAudioBodySchema = object({ base64: string() });
17216
+ var AudioBackendSchema = object({
17217
+ id: string(),
17218
+ name: string(),
17219
+ description: string(),
17220
+ available: boolean(),
17573
17221
  /**
17574
- * The zone crossing this event IS, when it is one. Absent on every other
17575
- * event kind (movement state, appearance, package) see
17576
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
17222
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
17223
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
17224
+ * the benchmark UI to populate the `enabledMicroClasses` filter
17225
+ * specific to the selected backend without a separate fetch.
17577
17226
  */
17578
- zoneCrossing: ZoneCrossingSchema.optional(),
17579
- /** Detection-frame dimensions in pixels — let consumers normalize the
17580
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
17581
- frameWidth: number().optional(),
17582
- frameHeight: number().optional(),
17583
- /** MediaStore key for the crop attached to this event (if any). */
17584
- mediaKey: string().optional(),
17585
- /** Design B: MediaStore key of the track's native-resolution key frame (the
17586
- * best-detection full frame). Resolve via the event-media data-plane
17587
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
17588
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
17589
- * sources — consumers fall back to `mediaKey` (the tight crop). */
17590
- keyFrameMediaKey: string().optional(),
17591
- /** Populated by B5 (recording playback URL for this event). */
17592
- mediaUrl: string().optional(),
17593
- /** The parent track's key-event importance [0,1], propagated to every object
17594
- * event of the track (so an event row can be sorted by importance without a
17595
- * track join). Absent on legacy rows / before the track was scored. */
17596
- importance: number().optional()
17227
+ rawLabels: array(string()).readonly().optional()
17597
17228
  });
17598
- var AudioEventSchema = object({
17599
- ...BaseEventFields,
17600
- kind: literal("audio"),
17601
- rms: number(),
17602
- dbfs: number(),
17603
- classification: object({
17604
- className: string(),
17605
- originalClass: string().optional(),
17606
- score: number()
17607
- }).optional(),
17608
- /** Populated by B5 (recording playback URL for this event). */
17609
- mediaUrl: string().optional()
17229
+ var AudioCapabilitiesSchema = object({
17230
+ activeBackend: string(),
17231
+ availableBackends: array(AudioBackendSchema).readonly(),
17232
+ sampleRate: number(),
17233
+ chunkDurationMs: number()
17610
17234
  });
17611
- var MediaFileKindEnum = _enum([
17612
- "crop",
17613
- "thumbnail",
17614
- "snapshot",
17615
- "firstFrame",
17616
- "lastFrame",
17617
- "fullFrame",
17618
- "fullFrameBoxed",
17619
- "faceCrop",
17620
- "plateCrop",
17621
- "keyFrame",
17622
- "keyFrameSmall",
17623
- "thumbnailSmall"
17624
- ]);
17625
- var MediaFileSchema = object({
17626
- key: string(),
17627
- kind: MediaFileKindEnum,
17628
- base64: string(),
17629
- sizeBytes: number(),
17630
- timestamp: number()
17235
+ var DownloadModelResultSchema = object({
17236
+ filePath: string(),
17237
+ sizeMB: number(),
17238
+ durationMs: number()
17631
17239
  });
17632
17240
  /**
17633
- * One media row WITHOUT its bytes.
17634
- *
17635
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
17636
- * 140 s track), and a client that renders tiles from the media data plane needs
17637
- * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
17638
- * with an immutable cache, instead of all at once inside a tRPC response that
17639
- * blocks the whole view.
17640
- *
17641
- * `sizeBytes` is carried because it is what lets a client decide between the
17642
- * stored blob and a `?variant=thumb` rendering without fetching either.
17643
- */
17644
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
17645
- /**
17646
- * The MACRO tier of an annotation — a CLOSED set.
17647
- *
17648
- * This is what the exported detector predicts, so a typo here is a new class
17649
- * with one example in it. `label` and `subLabel` are open strings by contrast:
17650
- * the whole point of the page is teaching the model things it does not know
17651
- * yet, and constraining that vocabulary would make it useless.
17652
- *
17653
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
17654
- * `subLabel` is one of these values, in any casing, because once `person`
17655
- * exists in both tiers "every person box" stops being answerable without
17656
- * knowing every string anyone ever typed — and the damage is retroactive.
17241
+ * Wrapper carrying a single test run's result. Replaces the legacy
17242
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
17243
+ * canonical `AudioResult` from the Phase 6 output rework: one
17244
+ * `AudioDetection` per class above `minScore`, top-N candidates in
17245
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
17246
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
17247
+ * benchmark UI can still report a clean failure when the classifier
17248
+ * cap isn't available.
17657
17249
  */
17658
- var RetrainMacroClassSchema = _enum([
17659
- "person",
17660
- "vehicle",
17661
- "animal",
17662
- "package",
17663
- "face",
17664
- "plate"
17665
- ]);
17666
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
17667
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
17668
- /** Did a human draw this box, or did the assist propose it? */
17669
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
17670
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
17671
- var RetrainBboxSchema = object({
17672
- x: number(),
17673
- y: number(),
17674
- w: number(),
17675
- h: number()
17250
+ var AudioTestResultSchema = object({
17251
+ success: boolean(),
17252
+ error: string().optional(),
17253
+ frame: custom().optional()
17676
17254
  });
17255
+ var PipelineConfigBridge = custom();
17256
+ var ConfigUISchemaBridge = custom();
17257
+ var ConfigUISchemaNullableBridge = custom();
17258
+ var InferenceCapabilitiesBridge = custom();
17259
+ var ModelAvailabilityListBridge = custom();
17260
+ var PipelineRunResultBridge = custom();
17677
17261
  /**
17678
- * One annotated subject.
17262
+ * Pipeline executor — detection engine + configuration + inference API.
17679
17263
  *
17680
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
17681
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
17682
- * derived from it at export and never stored — storing them is how one feature
17683
- * space ends up holding two crops of the same subject (D52).
17684
- */
17685
- var RetrainAnnotationSchema = object({
17686
- id: string(),
17687
- trackId: string(),
17688
- deviceId: number(),
17689
- /** The COPY in retrain storage — never the source track's media key. */
17690
- mediaKey: string(),
17691
- bbox: RetrainBboxSchema,
17692
- macroClass: RetrainMacroClassSchema,
17693
- label: string().optional(),
17694
- subLabel: string().optional(),
17695
- kind: RetrainAnnotationKindSchema,
17696
- source: RetrainAnnotationSourceSchema,
17697
- /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
17698
- assistModelId: string().optional(),
17699
- assistScore: number().optional(),
17700
- exportedInBatch: string().optional(),
17701
- createdAt: number()
17702
- });
17703
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
17704
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
17705
- id: true,
17706
- trackId: true,
17707
- deviceId: true,
17708
- mediaKey: true,
17709
- createdAt: true,
17710
- exportedInBatch: true
17711
- });
17712
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
17713
- var RetrainTrackSchema = object({
17714
- trackId: string(),
17715
- deviceId: number(),
17716
- className: string(),
17717
- label: string().optional(),
17718
- firstSeen: number(),
17719
- lastSeen: number(),
17720
- /** How many frames the dataset already holds from this track. */
17721
- frameCount: number().int(),
17722
- /** How many subjects have been annotated on those frames. `0` with
17723
- * `frameCount: 0` is exactly "staging, still to work". */
17724
- annotationCount: number().int()
17725
- });
17726
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
17727
- var RetrainFrameCandidateSchema = object({
17728
- mediaKey: string(),
17729
- kind: MediaFileKindEnum,
17730
- timestamp: number(),
17731
- sizeBytes: number().int(),
17732
- /** A copy of this original already exists — selecting it is free and cannot
17733
- * fail, whatever became of the original. */
17734
- copied: boolean()
17735
- });
17736
- /** A frame the dataset OWNS: bytes copied at selection time. */
17737
- var RetrainFrameSchema = object({
17738
- frameId: string(),
17739
- deviceId: number(),
17740
- trackId: string(),
17741
- /** Provenance only. It may already point at nothing — that is expected. */
17742
- sourceMediaKey: string(),
17743
- sourceKind: MediaFileKindEnum,
17744
- sizeBytes: number().int(),
17745
- width: number().int(),
17746
- height: number().int(),
17747
- copiedAt: number()
17748
- });
17749
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
17750
- var RetrainCopyRefusalSchema = _enum([
17751
- "source-missing",
17752
- "unreadable-image",
17753
- "write-failed"
17754
- ]);
17755
- var RetrainFrameSelectionSchema = object({
17756
- copied: array(RetrainFrameSchema).readonly(),
17757
- refused: array(object({
17758
- sourceMediaKey: string(),
17759
- reason: RetrainCopyRefusalSchema
17760
- })).readonly()
17761
- });
17762
- var RetrainFrameListSchema = object({
17763
- candidates: array(RetrainFrameCandidateSchema).readonly(),
17764
- copies: array(RetrainFrameSchema).readonly(),
17765
- /** What the page pre-selects — the native key frame when one survives. */
17766
- autoPickMediaKey: string().optional()
17767
- });
17768
- /** What the operator asked the assist to look for. */
17769
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
17770
- kind: literal("package"),
17771
- zone: RetrainBboxSchema.optional()
17772
- }), object({
17773
- kind: literal("objects"),
17774
- modelId: string(),
17775
- minScore: number().optional()
17776
- })]);
17777
- /**
17778
- * The assist's answer — a discriminated union, because "the model saw nothing"
17779
- * and "this node cannot run that model" lead to different next moves and a
17780
- * nullable result cannot tell them apart.
17264
+ * Merged from: pipeline-executor, pipeline-config, inference, detection-config.
17265
+ * Implemented by the detection-pipeline addon.
17266
+ *
17267
+ * Per-device surface (DeviceSettingsContribution + the "is detection
17268
+ * enabled for this camera?" toggle) lives on the paired
17269
+ * `detection-pipeline` cap (device-scoped, singleton, wrapper
17270
+ * defaultActive) — same split pattern used by stream-broker /
17271
+ * camera-streams and audio-analyzer / audio-analysis.
17781
17272
  */
17782
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
17783
- kind: literal("proposed"),
17784
- modelId: string(),
17785
- stepId: string(),
17786
- minScore: number(),
17787
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
17788
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
17789
- /** Returned by the runner but removed by the threshold. */
17790
- belowThreshold: number().int()
17791
- }), object({
17792
- kind: literal("refused"),
17793
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
17794
- reason: string(),
17795
- detail: string().optional()
17796
- })]);
17797
- /** The outcome of a lifecycle move owned by the retrain page. */
17798
- var RetrainTransitionResultSchema = object({
17799
- trackId: string(),
17800
- /** Where the track ended up, whatever happened. */
17801
- retrainStatus: RetrainStatusSchema,
17802
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
17803
- changed: boolean(),
17804
- reason: _enum([
17805
- "unknown-track",
17806
- "no-frames-copied",
17807
- "not-staging",
17808
- "not-trained",
17809
- "unchanged"
17810
- ]).optional()
17811
- });
17812
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
17813
- var MAX_EVENT_QUERY_LIMIT = 5e3;
17814
- var DeviceEventQueryInput = object({
17815
- deviceId: number(),
17816
- since: number().optional(),
17817
- until: number().optional(),
17818
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
17819
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
17820
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
17821
- * exact behaviour. Callers may omit this field the store defaults to
17822
- * `full` when not provided. */
17823
- projection: _enum(["full", "slim"]).optional()
17824
- });
17825
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
17826
- var RecentTracksQueryInput = object({
17827
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
17828
- deviceIds: array(number()),
17829
- /** Window lower bound on `lastSeen` (inclusive). */
17830
- since: number().optional(),
17831
- /** Window upper bound on `lastSeen` (inclusive). */
17832
- until: number().optional(),
17833
- /** Page size. Default 200, max 1000. */
17834
- limit: number().int().min(1).max(1e3).default(200),
17835
- /** Opaque continuation cursor from a previous page's `nextCursor`.
17836
- * Encodes the (lastSeen, trackId) sort position treat as opaque. */
17837
- cursor: string().optional(),
17838
- /** See {@link TrackProjectionSchema}. Default `full`. */
17839
- projection: TrackProjectionSchema.optional(),
17840
- /** Include stationary-promoted rows (parked objects). Default false: the
17841
- * feed lists passages; parking records live on the stationary registry. */
17842
- includeStationary: boolean().optional()
17843
- });
17844
- var RecentTracksPageSchema = object({
17845
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
17846
- tracks: array(TrackSchema).readonly(),
17847
- /** Cursor for the next page, or null when this page is the last. */
17848
- nextCursor: string().nullable()
17849
- });
17850
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
17851
- var LIST_GROUPS_MAX_LIMIT = 100;
17852
- var AnalyticsGroupRecordSchema = object({
17273
+ var pipelineExecutorCapability = {
17274
+ name: "pipeline-executor",
17275
+ scope: "system",
17276
+ mode: "singleton",
17277
+ methods: {
17278
+ getAvailableEngines: method(_void(), array(PipelineEngineChoiceSchema)),
17279
+ getSelectedEngine: method(_void(), PipelineEngineChoiceSchema),
17280
+ getDefaultSteps: method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)),
17281
+ /**
17282
+ * Per-node detection-engine provisioning snapshot. Returns the live
17283
+ * state of the lazy runtime-provisioning machine on `nodeId`
17284
+ * (idle / installing / verifying / ready / failed). The UI pairs this
17285
+ * one-shot query with the `pipeline.engine-provisioning` live event
17286
+ * (emitted on every transition) to drive a per-node "engine ready?"
17287
+ * indicator without polling. Phase 2.
17288
+ */
17289
+ getEngineProvisioning: method(object({ nodeId: string() }), EngineProvisioningSchema),
17290
+ getVideoPipelineSteps: method(_void(), record(string(), object({
17291
+ modelId: string(),
17292
+ settings: record(string(), unknown()).readonly()
17293
+ }))),
17294
+ setVideoPipelineSteps: method(object({ steps: record(string(), object({
17295
+ modelId: string(),
17296
+ settings: record(string(), unknown()).readonly()
17297
+ })) }), object({ success: literal(true) }), {
17298
+ kind: "mutation",
17299
+ auth: "admin"
17300
+ }),
17301
+ /**
17302
+ * Clear THIS node's executor-side PER-DEVICE settings stores (the
17303
+ * per-camera step overrides the object-detection root reads via
17304
+ * `applyDeviceOverridesToTree`). `nodeId` is the ROUTING key — the
17305
+ * generated cap-router strips it (default `nodeIdMode: 'routing'`) and
17306
+ * dispatches to that node, so the provider method runs ON the target
17307
+ * node and receives no `nodeId`.
17308
+ *
17309
+ * This is the slimmed executor leg of the orchestrator's
17310
+ * `resetNodePipelineDefaults` flow (which owns the real reset: node
17311
+ * addonDefaults pins + per-camera orchestrator overrides). The legacy
17312
+ * `resetToDefault` which reset a persisted global step-tree seed
17313
+ * nothing in the live per-camera path read — was removed together with
17314
+ * that seed.
17315
+ */
17316
+ clearDeviceOverrides: method(object({ nodeId: string() }), object({
17317
+ success: literal(true),
17318
+ clearedDevices: number()
17319
+ }), {
17320
+ kind: "mutation",
17321
+ auth: "admin"
17322
+ }),
17323
+ /**
17324
+ * Which of THIS node's inference devices the executor currently refuses,
17325
+ * and why. `nodeId` is the ROUTING key (stripped by the generated router).
17326
+ *
17327
+ * The channel that did not exist. Pool health was known only inside the
17328
+ * detection addon and was an input to no routing decision anywhere: the
17329
+ * per-dispatch capability gate is keyed on model FORMAT and so can never
17330
+ * separate `openvino:gpu` from `openvino:npu`, and the orchestrator's live
17331
+ * eligibility probe (`platformProbe.getCapabilities`) answers about
17332
+ * HARDWARE which was present throughout. So when the hub's `openvino:gpu`
17333
+ * Python worker was SIGABRT'd by the Intel GPU plugin on 2026-08-25, the
17334
+ * balancer went on handing that dead pool cameras by rotation for 31 hours:
17335
+ * ~370 000 `PoolWorker[w0]: not initialized` lines, every frame lost.
17336
+ *
17337
+ * Read semantics the caller depends on, and which the provider guarantees:
17338
+ * this is a synchronous read of in-memory state. It never probes hardware,
17339
+ * never spawns a pool and never throws — an EMPTY `unhealthy` means "asked,
17340
+ * nothing is refused", which is what re-admits a device. A read that FAILS
17341
+ * (node offline, version skew) must therefore be distinguishable from an
17342
+ * empty answer, and it is: it rejects.
17343
+ */
17344
+ getInferenceDeviceHealth: method(object({ nodeId: string() }), object({ unhealthy: array(object({
17345
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
17346
+ deviceKey: string(),
17347
+ /**
17348
+ * `failed` — the per-device restart budget is exhausted; no pool
17349
+ * will be spawned until an operator re-arms it or the runner
17350
+ * respawns. `backoff` — under budget, waiting out the backoff (or
17351
+ * a cached pool observed dead and not yet condemned).
17352
+ */
17353
+ state: _enum(["failed", "backoff"]),
17354
+ /** Epoch ms of the death that produced this state. */
17355
+ since: number(),
17356
+ /** Pool deaths inside the current window. */
17357
+ deaths: number(),
17358
+ /** The last death's message. */
17359
+ lastError: string()
17360
+ })).readonly() })),
17361
+ /**
17362
+ * Re-arm a terminally `failed` inference device on `nodeId`: forget its
17363
+ * restart budget so the next dispatch builds a fresh pool.
17364
+ *
17365
+ * The terminal state is deliberate (the abort it bounds is deterministic —
17366
+ * an automatic probation would just respawn Python forever, more slowly),
17367
+ * and a terminal state an operator cannot leave is a silent fault. This is
17368
+ * the way out. `rearmed:false` means there was nothing to forget.
17369
+ */
17370
+ rearmInferenceDevice: method(object({
17371
+ nodeId: string(),
17372
+ deviceKey: string()
17373
+ }), object({ rearmed: boolean() }), {
17374
+ kind: "mutation",
17375
+ auth: "admin"
17376
+ }),
17377
+ getSchema: method(_void(), PipelineSchemaSchema),
17378
+ getGlobalSteps: method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()),
17379
+ getGlobalPipelineConfig: method(_void(), PipelineConfigBridge),
17380
+ getOrchestratorConfigSchema: method(_void(), ConfigUISchemaBridge),
17381
+ /**
17382
+ * Gate B (pre-init config-correctness gate). PURE COMPUTE against this
17383
+ * node's `currentEngine.format` — resolves `steps` the same way the
17384
+ * runtime dispatch path would, and reports what WOULD happen without
17385
+ * touching any node-global state. Called by the orchestrator at attach
17386
+ * time (`attachOn`), node-pinned to the TARGET node, so config problems
17387
+ * surface BEFORE `pipelineRunner.attachCamera` rather than at the first
17388
+ * per-frame resolve. `ok` is false iff `issues` is non-empty (both
17389
+ * `unknown-addon` and `no-format-build` are HARD issues); `substitutions`
17390
+ * is informational (a degraded-but-loadable model swap) and never
17391
+ * affects `ok`. Never throws.
17392
+ */
17393
+ validatePipeline: method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema),
17394
+ listTemplates: method(_void(), array(PipelineTemplateSchema$1).readonly()),
17395
+ saveTemplate: method(object({
17396
+ name: string(),
17397
+ steps: array(PipelineTemplateStepSchema).readonly(),
17398
+ engine: PipelineEngineChoiceSchema
17399
+ }), PipelineTemplateSchema$1, { kind: "mutation" }),
17400
+ updateTemplate: method(object({
17401
+ id: string(),
17402
+ name: string().optional(),
17403
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
17404
+ }), PipelineTemplateSchema$1, { kind: "mutation" }),
17405
+ deleteTemplate: method(object({ id: string() }), _void(), { kind: "mutation" }),
17406
+ getCapabilities: method(_void(), InferenceCapabilitiesBridge),
17407
+ getAddonModels: method(object({ addonId: string() }), ModelAvailabilityListBridge),
17408
+ downloadModel: method(object({
17409
+ addonId: string(),
17410
+ modelId: string(),
17411
+ format: ModelFormatSchema$1
17412
+ }), DownloadModelResultSchema, { kind: "mutation" }),
17413
+ deleteModel: method(object({
17414
+ addonId: string(),
17415
+ modelId: string(),
17416
+ format: ModelFormatSchema$1
17417
+ }), object({ success: literal(true) }), { kind: "mutation" }),
17418
+ /**
17419
+ * Stateless single-frame execution. Callers (runner, benchmark) pass
17420
+ * the complete `engine` + `steps` tree; the executor holds no state
17421
+ * about cameras or saved pipelines.
17422
+ *
17423
+ * `engine` is optional during the migration window to preserve the
17424
+ * legacy call shape used by existing benchmark code; once all
17425
+ * callers pass it explicitly we make it required.
17426
+ *
17427
+ * Exactly one of `frame`, `frameRef`, `frameHandle`, `imageBase64`,
17428
+ * `referenceImage` must be provided:
17429
+ * - `frame`: runtime dispatch path (runner → decoded broker frame).
17430
+ * Carries the raw buffer, dimensions, and format; the executor
17431
+ * uses it directly without base64 round-tripping.
17432
+ * - `frameHandle` (CB5): a zero-pixel shm `FrameHandle` for the SAME
17433
+ * decoded frame. Both runner and executor are hub-local processes
17434
+ * sharing `/dev/shm`, so the executor maps the named segment and
17435
+ * reads the pixels back zero-copy — eliminating the ~1.2MB
17436
+ * re-serialisation over UDS/MsgPack the `frame` path pays per call.
17437
+ * High-risk: the FrameRing is a latest-wins seqlock with no
17438
+ * refcount, so a recycled slot yields a null read; the executor
17439
+ * then degrades to an empty result and the runner ships pixels via
17440
+ * `frame` as the fallback (queue-depth gated on the runner side).
17441
+ * - `imageBase64`: one-shot test path (benchmark ImageTab).
17442
+ * - `referenceImage`: named file from the reference-image store.
17443
+ */
17444
+ runPipeline: method(object({
17445
+ engine: PipelineEngineChoiceSchema.optional(),
17446
+ steps: array(PipelineStepInputSchema).min(1),
17447
+ frame: FrameInputSchema.optional(),
17448
+ /**
17449
+ * Process-local lazy frame. Valid only when caller and provider resolve
17450
+ * in the same execution-group process; split/cross-node callers use
17451
+ * `frame`/`image` inline compatibility instead.
17452
+ */
17453
+ frameRef: FrameRefSchema.optional(),
17454
+ /**
17455
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
17456
+ * the decoded pixels live in. One more member of the one-of
17457
+ * frame/frameHandle/image/imageBase64/referenceImage group.
17458
+ */
17459
+ frameHandle: FrameHandleSchema.optional(),
17460
+ imageBase64: string().optional(),
17461
+ /**
17462
+ * Binary JPEG bytes — preferred over `imageBase64` on internal
17463
+ * hops (hub → forked worker via Moleculer MsgPack) because it
17464
+ * skips the 33% base64 overhead + the per-call base64 decode on
17465
+ * the detection-pipeline worker. Callers can pass either; exactly
17466
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
17467
+ */
17468
+ image: _instanceof(Uint8Array).optional(),
17469
+ referenceImage: string().optional(),
17470
+ deviceId: number().optional(),
17471
+ sessionId: string().optional(),
17472
+ /**
17473
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
17474
+ * reference-image, and detail-subtree calls. 'frame' is the live
17475
+ * per-frame dispatch: ONLY root-plane steps run; crop children
17476
+ * (inputClasses ≠ null) are skipped and served per-track via
17477
+ * pipelineRunner.runDetailSubtree (two-plane design).
17478
+ */
17479
+ plane: _enum(["full", "frame"]).optional(),
17480
+ /**
17481
+ * Inference-device selector (Phase 2 multi-device). Format
17482
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
17483
+ * Omitted ⇒ the runner's default device (current single-engine
17484
+ * behaviour). Selects WHICH device pool of the node runs the call.
17485
+ */
17486
+ deviceKey: string().optional(),
17487
+ /**
17488
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
17489
+ * when the parent crop was resolved from the frame's retained NATIVE
17490
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
17491
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
17492
+ * resolution from that surface — the SAME quality path faces already
17493
+ * had — instead of the downscaled parent tile. `handle` keys the native
17494
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
17495
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
17496
+ * the executor's crop-normalized child ROI back into frame-normalized
17497
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
17498
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
17499
+ * (today's behaviour on the fallback path).
17500
+ */
17501
+ nativeCropRef: NativeCropRefSchema.optional()
17502
+ }), PipelineRunResultBridge, { kind: "mutation" }),
17503
+ /**
17504
+ * Batched run — N raw frames packed into one cap call. The provider
17505
+ * routes the batch through `SharedInferencePool.inferBatch`
17506
+ * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response
17507
+ * envelope cost is amortised N:1 vs N concurrent `runPipeline`
17508
+ * calls. Single root step + uniform model assumed; trees with crop
17509
+ * children fall back to sequential execution.
17510
+ *
17511
+ * Used by `scripts/bench-batch-style.mts` for batch benchmarking —
17512
+ * N frames in one call to amortise per-call IPC overhead.
17513
+ */
17514
+ runPipelineBatch: method(object({
17515
+ engine: PipelineEngineChoiceSchema.optional(),
17516
+ steps: array(PipelineStepInputSchema).min(1),
17517
+ frames: array(FrameInputSchema).min(1).max(255),
17518
+ deviceId: number().optional(),
17519
+ sessionId: string().optional(),
17520
+ /**
17521
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
17522
+ * the batch to the Python pool's bench preprocess cache
17523
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
17524
+ * preprocessed ONCE and every later inference is a pure-inference cache
17525
+ * hit — the sustained-throughput run measures inference, not
17526
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
17527
+ * full preprocess every call, correct). Fresh per sustained run;
17528
+ * released via `uncacheFrame`.
17529
+ */
17530
+ frameId: number().int().nonnegative().optional(),
17531
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
17532
+ deviceKey: string().optional()
17533
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }),
17534
+ /**
17535
+ * Cache a raw frame inside the Python inference pool's memory.
17536
+ * Returns a numeric `frameId` that `inferCached` references —
17537
+ * subsequent calls send only 5 bytes through the pipe instead of
17538
+ * 1.2MB raw data, eliminating the pipe transfer bottleneck.
17539
+ */
17540
+ cacheFrameInPool: method(object({
17541
+ data: _instanceof(Uint8Array),
17542
+ width: number().int().positive(),
17543
+ height: number().int().positive(),
17544
+ format: _enum([
17545
+ "rgb",
17546
+ "bgr",
17547
+ "gray"
17548
+ ])
17549
+ }), object({
17550
+ frameId: number(),
17551
+ width: number(),
17552
+ height: number()
17553
+ }), { kind: "mutation" }),
17554
+ /**
17555
+ * Run inference on a previously cached frame. Sends only 5 bytes
17556
+ * (model_idx + frameId) through the IPC pipe — eliminates the
17557
+ * ~35ms per-call overhead of transferring 1.2MB raw data.
17558
+ */
17559
+ inferCached: method(object({
17560
+ stepId: string(),
17561
+ frameId: number().int()
17562
+ }), record(string(), unknown()), { kind: "mutation" }),
17563
+ /**
17564
+ * Release a cached frame from the Python pool's memory.
17565
+ */
17566
+ uncacheFrame: method(object({ frameId: number().int() }), _void(), { kind: "mutation" }),
17567
+ /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */
17568
+ getEffectiveTuning: method(_void(), object({
17569
+ batchMode: string(),
17570
+ windowMs: number(),
17571
+ maxBatchSize: number(),
17572
+ concurrency: number()
17573
+ })),
17574
+ /**
17575
+ * List every EngineFactory currently loaded in this executor's RAM,
17576
+ * with the models resident and a coarse "in use" marker derived from
17577
+ * ongoing inference activity. Used by the Pipeline page Engines tab.
17578
+ */
17579
+ listLoadedEngines: method(_void(), array(object({
17580
+ engineKey: string(),
17581
+ engine: PipelineEngineChoiceSchema,
17582
+ modelsLoaded: array(string()).readonly(),
17583
+ inUseByCameras: array(number()).readonly(),
17584
+ /**
17585
+ * Origin of this resident factory.
17586
+ * - `runtime` — main camera-serving engine (no idle TTL).
17587
+ * - `warm-override` — benchmark/test override held in the warm
17588
+ * cache; auto-disposed after the idle TTL.
17589
+ * - `device-pool` — a concurrent per-device pool (Phase 2
17590
+ * multi-device, keyed by `deviceKey`) resolved
17591
+ * via `resolveDeviceFactory`. Runs alongside the
17592
+ * `runtime` engine on a DIFFERENT accelerator
17593
+ * (NPU / iGPU / Coral) — this is how the
17594
+ * Engines tab shows all pools running at once.
17595
+ */
17596
+ kind: _enum([
17597
+ "runtime",
17598
+ "warm-override",
17599
+ "device-pool"
17600
+ ]),
17601
+ /** Native pid of the underlying Python pool (null when no pool). */
17602
+ poolPid: number().nullable(),
17603
+ /** ms since this factory was last used (null when not warm-tracked). */
17604
+ idleMs: number().nullable(),
17605
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
17606
+ idleTtlMs: number().nullable()
17607
+ })).readonly()),
17608
+ /** Warm up an engine without running a frame. No-op if already loaded. */
17609
+ spinEngine: method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
17610
+ kind: "mutation",
17611
+ auth: "admin"
17612
+ }),
17613
+ /**
17614
+ * Unload an engine from RAM. `force:true` unloads even when cameras
17615
+ * are actively using it (they re-spin on next frame). Default is
17616
+ * gated — returns `{success:false, reason}` when in use.
17617
+ */
17618
+ killEngine: method(object({
17619
+ engine: PipelineEngineChoiceSchema,
17620
+ force: boolean().optional()
17621
+ }), object({
17622
+ success: boolean(),
17623
+ reason: string().optional()
17624
+ }), {
17625
+ kind: "mutation",
17626
+ auth: "admin"
17627
+ }),
17628
+ listReferenceImages: method(_void(), array(ReferenceImageEntrySchema).readonly()),
17629
+ getReferenceImage: method(object({ filename: string() }), ReferenceImageBodySchema.nullable()),
17630
+ getReferenceAudioFiles: method(_void(), array(ReferenceAudioEntrySchema).readonly()),
17631
+ getReferenceAudio: method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()),
17632
+ getAudioCapabilities: method(_void(), AudioCapabilitiesSchema),
17633
+ runAudioTest: method(object({
17634
+ addonId: string(),
17635
+ modelId: string(),
17636
+ filename: string().optional(),
17637
+ settings: record(string(), unknown()).optional()
17638
+ }), AudioTestResultSchema, { kind: "mutation" }),
17639
+ getDetectionConfigSchema: method(_void(), ConfigUISchemaNullableBridge)
17640
+ }
17641
+ };
17642
+ /**
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.
17655
+ */
17656
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
17657
+ /**
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:
17662
+ *
17663
+ * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
17664
+ * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
17665
+ * - future: notification rules, audio gating, etc.
17666
+ *
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.
17675
+ */
17676
+ var ZoneRuleSchema = object({
17677
+ /** Stable rule id — survives edits, used by the UI for diffing. */
17853
17678
  id: string(),
17854
- deviceId: number().int(),
17855
- openedAt: number().int(),
17856
- closedAt: number().int(),
17857
- timestamp: number().int(),
17858
- memberCount: number().int(),
17859
- memberTrackIds: array(string()).readonly(),
17860
- className: string(),
17861
- classes: array(string()).readonly(),
17862
- /** Relative event-media path, or null when the group has no picture yet. */
17863
- mediaUrl: string().nullable(),
17864
- singleton: boolean()
17865
- });
17866
- var AnalyticsGroupMemberSchema = object({
17867
- trackId: string(),
17868
- deviceId: number().int(),
17869
- className: string(),
17870
- firstSeen: number().int(),
17871
- lastSeen: number().int(),
17872
- mediaUrl: string().nullable()
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,
17687
+ /**
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`).
17691
+ */
17692
+ classFilter: array(string()).readonly().optional(),
17693
+ /**
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.
17700
+ */
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)
17873
17726
  });
17874
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
17875
- var ListGroupsQueryInput = object({
17876
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
17877
- deviceIds: array(number()),
17878
- /** Window lower bound on `closedAt` (inclusive). */
17879
- since: number().optional(),
17880
- /** Window upper bound on `openedAt` (inclusive). */
17881
- until: number().optional(),
17882
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
17883
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
17884
- cursor: string().optional()
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()
17885
17758
  });
17886
- var ListGroupsPageSchema = object({
17887
- groups: array(AnalyticsGroupRecordSchema).readonly(),
17888
- nextCursor: string().nullable()
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")
17889
17768
  });
17890
- var KeyEventQueryInput = object({
17891
- deviceId: number(),
17892
- /** Window lower bound (track firstSeen ≥ since). */
17893
- since: number(),
17894
- /** Window upper bound (track firstSeen until). */
17895
- until: number(),
17896
- limit: number().int().min(1).max(200).default(50),
17897
- /** Drop tracks scoring below this importance. */
17898
- minImportance: number().min(0).max(1).optional(),
17899
- /** Restrict to a single class (e.g. 'person'). */
17900
- classFilter: string().optional()
17901
- });
17902
- var KeyEventSchema = object({
17903
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
17904
- id: string(),
17905
- trackId: string(),
17906
- /** Track start time (firstSeen). */
17907
- timestamp: number(),
17908
- className: string(),
17909
- ...TieredLabelFields,
17910
- importance: number(),
17911
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
17912
- bestEventId: string(),
17913
- /** Track lifetime in ms (lastSeen - firstSeen). */
17914
- windowMs: number().optional(),
17915
- ...TrackFlagFields,
17916
- ...TrackRetrainFields
17769
+ /**
17770
+ * Zones capability — per-camera CRUD over polygon detection zones.
17771
+ *
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`.
17776
+ *
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`.
17781
+ */
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
+ };
17828
+ /**
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:
17833
+ *
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)
17841
+ *
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.
17851
+ */
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",
17874
+ "person",
17875
+ "vehicle",
17876
+ "animal",
17877
+ "door",
17878
+ "pir",
17879
+ "smoke",
17880
+ "water",
17881
+ "button",
17882
+ "package",
17883
+ "generic"
17884
+ ]);
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
+ })
17917
17920
  });
17918
- object({
17919
- trackId: string(),
17920
- className: string(),
17921
- confidence: number(),
17922
- bbox: BoundingBoxSchema,
17923
- zones: array(string()).readonly(),
17924
- state: TrackStateSchema
17921
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
17922
+ var EventKindsForDeviceSchema = object({
17923
+ deviceId: number(),
17924
+ kinds: array(EventKindDescriptorSchema).readonly()
17925
17925
  });
17926
- var OverlayDetectionSchema = looseObject({
17926
+ var SensorEventSchema = object({
17927
17927
  id: string(),
17928
- kind: _enum(["first-level", "detail"]),
17929
- macroClass: string(),
17930
- score: number(),
17931
- bbox: object({
17932
- x: number(),
17933
- y: number(),
17934
- width: number(),
17935
- height: number()
17936
- }),
17937
- labels: array(looseObject({
17938
- label: string(),
17939
- score: number()
17940
- })).readonly(),
17941
- parentId: string().optional()
17942
- });
17943
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
17944
- var SearchObjectEventsInput = object({
17945
- text: string(),
17946
- deviceId: number().optional(),
17947
- since: number().optional(),
17948
- until: number().optional(),
17949
- classFilter: string().optional(),
17950
- limit: number().default(50),
17951
- minScore: number().min(0).max(1).default(.2)
17952
- });
17953
- var TrackCascadeCountsSchema = object({
17954
- /** Persisted track roots deleted (authoritative). */
17955
- tracks: number().int(),
17956
- /** Object events removed with their tracks (best-effort; see note above). */
17957
- events: number().int(),
17958
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
17959
- media: number().int(),
17960
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
17961
- faces: number().int(),
17962
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
17963
- plates: number().int(),
17964
- /** Per-track CLIP search vectors removed (best-effort). */
17965
- embeddings: number().int(),
17966
- /** Group membership + group rows removed with their last member (best-effort). */
17967
- groups: number().int()
17928
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
17929
+ * yields N rows, one per camera). */
17930
+ deviceId: number(),
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()
17968
17938
  });
17969
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
17970
- var DiskReconcileCountsSchema = object({
17971
- mediaDropped: number().int(),
17972
- tracks: number().int(),
17973
- events: number().int()
17939
+ var TrackPositionSchema = object({
17940
+ x: number(),
17941
+ y: number(),
17942
+ timestamp: number(),
17943
+ bbox: BoundingBoxSchema
17974
17944
  });
17975
- /** Event-store footprint for one camera. */
17976
- var EventStoreDeviceFootprintSchema = object({
17977
- deviceId: number(),
17978
- /** Persisted event rows (motion + object + audio) for the camera. */
17979
- rows: number().int(),
17980
- /** Event-owned media bytes on disk for the camera. */
17981
- bytes: number().int()
17945
+ var TrackSnapshotSchema = object({
17946
+ timestamp: number(),
17947
+ position: TrackPositionSchema,
17948
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
17949
+ mediaKey: string()
17982
17950
  });
17983
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
17984
- var EventStoreFootprintSchema = object({
17985
- totalRows: number().int(),
17986
- totalBytes: number().int(),
17987
- devices: array(EventStoreDeviceFootprintSchema).readonly()
17951
+ /**
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.
17956
+ */
17957
+ var TrackEnvelopeSchema = object({
17958
+ minX: number(),
17959
+ minY: number(),
17960
+ maxX: number(),
17961
+ maxY: number()
17988
17962
  });
17989
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
17990
- var EventPruneCountsSchema = object({
17991
- motion: number().int(),
17992
- object: number().int(),
17993
- 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()
17994
17990
  });
17995
17991
  /**
17996
- * 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:
17997
17995
  *
17998
- * The reason this is an operator-callable method and not a migration script:
17999
- * every knob that decides what a vector MEANS encoder model, crop margin,
18000
- * squaring is only changeable if the existing vectors can be regenerated.
18001
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
18002
- * 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.
18003
18004
  */
18004
- var RebuildObjectEmbeddingsInput = object({
18005
- /** Restrict to one camera. Omit for the whole fleet. */
18006
- deviceId: number().optional(),
18007
- since: number().optional(),
18008
- until: number().optional(),
18009
- /** Stop after this many tracks; the result reports whether more remain. */
18010
- maxTracks: number().int().positive().optional(),
18011
- /**
18012
- * Run every embedding on THIS node instead of round-robining the fleet.
18013
- *
18014
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
18015
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
18016
- * calling it that would pin the rebuild REQUEST itself to that node — the
18017
- * rebuild orchestration lives on the hub, and only the per-track step runs
18018
- * remotely. This field is data; the per-track pin is applied inside.
18019
- *
18020
- * Absent ⇒ round-robin over every online node whose runner can serve the
18021
- * pinned model.
18022
- */
18023
- executeOnNodeId: string().optional(),
18024
- /**
18025
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
18026
- * run flat out.
18027
- *
18028
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
18029
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
18030
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
18031
- * force is logged at start and finish so a deliberately slow pass reads
18032
- * differently from a stalled one.
18033
- */
18034
- pacingMs: number().int().nonnegative().optional()
18035
- });
18005
+ var TrackSourceSchema = _enum([
18006
+ "pipeline",
18007
+ "sensor",
18008
+ "audio"
18009
+ ]);
18036
18010
  /**
18037
- * Result of emptying the CLIP index.
18011
+ * Where a track sits in the RETRAIN lifecycle (D81).
18038
18012
  *
18039
- * The clean slate before a policy change: a new crop margin or encoder model
18040
- * leaves two feature spaces in one index whose cosine scores are not
18041
- * comparable, so wiping and rebuilding is the only way to be sure every vector
18042
- * 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.
18043
18028
  */
18044
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
18029
+ var RetrainStatusSchema = _enum([
18030
+ "none",
18031
+ "staging",
18032
+ "trained"
18033
+ ]);
18045
18034
  /**
18046
- * 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.
18047
18038
  *
18048
- * The pass costs ~1s per track 45 minutes for a 2,600-track fleet so it
18049
- * runs detached and this returns immediately. Waiting for it made the client
18050
- * time out while the work carried on server-side, which is the worst of both:
18051
- * no result and no way to know it was still going. Poll
18052
- * `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.
18053
18056
  */
18054
- var RebuildObjectEmbeddingsResultSchema = object({
18055
- started: boolean(),
18056
- /** True when a pass was already running; the new request is ignored. */
18057
- alreadyRunning: boolean()
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({
18086
+ trackId: string(),
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
18058
18095
  });
18059
- var RebuildStatusSchema = object({
18060
- running: boolean(),
18061
- scanned: number(),
18062
- rebuilt: number(),
18063
- /** Tracks whose key frame is gone nothing to re-embed from. */
18064
- missingKeyFrame: number(),
18065
- /** Tracks with no usable detection box. */
18066
- missingBbox: number(),
18067
- /**
18068
- * Tracks an executing node REFUSED rather than broke on an unreadable key
18069
- * frame, a step that threw. Separate from `failed` because the remedy is
18070
- * different, and because a whole camera silently contributing zero vectors
18071
- * is the shape of failure a rebuild must never hide.
18072
- */
18073
- notRunnable: number(),
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(),
18074
18113
  /**
18075
- * The pass stopped because NO node could serve the pinned model.
18114
+ * The GALLERY id behind a recognised tier-2 label a face-gallery
18115
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
18076
18116
  *
18077
- * Distinct from `notRunnable` on purpose: that one says "this track was
18078
- * refused", this one says "the cluster cannot do this work at all" — every
18079
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
18080
- * pinned model for its engine format, or dropped out. The remedy is a model /
18081
- * engine change, not a per-camera one. Non-zero here always comes with
18082
- * `complete: false`.
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.
18083
18125
  */
18084
- noCapableNode: number(),
18085
- failed: number(),
18086
- /** Set once a pass ends: true only when EVERYTHING was covered. */
18087
- complete: boolean().nullable(),
18088
- startedAtMs: number().nullable(),
18089
- finishedAtMs: number().nullable(),
18090
- /** Present when the pass ended by throwing. */
18091
- error: string().nullable()
18126
+ identityId: string().optional()
18092
18127
  });
18093
- DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
18094
- deviceId: number(),
18095
- trackId: string()
18096
- }), TrackSchema.nullable()), method(object({
18097
- deviceId: number(),
18098
- since: number().optional(),
18099
- until: number().optional(),
18100
- limit: number().optional(),
18101
- /** Spatial filter — only tracks whose trajectory intersects the zone
18102
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
18103
- * envelope columns, then precisely tested per position. Tracks with
18104
- * an unknown envelope (no frame dims at persist time) always match. */
18105
- zone: TrackZoneFilterSchema.optional(),
18106
- /** See {@link TrackProjectionSchema}. Default `full` (backward
18107
- * compatible omitting the field keeps today's exact behaviour). */
18108
- projection: TrackProjectionSchema.optional(),
18109
- /** Include stationary-promoted rows (parked objects handed to the
18110
- * stationary registry). Default false: the timeline lists passages,
18111
- * not parking records (operator decision, 2026-08-15). */
18112
- includeStationary: boolean().optional()
18113
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
18114
- deviceId: number(),
18115
- groupId: string().min(1)
18116
- }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
18117
- kind: "mutation",
18118
- auth: "admin"
18119
- }), 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({
18120
- deviceId: number(),
18121
- since: number().optional(),
18122
- until: number().optional(),
18123
- kinds: array(string()).optional(),
18124
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
18125
- }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
18126
- deviceId: number(),
18127
- since: number(),
18128
- until: number(),
18129
- bucketMs: number().int().positive()
18130
- }), array(object({
18131
- bucketStart: number(),
18132
- motion: number().int(),
18133
- object: number().int(),
18134
- audio: number().int()
18135
- })).readonly()), method(object({
18136
- deviceId: number(),
18137
- cutoffMs: number()
18138
- }), object({
18139
- motion: number().int(),
18140
- object: number().int(),
18141
- audio: number().int()
18142
- }), {
18143
- kind: "mutation",
18144
- auth: "admin"
18145
- }), method(object({
18146
- deviceId: number(),
18147
- cutoffMs: number()
18148
- }), TrackCascadeCountsSchema, {
18149
- kind: "mutation",
18150
- auth: "admin"
18151
- }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
18152
- kind: "mutation",
18153
- auth: "admin"
18154
- }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
18155
- kind: "mutation",
18156
- auth: "admin"
18157
- }), method(object({
18158
- deviceId: number(),
18159
- trackIds: array(string()).min(1)
18160
- }), object({
18161
- deleted: number().int(),
18162
- failed: array(string()).readonly()
18163
- }), {
18164
- kind: "mutation",
18165
- auth: "admin"
18166
- }), method(object({
18167
- /** Log/audit scope only — the trackId is globally unique on its own. */
18168
- deviceId: number(),
18169
- trackId: string(),
18170
- flags: TrackFlagsPatchSchema
18171
- }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
18172
- kind: "query",
18173
- auth: "admin"
18174
- }), method(object({
18175
- olderThanMs: number(),
18176
- reason: OpsLogReasonSchema.optional()
18177
- }), EventPruneCountsSchema, {
18178
- kind: "mutation",
18179
- auth: "admin"
18180
- }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
18181
- kind: "mutation",
18182
- auth: "admin"
18183
- }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
18184
- kind: "mutation",
18185
- auth: "admin"
18186
- }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
18187
- kind: "mutation",
18188
- auth: "admin"
18189
- }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
18190
- kind: "mutation",
18191
- auth: "admin"
18192
- }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
18193
- kind: "mutation",
18194
- auth: "admin"
18195
- }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18196
- kind: "mutation",
18197
- auth: "admin"
18198
- }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
18199
- kind: "mutation",
18200
- auth: "admin"
18201
- }), method(object({}), array(RelocateJobSchema).readonly(), {
18202
- kind: "query",
18203
- auth: "admin"
18204
- }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
18205
- kind: "mutation",
18206
- auth: "admin"
18207
- }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
18208
- kind: "query",
18209
- auth: "admin"
18210
- }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
18211
- kind: "query",
18212
- auth: "admin"
18213
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18214
- kind: "query",
18215
- auth: "admin"
18216
- }), method(object({
18217
- /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
18218
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
18219
- * route it at one camera's owner, and "every camera" would stop being
18220
- * expressible at all. */
18221
- deviceIds: array(number()).optional(),
18222
- limit: number().int().min(1).max(500).optional()
18223
- }), array(RetrainTrackSchema).readonly(), {
18224
- kind: "query",
18225
- auth: "admin"
18226
- }), method(object({ trackId: string() }), RetrainFrameListSchema, {
18227
- kind: "query",
18228
- auth: "admin"
18229
- }), method(object({
18230
- deviceId: number(),
18231
- trackId: string(),
18232
- mediaKeys: array(string()).min(1)
18233
- }), RetrainFrameSelectionSchema, {
18234
- kind: "mutation",
18235
- auth: "admin"
18236
- }), method(object({
18237
- deviceId: number(),
18238
- trackId: string(),
18239
- frameId: string()
18240
- }), object({
18241
- removed: boolean(),
18242
- removedAnnotations: number().int()
18243
- }), {
18244
- kind: "mutation",
18245
- auth: "admin"
18246
- }), method(object({ frameId: string() }), object({
18247
- base64: string(),
18248
- width: number().int(),
18249
- height: number().int()
18250
- }), {
18251
- kind: "query",
18252
- auth: "admin"
18253
- }), method(object({
18254
- deviceId: number(),
18255
- trackId: string(),
18256
- frameId: string(),
18257
- subject: RetrainAssistSubjectSchema,
18258
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
18259
- nodeId: string().optional()
18260
- }), RetrainAssistResultSchema, {
18261
- kind: "mutation",
18262
- auth: "admin"
18263
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
18264
- kind: "query",
18265
- auth: "admin"
18266
- }), method(object({
18267
- deviceId: number(),
18268
- trackId: string(),
18269
- frameId: string(),
18270
- annotations: array(RetrainAnnotationDraftSchema)
18271
- }), array(RetrainAnnotationSchema).readonly(), {
18272
- kind: "mutation",
18273
- auth: "admin"
18274
- }), method(object({
18275
- deviceId: number(),
18276
- trackId: string()
18277
- }), RetrainTransitionResultSchema, {
18278
- kind: "mutation",
18279
- auth: "admin"
18280
- }), method(object({
18281
- deviceId: number(),
18282
- trackId: string()
18283
- }), RetrainTransitionResultSchema, {
18284
- kind: "mutation",
18285
- auth: "admin"
18286
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
18287
- kind: "query",
18288
- auth: "admin"
18289
- }), method(object({
18290
- eventId: string(),
18291
- kind: MediaFileKindEnum.optional(),
18292
- deviceId: number()
18293
- }), array(MediaFileSchema).readonly()), method(object({
18294
- trackId: string(),
18295
- kinds: array(MediaFileKindEnum).optional(),
18296
- deviceId: number()
18297
- }), array(MediaFileSchema).readonly()), method(object({
18298
- trackId: string(),
18299
- deviceId: number()
18300
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
18301
- kind: "mutation",
18302
- auth: "admin"
18303
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
18304
- kind: "mutation",
18305
- auth: "admin"
18306
- }), method(object({}), RebuildStatusSchema), object({
18307
- deviceId: number(),
18308
- timestamp: number(),
18309
- frameWidth: number(),
18310
- frameHeight: number(),
18311
- detections: array(OverlayDetectionSchema).readonly()
18312
- }), object({
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({
18313
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({
18314
18185
  trackId: string(),
18315
- className: string()
18316
- }), object({
18317
18186
  deviceId: number(),
18318
- trackId: string(),
18319
18187
  className: string(),
18320
- durationMs: number()
18321
- }), object({
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(),
18322
18319
  deviceId: number(),
18323
- kind: EventKindSchema,
18324
- eventId: string(),
18325
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()
18326
18338
  });
18327
18339
  /**
18328
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
18329
- * within the frame, so the executor can re-cut a leaf child ROI at native
18330
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
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`.
18331
18346
  */
18332
- var NativeCropRefSchema = object({
18333
- /** Handle keying the retained native surface (node-pinned to its owner). */
18334
- handle: FrameHandleSchema,
18335
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
18336
- cropFrameSpace: object({
18337
- x: number(),
18338
- y: number(),
18339
- w: number(),
18340
- h: number()
18341
- })
18342
- });
18343
- object({
18344
- crop: object({
18345
- left: number(),
18346
- top: number(),
18347
- width: number().positive(),
18348
- height: number().positive()
18349
- }).optional(),
18350
- content: object({
18351
- width: number().int().positive(),
18352
- height: number().int().positive()
18353
- }),
18354
- fit: _enum(["stretch", "contain"]),
18355
- format: _enum([
18356
- "rgb",
18357
- "gray",
18358
- "jpeg"
18359
- ])
18360
- });
18347
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
18361
18348
  /**
18362
- * Process-local frame identity. It is serializable so it can ride an in-process
18363
- * capability call, but `registryId` deliberately prevents resolution in any
18364
- * other process or execution group.
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.
18365
18363
  */
18366
- var FrameRefSchema = object({
18367
- registryId: string().min(1),
18368
- id: string().min(1),
18369
- width: number().int().positive(),
18370
- height: number().int().positive(),
18371
- format: _enum(["rgb", "gray"]),
18372
- timestamp: number(),
18373
- capturedAt: number().optional()
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()
18374
18370
  });
18375
- var ModelFormatSchema$1 = _enum([
18376
- "onnx",
18377
- "coreml",
18378
- "openvino",
18379
- "tflite",
18380
- "pt",
18381
- "gguf"
18382
- ]);
18383
- var PipelineSlotSchema = _enum([
18384
- "detector",
18385
- "cropper",
18386
- "classifier",
18387
- "refiner",
18388
- "audio-classifier"
18389
- ]);
18390
- var PipelineEngineChoiceSchema = object({
18391
- runtime: _enum(["node", "python"]),
18392
- backend: string(),
18393
- format: ModelFormatSchema$1,
18394
- device: string().optional()
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()
18395
18421
  });
18396
- var AvailableEngineSchema = object({
18397
- engine: PipelineEngineChoiceSchema,
18398
- devices: array(object({
18399
- id: string(),
18400
- label: string(),
18401
- description: string().optional()
18402
- })).readonly(),
18403
- defaultDevice: string()
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()
18404
18434
  });
18405
- var PipelineDefaultStepSchema = lazy(() => object({
18406
- addonId: string(),
18407
- addonName: string(),
18408
- slot: PipelineSlotSchema,
18409
- inputClasses: array(string()).readonly(),
18410
- outputClasses: array(string()).readonly(),
18411
- enabled: boolean(),
18412
- modelId: string(),
18413
- children: array(PipelineDefaultStepSchema).readonly(),
18414
- group: string().optional(),
18415
- settings: record(string(), unknown()).optional()
18416
- }));
18417
- var PipelineTemplateStepSchema = lazy(() => object({
18418
- addonId: string(),
18419
- enabled: boolean(),
18420
- modelId: string(),
18421
- children: array(PipelineTemplateStepSchema).readonly(),
18422
- settings: record(string(), unknown()).optional()
18423
- }));
18424
- var PipelineTemplateSchema$1 = object({
18425
- id: string(),
18426
- name: string(),
18427
- createdAt: string(),
18428
- updatedAt: string(),
18429
- engine: PipelineEngineChoiceSchema,
18430
- steps: array(PipelineTemplateStepSchema).readonly()
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,
18452
+ base64: string(),
18453
+ sizeBytes: number(),
18454
+ timestamp: number()
18431
18455
  });
18432
- var PipelineModelOptionSchema = object({
18433
- id: string(),
18434
- name: string(),
18435
- formats: record(string(), object({
18436
- downloaded: boolean(),
18437
- sizeMB: number()
18438
- })),
18439
- group: ModelVariantGroupSchema.optional(),
18440
- legacy: boolean().optional(),
18441
- provider: ModelProviderIdSchema.optional()
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()
18442
18500
  });
18443
- var ConfigFieldBridge = custom();
18444
- var PipelineAddonSchemaSchema = object({
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({
18445
18510
  id: string(),
18446
- name: string(),
18447
- slot: PipelineSlotSchema,
18448
- inputClasses: array(string()).readonly(),
18449
- outputClasses: array(string()).readonly(),
18450
- childSlots: array(PipelineSlotSchema).readonly(),
18451
- models: array(PipelineModelOptionSchema).readonly(),
18452
- defaultModelId: string(),
18453
- defaultModelIdByFormat: record(string(), string()).optional(),
18454
- enabledByDefault: boolean().optional(),
18455
- backfillIntoExistingOverrides: boolean().optional(),
18456
- defaultConfidence: number(),
18457
- group: string().optional(),
18458
- configSchema: array(ConfigFieldBridge).readonly().optional()
18511
+ trackId: string(),
18512
+ deviceId: number(),
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()
18459
18526
  });
18460
- var PipelineSlotSchemaSchema = object({
18461
- id: PipelineSlotSchema,
18462
- label: string(),
18463
- priority: number(),
18464
- parentSlot: PipelineSlotSchema.nullable(),
18465
- addons: array(PipelineAddonSchemaSchema).readonly()
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
18466
18535
  });
18467
- var PipelineSchemaSchema = object({
18468
- availableEngines: array(AvailableEngineSchema).readonly(),
18469
- selectedEngine: PipelineEngineChoiceSchema,
18470
- slots: array(PipelineSlotSchemaSchema).readonly()
18536
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
18537
+ var RetrainTrackSchema = object({
18538
+ trackId: string(),
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()
18471
18549
  });
18472
- var EngineProvisioningSchema = object({
18473
- runtimeId: _enum([
18474
- "onnx",
18475
- "openvino",
18476
- "coreml",
18477
- "edgetpu"
18478
- ]).nullable(),
18479
- device: string().nullable(),
18480
- state: _enum([
18481
- "idle",
18482
- "installing",
18483
- "verifying",
18484
- "ready",
18485
- "failed"
18486
- ]),
18487
- progress: number().optional(),
18488
- error: string().optional(),
18489
- nextRetryAt: number().optional(),
18490
- /**
18491
- * Gate A (config-correctness gate at engine change): human-readable
18492
- * config issues surfaced EAGERLY when the node's engine changes — model
18493
- * substitutions ("chose X, running Y") and zero-build steps ("no model
18494
- * has a <format> build"). Additive/optional: informational only, never
18495
- * enforced here — `assertEngineReady` (readiness) still gates inference.
18496
- * Absent/empty when the node-default tree resolves cleanly.
18497
- */
18498
- configIssues: array(string()).optional()
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,
18554
+ timestamp: number(),
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()
18499
18559
  });
18500
- var PipelineStepInputSchema = lazy(() => object({
18501
- addonId: string(),
18502
- modelId: string().optional(),
18503
- enabled: boolean().default(true),
18504
- children: array(PipelineStepInputSchema).optional(),
18505
- settings: record(string(), unknown()).optional(),
18506
- jumpDeviceKey: string().optional()
18507
- }));
18508
- var ModelSubstitutionSchema = object({
18509
- addonId: string(),
18510
- chosen: string(),
18511
- running: string(),
18512
- format: string()
18560
+ /** A frame the dataset OWNS: bytes copied at selection time. */
18561
+ var RetrainFrameSchema = object({
18562
+ frameId: string(),
18563
+ deviceId: number(),
18564
+ trackId: string(),
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()
18513
18572
  });
18514
- var PipelineValidationIssueSchema = object({
18515
- addonId: string(),
18516
- kind: _enum(["unknown-addon", "no-format-build"]),
18517
- detail: string()
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()
18518
18585
  });
18519
- var PipelineValidationResultSchema = object({
18520
- ok: boolean(),
18521
- issues: array(PipelineValidationIssueSchema).readonly(),
18522
- substitutions: array(ModelSubstitutionSchema).readonly(),
18523
- /** The node's `currentEngine.format` this validation ran against. */
18524
- format: string()
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()
18525
18591
  });
18526
- var ReferenceImageEntrySchema = object({
18527
- filename: string(),
18528
- stepIds: array(string()).readonly().optional()
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
+ })]);
18601
+ /**
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.
18605
+ */
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()
18529
18635
  });
18530
- var ReferenceImageBodySchema = object({
18531
- base64: string(),
18532
- filename: string()
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()
18533
18648
  });
18534
- var ReferenceAudioEntrySchema = object({
18535
- filename: string(),
18536
- sizeKb: number()
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()
18537
18667
  });
18538
- var ReferenceAudioBodySchema = object({ base64: string() });
18539
- var AudioBackendSchema = object({
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()
18673
+ });
18674
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
18675
+ var LIST_GROUPS_MAX_LIMIT = 100;
18676
+ var AnalyticsGroupRecordSchema = object({
18540
18677
  id: string(),
18541
- name: string(),
18542
- description: string(),
18543
- available: boolean(),
18544
- /**
18545
- * Raw classifier labels this backend can emit (e.g. YAMNet's
18546
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
18547
- * the benchmark UI to populate the `enabledMicroClasses` filter
18548
- * specific to the selected backend without a separate fetch.
18549
- */
18550
- rawLabels: array(string()).readonly().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()
18551
18689
  });
18552
- var AudioCapabilitiesSchema = object({
18553
- activeBackend: string(),
18554
- availableBackends: array(AudioBackendSchema).readonly(),
18555
- sampleRate: number(),
18556
- chunkDurationMs: number()
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()
18557
18697
  });
18558
- var DownloadModelResultSchema = object({
18559
- filePath: string(),
18560
- sizeMB: number(),
18561
- durationMs: number()
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()
18562
18709
  });
18563
- /**
18564
- * Wrapper carrying a single test run's result. Replaces the legacy
18565
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
18566
- * canonical `AudioResult` from the Phase 6 output rework: one
18567
- * `AudioDetection` per class above `minScore`, top-N candidates in
18568
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
18569
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
18570
- * benchmark UI can still report a clean failure when the classifier
18571
- * cap isn't available.
18572
- */
18573
- var AudioTestResultSchema = object({
18574
- success: boolean(),
18575
- error: string().optional(),
18576
- frame: custom().optional()
18710
+ var ListGroupsPageSchema = object({
18711
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
18712
+ nextCursor: string().nullable()
18577
18713
  });
18578
- var PipelineConfigBridge = custom();
18579
- var ConfigUISchemaBridge = custom();
18580
- var ConfigUISchemaNullableBridge = custom();
18581
- var InferenceCapabilitiesBridge = custom();
18582
- var ModelAvailabilityListBridge = custom();
18583
- var PipelineRunResultBridge = custom();
18584
- /**
18585
- * Pipeline executor detection engine + configuration + inference API.
18586
- *
18587
- * Merged from: pipeline-executor, pipeline-config, inference, detection-config.
18588
- * Implemented by the detection-pipeline addon.
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()
18725
+ });
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
18741
+ });
18742
+ object({
18743
+ trackId: string(),
18744
+ className: string(),
18745
+ confidence: number(),
18746
+ bbox: BoundingBoxSchema,
18747
+ zones: array(string()).readonly(),
18748
+ state: TrackStateSchema
18749
+ });
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()
18792
+ });
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()
18798
+ });
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()
18806
+ });
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()
18812
+ });
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.
18589
18821
  *
18590
- * Per-device surface (DeviceSettingsContribution + the "is detection
18591
- * enabled for this camera?" toggle) lives on the paired
18592
- * `detection-pipeline` cap (device-scoped, singleton, wrapper
18593
- * defaultActive) same split pattern used by stream-broker /
18594
- * camera-streams and audio-analyzer / audio-analysis.
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.
18595
18827
  */
18596
- var pipelineExecutorCapability = {
18597
- name: "pipeline-executor",
18598
- scope: "system",
18599
- mode: "singleton",
18600
- methods: {
18601
- getAvailableEngines: method(_void(), array(PipelineEngineChoiceSchema)),
18602
- getSelectedEngine: method(_void(), PipelineEngineChoiceSchema),
18603
- getDefaultSteps: method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)),
18604
- /**
18605
- * Per-node detection-engine provisioning snapshot. Returns the live
18606
- * state of the lazy runtime-provisioning machine on `nodeId`
18607
- * (idle / installing / verifying / ready / failed). The UI pairs this
18608
- * one-shot query with the `pipeline.engine-provisioning` live event
18609
- * (emitted on every transition) to drive a per-node "engine ready?"
18610
- * indicator without polling. Phase 2.
18611
- */
18612
- getEngineProvisioning: method(object({ nodeId: string() }), EngineProvisioningSchema),
18613
- getVideoPipelineSteps: method(_void(), record(string(), object({
18614
- modelId: string(),
18615
- settings: record(string(), unknown()).readonly()
18616
- }))),
18617
- setVideoPipelineSteps: method(object({ steps: record(string(), object({
18618
- modelId: string(),
18619
- settings: record(string(), unknown()).readonly()
18620
- })) }), object({ success: literal(true) }), {
18621
- kind: "mutation",
18622
- auth: "admin"
18623
- }),
18624
- /**
18625
- * Clear THIS node's executor-side PER-DEVICE settings stores (the
18626
- * per-camera step overrides the object-detection root reads via
18627
- * `applyDeviceOverridesToTree`). `nodeId` is the ROUTING key — the
18628
- * generated cap-router strips it (default `nodeIdMode: 'routing'`) and
18629
- * dispatches to that node, so the provider method runs ON the target
18630
- * node and receives no `nodeId`.
18631
- *
18632
- * This is the slimmed executor leg of the orchestrator's
18633
- * `resetNodePipelineDefaults` flow (which owns the real reset: node
18634
- * addonDefaults pins + per-camera orchestrator overrides). The legacy
18635
- * `resetToDefault` — which reset a persisted global step-tree seed
18636
- * nothing in the live per-camera path read — was removed together with
18637
- * that seed.
18638
- */
18639
- clearDeviceOverrides: method(object({ nodeId: string() }), object({
18640
- success: literal(true),
18641
- clearedDevices: number()
18642
- }), {
18643
- kind: "mutation",
18644
- auth: "admin"
18645
- }),
18646
- getSchema: method(_void(), PipelineSchemaSchema),
18647
- getGlobalSteps: method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()),
18648
- getGlobalPipelineConfig: method(_void(), PipelineConfigBridge),
18649
- getOrchestratorConfigSchema: method(_void(), ConfigUISchemaBridge),
18650
- /**
18651
- * Gate B (pre-init config-correctness gate). PURE COMPUTE against this
18652
- * node's `currentEngine.format` — resolves `steps` the same way the
18653
- * runtime dispatch path would, and reports what WOULD happen without
18654
- * touching any node-global state. Called by the orchestrator at attach
18655
- * time (`attachOn`), node-pinned to the TARGET node, so config problems
18656
- * surface BEFORE `pipelineRunner.attachCamera` rather than at the first
18657
- * per-frame resolve. `ok` is false iff `issues` is non-empty (both
18658
- * `unknown-addon` and `no-format-build` are HARD issues); `substitutions`
18659
- * is informational (a degraded-but-loadable model swap) and never
18660
- * affects `ok`. Never throws.
18661
- */
18662
- validatePipeline: method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema),
18663
- listTemplates: method(_void(), array(PipelineTemplateSchema$1).readonly()),
18664
- saveTemplate: method(object({
18665
- name: string(),
18666
- steps: array(PipelineTemplateStepSchema).readonly(),
18667
- engine: PipelineEngineChoiceSchema
18668
- }), PipelineTemplateSchema$1, { kind: "mutation" }),
18669
- updateTemplate: method(object({
18670
- id: string(),
18671
- name: string().optional(),
18672
- steps: array(PipelineTemplateStepSchema).readonly().optional()
18673
- }), PipelineTemplateSchema$1, { kind: "mutation" }),
18674
- deleteTemplate: method(object({ id: string() }), _void(), { kind: "mutation" }),
18675
- getCapabilities: method(_void(), InferenceCapabilitiesBridge),
18676
- getAddonModels: method(object({ addonId: string() }), ModelAvailabilityListBridge),
18677
- downloadModel: method(object({
18678
- addonId: string(),
18679
- modelId: string(),
18680
- format: ModelFormatSchema$1
18681
- }), DownloadModelResultSchema, { kind: "mutation" }),
18682
- deleteModel: method(object({
18683
- addonId: string(),
18684
- modelId: string(),
18685
- format: ModelFormatSchema$1
18686
- }), object({ success: literal(true) }), { kind: "mutation" }),
18687
- /**
18688
- * Stateless single-frame execution. Callers (runner, benchmark) pass
18689
- * the complete `engine` + `steps` tree; the executor holds no state
18690
- * about cameras or saved pipelines.
18691
- *
18692
- * `engine` is optional during the migration window to preserve the
18693
- * legacy call shape used by existing benchmark code; once all
18694
- * callers pass it explicitly we make it required.
18695
- *
18696
- * Exactly one of `frame`, `frameRef`, `frameHandle`, `imageBase64`,
18697
- * `referenceImage` must be provided:
18698
- * - `frame`: runtime dispatch path (runner decoded broker frame).
18699
- * Carries the raw buffer, dimensions, and format; the executor
18700
- * uses it directly without base64 round-tripping.
18701
- * - `frameHandle` (CB5): a zero-pixel shm `FrameHandle` for the SAME
18702
- * decoded frame. Both runner and executor are hub-local processes
18703
- * sharing `/dev/shm`, so the executor maps the named segment and
18704
- * reads the pixels back zero-copy — eliminating the ~1.2MB
18705
- * re-serialisation over UDS/MsgPack the `frame` path pays per call.
18706
- * High-risk: the FrameRing is a latest-wins seqlock with no
18707
- * refcount, so a recycled slot yields a null read; the executor
18708
- * then degrades to an empty result and the runner ships pixels via
18709
- * `frame` as the fallback (queue-depth gated on the runner side).
18710
- * - `imageBase64`: one-shot test path (benchmark ImageTab).
18711
- * - `referenceImage`: named file from the reference-image store.
18712
- */
18713
- runPipeline: method(object({
18714
- engine: PipelineEngineChoiceSchema.optional(),
18715
- steps: array(PipelineStepInputSchema).min(1),
18716
- frame: FrameInputSchema.optional(),
18717
- /**
18718
- * Process-local lazy frame. Valid only when caller and provider resolve
18719
- * in the same execution-group process; split/cross-node callers use
18720
- * `frame`/`image` inline compatibility instead.
18721
- */
18722
- frameRef: FrameRefSchema.optional(),
18723
- /**
18724
- * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
18725
- * the decoded pixels live in. One more member of the one-of
18726
- * frame/frameHandle/image/imageBase64/referenceImage group.
18727
- */
18728
- frameHandle: FrameHandleSchema.optional(),
18729
- imageBase64: string().optional(),
18730
- /**
18731
- * Binary JPEG bytes — preferred over `imageBase64` on internal
18732
- * hops (hub → forked worker via Moleculer MsgPack) because it
18733
- * skips the 33% base64 overhead + the per-call base64 decode on
18734
- * the detection-pipeline worker. Callers can pass either; exactly
18735
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
18736
- */
18737
- image: _instanceof(Uint8Array).optional(),
18738
- referenceImage: string().optional(),
18739
- deviceId: number().optional(),
18740
- sessionId: string().optional(),
18741
- /**
18742
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
18743
- * reference-image, and detail-subtree calls. 'frame' is the live
18744
- * per-frame dispatch: ONLY root-plane steps run; crop children
18745
- * (inputClasses ≠ null) are skipped and served per-track via
18746
- * pipelineRunner.runDetailSubtree (two-plane design).
18747
- */
18748
- plane: _enum(["full", "frame"]).optional(),
18749
- /**
18750
- * Inference-device selector (Phase 2 multi-device). Format
18751
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
18752
- * Omitted ⇒ the runner's default device (current single-engine
18753
- * behaviour). Selects WHICH device pool of the node runs the call.
18754
- */
18755
- deviceKey: string().optional(),
18756
- /**
18757
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
18758
- * when the parent crop was resolved from the frame's retained NATIVE
18759
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
18760
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
18761
- * resolution from that surface the SAME quality path faces already
18762
- * had — instead of the downscaled parent tile. `handle` keys the native
18763
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
18764
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
18765
- * the executor's crop-normalized child ROI back into frame-normalized
18766
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
18767
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
18768
- * (today's behaviour on the fallback path).
18769
- */
18770
- nativeCropRef: NativeCropRefSchema.optional()
18771
- }), PipelineRunResultBridge, { kind: "mutation" }),
18772
- /**
18773
- * Batched run — N raw frames packed into one cap call. The provider
18774
- * routes the batch through `SharedInferencePool.inferBatch`
18775
- * (`MSG_INFER_BATCH = 0x03`) so the IPC framing and JSON response
18776
- * envelope cost is amortised N:1 vs N concurrent `runPipeline`
18777
- * calls. Single root step + uniform model assumed; trees with crop
18778
- * children fall back to sequential execution.
18779
- *
18780
- * Used by `scripts/bench-batch-style.mts` for batch benchmarking —
18781
- * N frames in one call to amortise per-call IPC overhead.
18782
- */
18783
- runPipelineBatch: method(object({
18784
- engine: PipelineEngineChoiceSchema.optional(),
18785
- steps: array(PipelineStepInputSchema).min(1),
18786
- frames: array(FrameInputSchema).min(1).max(255),
18787
- deviceId: number().optional(),
18788
- sessionId: string().optional(),
18789
- /**
18790
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
18791
- * the batch to the Python pool's bench preprocess cache
18792
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
18793
- * preprocessed ONCE and every later inference is a pure-inference cache
18794
- * hit — the sustained-throughput run measures inference, not
18795
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
18796
- * full preprocess every call, correct). Fresh per sustained run;
18797
- * released via `uncacheFrame`.
18798
- */
18799
- frameId: number().int().nonnegative().optional(),
18800
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
18801
- deviceKey: string().optional()
18802
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }),
18803
- /**
18804
- * Cache a raw frame inside the Python inference pool's memory.
18805
- * Returns a numeric `frameId` that `inferCached` references
18806
- * subsequent calls send only 5 bytes through the pipe instead of
18807
- * 1.2MB raw data, eliminating the pipe transfer bottleneck.
18808
- */
18809
- cacheFrameInPool: method(object({
18810
- data: _instanceof(Uint8Array),
18811
- width: number().int().positive(),
18812
- height: number().int().positive(),
18813
- format: _enum([
18814
- "rgb",
18815
- "bgr",
18816
- "gray"
18817
- ])
18818
- }), object({
18819
- frameId: number(),
18820
- width: number(),
18821
- height: number()
18822
- }), { kind: "mutation" }),
18823
- /**
18824
- * Run inference on a previously cached frame. Sends only 5 bytes
18825
- * (model_idx + frameId) through the IPC pipe — eliminates the
18826
- * ~35ms per-call overhead of transferring 1.2MB raw data.
18827
- */
18828
- inferCached: method(object({
18829
- stepId: string(),
18830
- frameId: number().int()
18831
- }), record(string(), unknown()), { kind: "mutation" }),
18832
- /**
18833
- * Release a cached frame from the Python pool's memory.
18834
- */
18835
- uncacheFrame: method(object({ frameId: number().int() }), _void(), { kind: "mutation" }),
18836
- /** Returns the effective pool tuning (resolved from user overrides + backend defaults). */
18837
- getEffectiveTuning: method(_void(), object({
18838
- batchMode: string(),
18839
- windowMs: number(),
18840
- maxBatchSize: number(),
18841
- concurrency: number()
18842
- })),
18843
- /**
18844
- * List every EngineFactory currently loaded in this executor's RAM,
18845
- * with the models resident and a coarse "in use" marker derived from
18846
- * ongoing inference activity. Used by the Pipeline page Engines tab.
18847
- */
18848
- listLoadedEngines: method(_void(), array(object({
18849
- engineKey: string(),
18850
- engine: PipelineEngineChoiceSchema,
18851
- modelsLoaded: array(string()).readonly(),
18852
- inUseByCameras: array(number()).readonly(),
18853
- /**
18854
- * Origin of this resident factory.
18855
- * - `runtime` — main camera-serving engine (no idle TTL).
18856
- * - `warm-override` benchmark/test override held in the warm
18857
- * cache; auto-disposed after the idle TTL.
18858
- * - `device-pool` — a concurrent per-device pool (Phase 2
18859
- * multi-device, keyed by `deviceKey`) resolved
18860
- * via `resolveDeviceFactory`. Runs alongside the
18861
- * `runtime` engine on a DIFFERENT accelerator
18862
- * (NPU / iGPU / Coral) — this is how the
18863
- * Engines tab shows all pools running at once.
18864
- */
18865
- kind: _enum([
18866
- "runtime",
18867
- "warm-override",
18868
- "device-pool"
18869
- ]),
18870
- /** Native pid of the underlying Python pool (null when no pool). */
18871
- poolPid: number().nullable(),
18872
- /** ms since this factory was last used (null when not warm-tracked). */
18873
- idleMs: number().nullable(),
18874
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
18875
- idleTtlMs: number().nullable()
18876
- })).readonly()),
18877
- /** Warm up an engine without running a frame. No-op if already loaded. */
18878
- spinEngine: method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
18879
- kind: "mutation",
18880
- auth: "admin"
18881
- }),
18882
- /**
18883
- * Unload an engine from RAM. `force:true` unloads even when cameras
18884
- * are actively using it (they re-spin on next frame). Default is
18885
- * gated — returns `{success:false, reason}` when in use.
18886
- */
18887
- killEngine: method(object({
18888
- engine: PipelineEngineChoiceSchema,
18889
- force: boolean().optional()
18890
- }), object({
18891
- success: boolean(),
18892
- reason: string().optional()
18893
- }), {
18894
- kind: "mutation",
18895
- auth: "admin"
18896
- }),
18897
- listReferenceImages: method(_void(), array(ReferenceImageEntrySchema).readonly()),
18898
- getReferenceImage: method(object({ filename: string() }), ReferenceImageBodySchema.nullable()),
18899
- getReferenceAudioFiles: method(_void(), array(ReferenceAudioEntrySchema).readonly()),
18900
- getReferenceAudio: method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()),
18901
- getAudioCapabilities: method(_void(), AudioCapabilitiesSchema),
18902
- runAudioTest: method(object({
18903
- addonId: string(),
18904
- modelId: string(),
18905
- filename: string().optional(),
18906
- settings: record(string(), unknown()).optional()
18907
- }), AudioTestResultSchema, { kind: "mutation" }),
18908
- getDetectionConfigSchema: method(_void(), ConfigUISchemaNullableBridge)
18909
- }
18910
- };
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(),
18835
+ /**
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.
18846
+ */
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()
18859
+ });
18860
+ /**
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.
18867
+ */
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()
18882
+ });
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, {
19020
+ kind: "mutation",
19021
+ auth: "admin"
19022
+ }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
19023
+ kind: "mutation",
19024
+ auth: "admin"
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()
19082
+ }), object({
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, {
19136
+ kind: "mutation",
19137
+ auth: "admin"
19138
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
19139
+ kind: "query",
19140
+ auth: "admin"
19141
+ }), method(object({
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, {
19153
+ kind: "mutation",
19154
+ auth: "admin"
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
+ });
18911
19179
  object({
18912
19180
  activeCameras: number(),
18913
19181
  throttledCameras: number(),
@@ -18933,106 +19201,6 @@ var CameraMetricsSchema = object({
18933
19201
  });
18934
19202
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
18935
19203
  /**
18936
- * Zone — pure geometry + identity. NO filtering behaviour.
18937
- *
18938
- * Zones describe **where** in the frame the operator wants to flag
18939
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
18940
- * each pipeline stage uses them. Splitting the two means a single
18941
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
18942
- * a detection-include rule on `['car']`, and an occupancy aggregate
18943
- * — without three duplicated polygons.
18944
- *
18945
- * Owned by the orchestrator addon (provider) and mirrored into the
18946
- * `zones` device-state slice on every mutation. Consumers
18947
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
18948
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
18949
- * mirror with `onChanged`).
18950
- *
18951
- * Coordinates are normalised fractions of the frame (0–1) so zones
18952
- * survive resolution changes and stream profile switches.
18953
- *
18954
- * `kind` discriminates between full polygons (closed regions used
18955
- * for intrusion / occupancy filters) and tripwires (open 2-point
18956
- * line segments used for cross events). Onboard / firmware-reported
18957
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
18958
- * task list.
18959
- */
18960
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
18961
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
18962
- var PolygonPointSchema = object({
18963
- x: number(),
18964
- y: number()
18965
- });
18966
- /** A camera detection zone — pure geometry/identity. */
18967
- var ZoneSchema = object({
18968
- id: string(),
18969
- name: string(),
18970
- kind: ZoneKindEnum.default("polygon"),
18971
- /** Polygon vertices, fraction of frame (0–1). */
18972
- polygon: array(PolygonPointSchema).readonly(),
18973
- /** Visual color for UI rendering. */
18974
- color: string().default("#3b82f6")
18975
- });
18976
- /**
18977
- * Zones capability — per-camera CRUD over polygon detection zones.
18978
- *
18979
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
18980
- * to per-device settings and mirrors into the `zones` device-state
18981
- * slice on every mutation, so downstream consumers can subscribe via
18982
- * `dev.state.zones.onChanged`.
18983
- *
18984
- * The cap surface only handles geometry + identity; filtering
18985
- * behaviour (per-class, include/exclude, threshold) lives in the
18986
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
18987
- * `capabilities/schemas/zone-rule.js`.
18988
- */
18989
- var zonesCapability = {
18990
- name: "zones",
18991
- scope: "device",
18992
- mode: "singleton",
18993
- deviceTypes: [DeviceType.Camera],
18994
- methods: {
18995
- listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
18996
- addZone: method(object({
18997
- deviceId: number(),
18998
- zone: ZoneSchema
18999
- }), _void(), {
19000
- kind: "mutation",
19001
- auth: "admin"
19002
- }),
19003
- removeZone: method(object({
19004
- deviceId: number(),
19005
- zoneId: string()
19006
- }), _void(), {
19007
- kind: "mutation",
19008
- auth: "admin"
19009
- }),
19010
- updateZone: method(object({
19011
- deviceId: number(),
19012
- zone: ZoneSchema
19013
- }), _void(), {
19014
- kind: "mutation",
19015
- auth: "admin"
19016
- })
19017
- },
19018
- /**
19019
- * Runtime-state slice — the live zone catalogue mirrored by the
19020
- * orchestrator on every CRUD mutation. Consumers read via
19021
- * `device.state.zones.value` / `.watch(...)` without round-tripping
19022
- * the cap, and the codegen DeviceProxy auto-wires the reactive
19023
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
19024
- * (e.g. zone groupings) can sit alongside the polygon list.
19025
- */
19026
- runtimeState: object({ zones: array(ZoneSchema).readonly() }),
19027
- /**
19028
- * 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.
19029
- *
19030
- * See `RuntimeStateDurability`. Enforced by
19031
- * `scripts/check-runtime-state-durability.ts`.
19032
- */
19033
- durability: "restored"
19034
- };
19035
- /**
19036
19204
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
19037
19205
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
19038
19206
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -27095,92 +27263,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), SceneMonitorStatusSche
27095
27263
  kind: "mutation",
27096
27264
  auth: "admin"
27097
27265
  });
27098
- /**
27099
- * Per-stage gating mode applied to the zones a rule references.
27100
- *
27101
- * - `include`: the rule contributes to a **whitelist** for its stage.
27102
- * When at least one `include` rule fires for a stage, only entities
27103
- * inside one of those zones pass that stage.
27104
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
27105
- * Entities inside one of those zones are dropped at that stage.
27106
- *
27107
- * `monitor`-style observation (count without filtering) is not a rule
27108
- * mode — zones without any matching rule are observed naturally by
27109
- * `zone-analytics` (live snapshot + history), so an "I just want to
27110
- * count, not filter" use case needs no rule at all.
27111
- */
27112
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
27113
- /**
27114
- * Per-consumer rule that references existing zones (geometry) and
27115
- * defines how a specific pipeline stage should treat them. Each
27116
- * consumer addon owns its own `ZoneRule[]` array in its per-device
27117
- * settings:
27118
- *
27119
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
27120
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
27121
- * - future: notification rules, audio gating, etc.
27122
- *
27123
- * One rule applies to N zones (`zoneIds[]`) so the operator can
27124
- * express "ignore motion in ALL of {garden, street}" with a single
27125
- * rule. `classFilter` narrows the rule to specific object classes —
27126
- * "drop person detections in the street, but keep cars" is one
27127
- * `exclude` rule with `classFilter: ['person']`.
27128
- *
27129
- * `enabled` is a soft toggle — the operator can keep the rule
27130
- * configured but inert without deleting it.
27131
- */
27132
- var ZoneRuleSchema = object({
27133
- /** Stable rule id — survives edits, used by the UI for diffing. */
27134
- id: string(),
27135
- /** Optional human-readable label rendered in the rule editor. */
27136
- name: string().optional(),
27137
- /** Zones this rule targets. The rule's `mode` applies to ALL
27138
- * listed zones (OR-set: a detection in any one of them counts).
27139
- * At least one zone id required — a rule with no targets is a
27140
- * configuration mistake and the form validator rejects it. */
27141
- zoneIds: array(string()).min(1).readonly(),
27142
- mode: ZoneRuleModeEnum,
27143
- /**
27144
- * Class names this rule applies to. Empty / undefined ⇒ rule
27145
- * applies to every class. Class strings match the `macroClass`
27146
- * field on detections (e.g. `person`, `car`, `dog`).
27147
- */
27148
- classFilter: array(string()).readonly().optional(),
27149
- /**
27150
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
27151
- * required to consider an entity "in the zone". Defaults to the
27152
- * consumer's stage default when omitted. Kept for back-compat with
27153
- * existing per-rule overrides; new operators pick the value via
27154
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
27155
- * set, the lower-level engine reads it as a 0–1 fraction.
27156
- */
27157
- overlapThreshold: number().min(0).max(1).optional(),
27158
- /**
27159
- * Operator-friendly version of `overlapThreshold` — the percentage
27160
- * of the detection's bbox that must lie inside the zone for the
27161
- * rule to match. Documented default is 85%; the engine substitutes
27162
- * that when the field is omitted (kept optional so existing rules
27163
- * stored without it stay valid).
27164
- *
27165
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
27166
- * rule, the engine prefers `bboxInclusionPct` because it's the
27167
- * field exposed in the UI. Internally both feed the same gate.
27168
- */
27169
- bboxInclusionPct: number().min(0).max(100).optional(),
27170
- /**
27171
- * When `true` and a detection has a segmentation mask, use the
27172
- * mask for overlap instead of the bbox. Detection-stage only;
27173
- * motion rules ignore this field.
27174
- */
27175
- preferMask: boolean().optional(),
27176
- /**
27177
- * Soft-toggle: `false` disables the rule without deleting it.
27178
- * Defaults to `true` so operators creating a rule via the UI
27179
- * see it active immediately.
27180
- */
27181
- enabled: boolean().default(true)
27182
- });
27183
- array(ZoneRuleSchema).readonly();
27184
27266
  object({
27185
27267
  /** Whether the script is currently executing. */
27186
27268
  isRunning: boolean(),
@@ -31573,6 +31655,12 @@ Object.freeze({
31573
31655
  addonId: null,
31574
31656
  access: "create"
31575
31657
  },
31658
+ "pipelineAnalytics.runReplayFrameProcessor": {
31659
+ capName: "pipeline-analytics",
31660
+ capScope: "device",
31661
+ addonId: null,
31662
+ access: "create"
31663
+ },
31576
31664
  "pipelineAnalytics.saveRetrainAnnotations": {
31577
31665
  capName: "pipeline-analytics",
31578
31666
  capScope: "device",
@@ -31705,6 +31793,12 @@ Object.freeze({
31705
31793
  addonId: null,
31706
31794
  access: "view"
31707
31795
  },
31796
+ "pipelineExecutor.getInferenceDeviceHealth": {
31797
+ capName: "pipeline-executor",
31798
+ capScope: "system",
31799
+ addonId: null,
31800
+ access: "view"
31801
+ },
31708
31802
  "pipelineExecutor.getOrchestratorConfigSchema": {
31709
31803
  capName: "pipeline-executor",
31710
31804
  capScope: "system",
@@ -31777,6 +31871,12 @@ Object.freeze({
31777
31871
  addonId: null,
31778
31872
  access: "view"
31779
31873
  },
31874
+ "pipelineExecutor.rearmInferenceDevice": {
31875
+ capName: "pipeline-executor",
31876
+ capScope: "system",
31877
+ addonId: null,
31878
+ access: "create"
31879
+ },
31780
31880
  "pipelineExecutor.runAudioTest": {
31781
31881
  capName: "pipeline-executor",
31782
31882
  capScope: "system",
@@ -35025,6 +35125,11 @@ Object.freeze({
35025
35125
  form: "single",
35026
35126
  optional: false
35027
35127
  }],
35128
+ "pipelineAnalytics.runReplayFrameProcessor": [{
35129
+ name: "deviceId",
35130
+ form: "single",
35131
+ optional: false
35132
+ }],
35028
35133
  "pipelineAnalytics.saveRetrainAnnotations": [{
35029
35134
  name: "deviceId",
35030
35135
  form: "single",
@@ -36560,7 +36665,7 @@ function inferenceDeviceCaps(stored) {
36560
36665
  function isCpuFallback(view) {
36561
36666
  return view.backend === "cpu";
36562
36667
  }
36563
- function resolveInferenceDeviceEligibility(probed, stored, canRunRoot) {
36668
+ function resolveInferenceDeviceEligibility(probed, stored, canRunRoot, isPoolUsable) {
36564
36669
  const eligible = {};
36565
36670
  const excluded = [];
36566
36671
  const merged = mergeInferenceDevices(probed, stored);
@@ -36582,6 +36687,14 @@ function resolveInferenceDeviceEligibility(probed, stored, canRunRoot) {
36582
36687
  });
36583
36688
  continue;
36584
36689
  }
36690
+ if (isPoolUsable && !isPoolUsable(d.key)) {
36691
+ excluded.push({
36692
+ key: d.key,
36693
+ reason: "unavailable",
36694
+ format: d.format
36695
+ });
36696
+ continue;
36697
+ }
36585
36698
  if (canRunRoot && !canRunRoot(d.format)) {
36586
36699
  excluded.push({
36587
36700
  key: d.key,
@@ -36713,6 +36826,130 @@ var NodeInferenceUsabilityMirror = class {
36713
36826
  }
36714
36827
  };
36715
36828
  //#endregion
36829
+ //#region src/inference-device-usability-mirror.ts
36830
+ /**
36831
+ * InferenceDeviceUsabilityMirror — "can this NODE's THIS DEVICE still infer?",
36832
+ * kept off the placement path.
36833
+ *
36834
+ * The per-`(nodeId, deviceKey)` twin of {@link NodeInferenceUsabilityMirror},
36835
+ * and deliberately not a second mechanism: it composes the key and delegates
36836
+ * every decision to that class, so the arm/apply reluctance D49 pinned lives in
36837
+ * exactly one implementation and cannot drift between the node tier and the
36838
+ * device tier.
36839
+ *
36840
+ * ## Why this tier had to exist
36841
+ *
36842
+ * The node tier already answers "does this node have ANY usable accelerator".
36843
+ * On 2026-08-25 the hub's answer was, correctly, yes — its NPU was healthy the
36844
+ * whole time. What died was one DEVICE, `openvino:gpu`, and nothing anywhere
36845
+ * asked that question: the per-dispatch capability gate is keyed on model
36846
+ * FORMAT and `openvino:gpu` and `openvino:npu` share the format `openvino`, so
36847
+ * it is blind between them by construction. The balancer kept rotating cameras
36848
+ * onto the dead pool — 20 sessions in 20 minutes, every one `tieBreak:
36849
+ * "rotation"` — for 31 hours.
36850
+ *
36851
+ * ## Why a mirror and not the event
36852
+ *
36853
+ * D49, verbatim: *a one-shot event never gates on a fallible read*. The gate is
36854
+ * this in-memory mirror, refreshed off the event path by the same
36855
+ * `resolveEligibleInferenceDevices` the dispatcher already runs (plus the
36856
+ * session controller's background refresher). The consequences that buys:
36857
+ *
36858
+ * - **A read that fails changes nothing.** The caller folds in an observation
36859
+ * only when it HAS one; an unreachable node, a version-skewed executor or a
36860
+ * rejected RPC never reaches {@link observe}, so the previous verdict
36861
+ * stands. This is the whole reason the health read is specified as
36862
+ * "synchronous over in-memory state, never throws for its own reasons": an
36863
+ * empty answer must mean *nothing is refused*, not *I could not tell*.
36864
+ * - **Excluding a healthy device needs a second, consecutive read.** Exclusion
36865
+ * is the direction that DESTROYS work — it strands an accelerator that may
36866
+ * be perfectly fine — so one bad observation only ARMS.
36867
+ * - **Re-admitting is immediate and unconditional.** One good observation puts
36868
+ * the device straight back. Being slow to exclude costs some wasted
36869
+ * inference attempts; being slow to re-admit costs an idle accelerator and a
36870
+ * node that looks broken.
36871
+ */
36872
+ /**
36873
+ * NUL — impossible in both a Moleculer node id and a `<backend>:<device>` key,
36874
+ * so the composite key can never be ambiguous. A separator that CAN occur in
36875
+ * either half makes two distinct pairs collide, and a collision here silently
36876
+ * excludes an accelerator nobody reported.
36877
+ */
36878
+ var SEPARATOR = "\0";
36879
+ var InferenceDeviceUsabilityMirror = class {
36880
+ /** The one implementation of the arm/apply state machine (D49). */
36881
+ mirror = new NodeInferenceUsabilityMirror();
36882
+ /**
36883
+ * Fold one observation in and report whether the caller should act.
36884
+ * Never throws.
36885
+ */
36886
+ observe(nodeId, deviceKey, usable) {
36887
+ return this.mirror.observe(`${nodeId}${SEPARATOR}${deviceKey}`, usable);
36888
+ }
36889
+ /** Can the balancer put a session on this device? Unknown pairs answer YES. */
36890
+ isUsable(nodeId, deviceKey) {
36891
+ return this.mirror.isUsable(`${nodeId}${SEPARATOR}${deviceKey}`);
36892
+ }
36893
+ /** Pairs currently excluded — for the placement log and diagnostics. */
36894
+ unusableDevices() {
36895
+ return this.mirror.unusableNodeIds().map((composite) => {
36896
+ const at = composite.indexOf(SEPARATOR);
36897
+ return {
36898
+ nodeId: composite.slice(0, at),
36899
+ deviceKey: composite.slice(at + 1)
36900
+ };
36901
+ });
36902
+ }
36903
+ /** The excluded device keys on ONE node. */
36904
+ unusableDeviceKeys(nodeId) {
36905
+ return this.unusableDevices().filter((d) => d.nodeId === nodeId).map((d) => d.deviceKey);
36906
+ }
36907
+ forget(nodeId, deviceKey) {
36908
+ this.mirror.forget(`${nodeId}${SEPARATOR}${deviceKey}`);
36909
+ }
36910
+ reset() {
36911
+ this.mirror.reset();
36912
+ }
36913
+ };
36914
+ /**
36915
+ * Fold ONE node's health answer into the mirror and return what changed.
36916
+ *
36917
+ * This is the whole reading discipline, in one place, because both halves of it
36918
+ * are easy to get subtly wrong and neither failure is visible in a log:
36919
+ *
36920
+ * - **`unhealthy === null` — the read FAILED — changes nothing.** Not a single
36921
+ * entry is touched. An unreachable node, a version-skewed executor or a
36922
+ * rejected RPC must be distinguishable from "asked, nothing is refused", or
36923
+ * a flaky link silently re-admits a dead accelerator (D49).
36924
+ * - **Every device the node HAS is observed**, not merely the refused ones.
36925
+ * The first draft observed `refused ∪ already-excluded`, which omits exactly
36926
+ * the devices the mirror has ARMED — so their disarming good read never
36927
+ * arrived and two bad reads an HOUR apart, with a hundred healthy ones
36928
+ * between them, excluded a working accelerator. "Consecutive" is only a
36929
+ * property if the good observations are delivered.
36930
+ *
36931
+ * Pure with respect to everything except `mirror`, and never throws — it is
36932
+ * called from the dispatcher's own read path.
36933
+ */
36934
+ function foldInferenceDeviceHealth(mirror, nodeId, unhealthy, present) {
36935
+ if (unhealthy === null) return [];
36936
+ const refused = new Set(unhealthy);
36937
+ const observed = new Set([
36938
+ ...present,
36939
+ ...refused,
36940
+ ...mirror.unusableDeviceKeys(nodeId)
36941
+ ]);
36942
+ const changes = [];
36943
+ for (const deviceKey of observed) {
36944
+ const transition = mirror.observe(nodeId, deviceKey, !refused.has(deviceKey));
36945
+ if (transition !== null) changes.push({
36946
+ deviceKey,
36947
+ transition
36948
+ });
36949
+ }
36950
+ return changes;
36951
+ }
36952
+ //#endregion
36716
36953
  //#region src/orchestrator-types.ts
36717
36954
  var PHASE_MODE_VALUES = new Set([
36718
36955
  "disabled",
@@ -49915,7 +50152,7 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
49915
50152
  return {
49916
50153
  nodeId,
49917
50154
  reachable,
49918
- devices: annotateInferenceDeviceExclusions(mergeInferenceDevices(probed, stored), resolveInferenceDeviceEligibility(probed, stored, canRunRoot))
50155
+ devices: annotateInferenceDeviceExclusions(mergeInferenceDevices(probed, stored), resolveInferenceDeviceEligibility(probed, stored, canRunRoot, (deviceKey) => this.inferenceDeviceUsability.isUsable(nodeId, deviceKey)))
49919
50156
  };
49920
50157
  }
49921
50158
  /**
@@ -49928,9 +50165,10 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
49928
50165
  */
49929
50166
  async resolveEligibleInferenceDevices(nodeId) {
49930
50167
  const stored = (await this.settingsStore.readAgentSettingsMap())[nodeId]?.inferenceDevices ?? {};
49931
- const { probed } = await this.probeNodeInferenceDevices(nodeId);
50168
+ const [{ probed }, poolHealth] = await Promise.all([this.probeNodeInferenceDevices(nodeId), this.probeNodeInferenceDeviceHealth(nodeId)]);
50169
+ this.noteInferenceDeviceHealth(nodeId, poolHealth, probed.map((d) => d.key));
49932
50170
  const catalog = await this.settingsStore.getCatalogForNode(nodeId);
49933
- const eligibility = resolveInferenceDeviceEligibility(probed, stored, catalog ? makeRootCapabilityGuard(catalog) : void 0);
50171
+ const eligibility = resolveInferenceDeviceEligibility(probed, stored, catalog ? makeRootCapabilityGuard(catalog) : void 0, (deviceKey) => this.inferenceDeviceUsability.isUsable(nodeId, deviceKey));
49934
50172
  const { eligible, excluded } = eligibility;
49935
50173
  this.logInferenceDeviceShrinkage(nodeId, eligible, excluded);
49936
50174
  this.noteNodeInferenceUsability(nodeId, resolveNodeInferenceUsability(eligibility));
@@ -50005,6 +50243,78 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
50005
50243
  */
50006
50244
  nodeInferenceUsability = new NodeInferenceUsabilityMirror();
50007
50245
  /**
50246
+ * Which `(node, device)` pairs the balancer must stop choosing. Refreshed by
50247
+ * {@link resolveEligibleInferenceDevices} on the same cadence as the node
50248
+ * tier; read synchronously by `resolveInferenceDeviceEligibility`. See the
50249
+ * class docblock for why it is a mirror and not the event (D49).
50250
+ */
50251
+ inferenceDeviceUsability = new InferenceDeviceUsabilityMirror();
50252
+ /**
50253
+ * Ask ONE node's detection executor which of its inference devices it is
50254
+ * currently refusing.
50255
+ *
50256
+ * Returns the refused device keys, or **`null` when the question could not be
50257
+ * asked** — an offline node, a version-skewed executor without the method, a
50258
+ * rejected RPC. That distinction is the entire safety property: `null` is
50259
+ * dropped by {@link noteInferenceDeviceHealth} and changes no verdict, while
50260
+ * an empty array is a real answer that re-admits every device. Collapsing the
50261
+ * two — answering `[]` on error — would make a flaky link look exactly like a
50262
+ * healthy node and would silently re-admit a dead accelerator. NEVER throws.
50263
+ */
50264
+ async probeNodeInferenceDeviceHealth(nodeId) {
50265
+ try {
50266
+ const api = this.ctx.api;
50267
+ if (!api) return null;
50268
+ return (await api.pipelineExecutor.getInferenceDeviceHealth.query({ nodeId })).unhealthy.map((entry) => entry.deviceKey);
50269
+ } catch (err) {
50270
+ this.ctx.logger.warn("inference device health read failed — mirror left unchanged", {
50271
+ tags: { nodeId },
50272
+ meta: {
50273
+ nodeId,
50274
+ error: errMsg(err)
50275
+ }
50276
+ });
50277
+ return null;
50278
+ }
50279
+ }
50280
+ /**
50281
+ * Fold one health observation into the per-device mirror and say what
50282
+ * changed.
50283
+ *
50284
+ * The reading discipline itself lives in {@link foldInferenceDeviceHealth} —
50285
+ * a failed read changing nothing, and every device the node HAS being
50286
+ * observed rather than only the refused ones — because both halves are subtly
50287
+ * wrong-able and invisible when wrong, and the tests must exercise the same
50288
+ * implementation this does rather than a restatement of it. This method only
50289
+ * SAYS what changed.
50290
+ *
50291
+ * The exclusion is applied by the mirror's second CONSECUTIVE bad
50292
+ * observation, never the first — excluding a healthy accelerator is the
50293
+ * direction that destroys work.
50294
+ */
50295
+ noteInferenceDeviceHealth(nodeId, unhealthy, present) {
50296
+ const changes = foldInferenceDeviceHealth(this.inferenceDeviceUsability, nodeId, unhealthy, present);
50297
+ for (const { deviceKey, transition } of changes) {
50298
+ if (transition === "recovered") {
50299
+ this.ctx.logger.info("inference device recovered — back in the balancer candidate set", {
50300
+ tags: { nodeId },
50301
+ meta: {
50302
+ nodeId,
50303
+ deviceKey
50304
+ }
50305
+ });
50306
+ continue;
50307
+ }
50308
+ this.ctx.logger.error("inference device REFUSED by its executor — removed from the balancer candidate set", {
50309
+ tags: { nodeId },
50310
+ meta: {
50311
+ nodeId,
50312
+ deviceKey
50313
+ }
50314
+ });
50315
+ }
50316
+ }
50317
+ /**
50008
50318
  * Say out loud which of a node's inference devices were dropped from the
50009
50319
  * candidate set, and why.
50010
50320
  *