@camstack/addon-provider-dreame 0.2.29 → 0.2.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1889 -1816
  2. package/dist/addon.mjs +1889 -1816
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -66871,1760 +66871,1996 @@ var OauthIntegrationDescriptorSchema = object({
66871
66871
  });
66872
66872
  method(_void(), OauthIntegrationDescriptorSchema, { auth: "admin" });
66873
66873
  /**
66874
- * pipeline-analytics — device-scoped wrapper cap. Refines raw
66875
- * per-frame detections emitted by the pipeline runner into tracked
66876
- * objects, per-kind event collections (motion / object / audio), and
66877
- * persisted media. Owns the post-detection domain end-to-end:
66878
- *
66879
- * runner emits PipelineInferenceResult
66880
- * ↓ (event bus)
66881
- * pipeline-analytics subscriber
66882
- * ↓ SORT tracker + zone engine + state analyzer + event emitter
66883
- * → three DB collections (one per kind), one FS media tree, one
66884
- * unified event emitter (FrameTracked + TrackStarted/Ended +
66885
- * DetectionEvent on bus)
66886
- *
66887
- * Pure subscriber model. No `processFrame` cap method — the runner
66888
- * already publishes the raw frame on the bus. The cap surface is
66889
- * only QUERIES + per-device settings, bound on/off via
66890
- * `device-manager.setWrapperActive`. `defaultActive: true` because
66891
- * every camera with a detection pipeline wants its raw detections
66892
- * refined; operators opt out per-device via BindingsTab when needed.
66893
- *
66894
- * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
66895
- * (per-device surface) and `track-trail` caps — see P11 cleanup.
66874
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
66875
+ * within the frame, so the executor can re-cut a leaf child ROI at native
66876
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
66896
66877
  */
66897
- var TrackStateSchema = _enum([
66898
- "new",
66899
- "entered",
66900
- "left",
66901
- "moving",
66902
- "idle"
66903
- ]);
66904
- var EventKindSchema = _enum([
66905
- "motion",
66906
- "object",
66907
- "audio"
66908
- ]);
66878
+ var NativeCropRefSchema = object({
66879
+ /** Handle keying the retained native surface (node-pinned to its owner). */
66880
+ handle: FrameHandleSchema,
66881
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
66882
+ cropFrameSpace: object({
66883
+ x: number(),
66884
+ y: number(),
66885
+ w: number(),
66886
+ h: number()
66887
+ })
66888
+ });
66889
+ object({
66890
+ crop: object({
66891
+ left: number(),
66892
+ top: number(),
66893
+ width: number().positive(),
66894
+ height: number().positive()
66895
+ }).optional(),
66896
+ content: object({
66897
+ width: number().int().positive(),
66898
+ height: number().int().positive()
66899
+ }),
66900
+ fit: _enum(["stretch", "contain"]),
66901
+ format: _enum([
66902
+ "rgb",
66903
+ "gray",
66904
+ "jpeg"
66905
+ ])
66906
+ });
66909
66907
  /**
66910
- * Spatial filter for `listTracks` — the rect + polygon variants of the shared
66911
- * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
66912
- * of the camera frame (top-left origin), matching the drawing-plane editor.
66908
+ * Process-local frame identity. It is serializable so it can ride an in-process
66909
+ * capability call, but `registryId` deliberately prevents resolution in any
66910
+ * other process or execution group.
66913
66911
  */
66914
- var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
66915
- /** Closed icon vocabulary so clients render a known glyph per kind. */
66916
- var EventKindIconSchema = _enum([
66917
- "motion",
66918
- "audio",
66919
- "person",
66920
- "vehicle",
66921
- "animal",
66922
- "door",
66923
- "pir",
66924
- "smoke",
66925
- "water",
66926
- "button",
66927
- "package",
66928
- "generic"
66912
+ var FrameRefSchema = object({
66913
+ registryId: string().min(1),
66914
+ id: string().min(1),
66915
+ width: number().int().positive(),
66916
+ height: number().int().positive(),
66917
+ format: _enum(["rgb", "gray"]),
66918
+ timestamp: number(),
66919
+ capturedAt: number().optional()
66920
+ });
66921
+ var ModelFormatSchema$1 = _enum([
66922
+ "onnx",
66923
+ "coreml",
66924
+ "openvino",
66925
+ "tflite",
66926
+ "pt",
66927
+ "gguf"
66929
66928
  ]);
66930
- var EventKindCategorySchema = _enum([
66931
- "motion",
66932
- "audio",
66933
- "detection",
66934
- "sensor",
66935
- "control",
66936
- "custom",
66937
- "package"
66929
+ var PipelineSlotSchema = _enum([
66930
+ "detector",
66931
+ "cropper",
66932
+ "classifier",
66933
+ "refiner",
66934
+ "audio-classifier"
66938
66935
  ]);
66939
- /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
66940
- var EventKindLevelSchema = _enum(["macro", "sub"]);
66941
- var EventKindDescriptorSchema = object({
66942
- /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
66943
- kind: string(),
66944
- /** i18n key resolved on the UI side; `label` is the English fallback. */
66945
- labelKey: string(),
66946
- /** English fallback label (kept for clients that don't translate). */
66947
- label: string(),
66948
- /** Hex color for timeline/legend rendering. */
66949
- color: string(),
66950
- /** Dictionary id → lucide component on the UI side. */
66951
- iconId: string(),
66952
- /** Legacy closed-vocab glyph — fallback for `iconId`. */
66953
- icon: EventKindIconSchema,
66954
- category: EventKindCategorySchema,
66955
- /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
66956
- parentKind: string().nullable(),
66957
- /** Derived from `parentKind`, explicit for the client tree. */
66958
- level: EventKindLevelSchema,
66959
- /** Which cap + device contributes this kind. For built-ins the camera
66960
- * itself; for sensor kinds the LINKED source device. */
66961
- source: object({
66962
- capName: string(),
66963
- deviceId: number()
66964
- })
66936
+ var PipelineEngineChoiceSchema = object({
66937
+ runtime: _enum(["node", "python"]),
66938
+ backend: string(),
66939
+ format: ModelFormatSchema$1,
66940
+ device: string().optional()
66965
66941
  });
66966
- /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
66967
- var EventKindsForDeviceSchema = object({
66968
- deviceId: number(),
66969
- kinds: array(EventKindDescriptorSchema).readonly()
66942
+ var AvailableEngineSchema = object({
66943
+ engine: PipelineEngineChoiceSchema,
66944
+ devices: array(object({
66945
+ id: string(),
66946
+ label: string(),
66947
+ description: string().optional()
66948
+ })).readonly(),
66949
+ defaultDevice: string()
66970
66950
  });
66971
- var SensorEventSchema = object({
66951
+ var PipelineDefaultStepSchema = lazy(() => object({
66952
+ addonId: string(),
66953
+ addonName: string(),
66954
+ slot: PipelineSlotSchema,
66955
+ inputClasses: array(string()).readonly(),
66956
+ outputClasses: array(string()).readonly(),
66957
+ enabled: boolean(),
66958
+ modelId: string(),
66959
+ children: array(PipelineDefaultStepSchema).readonly(),
66960
+ group: string().optional(),
66961
+ settings: record(string(), unknown()).optional()
66962
+ }));
66963
+ var PipelineTemplateStepSchema = lazy(() => object({
66964
+ addonId: string(),
66965
+ enabled: boolean(),
66966
+ modelId: string(),
66967
+ children: array(PipelineTemplateStepSchema).readonly(),
66968
+ settings: record(string(), unknown()).optional()
66969
+ }));
66970
+ var PipelineTemplateSchema$1 = object({
66972
66971
  id: string(),
66973
- /** The CAMERA the event is attributed to (a sensor linked to N cameras
66974
- * yields N rows, one per camera). */
66975
- deviceId: number(),
66976
- /** The linked sensor device whose state changed. */
66977
- sourceDeviceId: number(),
66978
- /** Event kind id — matches an `EventKindDescriptor.kind`. */
66979
- kind: string(),
66980
- /** Snapshot of the sensor cap's runtime-state slice at the change. */
66981
- value: record(string(), unknown()).nullable(),
66982
- timestamp: number()
66972
+ name: string(),
66973
+ createdAt: string(),
66974
+ updatedAt: string(),
66975
+ engine: PipelineEngineChoiceSchema,
66976
+ steps: array(PipelineTemplateStepSchema).readonly()
66983
66977
  });
66984
- var TrackPositionSchema = object({
66985
- x: number(),
66986
- y: number(),
66987
- timestamp: number(),
66988
- bbox: BoundingBoxSchema
66978
+ var PipelineModelOptionSchema = object({
66979
+ id: string(),
66980
+ name: string(),
66981
+ formats: record(string(), object({
66982
+ downloaded: boolean(),
66983
+ sizeMB: number()
66984
+ })),
66985
+ group: ModelVariantGroupSchema.optional(),
66986
+ legacy: boolean().optional(),
66987
+ provider: ModelProviderIdSchema.optional()
66989
66988
  });
66990
- var TrackSnapshotSchema = object({
66991
- timestamp: number(),
66992
- position: TrackPositionSchema,
66993
- /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
66994
- mediaKey: string()
66989
+ var ConfigFieldBridge = custom();
66990
+ var PipelineAddonSchemaSchema = object({
66991
+ id: string(),
66992
+ name: string(),
66993
+ slot: PipelineSlotSchema,
66994
+ inputClasses: array(string()).readonly(),
66995
+ outputClasses: array(string()).readonly(),
66996
+ childSlots: array(PipelineSlotSchema).readonly(),
66997
+ models: array(PipelineModelOptionSchema).readonly(),
66998
+ defaultModelId: string(),
66999
+ defaultModelIdByFormat: record(string(), string()).optional(),
67000
+ enabledByDefault: boolean().optional(),
67001
+ backfillIntoExistingOverrides: boolean().optional(),
67002
+ defaultConfidence: number(),
67003
+ group: string().optional(),
67004
+ configSchema: array(ConfigFieldBridge).readonly().optional()
66995
67005
  });
66996
- /**
66997
- * Normalized 0..1 trajectory envelope (min/max over every position bbox,
66998
- * divided by the track's detection-frame dims), computed at persist time.
66999
- * Absent when the frame dims were unknown when the track was persisted
67000
- * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
67001
- */
67002
- var TrackEnvelopeSchema = object({
67003
- minX: number(),
67004
- minY: number(),
67005
- maxX: number(),
67006
- maxY: number()
67006
+ var PipelineSlotSchemaSchema = object({
67007
+ id: PipelineSlotSchema,
67008
+ label: string(),
67009
+ priority: number(),
67010
+ parentSlot: PipelineSlotSchema.nullable(),
67011
+ addons: array(PipelineAddonSchemaSchema).readonly()
67007
67012
  });
67008
- /**
67009
- * Row projection for track list queries. `full` (default) returns the
67010
- * complete Track including the frame-rate `positions[]` history and the
67011
- * `snapshots[]` references — megabytes across a page of tracks. `slim`
67012
- * keeps every scalar the list surfaces actually render (ids, class(es),
67013
- * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
67014
- * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
67015
- * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
67016
- * `getTrack`. Mirrors the event-store `projection` convention
67017
- * (`getObjectEvents` et al.).
67018
- */
67019
- var TrackProjectionSchema = _enum(["full", "slim"]);
67020
- /**
67021
- * One audio-classification label heard on the track's camera while the
67022
- * track was alive, aggregated per label. An "episode" is one persisted
67023
- * audio event (the confident-classification path: score ≥ the device's
67024
- * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
67025
- * one 32 ms inference chunk, so counts stay human-scaled.
67026
- */
67027
- var TrackAudioLabelSchema = object({
67028
- label: string(),
67029
- /** Highest classification score observed across the label's episodes. */
67030
- peakScore: number(),
67031
- /** Number of coalesced audio-event episodes carrying this label. */
67032
- count: number(),
67033
- firstAt: number(),
67034
- lastAt: number()
67013
+ var PipelineSchemaSchema = object({
67014
+ availableEngines: array(AvailableEngineSchema).readonly(),
67015
+ selectedEngine: PipelineEngineChoiceSchema,
67016
+ slots: array(PipelineSlotSchemaSchema).readonly()
67035
67017
  });
67036
- /**
67037
- * How a track was produced. `pipeline` (default / absent) = the spatial
67038
- * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
67039
- * no positions, a single snapshot, and no bbox trajectory at all:
67040
- *
67041
- * - `sensor` — a linked sensor/control device state change.
67042
- * - `audio` — an audio event on the camera itself that was anomalous for
67043
- * THAT camera, loud, and heard while nothing visual was happening (D62).
67044
- *
67045
- * The spatial subsystems (tracker association, occupancy count, re-id /
67046
- * embedding, resurrection) MUST skip every synthetic source. Test for that
67047
- * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
67048
- * check silently readmits every source added after it was written.
67049
- */
67050
- var TrackSourceSchema = _enum([
67051
- "pipeline",
67052
- "sensor",
67053
- "audio"
67054
- ]);
67055
- /**
67056
- * Where a track sits in the RETRAIN lifecycle (D81).
67057
- *
67058
- * - `none` — never marked, or un-marked. Evictable.
67059
- * - `staging` — the operator wants this track as training material and has not
67060
- * finished with it. **This is the only state retention holds**: the track and
67061
- * everything it owns (object events, crops, keyframes, CLIP vector) survive
67062
- * the device's age window.
67063
- * - `trained` — the retrain page has taken what it needed. The frames it chose
67064
- * were COPIED into the retrain dataset at selection time, so the dataset no
67065
- * longer depends on the track's media and the track becomes EVICTABLE again.
67066
- * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
67067
- * a deliberate action of the retrain page, not a side effect of a checkbox.
67068
- *
67069
- * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
67070
- * the store's filter language has only positive equality and `whereIn` — no
67071
- * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
67072
- * would make the entire pre-column history immortal in one deploy.
67073
- */
67074
- var RetrainStatusSchema = _enum([
67075
- "none",
67076
- "staging",
67077
- "trained"
67078
- ]);
67079
- /**
67080
- * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
67081
- * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
67082
- * so the two surfaces cannot drift.
67083
- *
67084
- * **Absent ≠ false.** A track that has never been touched omits the field; an
67085
- * explicitly un-flagged track carries `false`. Legacy rows written before the
67086
- * columns existed read as absent, and a consumer that needs a boolean should say
67087
- * `flag === true`, not `flag !== false`.
67088
- *
67089
- * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
67090
- * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
67091
- * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
67092
- * `trained` track reports `false` while refusing both writes. The boolean is
67093
- * kept because three surfaces drive a toggle off it; anything that needs to tell
67094
- * "never marked" from "already trained" must read `retrainStatus`.
67095
- *
67096
- * `debug` does NOT pin; it is attention, not durability.
67097
- *
67098
- * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
67099
- * A favourited track is skipped by retention the same way `staging` is, but
67100
- * it does not enter `none|staging|trained` and has no staging budget.
67101
- */
67102
- var TrackFlagFields = {
67103
- /** Operator marked this track as training material — i.e. `retrainStatus` is
67104
- * `'staging'`. */
67105
- markForTrain: boolean().optional(),
67106
- /** Operator marked this track for diagnostic attention. */
67107
- debug: boolean().optional(),
67108
- /** Operator favourited this track. Pins it against pruning. */
67109
- favourited: boolean().optional()
67110
- };
67111
- /**
67112
- * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
67113
- * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
67114
- * write patch, and the status is not something the toggle sets — it is what the
67115
- * toggle's boolean is derived from. Absent on an in-RAM track never touched;
67116
- * always present on a persisted row (the column default materialises `'none'`).
67117
- */
67118
- var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
67119
- /**
67120
- * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
67121
- * one flag can never clear the other — the toggles are independent and are
67122
- * driven from three surfaces that do not know about each other.
67123
- */
67124
- var TrackFlagsPatchSchema = object(TrackFlagFields);
67125
- /**
67126
- * The resolved flag state after a write. Both fields are REQUIRED here (absent
67127
- * collapses to `false`) so a caller can drive a toggle's checked state off the
67128
- * mutation result without a re-fetch.
67129
- */
67130
- var TrackFlagsSchema = object({
67131
- trackId: string(),
67132
- markForTrain: boolean(),
67133
- debug: boolean(),
67134
- favourited: boolean(),
67135
- /** The lifecycle state the boolean was derived from. Required here (unlike on
67136
- * a track row) because this shape is only ever produced by the write body,
67137
- * which always knows it — and a surface that has just written needs to render
67138
- * `trained` without a re-fetch. */
67139
- retrainStatus: RetrainStatusSchema
67018
+ var EngineProvisioningSchema = object({
67019
+ runtimeId: _enum([
67020
+ "onnx",
67021
+ "openvino",
67022
+ "coreml",
67023
+ "edgetpu"
67024
+ ]).nullable(),
67025
+ device: string().nullable(),
67026
+ state: _enum([
67027
+ "idle",
67028
+ "installing",
67029
+ "verifying",
67030
+ "ready",
67031
+ "failed"
67032
+ ]),
67033
+ progress: number().optional(),
67034
+ error: string().optional(),
67035
+ nextRetryAt: number().optional(),
67036
+ /**
67037
+ * Gate A (config-correctness gate at engine change): human-readable
67038
+ * config issues surfaced EAGERLY when the node's engine changes — model
67039
+ * substitutions ("chose X, running Y") and zero-build steps ("no model
67040
+ * has a <format> build"). Additive/optional: informational only, never
67041
+ * enforced here — `assertEngineReady` (readiness) still gates inference.
67042
+ * Absent/empty when the node-default tree resolves cleanly.
67043
+ */
67044
+ configIssues: array(string()).optional()
67140
67045
  });
67141
- union([literal(1), literal(2)]);
67142
- /**
67143
- * WHO decided a label, and when. Carried per tier so a value can be traced to
67144
- * the step and model that produced it — which is what makes the write rule
67145
- * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
67146
- * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
67147
- *
67148
- * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
67149
- * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
67150
- * `migration:4g` for a value the 4g migration moved from the single-slot era —
67151
- * that value has no provenance, and the write rule lets ANY properly-attributed
67152
- * write of the same tier replace it regardless of score.
67153
- */
67154
- var LabelAttributionSchema = object({
67155
- stepId: string(),
67046
+ var PipelineStepInputSchema = lazy(() => object({
67047
+ addonId: string(),
67156
67048
  modelId: string().optional(),
67157
- decidedAt: number(),
67049
+ enabled: boolean().default(true),
67050
+ children: array(PipelineStepInputSchema).optional(),
67051
+ settings: record(string(), unknown()).optional(),
67052
+ jumpDeviceKey: string().optional()
67053
+ }));
67054
+ var ModelSubstitutionSchema = object({
67055
+ addonId: string(),
67056
+ chosen: string(),
67057
+ running: string(),
67058
+ format: string()
67059
+ });
67060
+ var PipelineValidationIssueSchema = object({
67061
+ addonId: string(),
67062
+ kind: _enum(["unknown-addon", "no-format-build"]),
67063
+ detail: string()
67064
+ });
67065
+ var PipelineValidationResultSchema = object({
67066
+ ok: boolean(),
67067
+ issues: array(PipelineValidationIssueSchema).readonly(),
67068
+ substitutions: array(ModelSubstitutionSchema).readonly(),
67069
+ /** The node's `currentEngine.format` this validation ran against. */
67070
+ format: string()
67071
+ });
67072
+ var ReferenceImageEntrySchema = object({
67073
+ filename: string(),
67074
+ stepIds: array(string()).readonly().optional()
67075
+ });
67076
+ var ReferenceImageBodySchema = object({
67077
+ base64: string(),
67078
+ filename: string()
67079
+ });
67080
+ var ReferenceAudioEntrySchema = object({
67081
+ filename: string(),
67082
+ sizeKb: number()
67083
+ });
67084
+ var ReferenceAudioBodySchema = object({ base64: string() });
67085
+ var AudioBackendSchema = object({
67086
+ id: string(),
67087
+ name: string(),
67088
+ description: string(),
67089
+ available: boolean(),
67158
67090
  /**
67159
- * The GALLERY id behind a recognised tier-2 label — a face-gallery
67160
- * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
67161
- *
67162
- * The text alone is a DISPLAY NAME, and a display name is renameable: a
67163
- * notification rule authored on "Gianluca" stopped matching the moment the
67164
- * operator fixed the spelling in the gallery, and nothing said so. The id is
67165
- * the thing that does not move, so it is what a rule matches on
67166
- * (`NcConditions.identities`) and the text is what a human is shown.
67167
- *
67168
- * Absent when the label names no gallery row — a plate the OCR read but no
67169
- * vehicle claims, a sub-class, a species, any tier-1 value.
67091
+ * Raw classifier labels this backend can emit (e.g. YAMNet's
67092
+ * 521-class set or Apple SoundAnalysis's 303-class set). Used by
67093
+ * the benchmark UI to populate the `enabledMicroClasses` filter
67094
+ * specific to the selected backend without a separate fetch.
67170
67095
  */
67171
- identityId: string().optional()
67096
+ rawLabels: array(string()).readonly().optional()
67097
+ });
67098
+ var AudioCapabilitiesSchema = object({
67099
+ activeBackend: string(),
67100
+ availableBackends: array(AudioBackendSchema).readonly(),
67101
+ sampleRate: number(),
67102
+ chunkDurationMs: number()
67103
+ });
67104
+ var DownloadModelResultSchema = object({
67105
+ filePath: string(),
67106
+ sizeMB: number(),
67107
+ durationMs: number()
67172
67108
  });
67173
67109
  /**
67174
- * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
67175
- * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
67176
- * track and its events always answer the same question the same way.
67177
- *
67178
- * Two scalar columns, not an array: every consumer wants "the coarse one" or
67179
- * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
67180
- * is tier 2, and each carries its own score + attribution.
67181
- *
67182
- * **Reading it.** What a human should be shown is `subLabel ?? label` — the
67183
- * finest thing known. Before 4g the single `label` column held the finest
67184
- * value, so a consumer that has not been updated reads the tier-1 slot and
67185
- * shows nothing on a species-only row; that is why the migration puts every
67186
- * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
67187
- * and why the read surfaces were changed in the same train.
67188
- *
67189
- * **Writing it.** The slots are independent, which is the whole point: a
67190
- * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
67191
- * migratorius`), so fineness cannot regress by construction. Within a tier the
67192
- * higher score wins. One rule, one implementation — see
67193
- * `pipeline/label-tier.ts` in addon-post-analysis.
67194
- */
67195
- var TieredLabelFields = {
67196
- /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
67197
- label: string().optional(),
67198
- /** Confidence of the tier-1 value, as reported by the deciding step. */
67199
- labelScore: number().optional(),
67200
- /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
67201
- labelMeta: LabelAttributionSchema.optional(),
67202
- /** Tier 2 — the instance. See {@link LabelTierSchema}. */
67203
- subLabel: string().optional(),
67204
- /** Confidence of the tier-2 value, as reported by the deciding step. */
67205
- subLabelScore: number().optional(),
67206
- /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
67207
- subLabelMeta: LabelAttributionSchema.optional()
67208
- };
67209
- /** Per-camera slice of a training-export estimate. */
67210
- var TrainingExportDeviceTotalsSchema = object({
67211
- deviceId: number(),
67212
- tracks: number().int(),
67213
- files: number().int(),
67214
- bytes: number().int()
67215
- });
67216
- /**
67217
- * What a training export WOULD contain. Computed from media index rows only —
67218
- * no blob is read to produce this.
67110
+ * Wrapper carrying a single test run's result. Replaces the legacy
67111
+ * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
67112
+ * canonical `AudioResult` from the Phase 6 output rework: one
67113
+ * `AudioDetection` per class above `minScore`, top-N candidates in
67114
+ * `debug.alternateLabels['audio-classifier']`, per-source timings in
67115
+ * `debug.stepTimings`. The outer `success`/`error` fields stay so the
67116
+ * benchmark UI can still report a clean failure when the classifier
67117
+ * cap isn't available.
67219
67118
  */
67220
- var TrainingExportSummarySchema = object({
67221
- generatedAt: number(),
67222
- trackCount: number().int(),
67223
- fileCount: number().int(),
67224
- byteCount: number().int(),
67225
- /** More marked tracks exist than a single pass carries. */
67226
- truncated: boolean(),
67227
- devices: array(TrainingExportDeviceTotalsSchema).readonly()
67119
+ var AudioTestResultSchema = object({
67120
+ success: boolean(),
67121
+ error: string().optional(),
67122
+ frame: custom().optional()
67228
67123
  });
67229
- var TrackSchema = object({
67230
- trackId: string(),
67231
- deviceId: number(),
67232
- className: string(),
67233
- ...TieredLabelFields,
67234
- producingDeviceName: string().optional(),
67235
- /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
67236
- source: TrackSourceSchema.optional(),
67237
- firstSeen: number(),
67238
- lastSeen: number(),
67239
- /** Frame-rate position history (subject to maxPositionHistory cap). */
67240
- positions: array(TrackPositionSchema).readonly(),
67241
- /** Periodic snapshots at snapshotIntervalMs cadence (subject to
67242
- * saveThumbnails policy). */
67243
- snapshots: array(TrackSnapshotSchema).readonly(),
67244
- /** Deduplicated zones the track has entered at least once. Zone IDS. */
67245
- zonesVisited: array(string()).readonly(),
67124
+ var PipelineConfigBridge = custom();
67125
+ var ConfigUISchemaBridge = custom();
67126
+ var ConfigUISchemaNullableBridge = custom();
67127
+ var InferenceCapabilitiesBridge = custom();
67128
+ var ModelAvailabilityListBridge = custom();
67129
+ var PipelineRunResultBridge = custom();
67130
+ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
67131
+ modelId: string(),
67132
+ settings: record(string(), unknown()).readonly()
67133
+ }))), method(object({ steps: record(string(), object({
67134
+ modelId: string(),
67135
+ settings: record(string(), unknown()).readonly()
67136
+ })) }), object({ success: literal(true) }), {
67137
+ kind: "mutation",
67138
+ auth: "admin"
67139
+ }), method(object({ nodeId: string() }), object({
67140
+ success: literal(true),
67141
+ clearedDevices: number()
67142
+ }), {
67143
+ kind: "mutation",
67144
+ auth: "admin"
67145
+ }), method(object({ nodeId: string() }), object({ unhealthy: array(object({
67146
+ /** `<backend>:<device>`, e.g. `openvino:gpu`. */
67147
+ deviceKey: string(),
67246
67148
  /**
67247
- * Human NAMES for {@link zonesVisited}, resolved at READ time against the
67248
- * `zones` capability.
67249
- *
67250
- * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
67251
- * and no card can render — so every free-text search surface was structurally
67252
- * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
67253
- * just returned nothing. Resolving here rather than in each client keeps ONE
67254
- * derivation and costs the clients no extra call (the `zones` cap is
67255
- * per-device, so a client-side resolve would be a per-camera fan-out on a
67256
- * surface built to avoid exactly that).
67257
- *
67258
- * Resolved, never invented: a zone deleted since the track was written has no
67259
- * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
67260
- * two are not positionally aligned. Absent when the track visited no zone, or
67261
- * when the zone catalogue could not be read.
67149
+ * `failed` — the per-device restart budget is exhausted; no pool
67150
+ * will be spawned until an operator re-arms it or the runner
67151
+ * respawns. `backoff` — under budget, waiting out the backoff (or
67152
+ * a cached pool observed dead and not yet condemned).
67262
67153
  */
67263
- zoneNames: array(string()).readonly().optional(),
67264
- /** Deduplicated set of detector classes observed for this track over its
67265
- * life (a track may be reclassified, e.g. person→vehicle). Absent on
67266
- * legacy rows written before class accumulation shipped. */
67267
- classes: array(string()).readonly().optional(),
67268
- /** Cumulative normalized distance travelled (0..1 units = full frame width). */
67269
- totalDistance: number(),
67270
- state: TrackStateSchema,
67271
- active: boolean(),
67272
- /** Deterministic key-event importance score in [0,1] (server-computed at
67273
- * track expiry, recomputed on late label). Absent on legacy rows written
67274
- * before scoring shipped — consumers degrade to absence / compute-on-read. */
67275
- importance: number().optional(),
67276
- /** Id of the track's highest-confidence ObjectEvent (its representative
67277
- * "best" frame). Absent when the track produced no object events. */
67278
- bestEventId: string().optional(),
67279
- /** Tag of the importance sub-signal that dominated the score
67280
- * (identity|dwell|proximity|class|confidence|travel|zone). */
67281
- importanceReason: string().optional(),
67282
- /** Audio-classification labels heard on the camera during the track's
67283
- * life (score ≥ device `classificationMinScore`), aggregated per label.
67284
- * Absent on legacy rows / tracks with no confident audio. */
67285
- audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
67286
- /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
67287
- * Populated from the persisted envelope columns on historical reads;
67288
- * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
67289
- envelope: TrackEnvelopeSchema.optional(),
67154
+ state: _enum(["failed", "backoff"]),
67155
+ /** Epoch ms of the death that produced this state. */
67156
+ since: number(),
67157
+ /** Pool deaths inside the current window. */
67158
+ deaths: number(),
67159
+ /** The last death's message. */
67160
+ lastError: string()
67161
+ })).readonly() })), method(object({
67162
+ nodeId: string(),
67163
+ deviceKey: string()
67164
+ }), object({ rearmed: boolean() }), {
67165
+ kind: "mutation",
67166
+ auth: "admin"
67167
+ }), method(_void(), PipelineSchemaSchema), method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()), method(_void(), PipelineConfigBridge), method(_void(), ConfigUISchemaBridge), method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema), method(_void(), array(PipelineTemplateSchema$1).readonly()), method(object({
67168
+ name: string(),
67169
+ steps: array(PipelineTemplateStepSchema).readonly(),
67170
+ engine: PipelineEngineChoiceSchema
67171
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
67172
+ id: string(),
67173
+ name: string().optional(),
67174
+ steps: array(PipelineTemplateStepSchema).readonly().optional()
67175
+ }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
67176
+ addonId: string(),
67177
+ modelId: string(),
67178
+ format: ModelFormatSchema$1
67179
+ }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
67180
+ addonId: string(),
67181
+ modelId: string(),
67182
+ format: ModelFormatSchema$1
67183
+ }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
67184
+ engine: PipelineEngineChoiceSchema.optional(),
67185
+ steps: array(PipelineStepInputSchema).min(1),
67186
+ frame: FrameInputSchema.optional(),
67290
67187
  /**
67291
- * A face DETECTOR found a face on this track — nothing more. It says the
67292
- * detail plane produced a `face` detail; it does NOT say the face was
67293
- * embedded, matched, above `minFacePx`, or that the recognizer was even
67294
- * enabled. Set once and never cleared.
67295
- *
67296
- * **This exists so "face present but not recognised" is expressible.** A
67297
- * recognised identity lands in `subLabel` (attributed to the face chain via
67298
- * `subLabelMeta.stepId`), so before this field a track with an unmatched face
67299
- * and a track with no face at all were byte-identical on the wire and no
67300
- * surface could tell them apart. The read is `hasFace === true && subLabel
67301
- * === undefined`.
67302
- *
67303
- * **Absent ≠ false.** Every row written before the column existed omits it,
67304
- * and so does every server that predates the field — a consumer must test
67305
- * `=== true` and render nothing otherwise, never infer "no face".
67188
+ * Process-local lazy frame. Valid only when caller and provider resolve
67189
+ * in the same execution-group process; split/cross-node callers use
67190
+ * `frame`/`image` inline compatibility instead.
67306
67191
  */
67307
- hasFace: boolean().optional(),
67192
+ frameRef: FrameRefSchema.optional(),
67308
67193
  /**
67309
- * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
67310
- * face an operator could ASSIGN to an identity.
67311
- *
67312
- * The STRICT twin of {@link hasFace}, and the pair only earns its keep
67313
- * because the two disagree. `hasFace` is stamped at the TOP of the face
67314
- * branch, before every gate, and means no more than "a face detector produced
67315
- * a face detail". This one is stamped at the single moment the gallery row
67316
- * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
67317
- * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
67318
- * candidate gate, the imageless-track drop (no crop was ever captured) and
67319
- * the crop-store drop. Everything between the detector and that insert can
67320
- * legitimately refuse the face, so a flag written any earlier promises the
67321
- * operator something to assign and delivers nothing.
67322
- *
67323
- * **Independent of recognition.** A face collected but never auto-matched is
67324
- * still assignable — it is in fact the face an operator most wants to reach —
67325
- * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
67326
- * `subLabel`; this says only that the raw material exists.
67327
- *
67328
- * **Set once, never cleared.** A track that produced a gallery row produced
67329
- * one; deleting the row later is the gallery's business, not this flag's.
67330
- *
67331
- * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
67332
- * before the column omits it, and so does every server that predates the
67333
- * field. A consumer must test `=== true` and render nothing otherwise —
67334
- * never infer "no assignable face".
67194
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
67195
+ * the decoded pixels live in. One more member of the one-of
67196
+ * frame/frameHandle/image/imageBase64/referenceImage group.
67335
67197
  */
67336
- hasEmbeddedFace: boolean().optional(),
67198
+ frameHandle: FrameHandleSchema.optional(),
67199
+ imageBase64: string().optional(),
67337
67200
  /**
67338
- * This subject CONTAINS a folded rider — a person the rider-pairing step
67339
- * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
67340
- * so the passage is tracked once and as a VEHICLE.
67341
- *
67342
- * It exists because the fold's record was dishonest. D34 and the code both
67343
- * said "the person is not lost — it is reported so both entities stay on the
67344
- * record"; in fact the pair went into a per-processor RAM field behind an
67345
- * accessor nobody called, and every durable surface said `vehicle`, full
67346
- * stop. This is the composition note that makes the row true.
67347
- *
67348
- * A COMPOSITION, never a class and never a label. "This vehicle contains a
67349
- * person" is not an answer to "what is this" — both label tiers would refuse
67350
- * a macro token anyway (D89), and correctly. Nothing here changes what the
67351
- * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
67352
- * and a `person` rule still does not fire for someone cycling past.
67353
- *
67354
- * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
67355
- * the column, and every hub that predates the field, omits it. Test
67356
- * `=== true` and render nothing otherwise — never infer "no rider".
67201
+ * Binary JPEG bytes — preferred over `imageBase64` on internal
67202
+ * hops (hub → forked worker via Moleculer MsgPack) because it
67203
+ * skips the 33% base64 overhead + the per-call base64 decode on
67204
+ * the detection-pipeline worker. Callers can pass either; exactly
67205
+ * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
67357
67206
  */
67358
- hasRider: boolean().optional(),
67359
- ...TrackFlagFields,
67360
- ...TrackRetrainFields
67361
- });
67362
- var BaseEventFields = {
67363
- id: string(),
67364
- deviceId: number(),
67365
- timestamp: number()
67366
- };
67367
- var MotionEventSchema = object({
67368
- ...BaseEventFields,
67369
- kind: literal("motion"),
67370
- regionCount: number(),
67371
- /** Heavy JSON array — omitted in slim projection. */
67372
- regions: array(object({
67373
- bbox: BoundingBoxSchema,
67374
- pixelCount: number(),
67375
- intensity: number()
67376
- })).readonly().optional(),
67377
- /** Omitted in slim projection. */
67378
- frameWidth: number().optional(),
67379
- /** Omitted in slim projection. */
67380
- frameHeight: number().optional(),
67381
- /** Populated by B5 (recording playback URL for this event). */
67382
- mediaUrl: string().optional()
67383
- });
67207
+ image: _instanceof(Uint8Array).optional(),
67208
+ referenceImage: string().optional(),
67209
+ deviceId: number().optional(),
67210
+ sessionId: string().optional(),
67211
+ /**
67212
+ * Execution plane. 'full' (default) runs the whole tree — benchmark,
67213
+ * reference-image, and detail-subtree calls. 'frame' is the live
67214
+ * per-frame dispatch: ONLY root-plane steps run; crop children
67215
+ * (inputClasses ≠ null) are skipped and served per-track via
67216
+ * pipelineRunner.runDetailSubtree (two-plane design).
67217
+ */
67218
+ plane: _enum(["full", "frame"]).optional(),
67219
+ /**
67220
+ * Inference-device selector (Phase 2 multi-device). Format
67221
+ * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
67222
+ * Omitted ⇒ the runner's default device (current single-engine
67223
+ * behaviour). Selects WHICH device pool of the node runs the call.
67224
+ */
67225
+ deviceKey: string().optional(),
67226
+ /**
67227
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
67228
+ * when the parent crop was resolved from the frame's retained NATIVE
67229
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
67230
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
67231
+ * resolution from that surface — the SAME quality path faces already
67232
+ * had — instead of the downscaled parent tile. `handle` keys the native
67233
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
67234
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
67235
+ * the executor's crop-normalized child ROI back into frame-normalized
67236
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
67237
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
67238
+ * (today's behaviour on the fallback path).
67239
+ */
67240
+ nativeCropRef: NativeCropRefSchema.optional()
67241
+ }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
67242
+ engine: PipelineEngineChoiceSchema.optional(),
67243
+ steps: array(PipelineStepInputSchema).min(1),
67244
+ frames: array(FrameInputSchema).min(1).max(255),
67245
+ deviceId: number().optional(),
67246
+ sessionId: string().optional(),
67247
+ /**
67248
+ * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
67249
+ * the batch to the Python pool's bench preprocess cache
67250
+ * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
67251
+ * preprocessed ONCE and every later inference is a pure-inference cache
67252
+ * hit — the sustained-throughput run measures inference, not
67253
+ * decode+preprocess+infer. Omitted/0 for live frames (all different →
67254
+ * full preprocess every call, correct). Fresh per sustained run;
67255
+ * released via `uncacheFrame`.
67256
+ */
67257
+ frameId: number().int().nonnegative().optional(),
67258
+ /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
67259
+ deviceKey: string().optional()
67260
+ }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
67261
+ data: _instanceof(Uint8Array),
67262
+ width: number().int().positive(),
67263
+ height: number().int().positive(),
67264
+ format: _enum([
67265
+ "rgb",
67266
+ "bgr",
67267
+ "gray"
67268
+ ])
67269
+ }), object({
67270
+ frameId: number(),
67271
+ width: number(),
67272
+ height: number()
67273
+ }), { kind: "mutation" }), method(object({
67274
+ stepId: string(),
67275
+ frameId: number().int()
67276
+ }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
67277
+ batchMode: string(),
67278
+ windowMs: number(),
67279
+ maxBatchSize: number(),
67280
+ concurrency: number()
67281
+ })), method(_void(), array(object({
67282
+ engineKey: string(),
67283
+ engine: PipelineEngineChoiceSchema,
67284
+ modelsLoaded: array(string()).readonly(),
67285
+ inUseByCameras: array(number()).readonly(),
67286
+ /**
67287
+ * Origin of this resident factory.
67288
+ * - `runtime` — main camera-serving engine (no idle TTL).
67289
+ * - `warm-override` — benchmark/test override held in the warm
67290
+ * cache; auto-disposed after the idle TTL.
67291
+ * - `device-pool` — a concurrent per-device pool (Phase 2
67292
+ * multi-device, keyed by `deviceKey`) resolved
67293
+ * via `resolveDeviceFactory`. Runs alongside the
67294
+ * `runtime` engine on a DIFFERENT accelerator
67295
+ * (NPU / iGPU / Coral) — this is how the
67296
+ * Engines tab shows all pools running at once.
67297
+ */
67298
+ kind: _enum([
67299
+ "runtime",
67300
+ "warm-override",
67301
+ "device-pool"
67302
+ ]),
67303
+ /** Native pid of the underlying Python pool (null when no pool). */
67304
+ poolPid: number().nullable(),
67305
+ /** ms since this factory was last used (null when not warm-tracked). */
67306
+ idleMs: number().nullable(),
67307
+ /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
67308
+ idleTtlMs: number().nullable()
67309
+ })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
67310
+ kind: "mutation",
67311
+ auth: "admin"
67312
+ }), method(object({
67313
+ engine: PipelineEngineChoiceSchema,
67314
+ force: boolean().optional()
67315
+ }), object({
67316
+ success: boolean(),
67317
+ reason: string().optional()
67318
+ }), {
67319
+ kind: "mutation",
67320
+ auth: "admin"
67321
+ }), method(_void(), array(ReferenceImageEntrySchema).readonly()), method(object({ filename: string() }), ReferenceImageBodySchema.nullable()), method(_void(), array(ReferenceAudioEntrySchema).readonly()), method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()), method(_void(), AudioCapabilitiesSchema), method(object({
67322
+ addonId: string(),
67323
+ modelId: string(),
67324
+ filename: string().optional(),
67325
+ settings: record(string(), unknown()).optional()
67326
+ }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
67384
67327
  /**
67385
- * Which detection SOURCE produced an object event. `pipeline` = the ML
67386
- * detection pipeline (decoded-frame inference); `onboard` = the camera's
67387
- * native on-device AI. Both flow through the SAME analysis layers (zoning,
67388
- * tracking, per-kind persistence) but stay distinguishable so consumers
67389
- * (advanced-notifier, occupancy, …) can select which source(s) to act on.
67390
- * Absent on legacy rows ⇒ treat as `pipeline`.
67328
+ * Per-stage gating mode applied to the zones a rule references.
67329
+ *
67330
+ * - `include`: the rule contributes to a **whitelist** for its stage.
67331
+ * When at least one `include` rule fires for a stage, only entities
67332
+ * inside one of those zones pass that stage.
67333
+ * - `exclude`: the rule contributes to a **blacklist** for its stage.
67334
+ * Entities inside one of those zones are dropped at that stage.
67335
+ *
67336
+ * `monitor`-style observation (count without filtering) is not a rule
67337
+ * mode — zones without any matching rule are observed naturally by
67338
+ * `zone-analytics` (live snapshot + history), so an "I just want to
67339
+ * count, not filter" use case needs no rule at all.
67391
67340
  */
67392
- var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
67341
+ var ZoneRuleModeEnum = _enum(["include", "exclude"]);
67393
67342
  /**
67394
- * The confirmed zone crossing that produced an object event. Present ONLY on
67395
- * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
67396
- * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
67397
- * appearance event carry none, so a rule asking for a direction fails closed
67398
- * on them.
67343
+ * Per-consumer rule that references existing zones (geometry) and
67344
+ * defines how a specific pipeline stage should treat them. Each
67345
+ * consumer addon owns its own `ZoneRule[]` array in its per-device
67346
+ * settings:
67399
67347
  *
67400
- * Exactly ONE crossing per event: the emitter turns each confirmed crossing
67401
- * into its own event, so a frame in which a track enters A while leaving B
67402
- * produces two events with two directions — never one ambiguous row.
67348
+ * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
67349
+ * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
67350
+ * - future: notification rules, audio gating, etc.
67403
67351
  *
67404
- * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
67405
- * membership the box has NOW, and by definition it no longer contains the zone
67406
- * that was just left. Without the id here, a zone-scoped rule could never match
67407
- * the exit it asked for.
67352
+ * One rule applies to N zones (`zoneIds[]`) so the operator can
67353
+ * express "ignore motion in ALL of {garden, street}" with a single
67354
+ * rule. `classFilter` narrows the rule to specific object classes —
67355
+ * "drop person detections in the street, but keep cars" is one
67356
+ * `exclude` rule with `classFilter: ['person']`.
67357
+ *
67358
+ * `enabled` is a soft toggle — the operator can keep the rule
67359
+ * configured but inert without deleting it.
67408
67360
  */
67409
- var ZoneCrossingSchema = object({
67410
- direction: _enum(["enter", "exit"]),
67411
- /** Admin zone id crossed. */
67412
- zoneId: string(),
67413
- /** Zone display name at crossing time (falls back to the id). */
67414
- zoneName: string().optional()
67415
- });
67416
- var ObjectEventSchema = object({
67417
- ...BaseEventFields,
67418
- kind: literal("object"),
67419
- /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
67420
- source: DetectionSourceSchema.optional(),
67361
+ var ZoneRuleSchema = object({
67362
+ /** Stable rule id — survives edits, used by the UI for diffing. */
67363
+ id: string(),
67364
+ /** Optional human-readable label rendered in the rule editor. */
67365
+ name: string().optional(),
67366
+ /** Zones this rule targets. The rule's `mode` applies to ALL
67367
+ * listed zones (OR-set: a detection in any one of them counts).
67368
+ * At least one zone id required — a rule with no targets is a
67369
+ * configuration mistake and the form validator rejects it. */
67370
+ zoneIds: array(string()).min(1).readonly(),
67371
+ mode: ZoneRuleModeEnum,
67421
67372
  /**
67422
- * Inference-frame id shared by every object event emitted from the SAME frame
67423
- * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
67424
- * 2 people + 1 dog) under one full frame, and link a track's frames over time
67425
- * (group by `trackId`, pick a representative `frameId` as the parent frame).
67426
- * Optional for backward-compat with pre-existing rows / the slim projection
67427
- * includes it (it is light). Absent on rows written before this field.
67373
+ * Class names this rule applies to. Empty / undefined ⇒ rule
67374
+ * applies to every class. Class strings match the `macroClass`
67375
+ * field on detections (e.g. `person`, `car`, `dog`).
67428
67376
  */
67429
- frameId: string().optional(),
67430
- /** Omitted in slim projection. */
67431
- trackId: string().optional(),
67432
- className: string(),
67433
- ...TieredLabelFields,
67434
- /** Omitted in slim projection. */
67435
- confidence: number().optional(),
67436
- /** Heavy JSON — omitted in slim projection. */
67437
- bbox: BoundingBoxSchema.optional(),
67438
- /** Heavy JSON — omitted in slim projection. */
67439
- zones: array(string()).readonly().optional(),
67440
- /** Omitted in slim projection. */
67441
- state: TrackStateSchema.optional(),
67377
+ classFilter: array(string()).readonly().optional(),
67442
67378
  /**
67443
- * The zone crossing this event IS, when it is one. Absent on every other
67444
- * event kind (movement state, appearance, package) — see
67445
- * {@link ZoneCrossingSchema}. Omitted in slim projection.
67379
+ * Minimum bbox/mask overlap (0–1) with any of the rule's zones
67380
+ * required to consider an entity "in the zone". Defaults to the
67381
+ * consumer's stage default when omitted. Kept for back-compat with
67382
+ * existing per-rule overrides; new operators pick the value via
67383
+ * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
67384
+ * set, the lower-level engine reads it as a 0–1 fraction.
67446
67385
  */
67447
- zoneCrossing: ZoneCrossingSchema.optional(),
67448
- /** Detection-frame dimensions in pixels — let consumers normalize the
67449
- * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
67450
- frameWidth: number().optional(),
67451
- frameHeight: number().optional(),
67452
- /** MediaStore key for the crop attached to this event (if any). */
67453
- mediaKey: string().optional(),
67454
- /** Design B: MediaStore key of the track's native-resolution key frame (the
67455
- * best-detection full frame). Resolve via the event-media data-plane
67456
- * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
67457
- * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
67458
- * sources — consumers fall back to `mediaKey` (the tight crop). */
67459
- keyFrameMediaKey: string().optional(),
67460
- /** Populated by B5 (recording playback URL for this event). */
67461
- mediaUrl: string().optional(),
67462
- /** The parent track's key-event importance [0,1], propagated to every object
67463
- * event of the track (so an event row can be sorted by importance without a
67464
- * track join). Absent on legacy rows / before the track was scored. */
67465
- importance: number().optional()
67466
- });
67467
- var AudioEventSchema = object({
67468
- ...BaseEventFields,
67469
- kind: literal("audio"),
67470
- rms: number(),
67471
- dbfs: number(),
67472
- classification: object({
67473
- className: string(),
67474
- originalClass: string().optional(),
67475
- score: number()
67476
- }).optional(),
67477
- /** Populated by B5 (recording playback URL for this event). */
67478
- mediaUrl: string().optional()
67386
+ overlapThreshold: number().min(0).max(1).optional(),
67387
+ /**
67388
+ * Operator-friendly version of `overlapThreshold` — the percentage
67389
+ * of the detection's bbox that must lie inside the zone for the
67390
+ * rule to match. Documented default is 85%; the engine substitutes
67391
+ * that when the field is omitted (kept optional so existing rules
67392
+ * stored without it stay valid).
67393
+ *
67394
+ * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
67395
+ * rule, the engine prefers `bboxInclusionPct` because it's the
67396
+ * field exposed in the UI. Internally both feed the same gate.
67397
+ */
67398
+ bboxInclusionPct: number().min(0).max(100).optional(),
67399
+ /**
67400
+ * When `true` and a detection has a segmentation mask, use the
67401
+ * mask for overlap instead of the bbox. Detection-stage only;
67402
+ * motion rules ignore this field.
67403
+ */
67404
+ preferMask: boolean().optional(),
67405
+ /**
67406
+ * Soft-toggle: `false` disables the rule without deleting it.
67407
+ * Defaults to `true` so operators creating a rule via the UI
67408
+ * see it active immediately.
67409
+ */
67410
+ enabled: boolean().default(true)
67479
67411
  });
67480
- var MediaFileKindEnum = _enum([
67481
- "crop",
67482
- "thumbnail",
67483
- "snapshot",
67484
- "firstFrame",
67485
- "lastFrame",
67486
- "fullFrame",
67487
- "fullFrameBoxed",
67488
- "faceCrop",
67489
- "plateCrop",
67490
- "keyFrame",
67491
- "keyFrameSmall",
67492
- "thumbnailSmall"
67493
- ]);
67494
- var MediaFileSchema = object({
67495
- key: string(),
67496
- kind: MediaFileKindEnum,
67497
- base64: string(),
67498
- sizeBytes: number(),
67499
- timestamp: number()
67412
+ array(ZoneRuleSchema).readonly();
67413
+ /**
67414
+ * Zone — pure geometry + identity. NO filtering behaviour.
67415
+ *
67416
+ * Zones describe **where** in the frame the operator wants to flag
67417
+ * something; consumer-owned {@link ZoneRule} arrays describe **how**
67418
+ * each pipeline stage uses them. Splitting the two means a single
67419
+ * polygon "Driveway" can simultaneously back a motion-exclude rule,
67420
+ * a detection-include rule on `['car']`, and an occupancy aggregate
67421
+ * — without three duplicated polygons.
67422
+ *
67423
+ * Owned by the orchestrator addon (provider) and mirrored into the
67424
+ * `zones` device-state slice on every mutation. Consumers
67425
+ * (motion-wasm, pipeline-executor, analytics, admin UI) read either
67426
+ * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
67427
+ * mirror with `onChanged`).
67428
+ *
67429
+ * Coordinates are normalised fractions of the frame (0–1) so zones
67430
+ * survive resolution changes and stream profile switches.
67431
+ *
67432
+ * `kind` discriminates between full polygons (closed regions used
67433
+ * for intrusion / occupancy filters) and tripwires (open 2-point
67434
+ * line segments used for cross events). Onboard / firmware-reported
67435
+ * zones (Reolink, ONVIF) are out of scope for now — see the deferred
67436
+ * task list.
67437
+ */
67438
+ var ZoneKindEnum = _enum(["polygon", "tripwire"]);
67439
+ /** Polygon vertex in fraction-of-frame coordinates (0–1). */
67440
+ var PolygonPointSchema = object({
67441
+ x: number(),
67442
+ y: number()
67443
+ });
67444
+ /** A camera detection zone — pure geometry/identity. */
67445
+ var ZoneSchema = object({
67446
+ id: string(),
67447
+ name: string(),
67448
+ kind: ZoneKindEnum.default("polygon"),
67449
+ /** Polygon vertices, fraction of frame (0–1). */
67450
+ polygon: array(PolygonPointSchema).readonly(),
67451
+ /** Visual color for UI rendering. */
67452
+ color: string().default("#3b82f6")
67500
67453
  });
67501
67454
  /**
67502
- * One media row WITHOUT its bytes.
67455
+ * Zones capability — per-camera CRUD over polygon detection zones.
67503
67456
  *
67504
- * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
67505
- * 140 s track), and a client that renders tiles from the media data plane needs
67506
- * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
67507
- * with an immutable cache, instead of all at once inside a tRPC response that
67508
- * blocks the whole view.
67457
+ * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
67458
+ * to per-device settings and mirrors into the `zones` device-state
67459
+ * slice on every mutation, so downstream consumers can subscribe via
67460
+ * `dev.state.zones.onChanged`.
67509
67461
  *
67510
- * `sizeBytes` is carried because it is what lets a client decide between the
67511
- * stored blob and a `?variant=thumb` rendering without fetching either.
67462
+ * The cap surface only handles geometry + identity; filtering
67463
+ * behaviour (per-class, include/exclude, threshold) lives in the
67464
+ * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
67465
+ * `capabilities/schemas/zone-rule.js`.
67512
67466
  */
67513
- var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
67467
+ var zonesCapability = {
67468
+ name: "zones",
67469
+ scope: "device",
67470
+ mode: "singleton",
67471
+ deviceTypes: [DeviceType.Camera],
67472
+ methods: {
67473
+ listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
67474
+ addZone: method(object({
67475
+ deviceId: number(),
67476
+ zone: ZoneSchema
67477
+ }), _void(), {
67478
+ kind: "mutation",
67479
+ auth: "admin"
67480
+ }),
67481
+ removeZone: method(object({
67482
+ deviceId: number(),
67483
+ zoneId: string()
67484
+ }), _void(), {
67485
+ kind: "mutation",
67486
+ auth: "admin"
67487
+ }),
67488
+ updateZone: method(object({
67489
+ deviceId: number(),
67490
+ zone: ZoneSchema
67491
+ }), _void(), {
67492
+ kind: "mutation",
67493
+ auth: "admin"
67494
+ })
67495
+ },
67496
+ /**
67497
+ * Runtime-state slice — the live zone catalogue mirrored by the
67498
+ * orchestrator on every CRUD mutation. Consumers read via
67499
+ * `device.state.zones.value` / `.watch(...)` without round-tripping
67500
+ * the cap, and the codegen DeviceProxy auto-wires the reactive
67501
+ * handle. Slice shape is `{ zones: Zone[] }` so future extensions
67502
+ * (e.g. zone groupings) can sit alongside the polygon list.
67503
+ */
67504
+ runtimeState: object({ zones: array(ZoneSchema).readonly() }),
67505
+ /**
67506
+ * 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.
67507
+ *
67508
+ * See `RuntimeStateDurability`. Enforced by
67509
+ * `scripts/check-runtime-state-durability.ts`.
67510
+ */
67511
+ durability: "restored"
67512
+ };
67514
67513
  /**
67515
- * The MACRO tier of an annotation — a CLOSED set.
67514
+ * pipeline-analytics — device-scoped wrapper cap. Refines raw
67515
+ * per-frame detections emitted by the pipeline runner into tracked
67516
+ * objects, per-kind event collections (motion / object / audio), and
67517
+ * persisted media. Owns the post-detection domain end-to-end:
67516
67518
  *
67517
- * This is what the exported detector predicts, so a typo here is a new class
67518
- * with one example in it. `label` and `subLabel` are open strings by contrast:
67519
- * the whole point of the page is teaching the model things it does not know
67520
- * yet, and constraining that vocabulary would make it useless.
67519
+ * runner emits PipelineInferenceResult
67520
+ * ↓ (event bus)
67521
+ * pipeline-analytics subscriber
67522
+ * ↓ SORT tracker + zone engine + state analyzer + event emitter
67523
+ * → three DB collections (one per kind), one FS media tree, one
67524
+ * unified event emitter (FrameTracked + TrackStarted/Ended +
67525
+ * DetectionEvent on bus)
67521
67526
  *
67522
- * A macro class is NEVER a label. The provider refuses a write whose `label` or
67523
- * `subLabel` is one of these values, in any casing, because once `person`
67524
- * exists in both tiers "every person box" stops being answerable without
67525
- * knowing every string anyone ever typed — and the damage is retroactive.
67527
+ * Pure subscriber model. No `processFrame` cap method — the runner
67528
+ * already publishes the raw frame on the bus. The cap surface is
67529
+ * only QUERIES + per-device settings, bound on/off via
67530
+ * `device-manager.setWrapperActive`. `defaultActive: true` because
67531
+ * every camera with a detection pipeline wants its raw detections
67532
+ * refined; operators opt out per-device via BindingsTab when needed.
67533
+ *
67534
+ * Replaces the legacy `analysis-pipeline`, `analysis-data-persistence`
67535
+ * (per-device surface) and `track-trail` caps — see P11 cleanup.
67526
67536
  */
67527
- var RetrainMacroClassSchema = _enum([
67537
+ var TrackStateSchema = _enum([
67538
+ "new",
67539
+ "entered",
67540
+ "left",
67541
+ "moving",
67542
+ "idle"
67543
+ ]);
67544
+ var EventKindSchema = _enum([
67545
+ "motion",
67546
+ "object",
67547
+ "audio"
67548
+ ]);
67549
+ /**
67550
+ * Spatial filter for `listTracks` — the rect + polygon variants of the shared
67551
+ * MaskShape vocabulary (see `mask-shape.ts`). Coordinates are NORMALIZED 0..1
67552
+ * of the camera frame (top-left origin), matching the drawing-plane editor.
67553
+ */
67554
+ var TrackZoneFilterSchema = discriminatedUnion("kind", [MaskRectShapeSchema, MaskPolygonShapeSchema]);
67555
+ /** Closed icon vocabulary so clients render a known glyph per kind. */
67556
+ var EventKindIconSchema = _enum([
67557
+ "motion",
67558
+ "audio",
67528
67559
  "person",
67529
67560
  "vehicle",
67530
67561
  "animal",
67562
+ "door",
67563
+ "pir",
67564
+ "smoke",
67565
+ "water",
67566
+ "button",
67531
67567
  "package",
67532
- "face",
67533
- "plate"
67568
+ "generic"
67534
67569
  ]);
67535
- /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
67536
- var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
67537
- /** Did a human draw this box, or did the assist propose it? */
67538
- var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
67539
- /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
67540
- var RetrainBboxSchema = object({
67541
- x: number(),
67542
- y: number(),
67543
- w: number(),
67544
- h: number()
67570
+ var EventKindCategorySchema = _enum([
67571
+ "motion",
67572
+ "audio",
67573
+ "detection",
67574
+ "sensor",
67575
+ "control",
67576
+ "custom",
67577
+ "package"
67578
+ ]);
67579
+ /** Taxonomy level — macro (timeline lane) vs sub (events-page leaf). */
67580
+ var EventKindLevelSchema = _enum(["macro", "sub"]);
67581
+ var EventKindDescriptorSchema = object({
67582
+ /** Stable kind id (e.g. 'motion', 'vehicle', 'car', 'lock'). */
67583
+ kind: string(),
67584
+ /** i18n key resolved on the UI side; `label` is the English fallback. */
67585
+ labelKey: string(),
67586
+ /** English fallback label (kept for clients that don't translate). */
67587
+ label: string(),
67588
+ /** Hex color for timeline/legend rendering. */
67589
+ color: string(),
67590
+ /** Dictionary id → lucide component on the UI side. */
67591
+ iconId: string(),
67592
+ /** Legacy closed-vocab glyph — fallback for `iconId`. */
67593
+ icon: EventKindIconSchema,
67594
+ category: EventKindCategorySchema,
67595
+ /** Macro parent for this kind ('car' → 'vehicle'); null for a macro. */
67596
+ parentKind: string().nullable(),
67597
+ /** Derived from `parentKind`, explicit for the client tree. */
67598
+ level: EventKindLevelSchema,
67599
+ /** Which cap + device contributes this kind. For built-ins the camera
67600
+ * itself; for sensor kinds the LINKED source device. */
67601
+ source: object({
67602
+ capName: string(),
67603
+ deviceId: number()
67604
+ })
67545
67605
  });
67546
- /**
67547
- * One annotated subject.
67548
- *
67549
- * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
67550
- * (letterboxed root / zone-cropped package / subject-cropped classifier) are
67551
- * derived from it at export and never stored — storing them is how one feature
67552
- * space ends up holding two crops of the same subject (D52).
67553
- */
67554
- var RetrainAnnotationSchema = object({
67555
- id: string(),
67556
- trackId: string(),
67606
+ /** One camera's event vocabulary, as returned by `listEventKindsBatch`. */
67607
+ var EventKindsForDeviceSchema = object({
67557
67608
  deviceId: number(),
67558
- /** The COPY in retrain storage — never the source track's media key. */
67559
- mediaKey: string(),
67560
- bbox: RetrainBboxSchema,
67561
- macroClass: RetrainMacroClassSchema,
67562
- label: string().optional(),
67563
- subLabel: string().optional(),
67564
- kind: RetrainAnnotationKindSchema,
67565
- source: RetrainAnnotationSourceSchema,
67566
- /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
67567
- assistModelId: string().optional(),
67568
- assistScore: number().optional(),
67569
- exportedInBatch: string().optional(),
67570
- createdAt: number()
67571
- });
67572
- /** The write form — the server owns `id`, `createdAt` and the frame binding. */
67573
- var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
67574
- id: true,
67575
- trackId: true,
67576
- deviceId: true,
67577
- mediaKey: true,
67578
- createdAt: true,
67579
- exportedInBatch: true
67609
+ kinds: array(EventKindDescriptorSchema).readonly()
67580
67610
  });
67581
- /** A track sitting in `staging`, with everything the worklist needs to rank it. */
67582
- var RetrainTrackSchema = object({
67583
- trackId: string(),
67611
+ var SensorEventSchema = object({
67612
+ id: string(),
67613
+ /** The CAMERA the event is attributed to (a sensor linked to N cameras
67614
+ * yields N rows, one per camera). */
67584
67615
  deviceId: number(),
67585
- className: string(),
67586
- label: string().optional(),
67587
- firstSeen: number(),
67588
- lastSeen: number(),
67589
- /** How many frames the dataset already holds from this track. */
67590
- frameCount: number().int(),
67591
- /** How many subjects have been annotated on those frames. `0` with
67592
- * `frameCount: 0` is exactly "staging, still to work". */
67593
- annotationCount: number().int()
67616
+ /** The linked sensor device whose state changed. */
67617
+ sourceDeviceId: number(),
67618
+ /** Event kind id — matches an `EventKindDescriptor.kind`. */
67619
+ kind: string(),
67620
+ /** Snapshot of the sensor cap's runtime-state slice at the change. */
67621
+ value: record(string(), unknown()).nullable(),
67622
+ timestamp: number()
67594
67623
  });
67595
- /** A frame the picker may offer — an index row, no blob was read to produce it. */
67596
- var RetrainFrameCandidateSchema = object({
67597
- mediaKey: string(),
67598
- kind: MediaFileKindEnum,
67624
+ var TrackPositionSchema = object({
67625
+ x: number(),
67626
+ y: number(),
67599
67627
  timestamp: number(),
67600
- sizeBytes: number().int(),
67601
- /** A copy of this original already exists — selecting it is free and cannot
67602
- * fail, whatever became of the original. */
67603
- copied: boolean()
67604
- });
67605
- /** A frame the dataset OWNS: bytes copied at selection time. */
67606
- var RetrainFrameSchema = object({
67607
- frameId: string(),
67608
- deviceId: number(),
67609
- trackId: string(),
67610
- /** Provenance only. It may already point at nothing — that is expected. */
67611
- sourceMediaKey: string(),
67612
- sourceKind: MediaFileKindEnum,
67613
- sizeBytes: number().int(),
67614
- width: number().int(),
67615
- height: number().int(),
67616
- copiedAt: number()
67617
- });
67618
- /** Why a copy-on-select could not be honoured — named, never a silent skip. */
67619
- var RetrainCopyRefusalSchema = _enum([
67620
- "source-missing",
67621
- "unreadable-image",
67622
- "write-failed"
67623
- ]);
67624
- var RetrainFrameSelectionSchema = object({
67625
- copied: array(RetrainFrameSchema).readonly(),
67626
- refused: array(object({
67627
- sourceMediaKey: string(),
67628
- reason: RetrainCopyRefusalSchema
67629
- })).readonly()
67628
+ bbox: BoundingBoxSchema
67630
67629
  });
67631
- var RetrainFrameListSchema = object({
67632
- candidates: array(RetrainFrameCandidateSchema).readonly(),
67633
- copies: array(RetrainFrameSchema).readonly(),
67634
- /** What the page pre-selects — the native key frame when one survives. */
67635
- autoPickMediaKey: string().optional()
67630
+ var TrackSnapshotSchema = object({
67631
+ timestamp: number(),
67632
+ position: TrackPositionSchema,
67633
+ /** MediaStore key; resolve via `getTrackMedia({ trackId })`. */
67634
+ mediaKey: string()
67636
67635
  });
67637
- /** What the operator asked the assist to look for. */
67638
- var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
67639
- kind: literal("package"),
67640
- zone: RetrainBboxSchema.optional()
67641
- }), object({
67642
- kind: literal("objects"),
67643
- modelId: string(),
67644
- minScore: number().optional()
67645
- })]);
67646
67636
  /**
67647
- * The assist's answer — a discriminated union, because "the model saw nothing"
67648
- * and "this node cannot run that model" lead to different next moves and a
67649
- * nullable result cannot tell them apart.
67637
+ * Normalized 0..1 trajectory envelope (min/max over every position bbox,
67638
+ * divided by the track's detection-frame dims), computed at persist time.
67639
+ * Absent when the frame dims were unknown when the track was persisted
67640
+ * (legacy rows / dims-less sources) and on active (in-RAM) tracks.
67650
67641
  */
67651
- var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
67652
- kind: literal("proposed"),
67653
- modelId: string(),
67654
- stepId: string(),
67655
- minScore: number(),
67656
- /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
67657
- proposals: array(RetrainAnnotationDraftSchema).readonly(),
67658
- /** Returned by the runner but removed by the threshold. */
67659
- belowThreshold: number().int()
67660
- }), object({
67661
- kind: literal("refused"),
67662
- /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
67663
- reason: string(),
67664
- detail: string().optional()
67665
- })]);
67666
- /** The outcome of a lifecycle move owned by the retrain page. */
67667
- var RetrainTransitionResultSchema = object({
67668
- trackId: string(),
67669
- /** Where the track ended up, whatever happened. */
67670
- retrainStatus: RetrainStatusSchema,
67671
- /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
67672
- changed: boolean(),
67673
- reason: _enum([
67674
- "unknown-track",
67675
- "no-frames-copied",
67676
- "not-staging",
67677
- "not-trained",
67678
- "unchanged"
67679
- ]).optional()
67680
- });
67681
- var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
67682
- var MAX_EVENT_QUERY_LIMIT = 5e3;
67683
- var DeviceEventQueryInput = object({
67684
- deviceId: number(),
67685
- since: number().optional(),
67686
- until: number().optional(),
67687
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
67688
- /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
67689
- * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
67690
- * exact behaviour. Callers may omit this field — the store defaults to
67691
- * `full` when not provided. */
67692
- projection: _enum(["full", "slim"]).optional()
67693
- });
67694
- var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
67695
- var RecentTracksQueryInput = object({
67696
- /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
67697
- deviceIds: array(number()),
67698
- /** Window lower bound on `lastSeen` (inclusive). */
67699
- since: number().optional(),
67700
- /** Window upper bound on `lastSeen` (inclusive). */
67701
- until: number().optional(),
67702
- /** Page size. Default 200, max 1000. */
67703
- limit: number().int().min(1).max(1e3).default(200),
67704
- /** Opaque continuation cursor from a previous page's `nextCursor`.
67705
- * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
67706
- cursor: string().optional(),
67707
- /** See {@link TrackProjectionSchema}. Default `full`. */
67708
- projection: TrackProjectionSchema.optional(),
67709
- /** Include stationary-promoted rows (parked objects). Default false: the
67710
- * feed lists passages; parking records live on the stationary registry. */
67711
- includeStationary: boolean().optional()
67712
- });
67713
- var RecentTracksPageSchema = object({
67714
- /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
67715
- tracks: array(TrackSchema).readonly(),
67716
- /** Cursor for the next page, or null when this page is the last. */
67717
- nextCursor: string().nullable()
67718
- });
67719
- var LIST_GROUPS_DEFAULT_LIMIT = 40;
67720
- var LIST_GROUPS_MAX_LIMIT = 100;
67721
- var AnalyticsGroupRecordSchema = object({
67722
- id: string(),
67723
- deviceId: number().int(),
67724
- openedAt: number().int(),
67725
- closedAt: number().int(),
67726
- timestamp: number().int(),
67727
- memberCount: number().int(),
67728
- memberTrackIds: array(string()).readonly(),
67729
- className: string(),
67730
- classes: array(string()).readonly(),
67731
- /** Relative event-media path, or null when the group has no picture yet. */
67732
- mediaUrl: string().nullable(),
67733
- singleton: boolean()
67642
+ var TrackEnvelopeSchema = object({
67643
+ minX: number(),
67644
+ minY: number(),
67645
+ maxX: number(),
67646
+ maxY: number()
67734
67647
  });
67735
- var AnalyticsGroupMemberSchema = object({
67736
- trackId: string(),
67737
- deviceId: number().int(),
67738
- className: string(),
67739
- firstSeen: number().int(),
67740
- lastSeen: number().int(),
67741
- mediaUrl: string().nullable()
67742
- });
67743
- var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
67744
- var ListGroupsQueryInput = object({
67745
- /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
67746
- deviceIds: array(number()),
67747
- /** Window lower bound on `closedAt` (inclusive). */
67748
- since: number().optional(),
67749
- /** Window upper bound on `openedAt` (inclusive). */
67750
- until: number().optional(),
67751
- limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
67752
- /** Opaque continuation cursor from a previous page's `nextCursor`. */
67753
- cursor: string().optional()
67754
- });
67755
- var ListGroupsPageSchema = object({
67756
- groups: array(AnalyticsGroupRecordSchema).readonly(),
67757
- nextCursor: string().nullable()
67758
- });
67759
- var KeyEventQueryInput = object({
67760
- deviceId: number(),
67761
- /** Window lower bound (track firstSeen ≥ since). */
67762
- since: number(),
67763
- /** Window upper bound (track firstSeen ≤ until). */
67764
- until: number(),
67765
- limit: number().int().min(1).max(200).default(50),
67766
- /** Drop tracks scoring below this importance. */
67767
- minImportance: number().min(0).max(1).optional(),
67768
- /** Restrict to a single class (e.g. 'person'). */
67769
- classFilter: string().optional()
67770
- });
67771
- var KeyEventSchema = object({
67772
- /** The representative event id (the track's best ObjectEvent, else its trackId). */
67773
- id: string(),
67774
- trackId: string(),
67775
- /** Track start time (firstSeen). */
67776
- timestamp: number(),
67777
- className: string(),
67778
- ...TieredLabelFields,
67779
- importance: number(),
67780
- /** Highest-confidence ObjectEvent id for the track (empty when none). */
67781
- bestEventId: string(),
67782
- /** Track lifetime in ms (lastSeen - firstSeen). */
67783
- windowMs: number().optional(),
67784
- ...TrackFlagFields,
67785
- ...TrackRetrainFields
67786
- });
67787
- object({
67788
- trackId: string(),
67789
- className: string(),
67790
- confidence: number(),
67791
- bbox: BoundingBoxSchema,
67792
- zones: array(string()).readonly(),
67793
- state: TrackStateSchema
67794
- });
67795
- var OverlayDetectionSchema = looseObject({
67796
- id: string(),
67797
- kind: _enum(["first-level", "detail"]),
67798
- macroClass: string(),
67799
- score: number(),
67800
- bbox: object({
67801
- x: number(),
67802
- y: number(),
67803
- width: number(),
67804
- height: number()
67805
- }),
67806
- labels: array(looseObject({
67807
- label: string(),
67808
- score: number()
67809
- })).readonly(),
67810
- parentId: string().optional()
67811
- });
67812
- var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
67813
- var SearchObjectEventsInput = object({
67814
- text: string(),
67815
- deviceId: number().optional(),
67816
- since: number().optional(),
67817
- until: number().optional(),
67818
- classFilter: string().optional(),
67819
- limit: number().default(50),
67820
- minScore: number().min(0).max(1).default(.2)
67821
- });
67822
- var TrackCascadeCountsSchema = object({
67823
- /** Persisted track roots deleted (authoritative). */
67824
- tracks: number().int(),
67825
- /** Object events removed with their tracks (best-effort; see note above). */
67826
- events: number().int(),
67827
- /** Track/face/plate-owned media removed (best-effort). Never identity media. */
67828
- media: number().int(),
67829
- /** Unassigned (non-enrolled) face reads removed (best-effort). */
67830
- faces: number().int(),
67831
- /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
67832
- plates: number().int(),
67833
- /** Per-track CLIP search vectors removed (best-effort). */
67834
- embeddings: number().int(),
67835
- /** Group membership + group rows removed with their last member (best-effort). */
67836
- groups: number().int()
67837
- });
67838
- /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
67839
- var DiskReconcileCountsSchema = object({
67840
- mediaDropped: number().int(),
67841
- tracks: number().int(),
67842
- events: number().int()
67843
- });
67844
- /** Event-store footprint for one camera. */
67845
- var EventStoreDeviceFootprintSchema = object({
67846
- deviceId: number(),
67847
- /** Persisted event rows (motion + object + audio) for the camera. */
67848
- rows: number().int(),
67849
- /** Event-owned media bytes on disk for the camera. */
67850
- bytes: number().int()
67851
- });
67852
- /** Aggregate event-store footprint: global totals + per-camera breakdown. */
67853
- var EventStoreFootprintSchema = object({
67854
- totalRows: number().int(),
67855
- totalBytes: number().int(),
67856
- devices: array(EventStoreDeviceFootprintSchema).readonly()
67857
- });
67858
- /** Per-kind counts returned by the event-prune / device-delete mutations. */
67859
- var EventPruneCountsSchema = object({
67860
- motion: number().int(),
67861
- object: number().int(),
67862
- audio: number().int()
67648
+ /**
67649
+ * Row projection for track list queries. `full` (default) returns the
67650
+ * complete Track including the frame-rate `positions[]` history and the
67651
+ * `snapshots[]` references — megabytes across a page of tracks. `slim`
67652
+ * keeps every scalar the list surfaces actually render (ids, class(es),
67653
+ * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
67654
+ * zonesVisited, bestEventId, envelope, hasFace, hasEmbeddedFace, hasRider) and returns `positions` /
67655
+ * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
67656
+ * `getTrack`. Mirrors the event-store `projection` convention
67657
+ * (`getObjectEvents` et al.).
67658
+ */
67659
+ var TrackProjectionSchema = _enum(["full", "slim"]);
67660
+ /**
67661
+ * One audio-classification label heard on the track's camera while the
67662
+ * track was alive, aggregated per label. An "episode" is one persisted
67663
+ * audio event (the confident-classification path: score ≥ the device's
67664
+ * `classificationMinScore`, class-change-or-heartbeat coalesced) — NOT
67665
+ * one 32 ms inference chunk, so counts stay human-scaled.
67666
+ */
67667
+ var TrackAudioLabelSchema = object({
67668
+ label: string(),
67669
+ /** Highest classification score observed across the label's episodes. */
67670
+ peakScore: number(),
67671
+ /** Number of coalesced audio-event episodes carrying this label. */
67672
+ count: number(),
67673
+ firstAt: number(),
67674
+ lastAt: number()
67863
67675
  });
67864
67676
  /**
67865
- * Re-embed stored tracks from their key frames.
67677
+ * How a track was produced. `pipeline` (default / absent) = the spatial
67678
+ * detection+tracking pipeline. Every OTHER value is a SYNTHETIC projection —
67679
+ * no positions, a single snapshot, and no bbox trajectory at all:
67866
67680
  *
67867
- * The reason this is an operator-callable method and not a migration script:
67868
- * every knob that decides what a vector MEANS — encoder model, crop margin,
67869
- * squaring — is only changeable if the existing vectors can be regenerated.
67870
- * Mixing feature spaces in one index makes cosine scores incomparable, and the
67871
- * symptom is a quality regression with no visible cause.
67681
+ * - `sensor` — a linked sensor/control device state change.
67682
+ * - `audio` — an audio event on the camera itself that was anomalous for
67683
+ * THAT camera, loud, and heard while nothing visual was happening (D62).
67684
+ *
67685
+ * The spatial subsystems (tracker association, occupancy count, re-id /
67686
+ * embedding, resurrection) MUST skip every synthetic source. Test for that
67687
+ * with `isSpatialTrack`, which allow-lists `pipeline` — a `!== 'sensor'`
67688
+ * check silently readmits every source added after it was written.
67872
67689
  */
67873
- var RebuildObjectEmbeddingsInput = object({
67874
- /** Restrict to one camera. Omit for the whole fleet. */
67875
- deviceId: number().optional(),
67876
- since: number().optional(),
67877
- until: number().optional(),
67878
- /** Stop after this many tracks; the result reports whether more remain. */
67879
- maxTracks: number().int().positive().optional(),
67880
- /**
67881
- * Run every embedding on THIS node instead of round-robining the fleet.
67882
- *
67883
- * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
67884
- * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
67885
- * calling it that would pin the rebuild REQUEST itself to that node — the
67886
- * rebuild orchestration lives on the hub, and only the per-track step runs
67887
- * remotely. This field is data; the per-track pin is applied inside.
67888
- *
67889
- * Absent ⇒ round-robin over every online node whose runner can serve the
67890
- * pinned model.
67891
- */
67892
- executeOnNodeId: string().optional(),
67893
- /**
67894
- * Milliseconds to wait between tracks; omit for the built-in default, `0` to
67895
- * run flat out.
67896
- *
67897
- * A rebuild is bulk maintenance on hub-main's single thread. Measured
67898
- * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
67899
- * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
67900
- * force is logged at start and finish so a deliberately slow pass reads
67901
- * differently from a stalled one.
67902
- */
67903
- pacingMs: number().int().nonnegative().optional()
67904
- });
67690
+ var TrackSourceSchema = _enum([
67691
+ "pipeline",
67692
+ "sensor",
67693
+ "audio"
67694
+ ]);
67905
67695
  /**
67906
- * Result of emptying the CLIP index.
67696
+ * Where a track sits in the RETRAIN lifecycle (D81).
67907
67697
  *
67908
- * The clean slate before a policy change: a new crop margin or encoder model
67909
- * leaves two feature spaces in one index whose cosine scores are not
67910
- * comparable, so wiping and rebuilding is the only way to be sure every vector
67911
- * means the same thing.
67698
+ * - `none` — never marked, or un-marked. Evictable.
67699
+ * - `staging` — the operator wants this track as training material and has not
67700
+ * finished with it. **This is the only state retention holds**: the track and
67701
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
67702
+ * the device's age window.
67703
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
67704
+ * were COPIED into the retrain dataset at selection time, so the dataset no
67705
+ * longer depends on the track's media and the track becomes EVICTABLE again.
67706
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
67707
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
67708
+ *
67709
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
67710
+ * the store's filter language has only positive equality and `whereIn` — no
67711
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
67712
+ * would make the entire pre-column history immortal in one deploy.
67912
67713
  */
67913
- var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
67714
+ var RetrainStatusSchema = _enum([
67715
+ "none",
67716
+ "staging",
67717
+ "trained"
67718
+ ]);
67914
67719
  /**
67915
- * Acknowledgement that a rebuild STARTED.
67720
+ * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
67721
+ * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
67722
+ * so the two surfaces cannot drift.
67916
67723
  *
67917
- * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
67918
- * runs detached and this returns immediately. Waiting for it made the client
67919
- * time out while the work carried on server-side, which is the worst of both:
67920
- * no result and no way to know it was still going. Poll
67921
- * `getObjectEmbeddingRebuildStatus` for progress.
67724
+ * **Absent ≠ false.** A track that has never been touched omits the field; an
67725
+ * explicitly un-flagged track carries `false`. Legacy rows written before the
67726
+ * columns existed read as absent, and a consumer that needs a boolean should say
67727
+ * `flag === true`, not `flag !== false`.
67728
+ *
67729
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
67730
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
67731
+ * `true` moves `none → staging`, writing `false` moves `staging → none`, and a
67732
+ * `trained` track reports `false` while refusing both writes. The boolean is
67733
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
67734
+ * "never marked" from "already trained" must read `retrainStatus`.
67735
+ *
67736
+ * `debug` does NOT pin; it is attention, not durability.
67737
+ *
67738
+ * `favourited` IS a BOOLEAN pin (durability bit), not a retrain lifecycle.
67739
+ * A favourited track is skipped by retention the same way `staging` is, but
67740
+ * it does not enter `none|staging|trained` and has no staging budget.
67922
67741
  */
67923
- var RebuildObjectEmbeddingsResultSchema = object({
67924
- started: boolean(),
67925
- /** True when a pass was already running; the new request is ignored. */
67926
- alreadyRunning: boolean()
67927
- });
67928
- var RebuildStatusSchema = object({
67929
- running: boolean(),
67930
- scanned: number(),
67931
- rebuilt: number(),
67932
- /** Tracks whose key frame is gone — nothing to re-embed from. */
67933
- missingKeyFrame: number(),
67934
- /** Tracks with no usable detection box. */
67935
- missingBbox: number(),
67936
- /**
67937
- * Tracks an executing node REFUSED rather than broke on — an unreadable key
67938
- * frame, a step that threw. Separate from `failed` because the remedy is
67939
- * different, and because a whole camera silently contributing zero vectors
67940
- * is the shape of failure a rebuild must never hide.
67941
- */
67942
- notRunnable: number(),
67943
- /**
67944
- * The pass stopped because NO node could serve the pinned model.
67945
- *
67946
- * Distinct from `notRunnable` on purpose: that one says "this track was
67947
- * refused", this one says "the cluster cannot do this work at all" — every
67948
- * candidate node either lacks the `clip-embedding` step, lacks a build of the
67949
- * pinned model for its engine format, or dropped out. The remedy is a model /
67950
- * engine change, not a per-camera one. Non-zero here always comes with
67951
- * `complete: false`.
67952
- */
67953
- noCapableNode: number(),
67954
- failed: number(),
67955
- /** Set once a pass ends: true only when EVERYTHING was covered. */
67956
- complete: boolean().nullable(),
67957
- startedAtMs: number().nullable(),
67958
- finishedAtMs: number().nullable(),
67959
- /** Present when the pass ended by throwing. */
67960
- error: string().nullable()
67961
- });
67962
- DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
67963
- deviceId: number(),
67964
- trackId: string()
67965
- }), TrackSchema.nullable()), method(object({
67966
- deviceId: number(),
67967
- since: number().optional(),
67968
- until: number().optional(),
67969
- limit: number().optional(),
67970
- /** Spatial filter — only tracks whose trajectory intersects the zone
67971
- * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
67972
- * envelope columns, then precisely tested per position. Tracks with
67973
- * an unknown envelope (no frame dims at persist time) always match. */
67974
- zone: TrackZoneFilterSchema.optional(),
67975
- /** See {@link TrackProjectionSchema}. Default `full` (backward
67976
- * compatible — omitting the field keeps today's exact behaviour). */
67977
- projection: TrackProjectionSchema.optional(),
67978
- /** Include stationary-promoted rows (parked objects handed to the
67979
- * stationary registry). Default false: the timeline lists passages,
67980
- * not parking records (operator decision, 2026-08-15). */
67981
- includeStationary: boolean().optional()
67982
- }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
67983
- deviceId: number(),
67984
- groupId: string().min(1)
67985
- }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
67986
- kind: "mutation",
67987
- auth: "admin"
67988
- }), 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({
67989
- deviceId: number(),
67990
- since: number().optional(),
67991
- until: number().optional(),
67992
- kinds: array(string()).optional(),
67993
- limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
67994
- }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
67995
- deviceId: number(),
67996
- since: number(),
67997
- until: number(),
67998
- bucketMs: number().int().positive()
67999
- }), array(object({
68000
- bucketStart: number(),
68001
- motion: number().int(),
68002
- object: number().int(),
68003
- audio: number().int()
68004
- })).readonly()), method(object({
68005
- deviceId: number(),
68006
- cutoffMs: number()
68007
- }), object({
68008
- motion: number().int(),
68009
- object: number().int(),
68010
- audio: number().int()
68011
- }), {
68012
- kind: "mutation",
68013
- auth: "admin"
68014
- }), method(object({
68015
- deviceId: number(),
68016
- cutoffMs: number()
68017
- }), TrackCascadeCountsSchema, {
68018
- kind: "mutation",
68019
- auth: "admin"
68020
- }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
68021
- kind: "mutation",
68022
- auth: "admin"
68023
- }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
68024
- kind: "mutation",
68025
- auth: "admin"
68026
- }), method(object({
68027
- deviceId: number(),
68028
- trackIds: array(string()).min(1)
68029
- }), object({
68030
- deleted: number().int(),
68031
- failed: array(string()).readonly()
68032
- }), {
68033
- kind: "mutation",
68034
- auth: "admin"
68035
- }), method(object({
68036
- /** Log/audit scope only — the trackId is globally unique on its own. */
68037
- deviceId: number(),
67742
+ var TrackFlagFields = {
67743
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
67744
+ * `'staging'`. */
67745
+ markForTrain: boolean().optional(),
67746
+ /** Operator marked this track for diagnostic attention. */
67747
+ debug: boolean().optional(),
67748
+ /** Operator favourited this track. Pins it against pruning. */
67749
+ favourited: boolean().optional()
67750
+ };
67751
+ /**
67752
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
67753
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
67754
+ * write patch, and the status is not something the toggle sets — it is what the
67755
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
67756
+ * always present on a persisted row (the column default materialises `'none'`).
67757
+ */
67758
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
67759
+ /**
67760
+ * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
67761
+ * one flag can never clear the other — the toggles are independent and are
67762
+ * driven from three surfaces that do not know about each other.
67763
+ */
67764
+ var TrackFlagsPatchSchema = object(TrackFlagFields);
67765
+ /**
67766
+ * The resolved flag state after a write. Both fields are REQUIRED here (absent
67767
+ * collapses to `false`) so a caller can drive a toggle's checked state off the
67768
+ * mutation result without a re-fetch.
67769
+ */
67770
+ var TrackFlagsSchema = object({
68038
67771
  trackId: string(),
68039
- flags: TrackFlagsPatchSchema
68040
- }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
68041
- kind: "query",
68042
- auth: "admin"
68043
- }), method(object({
68044
- olderThanMs: number(),
68045
- reason: OpsLogReasonSchema.optional()
68046
- }), EventPruneCountsSchema, {
68047
- kind: "mutation",
68048
- auth: "admin"
68049
- }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
68050
- kind: "mutation",
68051
- auth: "admin"
68052
- }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
68053
- kind: "mutation",
68054
- auth: "admin"
68055
- }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
68056
- kind: "mutation",
68057
- auth: "admin"
68058
- }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
68059
- kind: "mutation",
68060
- auth: "admin"
68061
- }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
68062
- kind: "mutation",
68063
- auth: "admin"
68064
- }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
68065
- kind: "mutation",
68066
- auth: "admin"
68067
- }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
68068
- kind: "mutation",
68069
- auth: "admin"
68070
- }), method(object({}), array(RelocateJobSchema).readonly(), {
68071
- kind: "query",
68072
- auth: "admin"
68073
- }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
68074
- kind: "mutation",
68075
- auth: "admin"
68076
- }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
68077
- kind: "query",
68078
- auth: "admin"
68079
- }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
68080
- kind: "query",
68081
- auth: "admin"
68082
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
68083
- kind: "query",
68084
- auth: "admin"
68085
- }), method(object({
68086
- /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
68087
- * `deviceId`, deliberately: `deviceId` would make this device-bound and
68088
- * route it at one camera's owner, and "every camera" would stop being
68089
- * expressible at all. */
68090
- deviceIds: array(number()).optional(),
68091
- limit: number().int().min(1).max(500).optional()
68092
- }), array(RetrainTrackSchema).readonly(), {
68093
- kind: "query",
68094
- auth: "admin"
68095
- }), method(object({ trackId: string() }), RetrainFrameListSchema, {
68096
- kind: "query",
68097
- auth: "admin"
68098
- }), method(object({
67772
+ markForTrain: boolean(),
67773
+ debug: boolean(),
67774
+ favourited: boolean(),
67775
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
67776
+ * a track row) because this shape is only ever produced by the write body,
67777
+ * which always knows it — and a surface that has just written needs to render
67778
+ * `trained` without a re-fetch. */
67779
+ retrainStatus: RetrainStatusSchema
67780
+ });
67781
+ union([literal(1), literal(2)]);
67782
+ /**
67783
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
67784
+ * the step and model that produced it — which is what makes the write rule
67785
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
67786
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
67787
+ *
67788
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
67789
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
67790
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
67791
+ * that value has no provenance, and the write rule lets ANY properly-attributed
67792
+ * write of the same tier replace it regardless of score.
67793
+ */
67794
+ var LabelAttributionSchema = object({
67795
+ stepId: string(),
67796
+ modelId: string().optional(),
67797
+ decidedAt: number(),
67798
+ /**
67799
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
67800
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
67801
+ *
67802
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
67803
+ * notification rule authored on "Gianluca" stopped matching the moment the
67804
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
67805
+ * the thing that does not move, so it is what a rule matches on
67806
+ * (`NcConditions.identities`) and the text is what a human is shown.
67807
+ *
67808
+ * Absent when the label names no gallery row — a plate the OCR read but no
67809
+ * vehicle claims, a sub-class, a species, any tier-1 value.
67810
+ */
67811
+ identityId: string().optional()
67812
+ });
67813
+ /**
67814
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
67815
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
67816
+ * track and its events always answer the same question the same way.
67817
+ *
67818
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
67819
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
67820
+ * is tier 2, and each carries its own score + attribution.
67821
+ *
67822
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
67823
+ * finest thing known. Before 4g the single `label` column held the finest
67824
+ * value, so a consumer that has not been updated reads the tier-1 slot and
67825
+ * shows nothing on a species-only row; that is why the migration puts every
67826
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
67827
+ * and why the read surfaces were changed in the same train.
67828
+ *
67829
+ * **Writing it.** The slots are independent, which is the whole point: a
67830
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
67831
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
67832
+ * higher score wins. One rule, one implementation — see
67833
+ * `pipeline/label-tier.ts` in addon-post-analysis.
67834
+ */
67835
+ var TieredLabelFields = {
67836
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
67837
+ label: string().optional(),
67838
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
67839
+ labelScore: number().optional(),
67840
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
67841
+ labelMeta: LabelAttributionSchema.optional(),
67842
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
67843
+ subLabel: string().optional(),
67844
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
67845
+ subLabelScore: number().optional(),
67846
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
67847
+ subLabelMeta: LabelAttributionSchema.optional()
67848
+ };
67849
+ /** Per-camera slice of a training-export estimate. */
67850
+ var TrainingExportDeviceTotalsSchema = object({
68099
67851
  deviceId: number(),
67852
+ tracks: number().int(),
67853
+ files: number().int(),
67854
+ bytes: number().int()
67855
+ });
67856
+ /**
67857
+ * What a training export WOULD contain. Computed from media index rows only —
67858
+ * no blob is read to produce this.
67859
+ */
67860
+ var TrainingExportSummarySchema = object({
67861
+ generatedAt: number(),
67862
+ trackCount: number().int(),
67863
+ fileCount: number().int(),
67864
+ byteCount: number().int(),
67865
+ /** More marked tracks exist than a single pass carries. */
67866
+ truncated: boolean(),
67867
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
67868
+ });
67869
+ var TrackSchema = object({
68100
67870
  trackId: string(),
68101
- mediaKeys: array(string()).min(1)
68102
- }), RetrainFrameSelectionSchema, {
68103
- kind: "mutation",
68104
- auth: "admin"
68105
- }), method(object({
68106
67871
  deviceId: number(),
68107
- trackId: string(),
68108
- frameId: string()
68109
- }), object({
68110
- removed: boolean(),
68111
- removedAnnotations: number().int()
68112
- }), {
68113
- kind: "mutation",
68114
- auth: "admin"
68115
- }), method(object({ frameId: string() }), object({
67872
+ className: string(),
67873
+ ...TieredLabelFields,
67874
+ producingDeviceName: string().optional(),
67875
+ /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
67876
+ source: TrackSourceSchema.optional(),
67877
+ firstSeen: number(),
67878
+ lastSeen: number(),
67879
+ /** Frame-rate position history (subject to maxPositionHistory cap). */
67880
+ positions: array(TrackPositionSchema).readonly(),
67881
+ /** Periodic snapshots at snapshotIntervalMs cadence (subject to
67882
+ * saveThumbnails policy). */
67883
+ snapshots: array(TrackSnapshotSchema).readonly(),
67884
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
67885
+ zonesVisited: array(string()).readonly(),
67886
+ /**
67887
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
67888
+ * `zones` capability.
67889
+ *
67890
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
67891
+ * and no card can render — so every free-text search surface was structurally
67892
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
67893
+ * just returned nothing. Resolving here rather than in each client keeps ONE
67894
+ * derivation and costs the clients no extra call (the `zones` cap is
67895
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
67896
+ * surface built to avoid exactly that).
67897
+ *
67898
+ * Resolved, never invented: a zone deleted since the track was written has no
67899
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
67900
+ * two are not positionally aligned. Absent when the track visited no zone, or
67901
+ * when the zone catalogue could not be read.
67902
+ */
67903
+ zoneNames: array(string()).readonly().optional(),
67904
+ /** Deduplicated set of detector classes observed for this track over its
67905
+ * life (a track may be reclassified, e.g. person→vehicle). Absent on
67906
+ * legacy rows written before class accumulation shipped. */
67907
+ classes: array(string()).readonly().optional(),
67908
+ /** Cumulative normalized distance travelled (0..1 units = full frame width). */
67909
+ totalDistance: number(),
67910
+ state: TrackStateSchema,
67911
+ active: boolean(),
67912
+ /** Deterministic key-event importance score in [0,1] (server-computed at
67913
+ * track expiry, recomputed on late label). Absent on legacy rows written
67914
+ * before scoring shipped — consumers degrade to absence / compute-on-read. */
67915
+ importance: number().optional(),
67916
+ /** Id of the track's highest-confidence ObjectEvent (its representative
67917
+ * "best" frame). Absent when the track produced no object events. */
67918
+ bestEventId: string().optional(),
67919
+ /** Tag of the importance sub-signal that dominated the score
67920
+ * (identity|dwell|proximity|class|confidence|travel|zone). */
67921
+ importanceReason: string().optional(),
67922
+ /** Audio-classification labels heard on the camera during the track's
67923
+ * life (score ≥ device `classificationMinScore`), aggregated per label.
67924
+ * Absent on legacy rows / tracks with no confident audio. */
67925
+ audioLabels: array(TrackAudioLabelSchema).readonly().optional(),
67926
+ /** Normalized 0..1 trajectory envelope (see {@link TrackEnvelopeSchema}).
67927
+ * Populated from the persisted envelope columns on historical reads;
67928
+ * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
67929
+ envelope: TrackEnvelopeSchema.optional(),
67930
+ /**
67931
+ * A face DETECTOR found a face on this track — nothing more. It says the
67932
+ * detail plane produced a `face` detail; it does NOT say the face was
67933
+ * embedded, matched, above `minFacePx`, or that the recognizer was even
67934
+ * enabled. Set once and never cleared.
67935
+ *
67936
+ * **This exists so "face present but not recognised" is expressible.** A
67937
+ * recognised identity lands in `subLabel` (attributed to the face chain via
67938
+ * `subLabelMeta.stepId`), so before this field a track with an unmatched face
67939
+ * and a track with no face at all were byte-identical on the wire and no
67940
+ * surface could tell them apart. The read is `hasFace === true && subLabel
67941
+ * === undefined`.
67942
+ *
67943
+ * **Absent ≠ false.** Every row written before the column existed omits it,
67944
+ * and so does every server that predates the field — a consumer must test
67945
+ * `=== true` and render nothing otherwise, never infer "no face".
67946
+ */
67947
+ hasFace: boolean().optional(),
67948
+ /**
67949
+ * This track has a face row IN THE GALLERY: a crop **and** an embedding — a
67950
+ * face an operator could ASSIGN to an identity.
67951
+ *
67952
+ * The STRICT twin of {@link hasFace}, and the pair only earns its keep
67953
+ * because the two disagree. `hasFace` is stamped at the TOP of the face
67954
+ * branch, before every gate, and means no more than "a face detector produced
67955
+ * a face detail". This one is stamped at the single moment the gallery row
67956
+ * LANDS — after `FaceRecognizer.onTrackEnd` successfully persists it, i.e.
67957
+ * past the embedding-magnitude verdict, the `minFacePx` detection gate, the
67958
+ * candidate gate, the imageless-track drop (no crop was ever captured) and
67959
+ * the crop-store drop. Everything between the detector and that insert can
67960
+ * legitimately refuse the face, so a flag written any earlier promises the
67961
+ * operator something to assign and delivers nothing.
67962
+ *
67963
+ * **Independent of recognition.** A face collected but never auto-matched is
67964
+ * still assignable — it is in fact the face an operator most wants to reach —
67965
+ * so this is NOT gated on `recognizedIdentityId`. Recognition lands in
67966
+ * `subLabel`; this says only that the raw material exists.
67967
+ *
67968
+ * **Set once, never cleared.** A track that produced a gallery row produced
67969
+ * one; deleting the row later is the gallery's business, not this flag's.
67970
+ *
67971
+ * **Absent ≠ false**, the same rule as {@link hasFace}: every row written
67972
+ * before the column omits it, and so does every server that predates the
67973
+ * field. A consumer must test `=== true` and render nothing otherwise —
67974
+ * never infer "no assignable face".
67975
+ */
67976
+ hasEmbeddedFace: boolean().optional(),
67977
+ /**
67978
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
67979
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
67980
+ * so the passage is tracked once and as a VEHICLE.
67981
+ *
67982
+ * It exists because the fold's record was dishonest. D34 and the code both
67983
+ * said "the person is not lost — it is reported so both entities stay on the
67984
+ * record"; in fact the pair went into a per-processor RAM field behind an
67985
+ * accessor nobody called, and every durable surface said `vehicle`, full
67986
+ * stop. This is the composition note that makes the row true.
67987
+ *
67988
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
67989
+ * person" is not an answer to "what is this" — both label tiers would refuse
67990
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
67991
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
67992
+ * and a `person` rule still does not fire for someone cycling past.
67993
+ *
67994
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
67995
+ * the column, and every hub that predates the field, omits it. Test
67996
+ * `=== true` and render nothing otherwise — never infer "no rider".
67997
+ */
67998
+ hasRider: boolean().optional(),
67999
+ ...TrackFlagFields,
68000
+ ...TrackRetrainFields
68001
+ });
68002
+ var BaseEventFields = {
68003
+ id: string(),
68004
+ deviceId: number(),
68005
+ timestamp: number()
68006
+ };
68007
+ var MotionEventSchema = object({
68008
+ ...BaseEventFields,
68009
+ kind: literal("motion"),
68010
+ regionCount: number(),
68011
+ /** Heavy JSON array — omitted in slim projection. */
68012
+ regions: array(object({
68013
+ bbox: BoundingBoxSchema,
68014
+ pixelCount: number(),
68015
+ intensity: number()
68016
+ })).readonly().optional(),
68017
+ /** Omitted in slim projection. */
68018
+ frameWidth: number().optional(),
68019
+ /** Omitted in slim projection. */
68020
+ frameHeight: number().optional(),
68021
+ /** Populated by B5 (recording playback URL for this event). */
68022
+ mediaUrl: string().optional()
68023
+ });
68024
+ /**
68025
+ * Which detection SOURCE produced an object event. `pipeline` = the ML
68026
+ * detection pipeline (decoded-frame inference); `onboard` = the camera's
68027
+ * native on-device AI. Both flow through the SAME analysis layers (zoning,
68028
+ * tracking, per-kind persistence) but stay distinguishable so consumers
68029
+ * (advanced-notifier, occupancy, …) can select which source(s) to act on.
68030
+ * Absent on legacy rows ⇒ treat as `pipeline`.
68031
+ */
68032
+ var DetectionSourceSchema = _enum(["pipeline", "onboard"]);
68033
+ /**
68034
+ * The confirmed zone crossing that produced an object event. Present ONLY on
68035
+ * an event emitted BY a crossing (`zone.enter` / `zone.exit`); a movement-state
68036
+ * event (`object.entering` / `leaving` / `stationary` / `loitering`) and an
68037
+ * appearance event carry none, so a rule asking for a direction fails closed
68038
+ * on them.
68039
+ *
68040
+ * Exactly ONE crossing per event: the emitter turns each confirmed crossing
68041
+ * into its own event, so a frame in which a track enters A while leaving B
68042
+ * produces two events with two directions — never one ambiguous row.
68043
+ *
68044
+ * `zoneId` is load-bearing for an EXIT: the event's `zones` list is the
68045
+ * membership the box has NOW, and by definition it no longer contains the zone
68046
+ * that was just left. Without the id here, a zone-scoped rule could never match
68047
+ * the exit it asked for.
68048
+ */
68049
+ var ZoneCrossingSchema = object({
68050
+ direction: _enum(["enter", "exit"]),
68051
+ /** Admin zone id crossed. */
68052
+ zoneId: string(),
68053
+ /** Zone display name at crossing time (falls back to the id). */
68054
+ zoneName: string().optional()
68055
+ });
68056
+ var ObjectEventSchema = object({
68057
+ ...BaseEventFields,
68058
+ kind: literal("object"),
68059
+ /** Detection source. Optional for backward-compat; absent ⇒ `pipeline`. */
68060
+ source: DetectionSourceSchema.optional(),
68061
+ /**
68062
+ * Inference-frame id shared by every object event emitted from the SAME frame
68063
+ * — the "scene/parent" key. Lets a consumer group co-occurring detections (e.g.
68064
+ * 2 people + 1 dog) under one full frame, and link a track's frames over time
68065
+ * (group by `trackId`, pick a representative `frameId` as the parent frame).
68066
+ * Optional for backward-compat with pre-existing rows / the slim projection
68067
+ * includes it (it is light). Absent on rows written before this field.
68068
+ */
68069
+ frameId: string().optional(),
68070
+ /** Omitted in slim projection. */
68071
+ trackId: string().optional(),
68072
+ className: string(),
68073
+ ...TieredLabelFields,
68074
+ /** Omitted in slim projection. */
68075
+ confidence: number().optional(),
68076
+ /** Heavy JSON — omitted in slim projection. */
68077
+ bbox: BoundingBoxSchema.optional(),
68078
+ /** Heavy JSON — omitted in slim projection. */
68079
+ zones: array(string()).readonly().optional(),
68080
+ /** Omitted in slim projection. */
68081
+ state: TrackStateSchema.optional(),
68082
+ /**
68083
+ * The zone crossing this event IS, when it is one. Absent on every other
68084
+ * event kind (movement state, appearance, package) — see
68085
+ * {@link ZoneCrossingSchema}. Omitted in slim projection.
68086
+ */
68087
+ zoneCrossing: ZoneCrossingSchema.optional(),
68088
+ /** Detection-frame dimensions in pixels — let consumers normalize the
68089
+ * pixel-space `bbox` onto a displayed image. Omitted in slim projection. */
68090
+ frameWidth: number().optional(),
68091
+ frameHeight: number().optional(),
68092
+ /** MediaStore key for the crop attached to this event (if any). */
68093
+ mediaKey: string().optional(),
68094
+ /** Design B: MediaStore key of the track's native-resolution key frame (the
68095
+ * best-detection full frame). Resolve via the event-media data-plane
68096
+ * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`) for a detail view that
68097
+ * draws `bbox` over the native frame. Absent on legacy rows / non-decoded
68098
+ * sources — consumers fall back to `mediaKey` (the tight crop). */
68099
+ keyFrameMediaKey: string().optional(),
68100
+ /** Populated by B5 (recording playback URL for this event). */
68101
+ mediaUrl: string().optional(),
68102
+ /** The parent track's key-event importance [0,1], propagated to every object
68103
+ * event of the track (so an event row can be sorted by importance without a
68104
+ * track join). Absent on legacy rows / before the track was scored. */
68105
+ importance: number().optional()
68106
+ });
68107
+ var AudioEventSchema = object({
68108
+ ...BaseEventFields,
68109
+ kind: literal("audio"),
68110
+ rms: number(),
68111
+ dbfs: number(),
68112
+ classification: object({
68113
+ className: string(),
68114
+ originalClass: string().optional(),
68115
+ score: number()
68116
+ }).optional(),
68117
+ /** Populated by B5 (recording playback URL for this event). */
68118
+ mediaUrl: string().optional()
68119
+ });
68120
+ var MediaFileKindEnum = _enum([
68121
+ "crop",
68122
+ "thumbnail",
68123
+ "snapshot",
68124
+ "firstFrame",
68125
+ "lastFrame",
68126
+ "fullFrame",
68127
+ "fullFrameBoxed",
68128
+ "faceCrop",
68129
+ "plateCrop",
68130
+ "keyFrame",
68131
+ "keyFrameSmall",
68132
+ "thumbnailSmall"
68133
+ ]);
68134
+ var MediaFileSchema = object({
68135
+ key: string(),
68136
+ kind: MediaFileKindEnum,
68116
68137
  base64: string(),
68117
- width: number().int(),
68118
- height: number().int()
68119
- }), {
68120
- kind: "query",
68121
- auth: "admin"
68122
- }), method(object({
68123
- deviceId: number(),
68124
- trackId: string(),
68125
- frameId: string(),
68126
- subject: RetrainAssistSubjectSchema,
68127
- /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
68128
- nodeId: string().optional()
68129
- }), RetrainAssistResultSchema, {
68130
- kind: "mutation",
68131
- auth: "admin"
68132
- }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
68133
- kind: "query",
68134
- auth: "admin"
68135
- }), method(object({
68136
- deviceId: number(),
68138
+ sizeBytes: number(),
68139
+ timestamp: number()
68140
+ });
68141
+ /**
68142
+ * One media row WITHOUT its bytes.
68143
+ *
68144
+ * A track's media is 5-8 MB of base64 (measured: 7.67 MB across 23 files for a
68145
+ * 140 s track), and a client that renders tiles from the media data plane needs
68146
+ * to know only WHAT EXISTS — the bytes then arrive per tile, lazily, over HTTP
68147
+ * with an immutable cache, instead of all at once inside a tRPC response that
68148
+ * blocks the whole view.
68149
+ *
68150
+ * `sizeBytes` is carried because it is what lets a client decide between the
68151
+ * stored blob and a `?variant=thumb` rendering without fetching either.
68152
+ */
68153
+ var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
68154
+ /**
68155
+ * The MACRO tier of an annotation — a CLOSED set.
68156
+ *
68157
+ * This is what the exported detector predicts, so a typo here is a new class
68158
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
68159
+ * the whole point of the page is teaching the model things it does not know
68160
+ * yet, and constraining that vocabulary would make it useless.
68161
+ *
68162
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
68163
+ * `subLabel` is one of these values, in any casing, because once `person`
68164
+ * exists in both tiers "every person box" stops being answerable without
68165
+ * knowing every string anyone ever typed — and the damage is retroactive.
68166
+ */
68167
+ var RetrainMacroClassSchema = _enum([
68168
+ "person",
68169
+ "vehicle",
68170
+ "animal",
68171
+ "package",
68172
+ "face",
68173
+ "plate"
68174
+ ]);
68175
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
68176
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
68177
+ /** Did a human draw this box, or did the assist propose it? */
68178
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
68179
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
68180
+ var RetrainBboxSchema = object({
68181
+ x: number(),
68182
+ y: number(),
68183
+ w: number(),
68184
+ h: number()
68185
+ });
68186
+ /**
68187
+ * One annotated subject.
68188
+ *
68189
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
68190
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
68191
+ * derived from it at export and never stored — storing them is how one feature
68192
+ * space ends up holding two crops of the same subject (D52).
68193
+ */
68194
+ var RetrainAnnotationSchema = object({
68195
+ id: string(),
68137
68196
  trackId: string(),
68138
- frameId: string(),
68139
- annotations: array(RetrainAnnotationDraftSchema)
68140
- }), array(RetrainAnnotationSchema).readonly(), {
68141
- kind: "mutation",
68142
- auth: "admin"
68143
- }), method(object({
68144
- deviceId: number(),
68145
- trackId: string()
68146
- }), RetrainTransitionResultSchema, {
68147
- kind: "mutation",
68148
- auth: "admin"
68149
- }), method(object({
68150
68197
  deviceId: number(),
68151
- trackId: string()
68152
- }), RetrainTransitionResultSchema, {
68153
- kind: "mutation",
68154
- auth: "admin"
68155
- }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
68156
- kind: "query",
68157
- auth: "admin"
68158
- }), method(object({
68159
- eventId: string(),
68160
- kind: MediaFileKindEnum.optional(),
68161
- deviceId: number()
68162
- }), array(MediaFileSchema).readonly()), method(object({
68163
- trackId: string(),
68164
- kinds: array(MediaFileKindEnum).optional(),
68165
- deviceId: number()
68166
- }), array(MediaFileSchema).readonly()), method(object({
68198
+ /** The COPY in retrain storage — never the source track's media key. */
68199
+ mediaKey: string(),
68200
+ bbox: RetrainBboxSchema,
68201
+ macroClass: RetrainMacroClassSchema,
68202
+ label: string().optional(),
68203
+ subLabel: string().optional(),
68204
+ kind: RetrainAnnotationKindSchema,
68205
+ source: RetrainAnnotationSourceSchema,
68206
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
68207
+ assistModelId: string().optional(),
68208
+ assistScore: number().optional(),
68209
+ exportedInBatch: string().optional(),
68210
+ createdAt: number()
68211
+ });
68212
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
68213
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
68214
+ id: true,
68215
+ trackId: true,
68216
+ deviceId: true,
68217
+ mediaKey: true,
68218
+ createdAt: true,
68219
+ exportedInBatch: true
68220
+ });
68221
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
68222
+ var RetrainTrackSchema = object({
68167
68223
  trackId: string(),
68168
- deviceId: number()
68169
- }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
68170
- kind: "mutation",
68171
- auth: "admin"
68172
- }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
68173
- kind: "mutation",
68174
- auth: "admin"
68175
- }), method(object({}), RebuildStatusSchema), object({
68176
68224
  deviceId: number(),
68225
+ className: string(),
68226
+ label: string().optional(),
68227
+ firstSeen: number(),
68228
+ lastSeen: number(),
68229
+ /** How many frames the dataset already holds from this track. */
68230
+ frameCount: number().int(),
68231
+ /** How many subjects have been annotated on those frames. `0` with
68232
+ * `frameCount: 0` is exactly "staging, still to work". */
68233
+ annotationCount: number().int()
68234
+ });
68235
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
68236
+ var RetrainFrameCandidateSchema = object({
68237
+ mediaKey: string(),
68238
+ kind: MediaFileKindEnum,
68177
68239
  timestamp: number(),
68178
- frameWidth: number(),
68179
- frameHeight: number(),
68180
- detections: array(OverlayDetectionSchema).readonly()
68181
- }), object({
68182
- deviceId: number(),
68183
- trackId: string(),
68184
- className: string()
68185
- }), object({
68240
+ sizeBytes: number().int(),
68241
+ /** A copy of this original already exists — selecting it is free and cannot
68242
+ * fail, whatever became of the original. */
68243
+ copied: boolean()
68244
+ });
68245
+ /** A frame the dataset OWNS: bytes copied at selection time. */
68246
+ var RetrainFrameSchema = object({
68247
+ frameId: string(),
68186
68248
  deviceId: number(),
68187
68249
  trackId: string(),
68188
- className: string(),
68189
- durationMs: number()
68190
- }), object({
68191
- deviceId: number(),
68192
- kind: EventKindSchema,
68193
- eventId: string(),
68194
- timestamp: number()
68250
+ /** Provenance only. It may already point at nothing — that is expected. */
68251
+ sourceMediaKey: string(),
68252
+ sourceKind: MediaFileKindEnum,
68253
+ sizeBytes: number().int(),
68254
+ width: number().int(),
68255
+ height: number().int(),
68256
+ copiedAt: number()
68195
68257
  });
68196
- /**
68197
- * Reference to the frame's retained NATIVE surface + the parent crop's placement
68198
- * within the frame, so the executor can re-cut a leaf child ROI at native
68199
- * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
68200
- */
68201
- var NativeCropRefSchema = object({
68202
- /** Handle keying the retained native surface (node-pinned to its owner). */
68203
- handle: FrameHandleSchema,
68204
- /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
68205
- cropFrameSpace: object({
68206
- x: number(),
68207
- y: number(),
68208
- w: number(),
68209
- h: number()
68210
- })
68258
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
68259
+ var RetrainCopyRefusalSchema = _enum([
68260
+ "source-missing",
68261
+ "unreadable-image",
68262
+ "write-failed"
68263
+ ]);
68264
+ var RetrainFrameSelectionSchema = object({
68265
+ copied: array(RetrainFrameSchema).readonly(),
68266
+ refused: array(object({
68267
+ sourceMediaKey: string(),
68268
+ reason: RetrainCopyRefusalSchema
68269
+ })).readonly()
68211
68270
  });
68212
- object({
68213
- crop: object({
68214
- left: number(),
68215
- top: number(),
68216
- width: number().positive(),
68217
- height: number().positive()
68218
- }).optional(),
68219
- content: object({
68220
- width: number().int().positive(),
68221
- height: number().int().positive()
68222
- }),
68223
- fit: _enum(["stretch", "contain"]),
68224
- format: _enum([
68225
- "rgb",
68226
- "gray",
68227
- "jpeg"
68228
- ])
68271
+ var RetrainFrameListSchema = object({
68272
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
68273
+ copies: array(RetrainFrameSchema).readonly(),
68274
+ /** What the page pre-selects — the native key frame when one survives. */
68275
+ autoPickMediaKey: string().optional()
68229
68276
  });
68277
+ /** What the operator asked the assist to look for. */
68278
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
68279
+ kind: literal("package"),
68280
+ zone: RetrainBboxSchema.optional()
68281
+ }), object({
68282
+ kind: literal("objects"),
68283
+ modelId: string(),
68284
+ minScore: number().optional()
68285
+ })]);
68230
68286
  /**
68231
- * Process-local frame identity. It is serializable so it can ride an in-process
68232
- * capability call, but `registryId` deliberately prevents resolution in any
68233
- * other process or execution group.
68287
+ * The assist's answer — a discriminated union, because "the model saw nothing"
68288
+ * and "this node cannot run that model" lead to different next moves and a
68289
+ * nullable result cannot tell them apart.
68234
68290
  */
68235
- var FrameRefSchema = object({
68236
- registryId: string().min(1),
68237
- id: string().min(1),
68238
- width: number().int().positive(),
68239
- height: number().int().positive(),
68240
- format: _enum(["rgb", "gray"]),
68241
- timestamp: number(),
68242
- capturedAt: number().optional()
68291
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
68292
+ kind: literal("proposed"),
68293
+ modelId: string(),
68294
+ stepId: string(),
68295
+ minScore: number(),
68296
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
68297
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
68298
+ /** Returned by the runner but removed by the threshold. */
68299
+ belowThreshold: number().int()
68300
+ }), object({
68301
+ kind: literal("refused"),
68302
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
68303
+ reason: string(),
68304
+ detail: string().optional()
68305
+ })]);
68306
+ /** The outcome of a lifecycle move owned by the retrain page. */
68307
+ var RetrainTransitionResultSchema = object({
68308
+ trackId: string(),
68309
+ /** Where the track ended up, whatever happened. */
68310
+ retrainStatus: RetrainStatusSchema,
68311
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
68312
+ changed: boolean(),
68313
+ reason: _enum([
68314
+ "unknown-track",
68315
+ "no-frames-copied",
68316
+ "not-staging",
68317
+ "not-trained",
68318
+ "unchanged"
68319
+ ]).optional()
68243
68320
  });
68244
- var ModelFormatSchema$1 = _enum([
68245
- "onnx",
68246
- "coreml",
68247
- "openvino",
68248
- "tflite",
68249
- "pt",
68250
- "gguf"
68251
- ]);
68252
- var PipelineSlotSchema = _enum([
68253
- "detector",
68254
- "cropper",
68255
- "classifier",
68256
- "refiner",
68257
- "audio-classifier"
68258
- ]);
68259
- var PipelineEngineChoiceSchema = object({
68260
- runtime: _enum(["node", "python"]),
68261
- backend: string(),
68262
- format: ModelFormatSchema$1,
68263
- device: string().optional()
68321
+ var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
68322
+ var MAX_EVENT_QUERY_LIMIT = 5e3;
68323
+ var DeviceEventQueryInput = object({
68324
+ deviceId: number(),
68325
+ since: number().optional(),
68326
+ until: number().optional(),
68327
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT),
68328
+ /** `slim` drops heavy JSON fields (regions/bbox/zones) and carries an
68329
+ * optional `mediaUrl` (populated by B5). `full` (default) keeps today's
68330
+ * exact behaviour. Callers may omit this field — the store defaults to
68331
+ * `full` when not provided. */
68332
+ projection: _enum(["full", "slim"]).optional()
68264
68333
  });
68265
- var AvailableEngineSchema = object({
68266
- engine: PipelineEngineChoiceSchema,
68267
- devices: array(object({
68268
- id: string(),
68269
- label: string(),
68270
- description: string().optional()
68271
- })).readonly(),
68272
- defaultDevice: string()
68334
+ var ObjectEventQueryInput = DeviceEventQueryInput.extend({ classFilter: string().optional() });
68335
+ var RecentTracksQueryInput = object({
68336
+ /** Devices to merge. An empty array yields `{ tracks: [], nextCursor: null }`. */
68337
+ deviceIds: array(number()),
68338
+ /** Window lower bound on `lastSeen` (inclusive). */
68339
+ since: number().optional(),
68340
+ /** Window upper bound on `lastSeen` (inclusive). */
68341
+ until: number().optional(),
68342
+ /** Page size. Default 200, max 1000. */
68343
+ limit: number().int().min(1).max(1e3).default(200),
68344
+ /** Opaque continuation cursor from a previous page's `nextCursor`.
68345
+ * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
68346
+ cursor: string().optional(),
68347
+ /** See {@link TrackProjectionSchema}. Default `full`. */
68348
+ projection: TrackProjectionSchema.optional(),
68349
+ /** Include stationary-promoted rows (parked objects). Default false: the
68350
+ * feed lists passages; parking records live on the stationary registry. */
68351
+ includeStationary: boolean().optional()
68273
68352
  });
68274
- var PipelineDefaultStepSchema = lazy(() => object({
68275
- addonId: string(),
68276
- addonName: string(),
68277
- slot: PipelineSlotSchema,
68278
- inputClasses: array(string()).readonly(),
68279
- outputClasses: array(string()).readonly(),
68280
- enabled: boolean(),
68281
- modelId: string(),
68282
- children: array(PipelineDefaultStepSchema).readonly(),
68283
- group: string().optional(),
68284
- settings: record(string(), unknown()).optional()
68285
- }));
68286
- var PipelineTemplateStepSchema = lazy(() => object({
68287
- addonId: string(),
68288
- enabled: boolean(),
68289
- modelId: string(),
68290
- children: array(PipelineTemplateStepSchema).readonly(),
68291
- settings: record(string(), unknown()).optional()
68292
- }));
68293
- var PipelineTemplateSchema$1 = object({
68294
- id: string(),
68295
- name: string(),
68296
- createdAt: string(),
68297
- updatedAt: string(),
68298
- engine: PipelineEngineChoiceSchema,
68299
- steps: array(PipelineTemplateStepSchema).readonly()
68353
+ var RecentTracksPageSchema = object({
68354
+ /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
68355
+ tracks: array(TrackSchema).readonly(),
68356
+ /** Cursor for the next page, or null when this page is the last. */
68357
+ nextCursor: string().nullable()
68300
68358
  });
68301
- var PipelineModelOptionSchema = object({
68359
+ var LIST_GROUPS_DEFAULT_LIMIT = 40;
68360
+ var LIST_GROUPS_MAX_LIMIT = 100;
68361
+ var AnalyticsGroupRecordSchema = object({
68302
68362
  id: string(),
68303
- name: string(),
68304
- formats: record(string(), object({
68305
- downloaded: boolean(),
68306
- sizeMB: number()
68307
- })),
68308
- group: ModelVariantGroupSchema.optional(),
68309
- legacy: boolean().optional(),
68310
- provider: ModelProviderIdSchema.optional()
68363
+ deviceId: number().int(),
68364
+ openedAt: number().int(),
68365
+ closedAt: number().int(),
68366
+ timestamp: number().int(),
68367
+ memberCount: number().int(),
68368
+ memberTrackIds: array(string()).readonly(),
68369
+ className: string(),
68370
+ classes: array(string()).readonly(),
68371
+ /** Relative event-media path, or null when the group has no picture yet. */
68372
+ mediaUrl: string().nullable(),
68373
+ singleton: boolean()
68311
68374
  });
68312
- var ConfigFieldBridge = custom();
68313
- var PipelineAddonSchemaSchema = object({
68314
- id: string(),
68315
- name: string(),
68316
- slot: PipelineSlotSchema,
68317
- inputClasses: array(string()).readonly(),
68318
- outputClasses: array(string()).readonly(),
68319
- childSlots: array(PipelineSlotSchema).readonly(),
68320
- models: array(PipelineModelOptionSchema).readonly(),
68321
- defaultModelId: string(),
68322
- defaultModelIdByFormat: record(string(), string()).optional(),
68323
- enabledByDefault: boolean().optional(),
68324
- backfillIntoExistingOverrides: boolean().optional(),
68325
- defaultConfidence: number(),
68326
- group: string().optional(),
68327
- configSchema: array(ConfigFieldBridge).readonly().optional()
68375
+ var AnalyticsGroupMemberSchema = object({
68376
+ trackId: string(),
68377
+ deviceId: number().int(),
68378
+ className: string(),
68379
+ firstSeen: number().int(),
68380
+ lastSeen: number().int(),
68381
+ mediaUrl: string().nullable()
68328
68382
  });
68329
- var PipelineSlotSchemaSchema = object({
68330
- id: PipelineSlotSchema,
68331
- label: string(),
68332
- priority: number(),
68333
- parentSlot: PipelineSlotSchema.nullable(),
68334
- addons: array(PipelineAddonSchemaSchema).readonly()
68383
+ var AnalyticsGroupDetailSchema = AnalyticsGroupRecordSchema.extend({ members: array(AnalyticsGroupMemberSchema).readonly() });
68384
+ var ListGroupsQueryInput = object({
68385
+ /** Devices to merge. An empty array yields `{ groups: [], nextCursor: null }`. */
68386
+ deviceIds: array(number()),
68387
+ /** Window lower bound on `closedAt` (inclusive). */
68388
+ since: number().optional(),
68389
+ /** Window upper bound on `openedAt` (inclusive). */
68390
+ until: number().optional(),
68391
+ limit: number().int().min(1).max(LIST_GROUPS_MAX_LIMIT).default(LIST_GROUPS_DEFAULT_LIMIT),
68392
+ /** Opaque continuation cursor from a previous page's `nextCursor`. */
68393
+ cursor: string().optional()
68335
68394
  });
68336
- var PipelineSchemaSchema = object({
68337
- availableEngines: array(AvailableEngineSchema).readonly(),
68338
- selectedEngine: PipelineEngineChoiceSchema,
68339
- slots: array(PipelineSlotSchemaSchema).readonly()
68395
+ var ListGroupsPageSchema = object({
68396
+ groups: array(AnalyticsGroupRecordSchema).readonly(),
68397
+ nextCursor: string().nullable()
68340
68398
  });
68341
- var EngineProvisioningSchema = object({
68342
- runtimeId: _enum([
68343
- "onnx",
68344
- "openvino",
68345
- "coreml",
68346
- "edgetpu"
68347
- ]).nullable(),
68348
- device: string().nullable(),
68349
- state: _enum([
68350
- "idle",
68351
- "installing",
68352
- "verifying",
68353
- "ready",
68354
- "failed"
68355
- ]),
68356
- progress: number().optional(),
68357
- error: string().optional(),
68358
- nextRetryAt: number().optional(),
68359
- /**
68360
- * Gate A (config-correctness gate at engine change): human-readable
68361
- * config issues surfaced EAGERLY when the node's engine changes — model
68362
- * substitutions ("chose X, running Y") and zero-build steps ("no model
68363
- * has a <format> build"). Additive/optional: informational only, never
68364
- * enforced here — `assertEngineReady` (readiness) still gates inference.
68365
- * Absent/empty when the node-default tree resolves cleanly.
68366
- */
68367
- configIssues: array(string()).optional()
68399
+ var KeyEventQueryInput = object({
68400
+ deviceId: number(),
68401
+ /** Window lower bound (track firstSeen ≥ since). */
68402
+ since: number(),
68403
+ /** Window upper bound (track firstSeen ≤ until). */
68404
+ until: number(),
68405
+ limit: number().int().min(1).max(200).default(50),
68406
+ /** Drop tracks scoring below this importance. */
68407
+ minImportance: number().min(0).max(1).optional(),
68408
+ /** Restrict to a single class (e.g. 'person'). */
68409
+ classFilter: string().optional()
68368
68410
  });
68369
- var PipelineStepInputSchema = lazy(() => object({
68370
- addonId: string(),
68371
- modelId: string().optional(),
68372
- enabled: boolean().default(true),
68373
- children: array(PipelineStepInputSchema).optional(),
68374
- settings: record(string(), unknown()).optional(),
68375
- jumpDeviceKey: string().optional()
68376
- }));
68377
- var ModelSubstitutionSchema = object({
68378
- addonId: string(),
68379
- chosen: string(),
68380
- running: string(),
68381
- format: string()
68411
+ var KeyEventSchema = object({
68412
+ /** The representative event id (the track's best ObjectEvent, else its trackId). */
68413
+ id: string(),
68414
+ trackId: string(),
68415
+ /** Track start time (firstSeen). */
68416
+ timestamp: number(),
68417
+ className: string(),
68418
+ ...TieredLabelFields,
68419
+ importance: number(),
68420
+ /** Highest-confidence ObjectEvent id for the track (empty when none). */
68421
+ bestEventId: string(),
68422
+ /** Track lifetime in ms (lastSeen - firstSeen). */
68423
+ windowMs: number().optional(),
68424
+ ...TrackFlagFields,
68425
+ ...TrackRetrainFields
68382
68426
  });
68383
- var PipelineValidationIssueSchema = object({
68384
- addonId: string(),
68385
- kind: _enum(["unknown-addon", "no-format-build"]),
68386
- detail: string()
68427
+ object({
68428
+ trackId: string(),
68429
+ className: string(),
68430
+ confidence: number(),
68431
+ bbox: BoundingBoxSchema,
68432
+ zones: array(string()).readonly(),
68433
+ state: TrackStateSchema
68387
68434
  });
68388
- var PipelineValidationResultSchema = object({
68389
- ok: boolean(),
68390
- issues: array(PipelineValidationIssueSchema).readonly(),
68391
- substitutions: array(ModelSubstitutionSchema).readonly(),
68392
- /** The node's `currentEngine.format` this validation ran against. */
68393
- format: string()
68435
+ var OverlayDetectionSchema = looseObject({
68436
+ id: string(),
68437
+ kind: _enum(["first-level", "detail"]),
68438
+ macroClass: string(),
68439
+ score: number(),
68440
+ bbox: object({
68441
+ x: number(),
68442
+ y: number(),
68443
+ width: number(),
68444
+ height: number()
68445
+ }),
68446
+ labels: array(looseObject({
68447
+ label: string(),
68448
+ score: number()
68449
+ })).readonly(),
68450
+ parentId: string().optional()
68451
+ });
68452
+ var ScoredObjectEventSchema = ObjectEventSchema.extend({ score: number() });
68453
+ var SearchObjectEventsInput = object({
68454
+ text: string(),
68455
+ deviceId: number().optional(),
68456
+ since: number().optional(),
68457
+ until: number().optional(),
68458
+ classFilter: string().optional(),
68459
+ limit: number().default(50),
68460
+ minScore: number().min(0).max(1).default(.2)
68461
+ });
68462
+ var TrackCascadeCountsSchema = object({
68463
+ /** Persisted track roots deleted (authoritative). */
68464
+ tracks: number().int(),
68465
+ /** Object events removed with their tracks (best-effort; see note above). */
68466
+ events: number().int(),
68467
+ /** Track/face/plate-owned media removed (best-effort). Never identity media. */
68468
+ media: number().int(),
68469
+ /** Unassigned (non-enrolled) face reads removed (best-effort). */
68470
+ faces: number().int(),
68471
+ /** Unassigned plate reads removed (best-effort; plate leg deferred to plate-intelligence). */
68472
+ plates: number().int(),
68473
+ /** Per-track CLIP search vectors removed (best-effort). */
68474
+ embeddings: number().int(),
68475
+ /** Group membership + group rows removed with their last member (best-effort). */
68476
+ groups: number().int()
68394
68477
  });
68395
- var ReferenceImageEntrySchema = object({
68396
- filename: string(),
68397
- stepIds: array(string()).readonly().optional()
68478
+ /** Disk-wins reconcile: media rows whose blobs are gone, then empty tracks. */
68479
+ var DiskReconcileCountsSchema = object({
68480
+ mediaDropped: number().int(),
68481
+ tracks: number().int(),
68482
+ events: number().int()
68398
68483
  });
68399
- var ReferenceImageBodySchema = object({
68400
- base64: string(),
68401
- filename: string()
68484
+ /** Event-store footprint for one camera. */
68485
+ var EventStoreDeviceFootprintSchema = object({
68486
+ deviceId: number(),
68487
+ /** Persisted event rows (motion + object + audio) for the camera. */
68488
+ rows: number().int(),
68489
+ /** Event-owned media bytes on disk for the camera. */
68490
+ bytes: number().int()
68402
68491
  });
68403
- var ReferenceAudioEntrySchema = object({
68404
- filename: string(),
68405
- sizeKb: number()
68492
+ /** Aggregate event-store footprint: global totals + per-camera breakdown. */
68493
+ var EventStoreFootprintSchema = object({
68494
+ totalRows: number().int(),
68495
+ totalBytes: number().int(),
68496
+ devices: array(EventStoreDeviceFootprintSchema).readonly()
68406
68497
  });
68407
- var ReferenceAudioBodySchema = object({ base64: string() });
68408
- var AudioBackendSchema = object({
68409
- id: string(),
68410
- name: string(),
68411
- description: string(),
68412
- available: boolean(),
68498
+ /** Per-kind counts returned by the event-prune / device-delete mutations. */
68499
+ var EventPruneCountsSchema = object({
68500
+ motion: number().int(),
68501
+ object: number().int(),
68502
+ audio: number().int()
68503
+ });
68504
+ /**
68505
+ * Re-embed stored tracks from their key frames.
68506
+ *
68507
+ * The reason this is an operator-callable method and not a migration script:
68508
+ * every knob that decides what a vector MEANS — encoder model, crop margin,
68509
+ * squaring — is only changeable if the existing vectors can be regenerated.
68510
+ * Mixing feature spaces in one index makes cosine scores incomparable, and the
68511
+ * symptom is a quality regression with no visible cause.
68512
+ */
68513
+ var RebuildObjectEmbeddingsInput = object({
68514
+ /** Restrict to one camera. Omit for the whole fleet. */
68515
+ deviceId: number().optional(),
68516
+ since: number().optional(),
68517
+ until: number().optional(),
68518
+ /** Stop after this many tracks; the result reports whether more remain. */
68519
+ maxTracks: number().int().positive().optional(),
68413
68520
  /**
68414
- * Raw classifier labels this backend can emit (e.g. YAMNet's
68415
- * 521-class set or Apple SoundAnalysis's 303-class set). Used by
68416
- * the benchmark UI to populate the `enabledMicroClasses` filter
68417
- * specific to the selected backend without a separate fetch.
68521
+ * Run every embedding on THIS node instead of round-robining the fleet.
68522
+ *
68523
+ * Named `executeOnNodeId` and not `nodeId` on purpose: an inline `nodeId`
68524
+ * field in cap args is read by `parent-unowned-call.ts` as a ROUTING PIN, so
68525
+ * calling it that would pin the rebuild REQUEST itself to that node — the
68526
+ * rebuild orchestration lives on the hub, and only the per-track step runs
68527
+ * remotely. This field is data; the per-track pin is applied inside.
68528
+ *
68529
+ * Absent ⇒ round-robin over every online node whose runner can serve the
68530
+ * pinned model.
68418
68531
  */
68419
- rawLabels: array(string()).readonly().optional()
68420
- });
68421
- var AudioCapabilitiesSchema = object({
68422
- activeBackend: string(),
68423
- availableBackends: array(AudioBackendSchema).readonly(),
68424
- sampleRate: number(),
68425
- chunkDurationMs: number()
68426
- });
68427
- var DownloadModelResultSchema = object({
68428
- filePath: string(),
68429
- sizeMB: number(),
68430
- durationMs: number()
68532
+ executeOnNodeId: string().optional(),
68533
+ /**
68534
+ * Milliseconds to wait between tracks; omit for the built-in default, `0` to
68535
+ * run flat out.
68536
+ *
68537
+ * A rebuild is bulk maintenance on hub-main's single thread. Measured
68538
+ * 2026-08-06, an unpaced pass held that thread busy 82.2 s out of 120 and
68539
+ * pushed `nodes.topology` from 0.25 s to 26 s for 43 minutes. The value in
68540
+ * force is logged at start and finish so a deliberately slow pass reads
68541
+ * differently from a stalled one.
68542
+ */
68543
+ pacingMs: number().int().nonnegative().optional()
68431
68544
  });
68432
68545
  /**
68433
- * Wrapper carrying a single test run's result. Replaces the legacy
68434
- * ad-hoc `{labels: [{className, originalClass, score}]}` shape with the
68435
- * canonical `AudioResult` from the Phase 6 output rework: one
68436
- * `AudioDetection` per class above `minScore`, top-N candidates in
68437
- * `debug.alternateLabels['audio-classifier']`, per-source timings in
68438
- * `debug.stepTimings`. The outer `success`/`error` fields stay so the
68439
- * benchmark UI can still report a clean failure when the classifier
68440
- * cap isn't available.
68546
+ * Result of emptying the CLIP index.
68547
+ *
68548
+ * The clean slate before a policy change: a new crop margin or encoder model
68549
+ * leaves two feature spaces in one index whose cosine scores are not
68550
+ * comparable, so wiping and rebuilding is the only way to be sure every vector
68551
+ * means the same thing.
68441
68552
  */
68442
- var AudioTestResultSchema = object({
68443
- success: boolean(),
68444
- error: string().optional(),
68445
- frame: custom().optional()
68553
+ var WipeObjectEmbeddingsResultSchema = object({ deleted: number() });
68554
+ /**
68555
+ * Acknowledgement that a rebuild STARTED.
68556
+ *
68557
+ * The pass costs ~1s per track — 45 minutes for a 2,600-track fleet — so it
68558
+ * runs detached and this returns immediately. Waiting for it made the client
68559
+ * time out while the work carried on server-side, which is the worst of both:
68560
+ * no result and no way to know it was still going. Poll
68561
+ * `getObjectEmbeddingRebuildStatus` for progress.
68562
+ */
68563
+ var RebuildObjectEmbeddingsResultSchema = object({
68564
+ started: boolean(),
68565
+ /** True when a pass was already running; the new request is ignored. */
68566
+ alreadyRunning: boolean()
68446
68567
  });
68447
- var PipelineConfigBridge = custom();
68448
- var ConfigUISchemaBridge = custom();
68449
- var ConfigUISchemaNullableBridge = custom();
68450
- var InferenceCapabilitiesBridge = custom();
68451
- var ModelAvailabilityListBridge = custom();
68452
- var PipelineRunResultBridge = custom();
68453
- method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngineChoiceSchema), method(PipelineEngineChoiceSchema, array(PipelineDefaultStepSchema)), method(object({ nodeId: string() }), EngineProvisioningSchema), method(_void(), record(string(), object({
68454
- modelId: string(),
68455
- settings: record(string(), unknown()).readonly()
68456
- }))), method(object({ steps: record(string(), object({
68457
- modelId: string(),
68458
- settings: record(string(), unknown()).readonly()
68459
- })) }), object({ success: literal(true) }), {
68568
+ var RebuildStatusSchema = object({
68569
+ running: boolean(),
68570
+ scanned: number(),
68571
+ rebuilt: number(),
68572
+ /** Tracks whose key frame is gone — nothing to re-embed from. */
68573
+ missingKeyFrame: number(),
68574
+ /** Tracks with no usable detection box. */
68575
+ missingBbox: number(),
68576
+ /**
68577
+ * Tracks an executing node REFUSED rather than broke on — an unreadable key
68578
+ * frame, a step that threw. Separate from `failed` because the remedy is
68579
+ * different, and because a whole camera silently contributing zero vectors
68580
+ * is the shape of failure a rebuild must never hide.
68581
+ */
68582
+ notRunnable: number(),
68583
+ /**
68584
+ * The pass stopped because NO node could serve the pinned model.
68585
+ *
68586
+ * Distinct from `notRunnable` on purpose: that one says "this track was
68587
+ * refused", this one says "the cluster cannot do this work at all" — every
68588
+ * candidate node either lacks the `clip-embedding` step, lacks a build of the
68589
+ * pinned model for its engine format, or dropped out. The remedy is a model /
68590
+ * engine change, not a per-camera one. Non-zero here always comes with
68591
+ * `complete: false`.
68592
+ */
68593
+ noCapableNode: number(),
68594
+ failed: number(),
68595
+ /** Set once a pass ends: true only when EVERYTHING was covered. */
68596
+ complete: boolean().nullable(),
68597
+ startedAtMs: number().nullable(),
68598
+ finishedAtMs: number().nullable(),
68599
+ /** Present when the pass ended by throwing. */
68600
+ error: string().nullable()
68601
+ });
68602
+ var ReplayFrameInputSchema = object({
68603
+ timestamp: number(),
68604
+ frame: PipelineRunResultBridge
68605
+ });
68606
+ var RunReplayFrameProcessorResultSchema = object({ tracks: array(object({
68607
+ className: string(),
68608
+ firstSeenMs: number(),
68609
+ lastSeenMs: number(),
68610
+ /** Bbox of the track's FIRST matched detection, pixel-space in the clip's
68611
+ * frame — a representative box for the diff's `(className, window, IoU)`
68612
+ * pairing (`replay-diff.ts`). A replay does not need the full per-frame
68613
+ * trajectory production's `Track.positions` keeps. */
68614
+ bbox: BoundingBoxSchema,
68615
+ /** How many of the input frames this track matched a real detection on
68616
+ * (never a coasted/extrapolated frame) — the replay's own signal for "how
68617
+ * solid is this track", cheaper than re-deriving it from a trajectory. */
68618
+ framesMatched: number().int()
68619
+ })).readonly() });
68620
+ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).readonly()), method(object({
68621
+ deviceId: number(),
68622
+ trackId: string()
68623
+ }), TrackSchema.nullable()), method(object({
68624
+ deviceId: number(),
68625
+ since: number().optional(),
68626
+ until: number().optional(),
68627
+ limit: number().optional(),
68628
+ /** Spatial filter — only tracks whose trajectory intersects the zone
68629
+ * (normalized 0..1 rect or polygon). SQL-prefiltered on the persisted
68630
+ * envelope columns, then precisely tested per position. Tracks with
68631
+ * an unknown envelope (no frame dims at persist time) always match. */
68632
+ zone: TrackZoneFilterSchema.optional(),
68633
+ /** See {@link TrackProjectionSchema}. Default `full` (backward
68634
+ * compatible — omitting the field keeps today's exact behaviour). */
68635
+ projection: TrackProjectionSchema.optional(),
68636
+ /** Include stationary-promoted rows (parked objects handed to the
68637
+ * stationary registry). Default false: the timeline lists passages,
68638
+ * not parking records (operator decision, 2026-08-15). */
68639
+ includeStationary: boolean().optional()
68640
+ }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(ListGroupsQueryInput, ListGroupsPageSchema), method(object({
68641
+ deviceId: number(),
68642
+ groupId: string().min(1)
68643
+ }), AnalyticsGroupDetailSchema.nullable()), method(object({ deviceId: number() }), _void(), {
68644
+ kind: "mutation",
68645
+ auth: "admin"
68646
+ }), 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({
68647
+ deviceId: number(),
68648
+ since: number().optional(),
68649
+ until: number().optional(),
68650
+ kinds: array(string()).optional(),
68651
+ limit: number().int().min(1).max(MAX_EVENT_QUERY_LIMIT).default(DEFAULT_EVENT_QUERY_LIMIT)
68652
+ }), array(SensorEventSchema).readonly()), method(KeyEventQueryInput, array(KeyEventSchema).readonly()), method(object({
68653
+ deviceId: number(),
68654
+ since: number(),
68655
+ until: number(),
68656
+ bucketMs: number().int().positive()
68657
+ }), array(object({
68658
+ bucketStart: number(),
68659
+ motion: number().int(),
68660
+ object: number().int(),
68661
+ audio: number().int()
68662
+ })).readonly()), method(object({
68663
+ deviceId: number(),
68664
+ cutoffMs: number()
68665
+ }), object({
68666
+ motion: number().int(),
68667
+ object: number().int(),
68668
+ audio: number().int()
68669
+ }), {
68670
+ kind: "mutation",
68671
+ auth: "admin"
68672
+ }), method(object({
68673
+ deviceId: number(),
68674
+ cutoffMs: number()
68675
+ }), TrackCascadeCountsSchema, {
68676
+ kind: "mutation",
68677
+ auth: "admin"
68678
+ }), method(object({ deviceId: number() }), TrackCascadeCountsSchema, {
68679
+ kind: "mutation",
68680
+ auth: "admin"
68681
+ }), method(object({ deviceId: number() }), DiskReconcileCountsSchema, {
68682
+ kind: "mutation",
68683
+ auth: "admin"
68684
+ }), method(object({
68685
+ deviceId: number(),
68686
+ trackIds: array(string()).min(1)
68687
+ }), object({
68688
+ deleted: number().int(),
68689
+ failed: array(string()).readonly()
68690
+ }), {
68691
+ kind: "mutation",
68692
+ auth: "admin"
68693
+ }), method(object({
68694
+ /** Log/audit scope only — the trackId is globally unique on its own. */
68695
+ deviceId: number(),
68696
+ trackId: string(),
68697
+ flags: TrackFlagsPatchSchema
68698
+ }), TrackFlagsSchema, { kind: "mutation" }), method(object({}), EventStoreFootprintSchema, {
68699
+ kind: "query",
68700
+ auth: "admin"
68701
+ }), method(object({
68702
+ olderThanMs: number(),
68703
+ reason: OpsLogReasonSchema.optional()
68704
+ }), EventPruneCountsSchema, {
68460
68705
  kind: "mutation",
68461
68706
  auth: "admin"
68462
- }), method(object({ nodeId: string() }), object({
68463
- success: literal(true),
68464
- clearedDevices: number()
68465
- }), {
68707
+ }), method(object({ deviceId: number() }), EventPruneCountsSchema, {
68466
68708
  kind: "mutation",
68467
68709
  auth: "admin"
68468
- }), method(_void(), PipelineSchemaSchema), method(_void(), array(PipelineDefaultStepSchema).readonly().nullable()), method(_void(), PipelineConfigBridge), method(_void(), ConfigUISchemaBridge), method(object({ steps: array(PipelineStepInputSchema) }), PipelineValidationResultSchema), method(_void(), array(PipelineTemplateSchema$1).readonly()), method(object({
68469
- name: string(),
68470
- steps: array(PipelineTemplateStepSchema).readonly(),
68471
- engine: PipelineEngineChoiceSchema
68472
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({
68473
- id: string(),
68474
- name: string().optional(),
68475
- steps: array(PipelineTemplateStepSchema).readonly().optional()
68476
- }), PipelineTemplateSchema$1, { kind: "mutation" }), method(object({ id: string() }), _void(), { kind: "mutation" }), method(_void(), InferenceCapabilitiesBridge), method(object({ addonId: string() }), ModelAvailabilityListBridge), method(object({
68477
- addonId: string(),
68478
- modelId: string(),
68479
- format: ModelFormatSchema$1
68480
- }), DownloadModelResultSchema, { kind: "mutation" }), method(object({
68481
- addonId: string(),
68482
- modelId: string(),
68483
- format: ModelFormatSchema$1
68484
- }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
68485
- engine: PipelineEngineChoiceSchema.optional(),
68486
- steps: array(PipelineStepInputSchema).min(1),
68487
- frame: FrameInputSchema.optional(),
68488
- /**
68489
- * Process-local lazy frame. Valid only when caller and provider resolve
68490
- * in the same execution-group process; split/cross-node callers use
68491
- * `frame`/`image` inline compatibility instead.
68492
- */
68493
- frameRef: FrameRefSchema.optional(),
68494
- /**
68495
- * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
68496
- * the decoded pixels live in. One more member of the one-of
68497
- * frame/frameHandle/image/imageBase64/referenceImage group.
68498
- */
68499
- frameHandle: FrameHandleSchema.optional(),
68500
- imageBase64: string().optional(),
68501
- /**
68502
- * Binary JPEG bytes — preferred over `imageBase64` on internal
68503
- * hops (hub → forked worker via Moleculer MsgPack) because it
68504
- * skips the 33% base64 overhead + the per-call base64 decode on
68505
- * the detection-pipeline worker. Callers can pass either; exactly
68506
- * one of `frame`/`image`/`imageBase64`/`referenceImage` is required.
68507
- */
68508
- image: _instanceof(Uint8Array).optional(),
68509
- referenceImage: string().optional(),
68510
- deviceId: number().optional(),
68511
- sessionId: string().optional(),
68512
- /**
68513
- * Execution plane. 'full' (default) runs the whole tree — benchmark,
68514
- * reference-image, and detail-subtree calls. 'frame' is the live
68515
- * per-frame dispatch: ONLY root-plane steps run; crop children
68516
- * (inputClasses ≠ null) are skipped and served per-track via
68517
- * pipelineRunner.runDetailSubtree (two-plane design).
68518
- */
68519
- plane: _enum(["full", "frame"]).optional(),
68520
- /**
68521
- * Inference-device selector (Phase 2 multi-device). Format
68522
- * `<backend>:<device>` (e.g. `openvino:gpu`, `edgetpu:usb`, `cpu`).
68523
- * Omitted ⇒ the runner's default device (current single-engine
68524
- * behaviour). Selects WHICH device pool of the node runs the call.
68525
- */
68526
- deviceKey: string().optional(),
68527
- /**
68528
- * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
68529
- * when the parent crop was resolved from the frame's retained NATIVE
68530
- * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
68531
- * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
68532
- * resolution from that surface — the SAME quality path faces already
68533
- * had — instead of the downscaled parent tile. `handle` keys the native
68534
- * surface (node-pinned to its owner); `cropFrameSpace` is the parent
68535
- * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
68536
- * the executor's crop-normalized child ROI back into frame-normalized
68537
- * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
68538
- * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
68539
- * (today's behaviour on the fallback path).
68540
- */
68541
- nativeCropRef: NativeCropRefSchema.optional()
68542
- }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
68543
- engine: PipelineEngineChoiceSchema.optional(),
68544
- steps: array(PipelineStepInputSchema).min(1),
68545
- frames: array(FrameInputSchema).min(1).max(255),
68546
- deviceId: number().optional(),
68547
- sessionId: string().optional(),
68548
- /**
68549
- * Pure-inference benchmark hint. A NONZERO uint32 pins every frame in
68550
- * the batch to the Python pool's bench preprocess cache
68551
- * (`_bench_frame_id`) so a REPEATED benchmark frame is decoded +
68552
- * preprocessed ONCE and every later inference is a pure-inference cache
68553
- * hit — the sustained-throughput run measures inference, not
68554
- * decode+preprocess+infer. Omitted/0 for live frames (all different →
68555
- * full preprocess every call, correct). Fresh per sustained run;
68556
- * released via `uncacheFrame`.
68557
- */
68558
- frameId: number().int().nonnegative().optional(),
68559
- /** Inference-device selector (Phase 2 multi-device); see runPipeline. */
68560
- deviceKey: string().optional()
68561
- }), object({ results: array(PipelineRunResultBridge).readonly() }), { kind: "mutation" }), method(object({
68562
- data: _instanceof(Uint8Array),
68563
- width: number().int().positive(),
68564
- height: number().int().positive(),
68565
- format: _enum([
68566
- "rgb",
68567
- "bgr",
68568
- "gray"
68569
- ])
68710
+ }), method(StorageMigrationLeaseInputSchema, object({ paused: literal(true) }), {
68711
+ kind: "mutation",
68712
+ auth: "admin"
68713
+ }), method(StorageMigrationLeaseInputSchema, object({ resumed: literal(true) }), {
68714
+ kind: "mutation",
68715
+ auth: "admin"
68716
+ }), method(StorageMigrationLeaseInputSchema, object({ refreshed: literal(true) }), {
68717
+ kind: "mutation",
68718
+ auth: "admin"
68719
+ }), method(StorageMigrationMediaMoveInputSchema, object({ jobId: string() }), {
68720
+ kind: "mutation",
68721
+ auth: "admin"
68722
+ }), method(object({ jobId: string() }), RelocateJobSchema.nullable(), { auth: "admin" }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
68723
+ kind: "mutation",
68724
+ auth: "admin"
68725
+ }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
68726
+ kind: "mutation",
68727
+ auth: "admin"
68728
+ }), method(object({}), array(RelocateJobSchema).readonly(), {
68729
+ kind: "query",
68730
+ auth: "admin"
68731
+ }), method(object({ jobId: string() }), object({ cancelled: boolean() }), {
68732
+ kind: "mutation",
68733
+ auth: "admin"
68734
+ }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
68735
+ kind: "query",
68736
+ auth: "admin"
68737
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
68738
+ kind: "query",
68739
+ auth: "admin"
68740
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
68741
+ kind: "query",
68742
+ auth: "admin"
68743
+ }), method(object({
68744
+ /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
68745
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
68746
+ * route it at one camera's owner, and "every camera" would stop being
68747
+ * expressible at all. */
68748
+ deviceIds: array(number()).optional(),
68749
+ limit: number().int().min(1).max(500).optional()
68750
+ }), array(RetrainTrackSchema).readonly(), {
68751
+ kind: "query",
68752
+ auth: "admin"
68753
+ }), method(object({ trackId: string() }), RetrainFrameListSchema, {
68754
+ kind: "query",
68755
+ auth: "admin"
68756
+ }), method(object({
68757
+ deviceId: number(),
68758
+ trackId: string(),
68759
+ mediaKeys: array(string()).min(1)
68760
+ }), RetrainFrameSelectionSchema, {
68761
+ kind: "mutation",
68762
+ auth: "admin"
68763
+ }), method(object({
68764
+ deviceId: number(),
68765
+ trackId: string(),
68766
+ frameId: string()
68570
68767
  }), object({
68571
- frameId: number(),
68572
- width: number(),
68573
- height: number()
68574
- }), { kind: "mutation" }), method(object({
68575
- stepId: string(),
68576
- frameId: number().int()
68577
- }), record(string(), unknown()), { kind: "mutation" }), method(object({ frameId: number().int() }), _void(), { kind: "mutation" }), method(_void(), object({
68578
- batchMode: string(),
68579
- windowMs: number(),
68580
- maxBatchSize: number(),
68581
- concurrency: number()
68582
- })), method(_void(), array(object({
68583
- engineKey: string(),
68584
- engine: PipelineEngineChoiceSchema,
68585
- modelsLoaded: array(string()).readonly(),
68586
- inUseByCameras: array(number()).readonly(),
68587
- /**
68588
- * Origin of this resident factory.
68589
- * - `runtime` — main camera-serving engine (no idle TTL).
68590
- * - `warm-override` — benchmark/test override held in the warm
68591
- * cache; auto-disposed after the idle TTL.
68592
- * - `device-pool` — a concurrent per-device pool (Phase 2
68593
- * multi-device, keyed by `deviceKey`) resolved
68594
- * via `resolveDeviceFactory`. Runs alongside the
68595
- * `runtime` engine on a DIFFERENT accelerator
68596
- * (NPU / iGPU / Coral) — this is how the
68597
- * Engines tab shows all pools running at once.
68598
- */
68599
- kind: _enum([
68600
- "runtime",
68601
- "warm-override",
68602
- "device-pool"
68603
- ]),
68604
- /** Native pid of the underlying Python pool (null when no pool). */
68605
- poolPid: number().nullable(),
68606
- /** ms since this factory was last used (null when not warm-tracked). */
68607
- idleMs: number().nullable(),
68608
- /** Idle TTL after which `warm-override` factories self-evict (null when not applicable). */
68609
- idleTtlMs: number().nullable()
68610
- })).readonly()), method(object({ engine: PipelineEngineChoiceSchema }), object({ success: literal(true) }), {
68768
+ removed: boolean(),
68769
+ removedAnnotations: number().int()
68770
+ }), {
68771
+ kind: "mutation",
68772
+ auth: "admin"
68773
+ }), method(object({ frameId: string() }), object({
68774
+ base64: string(),
68775
+ width: number().int(),
68776
+ height: number().int()
68777
+ }), {
68778
+ kind: "query",
68779
+ auth: "admin"
68780
+ }), method(object({
68781
+ deviceId: number(),
68782
+ trackId: string(),
68783
+ frameId: string(),
68784
+ subject: RetrainAssistSubjectSchema,
68785
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
68786
+ nodeId: string().optional()
68787
+ }), RetrainAssistResultSchema, {
68788
+ kind: "mutation",
68789
+ auth: "admin"
68790
+ }), method(object({
68791
+ deviceId: number(),
68792
+ source: DetectionSourceSchema,
68793
+ zones: array(ZoneSchema).readonly().optional(),
68794
+ detectionRules: array(ZoneRuleSchema).readonly().optional(),
68795
+ zoneMembershipMinOverlap: number().min(0).max(1).optional(),
68796
+ frames: array(ReplayFrameInputSchema).min(1)
68797
+ }), RunReplayFrameProcessorResultSchema, {
68798
+ kind: "mutation",
68799
+ auth: "admin"
68800
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
68801
+ kind: "query",
68802
+ auth: "admin"
68803
+ }), method(object({
68804
+ deviceId: number(),
68805
+ trackId: string(),
68806
+ frameId: string(),
68807
+ annotations: array(RetrainAnnotationDraftSchema)
68808
+ }), array(RetrainAnnotationSchema).readonly(), {
68809
+ kind: "mutation",
68810
+ auth: "admin"
68811
+ }), method(object({
68812
+ deviceId: number(),
68813
+ trackId: string()
68814
+ }), RetrainTransitionResultSchema, {
68815
+ kind: "mutation",
68816
+ auth: "admin"
68817
+ }), method(object({
68818
+ deviceId: number(),
68819
+ trackId: string()
68820
+ }), RetrainTransitionResultSchema, {
68611
68821
  kind: "mutation",
68612
68822
  auth: "admin"
68823
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
68824
+ kind: "query",
68825
+ auth: "admin"
68613
68826
  }), method(object({
68614
- engine: PipelineEngineChoiceSchema,
68615
- force: boolean().optional()
68616
- }), object({
68617
- success: boolean(),
68618
- reason: string().optional()
68619
- }), {
68827
+ eventId: string(),
68828
+ kind: MediaFileKindEnum.optional(),
68829
+ deviceId: number()
68830
+ }), array(MediaFileSchema).readonly()), method(object({
68831
+ trackId: string(),
68832
+ kinds: array(MediaFileKindEnum).optional(),
68833
+ deviceId: number()
68834
+ }), array(MediaFileSchema).readonly()), method(object({
68835
+ trackId: string(),
68836
+ deviceId: number()
68837
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
68620
68838
  kind: "mutation",
68621
68839
  auth: "admin"
68622
- }), method(_void(), array(ReferenceImageEntrySchema).readonly()), method(object({ filename: string() }), ReferenceImageBodySchema.nullable()), method(_void(), array(ReferenceAudioEntrySchema).readonly()), method(object({ filename: string() }), ReferenceAudioBodySchema.nullable()), method(_void(), AudioCapabilitiesSchema), method(object({
68623
- addonId: string(),
68624
- modelId: string(),
68625
- filename: string().optional(),
68626
- settings: record(string(), unknown()).optional()
68627
- }), AudioTestResultSchema, { kind: "mutation" }), method(_void(), ConfigUISchemaNullableBridge);
68840
+ }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
68841
+ kind: "mutation",
68842
+ auth: "admin"
68843
+ }), method(object({}), RebuildStatusSchema), object({
68844
+ deviceId: number(),
68845
+ timestamp: number(),
68846
+ frameWidth: number(),
68847
+ frameHeight: number(),
68848
+ detections: array(OverlayDetectionSchema).readonly()
68849
+ }), object({
68850
+ deviceId: number(),
68851
+ trackId: string(),
68852
+ className: string()
68853
+ }), object({
68854
+ deviceId: number(),
68855
+ trackId: string(),
68856
+ className: string(),
68857
+ durationMs: number()
68858
+ }), object({
68859
+ deviceId: number(),
68860
+ kind: EventKindSchema,
68861
+ eventId: string(),
68862
+ timestamp: number()
68863
+ });
68628
68864
  object({
68629
68865
  activeCameras: number(),
68630
68866
  throttledCameras: number(),
@@ -68650,106 +68886,6 @@ var CameraMetricsSchema = object({
68650
68886
  });
68651
68887
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
68652
68888
  /**
68653
- * Zone — pure geometry + identity. NO filtering behaviour.
68654
- *
68655
- * Zones describe **where** in the frame the operator wants to flag
68656
- * something; consumer-owned {@link ZoneRule} arrays describe **how**
68657
- * each pipeline stage uses them. Splitting the two means a single
68658
- * polygon "Driveway" can simultaneously back a motion-exclude rule,
68659
- * a detection-include rule on `['car']`, and an occupancy aggregate
68660
- * — without three duplicated polygons.
68661
- *
68662
- * Owned by the orchestrator addon (provider) and mirrored into the
68663
- * `zones` device-state slice on every mutation. Consumers
68664
- * (motion-wasm, pipeline-executor, analytics, admin UI) read either
68665
- * via `api.zones.listZones` (one-shot) or via `dev.state.zones` (live
68666
- * mirror with `onChanged`).
68667
- *
68668
- * Coordinates are normalised fractions of the frame (0–1) so zones
68669
- * survive resolution changes and stream profile switches.
68670
- *
68671
- * `kind` discriminates between full polygons (closed regions used
68672
- * for intrusion / occupancy filters) and tripwires (open 2-point
68673
- * line segments used for cross events). Onboard / firmware-reported
68674
- * zones (Reolink, ONVIF) are out of scope for now — see the deferred
68675
- * task list.
68676
- */
68677
- var ZoneKindEnum = _enum(["polygon", "tripwire"]);
68678
- /** Polygon vertex in fraction-of-frame coordinates (0–1). */
68679
- var PolygonPointSchema = object({
68680
- x: number(),
68681
- y: number()
68682
- });
68683
- /** A camera detection zone — pure geometry/identity. */
68684
- var ZoneSchema = object({
68685
- id: string(),
68686
- name: string(),
68687
- kind: ZoneKindEnum.default("polygon"),
68688
- /** Polygon vertices, fraction of frame (0–1). */
68689
- polygon: array(PolygonPointSchema).readonly(),
68690
- /** Visual color for UI rendering. */
68691
- color: string().default("#3b82f6")
68692
- });
68693
- /**
68694
- * Zones capability — per-camera CRUD over polygon detection zones.
68695
- *
68696
- * Provider lives in `addon-pipeline-orchestrator` (hub-only). Persists
68697
- * to per-device settings and mirrors into the `zones` device-state
68698
- * slice on every mutation, so downstream consumers can subscribe via
68699
- * `dev.state.zones.onChanged`.
68700
- *
68701
- * The cap surface only handles geometry + identity; filtering
68702
- * behaviour (per-class, include/exclude, threshold) lives in the
68703
- * consumer addons' rule arrays — see `ZoneRuleSchema` exported from
68704
- * `capabilities/schemas/zone-rule.js`.
68705
- */
68706
- var zonesCapability = {
68707
- name: "zones",
68708
- scope: "device",
68709
- mode: "singleton",
68710
- deviceTypes: [DeviceType.Camera],
68711
- methods: {
68712
- listZones: method(object({ deviceId: number() }), array(ZoneSchema).readonly()),
68713
- addZone: method(object({
68714
- deviceId: number(),
68715
- zone: ZoneSchema
68716
- }), _void(), {
68717
- kind: "mutation",
68718
- auth: "admin"
68719
- }),
68720
- removeZone: method(object({
68721
- deviceId: number(),
68722
- zoneId: string()
68723
- }), _void(), {
68724
- kind: "mutation",
68725
- auth: "admin"
68726
- }),
68727
- updateZone: method(object({
68728
- deviceId: number(),
68729
- zone: ZoneSchema
68730
- }), _void(), {
68731
- kind: "mutation",
68732
- auth: "admin"
68733
- })
68734
- },
68735
- /**
68736
- * Runtime-state slice — the live zone catalogue mirrored by the
68737
- * orchestrator on every CRUD mutation. Consumers read via
68738
- * `device.state.zones.value` / `.watch(...)` without round-tripping
68739
- * the cap, and the codegen DeviceProxy auto-wires the reactive
68740
- * handle. Slice shape is `{ zones: Zone[] }` so future extensions
68741
- * (e.g. zone groupings) can sit alongside the polygon list.
68742
- */
68743
- runtimeState: object({ zones: array(ZoneSchema).readonly() }),
68744
- /**
68745
- * 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.
68746
- *
68747
- * See `RuntimeStateDurability`. Enforced by
68748
- * `scripts/check-runtime-state-durability.ts`.
68749
- */
68750
- durability: "restored"
68751
- };
68752
- /**
68753
68889
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
68754
68890
  * decode worker resolves it against the RETAINED native frame's real pixel dims,
68755
68891
  * so the caller supplies only the detection-res bbox divided by the detection
@@ -78085,92 +78221,6 @@ var sceneMonitorCapability = {
78085
78221
  durability: "session"
78086
78222
  };
78087
78223
  /**
78088
- * Per-stage gating mode applied to the zones a rule references.
78089
- *
78090
- * - `include`: the rule contributes to a **whitelist** for its stage.
78091
- * When at least one `include` rule fires for a stage, only entities
78092
- * inside one of those zones pass that stage.
78093
- * - `exclude`: the rule contributes to a **blacklist** for its stage.
78094
- * Entities inside one of those zones are dropped at that stage.
78095
- *
78096
- * `monitor`-style observation (count without filtering) is not a rule
78097
- * mode — zones without any matching rule are observed naturally by
78098
- * `zone-analytics` (live snapshot + history), so an "I just want to
78099
- * count, not filter" use case needs no rule at all.
78100
- */
78101
- var ZoneRuleModeEnum = _enum(["include", "exclude"]);
78102
- /**
78103
- * Per-consumer rule that references existing zones (geometry) and
78104
- * defines how a specific pipeline stage should treat them. Each
78105
- * consumer addon owns its own `ZoneRule[]` array in its per-device
78106
- * settings:
78107
- *
78108
- * - `addon-motion-wasm` → `motionZoneRules: ZoneRule[]` (motion stage)
78109
- * - `addon-detection-pipeline` → `detectionZoneRules: ZoneRule[]` (detection stage)
78110
- * - future: notification rules, audio gating, etc.
78111
- *
78112
- * One rule applies to N zones (`zoneIds[]`) so the operator can
78113
- * express "ignore motion in ALL of {garden, street}" with a single
78114
- * rule. `classFilter` narrows the rule to specific object classes —
78115
- * "drop person detections in the street, but keep cars" is one
78116
- * `exclude` rule with `classFilter: ['person']`.
78117
- *
78118
- * `enabled` is a soft toggle — the operator can keep the rule
78119
- * configured but inert without deleting it.
78120
- */
78121
- var ZoneRuleSchema = object({
78122
- /** Stable rule id — survives edits, used by the UI for diffing. */
78123
- id: string(),
78124
- /** Optional human-readable label rendered in the rule editor. */
78125
- name: string().optional(),
78126
- /** Zones this rule targets. The rule's `mode` applies to ALL
78127
- * listed zones (OR-set: a detection in any one of them counts).
78128
- * At least one zone id required — a rule with no targets is a
78129
- * configuration mistake and the form validator rejects it. */
78130
- zoneIds: array(string()).min(1).readonly(),
78131
- mode: ZoneRuleModeEnum,
78132
- /**
78133
- * Class names this rule applies to. Empty / undefined ⇒ rule
78134
- * applies to every class. Class strings match the `macroClass`
78135
- * field on detections (e.g. `person`, `car`, `dog`).
78136
- */
78137
- classFilter: array(string()).readonly().optional(),
78138
- /**
78139
- * Minimum bbox/mask overlap (0–1) with any of the rule's zones
78140
- * required to consider an entity "in the zone". Defaults to the
78141
- * consumer's stage default when omitted. Kept for back-compat with
78142
- * existing per-rule overrides; new operators pick the value via
78143
- * `bboxInclusionPct` (operator-friendly 0–100). Whichever field is
78144
- * set, the lower-level engine reads it as a 0–1 fraction.
78145
- */
78146
- overlapThreshold: number().min(0).max(1).optional(),
78147
- /**
78148
- * Operator-friendly version of `overlapThreshold` — the percentage
78149
- * of the detection's bbox that must lie inside the zone for the
78150
- * rule to match. Documented default is 85%; the engine substitutes
78151
- * that when the field is omitted (kept optional so existing rules
78152
- * stored without it stay valid).
78153
- *
78154
- * When BOTH `overlapThreshold` and `bboxInclusionPct` are set on a
78155
- * rule, the engine prefers `bboxInclusionPct` because it's the
78156
- * field exposed in the UI. Internally both feed the same gate.
78157
- */
78158
- bboxInclusionPct: number().min(0).max(100).optional(),
78159
- /**
78160
- * When `true` and a detection has a segmentation mask, use the
78161
- * mask for overlap instead of the bbox. Detection-stage only;
78162
- * motion rules ignore this field.
78163
- */
78164
- preferMask: boolean().optional(),
78165
- /**
78166
- * Soft-toggle: `false` disables the rule without deleting it.
78167
- * Defaults to `true` so operators creating a rule via the UI
78168
- * see it active immediately.
78169
- */
78170
- enabled: boolean().default(true)
78171
- });
78172
- array(ZoneRuleSchema).readonly();
78173
- /**
78174
78224
  * Script-runner cap. Models HA `script.*` entities on
78175
78225
  * `DeviceType.Script`. A Script is a pre-recorded action sequence
78176
78226
  * that can be invoked imperatively — optionally with a variables
@@ -84107,6 +84157,12 @@ Object.freeze({
84107
84157
  addonId: null,
84108
84158
  access: "create"
84109
84159
  },
84160
+ "pipelineAnalytics.runReplayFrameProcessor": {
84161
+ capName: "pipeline-analytics",
84162
+ capScope: "device",
84163
+ addonId: null,
84164
+ access: "create"
84165
+ },
84110
84166
  "pipelineAnalytics.saveRetrainAnnotations": {
84111
84167
  capName: "pipeline-analytics",
84112
84168
  capScope: "device",
@@ -84239,6 +84295,12 @@ Object.freeze({
84239
84295
  addonId: null,
84240
84296
  access: "view"
84241
84297
  },
84298
+ "pipelineExecutor.getInferenceDeviceHealth": {
84299
+ capName: "pipeline-executor",
84300
+ capScope: "system",
84301
+ addonId: null,
84302
+ access: "view"
84303
+ },
84242
84304
  "pipelineExecutor.getOrchestratorConfigSchema": {
84243
84305
  capName: "pipeline-executor",
84244
84306
  capScope: "system",
@@ -84311,6 +84373,12 @@ Object.freeze({
84311
84373
  addonId: null,
84312
84374
  access: "view"
84313
84375
  },
84376
+ "pipelineExecutor.rearmInferenceDevice": {
84377
+ capName: "pipeline-executor",
84378
+ capScope: "system",
84379
+ addonId: null,
84380
+ access: "create"
84381
+ },
84314
84382
  "pipelineExecutor.runAudioTest": {
84315
84383
  capName: "pipeline-executor",
84316
84384
  capScope: "system",
@@ -87559,6 +87627,11 @@ Object.freeze({
87559
87627
  form: "single",
87560
87628
  optional: false
87561
87629
  }],
87630
+ "pipelineAnalytics.runReplayFrameProcessor": [{
87631
+ name: "deviceId",
87632
+ form: "single",
87633
+ optional: false
87634
+ }],
87562
87635
  "pipelineAnalytics.saveRetrainAnnotations": [{
87563
87636
  name: "deviceId",
87564
87637
  form: "single",