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