@camstack/addon-pipeline-orchestrator 1.2.51 → 1.2.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -13865,7 +13865,23 @@ var NotificationActionSchema = object({
13865
13865
  * else — see `notification-center/action-token.ts` for what that does and
13866
13866
  * does not buy.
13867
13867
  */
13868
- destructive: boolean().optional()
13868
+ destructive: boolean().optional(),
13869
+ /**
13870
+ * How the tap should REACH the url.
13871
+ *
13872
+ * `navigate` (absent, and every button authored before this field) opens it:
13873
+ * the phone leaves the notification and shows whatever the callback returns.
13874
+ * That is right for a button whose answer the operator wants to read.
13875
+ *
13876
+ * `background` fires it as a POST and stays put. It exists for the buttons
13877
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
13878
+ * an answer to the notification, and being thrown into a browser tab to
13879
+ * confirm it costs more attention than the notification did. A backend that
13880
+ * cannot do a background call renders it as an ordinary link (the adapters
13881
+ * fall back rather than dropping the button), so this is a preference, never
13882
+ * a requirement.
13883
+ */
13884
+ mode: _enum(["navigate", "background"]).optional()
13869
13885
  });
13870
13886
  /**
13871
13887
  * The canonical notification. `body` is the only hard field (Apprise model).
@@ -14866,6 +14882,9 @@ var NcSystemEventConditionSchema = object({
14866
14882
  nodeIds: array(string().min(1)).min(1).optional(),
14867
14883
  packageNames: array(string().min(1)).min(1).optional()
14868
14884
  });
14885
+ /** Hard ceiling on a window (24h). A snooze that could not expire would be an
14886
+ * outage the operator asked for once and forgot. */
14887
+ var NC_SNOOZE_MAX_MINUTES = 1440;
14869
14888
  /** Weekly schedule — OR of windows; absence on the rule = always active. */
14870
14889
  var NcScheduleSchema = object({
14871
14890
  windows: array(object({
@@ -15242,15 +15261,15 @@ var NcConditionsSchema = object({
15242
15261
  * (an `immediate` rule naming an `audio-*` class, one notification per
15243
15262
  * classified sample) stays exactly as it was for rules that already use it.
15244
15263
  *
15245
- * NOT in {@link NC_CONDITION_CATALOG} yet, and that is the sequencing rule
15246
- * rather than an oversight: the viewer mirrors the descriptor enums BY HAND
15247
- * (`camstack/src/data/notification-center.ts`, guarded by
15248
- * `scripts/check-viewer-condition-mirror.ts`) and its rule editor STRIPS the
15264
+ * In {@link NC_CONDITION_CATALOG} since P2, and the ORDER it got there is the
15265
+ * rule rather than an accident: the viewer mirrors the descriptor enums BY
15266
+ * HAND (`camstack/src/data/notification-center.ts`, guarded by
15267
+ * `scripts/check-viewer-condition-mirror.ts`) and its rule editor strips the
15249
15268
  * condition fields it does not know when a rule is saved from the phone.
15250
15269
  * Publishing an editor for a condition the app cannot round-trip is how an
15251
- * operator loses a rule's conditions by opening it — so the descriptor, the
15252
- * admin widget and the viewer mirror land together (P2 + P3), and only then
15253
- * does an audio rule become authorable.
15270
+ * operator loses a rule's conditions by opening it — so the viewer mirror
15271
+ * (P3, shipped) went FIRST, and the descriptor an editor renders from
15272
+ * follows here.
15254
15273
  */
15255
15274
  audio: NcAudioConditionSchema.optional()
15256
15275
  });
@@ -15486,6 +15505,30 @@ var NcRuleInputSchema = object({
15486
15505
  */
15487
15506
  snoozeAllowGlobal: boolean().optional(),
15488
15507
  /**
15508
+ * The snooze durations THIS rule's notification offers as buttons, in
15509
+ * minutes.
15510
+ *
15511
+ * Three states, and all three are distinct — which is exactly why this is
15512
+ * `.optional()` and never `.default()`. A Zod default does not run on the
15513
+ * addon cap path (three production failures in one day), so a schema default
15514
+ * would collapse the first two:
15515
+ *
15516
+ * | value | meaning |
15517
+ * | --- | --- |
15518
+ * | absent | the operator never said ⇒ {@link NC_DEFAULT_SNOOZE_MINUTES} |
15519
+ * | `[]` | **no snooze buttons on this rule** — the explicit override |
15520
+ * | a list | these choices, de-duplicated and sorted, at most four |
15521
+ *
15522
+ * `.max(4)` because the notifier's own action budget is small (ntfy allows
15523
+ * three buttons in total) and a rule that spent it all on snooze choices
15524
+ * would push its own tap-through actions off the notification.
15525
+ *
15526
+ * An empty list is NOT an alarm exemption: a rule the alarm is about, or
15527
+ * that arms the panel, is exempt automatically and cannot be silenced by a
15528
+ * window from anywhere (D133).
15529
+ */
15530
+ snoozeOptions: array(number().int().min(1).max(NC_SNOOZE_MAX_MINUTES)).max(4).optional(),
15531
+ /**
15489
15532
  * Devices this rule ACTUATES — arm the alarm, open a gate, turn on a light.
15490
15533
  *
15491
15534
  * This is what makes the rule set the alarm's trigger set without the alarm
@@ -15585,6 +15628,7 @@ var NcConditionDescriptorSchema = object({
15585
15628
  "device",
15586
15629
  "package",
15587
15630
  "occupancy",
15631
+ "audio",
15588
15632
  "system"
15589
15633
  ]),
15590
15634
  label: string(),
@@ -15603,6 +15647,7 @@ var NcConditionDescriptorSchema = object({
15603
15647
  "crossingSelect",
15604
15648
  "polygonDraw",
15605
15649
  "occupancy",
15650
+ "audio",
15606
15651
  "deviceState",
15607
15652
  "systemEvent"
15608
15653
  ]),
@@ -15754,7 +15799,20 @@ var NcSnoozeInputSchema = object({
15754
15799
  ruleId: string().optional(),
15755
15800
  /** Required when `scope: 'device'`. */
15756
15801
  deviceId: number().int().optional(),
15757
- durationMinutes: number().int().min(1).max(1440),
15802
+ /**
15803
+ * Narrow the window to these subject classes — "the cat, not the person".
15804
+ *
15805
+ * ORTHOGONAL to `scope`, deliberately, and absent means EVERY class: that is
15806
+ * what every window authored before this field meant, so no persisted row
15807
+ * changes meaning and no client has to learn anything to keep working.
15808
+ *
15809
+ * It is what makes the window's real key `(deviceId, classes[])` and lets it
15810
+ * cross rules (D133): the operator points at a camera and a kind of thing,
15811
+ * not at whichever of their four rules happened to produce the notification
15812
+ * they are dismissing.
15813
+ */
15814
+ classes: array(string().min(1)).min(1).optional(),
15815
+ durationMinutes: number().int().min(1).max(NC_SNOOZE_MAX_MINUTES),
15758
15816
  /**
15759
15817
  * Silence this for EVERY recipient, not just the caller. Permission is
15760
15818
  * checked server-side (the rule's `snoozeAllowGlobal`, or admin for the
@@ -15779,6 +15837,10 @@ var NcSnoozeSchema = object({
15779
15837
  scope: NcSnoozeScopeSchema,
15780
15838
  ruleId: string().optional(),
15781
15839
  deviceId: number().int().optional(),
15840
+ /** Subject classes this window covers. ABSENT = every class — see
15841
+ * {@link NcSnoozeInputSchema.shape.classes}. Lives in the JSON blob and has
15842
+ * no SQLite column: nothing queries a window by class. */
15843
+ classes: array(string().min(1)).min(1).optional(),
15782
15844
  startedAt: number(),
15783
15845
  /** Exclusive: at exactly this instant the snooze is over. Expiry is a
15784
15846
  * COMPARISON, not a job — no sweeper can leave the operator silenced. */
@@ -18031,7 +18093,14 @@ var zonesCapability = {
18031
18093
  * handle. Slice shape is `{ zones: Zone[] }` so future extensions
18032
18094
  * (e.g. zone groupings) can sit alongside the polygon list.
18033
18095
  */
18034
- runtimeState: object({ zones: array(ZoneSchema).readonly() })
18096
+ runtimeState: object({ zones: array(ZoneSchema).readonly() }),
18097
+ /**
18098
+ * 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.
18099
+ *
18100
+ * See `RuntimeStateDurability`. Enforced by
18101
+ * `scripts/check-runtime-state-durability.ts`.
18102
+ */
18103
+ durability: "restored"
18035
18104
  };
18036
18105
  /**
18037
18106
  * A bounding box in NORMALIZED [0,1] frame coordinates for `getNativeCrop`. The
@@ -26385,7 +26454,14 @@ var zoneRulesCapability = {
26385
26454
  motion: array(ZoneRuleSchema).readonly(),
26386
26455
  detection: array(ZoneRuleSchema).readonly(),
26387
26456
  package: array(ZoneRuleSchema).readonly()
26388
- })
26457
+ }),
26458
+ /**
26459
+ * Runtime-state durability: **restored** — operator intent, mutation-only, same argument as `zones`.
26460
+ *
26461
+ * See `RuntimeStateDurability`. Enforced by
26462
+ * `scripts/check-runtime-state-durability.ts`.
26463
+ */
26464
+ durability: "restored"
26389
26465
  };
26390
26466
  /**
26391
26467
  * Accessory device helpers — shared across drivers.
@@ -32066,6 +32142,7 @@ Object.freeze({
32066
32142
  "network-access": "ingress",
32067
32143
  "smtp-provider": "email"
32068
32144
  });
32145
+ new Map(AUDIO_MACRO_LABELS.flatMap((macro) => macro.icon === void 0 ? [] : [[macro.id, macro.icon]]));
32069
32146
  new Set(["devices", "classes"]);
32070
32147
  /**
32071
32148
  * TimelapseRule — the STANDALONE scheduled timelapse producer's rule model.
@@ -32885,7 +32962,55 @@ var OrchestratorDiagnosticsSchema = object({
32885
32962
  cameraConfigCount: number().int().min(0),
32886
32963
  activeDetectionCount: number().int().min(0)
32887
32964
  });
32888
- var pipelineOrchestratorActions = defineCustomActions({ dumpState: customAction(_void(), OrchestratorDiagnosticsSchema) });
32965
+ /**
32966
+ * The node-stress long-term-statistics read surface.
32967
+ *
32968
+ * A custom action rather than a cap method, matching how the orchestrator
32969
+ * already serves `dumpState`: this is a hub-local read over a table the hub
32970
+ * owns, and it ships with one `camstack deploy` instead of a release train.
32971
+ * The MEAN is derived here and returned alongside the addable `sum`/`samples`
32972
+ * — a chart wants the first, a re-bucketing caller wants the second, and a
32973
+ * stored mean is a field that can disagree with both.
32974
+ */
32975
+ var NodeStressStatsInputSchema = object({
32976
+ /** `node-score` | `node-queue-pressure` | `node-drop-ratio` | `node-fps-deficit`. */
32977
+ series: string().optional(),
32978
+ /** A node id. Omit for every node. */
32979
+ subject: string().optional(),
32980
+ /** Inclusive bucket-start bounds, ms. */
32981
+ from: number().int().optional(),
32982
+ to: number().int().optional(),
32983
+ limit: number().int().positive().max(5e3).optional()
32984
+ });
32985
+ var NodeStressStatsRowSchema = object({
32986
+ subject: string(),
32987
+ series: string(),
32988
+ scope: string(),
32989
+ bucketStart: number(),
32990
+ samples: number(),
32991
+ sum: number(),
32992
+ mean: number(),
32993
+ min: number(),
32994
+ max: number()
32995
+ });
32996
+ var NodeStressStatsOutputSchema = object({
32997
+ rows: array(NodeStressStatsRowSchema).readonly(),
32998
+ /** Buckets still accumulating — "is it running" answerable at once, rather
32999
+ * than after five minutes of indistinguishable silence. */
33000
+ open: array(NodeStressStatsRowSchema).readonly(),
33001
+ /** The durable failover history the anti-flap guards read, newest first.
33002
+ * Exposed for the same reason the heartbeat exists: "nothing moved" has to
33003
+ * be distinguishable from "nothing is watching". */
33004
+ moves: array(object({
33005
+ deviceId: number(),
33006
+ fromNodeId: string(),
33007
+ at: number()
33008
+ })).readonly()
33009
+ });
33010
+ var pipelineOrchestratorActions = defineCustomActions({
33011
+ dumpState: customAction(_void(), OrchestratorDiagnosticsSchema),
33012
+ nodeStressStats: customAction(NodeStressStatsInputSchema, NodeStressStatsOutputSchema, { auth: "admin" })
33013
+ });
32889
33014
  /**
32890
33015
  * Sentinel returned by `buildDetectionConfig` when the profile-slot READ
32891
33016
  * itself failed transiently (e.g. `listAllProfileSlots` discovery timeout
@@ -35605,12 +35730,341 @@ function buildRunnerConfig(base, overrides) {
35605
35730
  };
35606
35731
  }
35607
35732
  //#endregion
35608
- //#region src/device-features-mirror.ts
35733
+ //#region src/durable/durable-ledger.ts
35734
+ /** Default reseed cap — every current consumer's row set is installation-bounded. */
35735
+ var DEFAULT_LOAD_LIMIT = 1e5;
35736
+ var DurableLedger = class DurableLedger {
35737
+ mirror = /* @__PURE__ */ new Map();
35738
+ spec;
35739
+ store;
35740
+ logger;
35741
+ constructor(deps) {
35742
+ this.spec = deps.spec;
35743
+ this.store = deps.store;
35744
+ this.logger = deps.logger;
35745
+ }
35746
+ /**
35747
+ * Register the collection. MUST run at boot, before any read or write: the
35748
+ * SQLite backend answers 412 for an undeclared collection and takes the whole
35749
+ * runner down with it (the addon-ai boot-crash lesson).
35750
+ */
35751
+ static declare(store, spec) {
35752
+ return store.declareCollection.mutate({
35753
+ collection: spec.collection,
35754
+ columns: [...spec.columns],
35755
+ ...spec.indexes !== void 0 ? { indexes: [...spec.indexes] } : {}
35756
+ });
35757
+ }
35758
+ declare() {
35759
+ return DurableLedger.declare(this.store, this.spec);
35760
+ }
35761
+ /** The collection this ledger owns — for the caller's own log lines. */
35762
+ get collection() {
35763
+ return this.spec.collection;
35764
+ }
35765
+ /**
35766
+ * Boot reseed. Replaces the mirror with what the store holds and returns the
35767
+ * rows, so a caller that must hydrate something else (a watcher, a registry)
35768
+ * gets them without a second read.
35769
+ *
35770
+ * **A failure returns what is already mirrored** rather than clearing it —
35771
+ * see contract rule 2. The count is worth logging out loud at the call site:
35772
+ * "loaded 0" after a container recreate is the one line that explains a
35773
+ * silent flood.
35774
+ */
35775
+ async load() {
35776
+ try {
35777
+ const records = await this.store.query.query({
35778
+ collection: this.spec.collection,
35779
+ filter: { limit: this.spec.loadLimit ?? DEFAULT_LOAD_LIMIT }
35780
+ });
35781
+ const next = /* @__PURE__ */ new Map();
35782
+ let skipped = 0;
35783
+ for (const record of records) {
35784
+ const row = this.spec.fromRecord(record.id, record.data);
35785
+ if (row === null) {
35786
+ skipped += 1;
35787
+ continue;
35788
+ }
35789
+ next.set(this.spec.keyOf(row), row);
35790
+ }
35791
+ this.mirror.clear();
35792
+ for (const [key, row] of next) this.mirror.set(key, row);
35793
+ if (skipped > 0) this.logger.warn("durable rows skipped as malformed — they gate NOTHING", { meta: {
35794
+ collection: this.spec.collection,
35795
+ skipped
35796
+ } });
35797
+ return [...this.mirror.values()];
35798
+ } catch (err) {
35799
+ this.logger.warn("durable load failed — keeping the state already in memory", { meta: {
35800
+ collection: this.spec.collection,
35801
+ error: String(err),
35802
+ held: this.mirror.size
35803
+ } });
35804
+ return [...this.mirror.values()];
35805
+ }
35806
+ }
35807
+ /** Every mirrored row, insertion-ordered. */
35808
+ snapshot() {
35809
+ return [...this.mirror.values()];
35810
+ }
35811
+ /** The row currently held for a key, if any. Pure RAM — never I/O. */
35812
+ get(key) {
35813
+ return this.mirror.get(key);
35814
+ }
35815
+ has(key) {
35816
+ return this.mirror.has(key);
35817
+ }
35818
+ get size() {
35819
+ return this.mirror.size;
35820
+ }
35821
+ /**
35822
+ * Judge ONE observation against what the ledger already accepted, and advance
35823
+ * it.
35824
+ *
35825
+ * Synchronous on purpose: the verdict is a function of the in-RAM mirror
35826
+ * alone, so a decision can never be gated on an I/O that might fail (D49).
35827
+ * The durable write is kicked off behind it and its failure changes no
35828
+ * verdict.
35829
+ *
35830
+ * `no-flip` leaves the held row UNTOUCHED — including any timestamp it
35831
+ * carries, which therefore means "when this key last CHANGED", not "when it
35832
+ * last spoke". That is the timestamp anyone reading the table wants.
35833
+ */
35834
+ observe(row) {
35835
+ const equalFact = this.spec.equalFact;
35836
+ if (equalFact === void 0) throw new Error(`DurableLedger(${this.spec.collection}): observe() requires the spec to declare equalFact`);
35837
+ const key = this.spec.keyOf(row);
35838
+ const held = this.mirror.get(key);
35839
+ if (held !== void 0 && equalFact(held, row)) return "no-flip";
35840
+ this.mirror.set(key, row);
35841
+ this.persist(row);
35842
+ return held === void 0 ? "seeded" : "flip";
35843
+ }
35844
+ /**
35845
+ * Upsert a row without a verdict — the write path for a ledger whose owner
35846
+ * has already decided the value changed.
35847
+ *
35848
+ * The order of the mirror advance and the durable write is the spec's
35849
+ * {@link DurableWriteMode}, not the call site's: two call sites that
35850
+ * disagreed about it would be two different durability guarantees on one
35851
+ * collection.
35852
+ */
35853
+ async put(row) {
35854
+ const key = this.spec.keyOf(row);
35855
+ if (this.spec.writeMode === "write-behind") {
35856
+ this.mirror.set(key, row);
35857
+ await this.persist(row);
35858
+ return;
35859
+ }
35860
+ await this.store.set.mutate({
35861
+ collection: this.spec.collection,
35862
+ key,
35863
+ value: this.spec.toValue(row)
35864
+ });
35865
+ this.mirror.set(key, row);
35866
+ }
35867
+ /**
35868
+ * Advance the mirror WITHOUT persisting, for an owner that deliberately
35869
+ * coalesces its writes.
35870
+ *
35871
+ * The stationary registry is the reason this exists: a parked car is
35872
+ * re-confirmed on every processed frame (5–30 Hz), and persisting each
35873
+ * confirmation would offer thousands of commits a day to the checkpoint
35874
+ * lottery (D96) to maintain a handful of rows. It stages the advance and
35875
+ * flushes on its 5-minute sweep — 288 writes a day instead of ~10⁶.
35876
+ *
35877
+ * **The cost is stated, not hidden**: a staged value that is never flushed
35878
+ * is lost on a crash. An owner may only stage a field whose staleness its
35879
+ * own TTL absorbs. Anything that GATES work must go through {@link put} or
35880
+ * {@link observe}.
35881
+ */
35882
+ stage(row) {
35883
+ this.mirror.set(this.spec.keyOf(row), row);
35884
+ }
35885
+ /**
35886
+ * Drop a key from the MIRROR only — the durable row survives.
35887
+ *
35888
+ * What a scope-unbind needs: this process stops holding the value, and a
35889
+ * rebind reloads it from the store. Deliberately distinct from
35890
+ * {@link forget}, which deletes; conflating the two is how an unbind turns
35891
+ * into a wipe.
35892
+ */
35893
+ evict(key) {
35894
+ this.mirror.delete(key);
35895
+ }
35896
+ /**
35897
+ * Drop one key, mirror and row. Best-effort on the durable half: a failed
35898
+ * delete leaves a row that the next load will re-mirror, which is a stale
35899
+ * value rather than a lost one.
35900
+ */
35901
+ async forget(key) {
35902
+ this.mirror.delete(key);
35903
+ try {
35904
+ await this.store.delete.mutate({
35905
+ collection: this.spec.collection,
35906
+ key
35907
+ });
35908
+ } catch (err) {
35909
+ this.logger.debug("durable delete failed", { meta: {
35910
+ collection: this.spec.collection,
35911
+ key,
35912
+ error: String(err)
35913
+ } });
35914
+ }
35915
+ }
35916
+ /**
35917
+ * Drop every mirrored key NOT in `activeKeys`. Returns how many rows went.
35918
+ *
35919
+ * **The caller must hold an AUTHORITATIVE active set.** A prune driven by a
35920
+ * fallible read is work destroyed on an error (D49/D130) — that is why this
35921
+ * is a method a feature opts into rather than a policy the primitive runs.
35922
+ * Best-effort per row: a failed delete keeps the key (retried next prune)
35923
+ * rather than aborting the sweep.
35924
+ */
35925
+ async pruneExcept(activeKeys) {
35926
+ let pruned = 0;
35927
+ for (const key of [...this.mirror.keys()]) {
35928
+ if (activeKeys.has(key)) continue;
35929
+ try {
35930
+ await this.store.delete.mutate({
35931
+ collection: this.spec.collection,
35932
+ key
35933
+ });
35934
+ this.mirror.delete(key);
35935
+ pruned += 1;
35936
+ } catch (err) {
35937
+ this.logger.debug("durable prune delete failed", { meta: {
35938
+ collection: this.spec.collection,
35939
+ key,
35940
+ error: String(err)
35941
+ } });
35942
+ }
35943
+ }
35944
+ return pruned;
35945
+ }
35946
+ /**
35947
+ * Write-behind durable upsert. Best-effort and logged, never thrown at the
35948
+ * decision path: the mirror already holds the truth for this process, and the
35949
+ * worst a lost write can do is one silent re-seed after the next restart.
35950
+ */
35951
+ async persist(row) {
35952
+ const deviceId = this.spec.deviceIdOf?.(row);
35953
+ try {
35954
+ await this.store.set.mutate({
35955
+ collection: this.spec.collection,
35956
+ key: this.spec.keyOf(row),
35957
+ value: this.spec.toValue(row)
35958
+ });
35959
+ } catch (err) {
35960
+ this.logger.warn("durable persist failed — this key may re-seed on boot", {
35961
+ ...deviceId !== void 0 ? { tags: { deviceId } } : {},
35962
+ meta: {
35963
+ collection: this.spec.collection,
35964
+ key: this.spec.keyOf(row),
35965
+ error: String(err)
35966
+ }
35967
+ });
35968
+ }
35969
+ }
35970
+ };
35971
+ var DEVICE_FEATURES_SPEC = {
35972
+ collection: "pipeline-orchestrator:device-features",
35973
+ columns: [
35974
+ {
35975
+ name: "deviceId",
35976
+ type: "TEXT",
35977
+ primaryKey: true,
35978
+ notNull: true
35979
+ },
35980
+ (
35981
+ /** The feature name list, verbatim. */
35982
+ {
35983
+ name: "features",
35984
+ type: "JSON",
35985
+ notNull: true
35986
+ }),
35987
+ {
35988
+ name: "updatedAt",
35989
+ type: "INTEGER",
35990
+ notNull: true
35991
+ }
35992
+ ],
35993
+ writeMode: "write-behind",
35994
+ keyOf: (row) => String(row.deviceId),
35995
+ toValue: (row) => ({
35996
+ features: [...row.features],
35997
+ updatedAt: row.updatedAt
35998
+ }),
35999
+ fromRecord: (key, data) => {
36000
+ const deviceId = Number(key);
36001
+ const raw = data["features"];
36002
+ if (!Number.isFinite(deviceId) || !Array.isArray(raw)) return null;
36003
+ const features = raw.filter((f) => typeof f === "string");
36004
+ if (features.length === 0) return null;
36005
+ const updatedAt = Number(data["updatedAt"]);
36006
+ return {
36007
+ deviceId,
36008
+ features,
36009
+ updatedAt: Number.isFinite(updatedAt) ? updatedAt : 0,
36010
+ restored: true
36011
+ };
36012
+ },
36013
+ deviceIdOf: (row) => row.deviceId
36014
+ };
35609
36015
  var DeviceFeaturesMirror = class {
36016
+ /** Process-local fallback, used only when no store was supplied. */
36017
+ local = /* @__PURE__ */ new Map();
36018
+ durable;
35610
36019
  logger;
35611
- lastKnown = /* @__PURE__ */ new Map();
35612
- constructor(logger) {
35613
- this.logger = logger;
36020
+ now;
36021
+ constructor(deps) {
36022
+ this.logger = deps.logger;
36023
+ this.now = deps.now ?? (() => Date.now());
36024
+ this.durable = deps.store === void 0 ? null : new DurableLedger({
36025
+ spec: DEVICE_FEATURES_SPEC,
36026
+ store: deps.store,
36027
+ logger: deps.logger
36028
+ });
36029
+ }
36030
+ static declare(store) {
36031
+ return DurableLedger.declare(store, DEVICE_FEATURES_SPEC);
36032
+ }
36033
+ /**
36034
+ * Seed the mirror from the last session. Call once at boot, after `declare`
36035
+ * and BEFORE the first `resolve` — the whole value of the row is that it is
36036
+ * already there when the first read fails.
36037
+ */
36038
+ async hydrate() {
36039
+ if (this.durable === null) return 0;
36040
+ const rows = await this.durable.load();
36041
+ this.logger.info("device-features mirror restored", { meta: { devices: rows.length } });
36042
+ return rows.length;
36043
+ }
36044
+ held(deviceId) {
36045
+ return this.durable === null ? this.local.get(deviceId) : this.durable.get(String(deviceId));
36046
+ }
36047
+ remember(deviceId, features) {
36048
+ const row = {
36049
+ deviceId,
36050
+ features: [...features],
36051
+ updatedAt: this.now(),
36052
+ restored: false
36053
+ };
36054
+ if (this.durable === null) {
36055
+ this.local.set(deviceId, row);
36056
+ return;
36057
+ }
36058
+ const held = this.durable.get(String(deviceId));
36059
+ if (held !== void 0 && !held.restored && sameFeatures(held.features, features)) return;
36060
+ this.durable.put(row);
36061
+ }
36062
+ drop(deviceId) {
36063
+ if (this.durable === null) {
36064
+ this.local.delete(deviceId);
36065
+ return;
36066
+ }
36067
+ this.durable.forget(String(deviceId));
35614
36068
  }
35615
36069
  /**
35616
36070
  * Resolve a device's features, preferring a fresh read but never letting a
@@ -35619,15 +36073,19 @@ var DeviceFeaturesMirror = class {
35619
36073
  async resolve(deviceId, read) {
35620
36074
  const first = await read();
35621
36075
  if (first !== null && first.length > 0) {
35622
- this.lastKnown.set(deviceId, [...first]);
36076
+ this.remember(deviceId, first);
35623
36077
  return first;
35624
36078
  }
35625
- const mirrored = this.lastKnown.get(deviceId);
36079
+ const heldRow = this.held(deviceId);
36080
+ const mirrored = heldRow?.features;
35626
36081
  if (first === null) {
35627
36082
  if (mirrored !== void 0) {
35628
36083
  this.logger.warn("device features unavailable — serving last-known mirror", {
35629
36084
  tags: { deviceId },
35630
- meta: { mirrored: mirrored.length }
36085
+ meta: {
36086
+ mirrored: mirrored.length,
36087
+ restored: heldRow?.restored === true
36088
+ }
35631
36089
  });
35632
36090
  return mirrored;
35633
36091
  }
@@ -35641,7 +36099,7 @@ var DeviceFeaturesMirror = class {
35641
36099
  tags: { deviceId },
35642
36100
  meta: { features: second.length }
35643
36101
  });
35644
- this.lastKnown.set(deviceId, [...second]);
36102
+ this.remember(deviceId, second);
35645
36103
  return second;
35646
36104
  }
35647
36105
  if (second === null) {
@@ -35652,14 +36110,20 @@ var DeviceFeaturesMirror = class {
35652
36110
  tags: { deviceId },
35653
36111
  meta: { previously: mirrored.length }
35654
36112
  });
35655
- this.lastKnown.delete(deviceId);
36113
+ this.drop(deviceId);
35656
36114
  return [];
35657
36115
  }
35658
36116
  /** Drop a device's mirror — call when the device is removed. */
35659
36117
  forget(deviceId) {
35660
- this.lastKnown.delete(deviceId);
36118
+ this.drop(deviceId);
35661
36119
  }
35662
36120
  };
36121
+ /** Order-insensitive feature-set equality — the read's order is not a fact. */
36122
+ function sameFeatures(a, b) {
36123
+ if (a.length !== b.length) return false;
36124
+ const held = new Set(a);
36125
+ return b.every((f) => held.has(f));
36126
+ }
35663
36127
  //#endregion
35664
36128
  //#region src/watchdog-camera.ts
35665
36129
  /**
@@ -35726,7 +36190,20 @@ var DetectionWiringController = class {
35726
36190
  featuresMirror;
35727
36191
  constructor(deps) {
35728
36192
  this.deps = deps;
35729
- this.featuresMirror = new DeviceFeaturesMirror(deps.logger);
36193
+ this.featuresMirror = new DeviceFeaturesMirror({
36194
+ logger: deps.logger,
36195
+ ...deps.featuresStore !== void 0 ? { store: deps.featuresStore } : {}
36196
+ });
36197
+ }
36198
+ /**
36199
+ * Declare + seed the device-features mirror. Call once at boot, BEFORE the
36200
+ * first detection start — the restored row is worth nothing after the read
36201
+ * that would have needed it.
36202
+ */
36203
+ async hydrateFeaturesMirror() {
36204
+ if (this.deps.featuresStore === void 0) return;
36205
+ await DeviceFeaturesMirror.declare(this.deps.featuresStore);
36206
+ await this.featuresMirror.hydrate();
35730
36207
  }
35731
36208
  /** `activeDetections.get(deviceId)`. */
35732
36209
  getActiveDetectionConfig(deviceId) {
@@ -36937,7 +37414,6 @@ var NodeStressController = class NodeStressController {
36937
37414
  static HEARTBEAT_MS = 60 * 6e4;
36938
37415
  samples = /* @__PURE__ */ new Map();
36939
37416
  memories = /* @__PURE__ */ new Map();
36940
- history = [];
36941
37417
  /** When the last heartbeat went out. `null` ⇒ the next sweep emits one. */
36942
37418
  lastHeartbeatAt = null;
36943
37419
  timer = null;
@@ -36981,6 +37457,18 @@ var NodeStressController = class NodeStressController {
36981
37457
  forgetDevice(deviceId) {
36982
37458
  this.samples.delete(deviceId);
36983
37459
  }
37460
+ /**
37461
+ * Recover the move history from disk BEFORE the first sweep can act.
37462
+ *
37463
+ * Best-effort by construction (the ledger keeps whatever it already has on a
37464
+ * read failure), and the count is logged out loud: a restart that recovers 0
37465
+ * moves while the operator remembers three is the line that says the budget
37466
+ * has been reset.
37467
+ */
37468
+ async hydrate() {
37469
+ const recovered = await this.deps.moves.load();
37470
+ this.deps.logger.info("node-stress move history recovered", { meta: { moves: recovered } });
37471
+ }
36984
37472
  start() {
36985
37473
  if (this.timer) return;
36986
37474
  this.timer = setInterval(() => {
@@ -36996,12 +37484,24 @@ var NodeStressController = class NodeStressController {
36996
37484
  }
36997
37485
  this.samples.clear();
36998
37486
  this.memories.clear();
36999
- this.history = [];
37000
37487
  }
37001
37488
  /** The last computed state per node — empty before the first sweep. */
37002
37489
  statesView() {
37003
37490
  return new Map([...this.memories].map(([nodeId, m]) => [nodeId, m.state]));
37004
37491
  }
37492
+ /** The durable move history, newest first — the guards' own evidence, so an
37493
+ * operator asking "why did nothing move" can read the budget. */
37494
+ historyView() {
37495
+ return this.deps.moves.entries().toSorted((a, b) => b.at - a.at);
37496
+ }
37497
+ /**
37498
+ * The per-node stress signals as of `now`, for the LTS aggregator and for
37499
+ * diagnostics. Computed from the same live samples the sweep uses, so a
37500
+ * chart can never disagree with a verdict.
37501
+ */
37502
+ signalsView(now) {
37503
+ return new Map(this.buildInputs(now).map((input) => [input.nodeId, input.signals]));
37504
+ }
37005
37505
  /** Group live samples by node and reduce each group. Exposed for tests. */
37006
37506
  buildInputs(now) {
37007
37507
  const byNode = /* @__PURE__ */ new Map();
@@ -37032,6 +37532,7 @@ var NodeStressController = class NodeStressController {
37032
37532
  const verdicts = evaluateNodeStress(this.memories, this.buildInputs(now), now, this.thresholds());
37033
37533
  for (const v of verdicts) {
37034
37534
  this.memories.set(v.nodeId, v.memory);
37535
+ this.deps.lts?.noteSignals(v.nodeId, v.signals, now);
37035
37536
  if (v.changed) this.logTransition(v);
37036
37537
  }
37037
37538
  this.maybeHeartbeat(mode, verdicts, now);
@@ -37090,11 +37591,12 @@ var NodeStressController = class NodeStressController {
37090
37591
  async actOn(verdicts, now) {
37091
37592
  if (this.moveInFlight) return;
37092
37593
  if (!verdicts.some((v) => v.state === "saturated")) return;
37093
- this.history = this.history.filter((h) => now - h.at < NodeStressController.HISTORY_TTL_MS);
37594
+ this.deps.moves.pruneOlderThan(now - NodeStressController.HISTORY_TTL_MS);
37595
+ const history = this.deps.moves.entries().filter((h) => now - h.at < NodeStressController.HISTORY_TTL_MS);
37094
37596
  const plan = planStressFailover({
37095
37597
  verdicts,
37096
37598
  candidates: await this.collectCandidates(now),
37097
- history: this.history,
37599
+ history,
37098
37600
  nodeCaps: await this.deps.settingsStore.buildNodeCaps(),
37099
37601
  attachedByNode: this.attachedByNode()
37100
37602
  }, now, this.guards());
@@ -37118,7 +37620,7 @@ var NodeStressController = class NodeStressController {
37118
37620
  await this.deps.detach(plan.fromNodeId, plan.deviceId);
37119
37621
  await this.deps.attach(plan.toNodeId, config);
37120
37622
  this.deps.ledger.recordAssignment(plan.deviceId, plan.toNodeId, "rebalance", false);
37121
- this.history.push({
37623
+ this.deps.moves.record({
37122
37624
  deviceId: plan.deviceId,
37123
37625
  fromNodeId: plan.fromNodeId,
37124
37626
  at: now
@@ -37190,6 +37692,513 @@ var NodeStressController = class NodeStressController {
37190
37692
  }
37191
37693
  };
37192
37694
  //#endregion
37695
+ //#region src/durable/lts-aggregator.ts
37696
+ /** Wall-clock bucket width. Five minutes, matching HA's statistics tier. */
37697
+ var LTS_BUCKET_MS = 5 * 6e4;
37698
+ /** How often the row cap is enforced. Rarely: it is a bound, not a deadline. */
37699
+ var CAP_SWEEP_INTERVAL_MS = 6 * 36e5;
37700
+ var LTS_COLUMNS = [
37701
+ (
37702
+ /** `<subject>|<series>|<scope>|<bucketStart>` — deterministic, so a bucket
37703
+ * flushed twice replaces itself rather than doubling. */
37704
+ {
37705
+ name: "id",
37706
+ type: "TEXT",
37707
+ primaryKey: true,
37708
+ notNull: true
37709
+ }),
37710
+ (
37711
+ /** The camera id, or the node id. One column, because every query is
37712
+ * "this thing over time" and the thing is one or the other. */
37713
+ {
37714
+ name: "subject",
37715
+ type: "TEXT",
37716
+ notNull: true
37717
+ }),
37718
+ (
37719
+ /** Numeric mirror of `subject` for camera rows, so a per-camera question is
37720
+ * answered by an integer index — every log line and every query about a
37721
+ * device in this repo is keyed by the numeric id. `NULL` for node rows. */
37722
+ {
37723
+ name: "deviceId",
37724
+ type: "INTEGER"
37725
+ }),
37726
+ {
37727
+ name: "series",
37728
+ type: "TEXT",
37729
+ notNull: true
37730
+ },
37731
+ (
37732
+ /** Sub-scope within a series: a zoneId for occupancy, `''` otherwise. */
37733
+ {
37734
+ name: "scope",
37735
+ type: "TEXT",
37736
+ notNull: true
37737
+ }),
37738
+ (
37739
+ /** Bucket start, wall-clock aligned to {@link LTS_BUCKET_MS}. */
37740
+ {
37741
+ name: "bucketStart",
37742
+ type: "INTEGER",
37743
+ notNull: true
37744
+ }),
37745
+ {
37746
+ name: "samples",
37747
+ type: "INTEGER",
37748
+ notNull: true
37749
+ },
37750
+ {
37751
+ name: "sum",
37752
+ type: "REAL",
37753
+ notNull: true
37754
+ },
37755
+ {
37756
+ name: "min",
37757
+ type: "REAL",
37758
+ notNull: true
37759
+ },
37760
+ {
37761
+ name: "max",
37762
+ type: "REAL",
37763
+ notNull: true
37764
+ }
37765
+ ];
37766
+ var LTS_INDEXES = [{
37767
+ name: "idx_lts_series_bucket",
37768
+ columns: ["series", "bucketStart"]
37769
+ }, {
37770
+ name: "idx_lts_device",
37771
+ columns: ["deviceId"]
37772
+ }];
37773
+ function ltsBucketStart(at, bucketMs = LTS_BUCKET_MS) {
37774
+ return Math.floor(at / bucketMs) * bucketMs;
37775
+ }
37776
+ var LtsAggregator = class {
37777
+ open = /* @__PURE__ */ new Map();
37778
+ /** Every (subject, series, scope) that has produced a row in this process —
37779
+ * the groups the cap sweep has any reason to look at. */
37780
+ groups = /* @__PURE__ */ new Set();
37781
+ lastCapSweepAt = 0;
37782
+ collection;
37783
+ store;
37784
+ logger;
37785
+ nowFn;
37786
+ bucketMs;
37787
+ maxRows;
37788
+ constructor(deps) {
37789
+ this.collection = deps.collection;
37790
+ this.store = deps.store;
37791
+ this.logger = deps.logger;
37792
+ this.nowFn = deps.now ?? (() => Date.now());
37793
+ this.bucketMs = deps.bucketMs ?? 3e5;
37794
+ this.maxRows = deps.maxRowsPerSeries ?? 105120;
37795
+ }
37796
+ static declare(store, collection) {
37797
+ return store.declareCollection.mutate({
37798
+ collection,
37799
+ columns: [...LTS_COLUMNS],
37800
+ indexes: [...LTS_INDEXES]
37801
+ });
37802
+ }
37803
+ /**
37804
+ * Record one observation. Synchronous, allocation-free after the first
37805
+ * sample of a bucket, and it cannot throw — it sits on paths that are
37806
+ * already producing the value for another reason and must not learn a new
37807
+ * failure mode.
37808
+ *
37809
+ * A non-finite value is DROPPED rather than folded in: one `NaN` would make
37810
+ * `sum`, `min` and `max` all `NaN` for the whole bucket, turning a skewed
37811
+ * row into a meaningless one.
37812
+ */
37813
+ note(input) {
37814
+ if (!Number.isFinite(input.value)) return;
37815
+ const at = input.at ?? this.nowFn();
37816
+ const scope = input.scope ?? "";
37817
+ const bucketStart = ltsBucketStart(at, this.bucketMs);
37818
+ const key = rowId(input.subject, input.series, scope, bucketStart);
37819
+ const held = this.open.get(key);
37820
+ if (held === void 0) {
37821
+ this.open.set(key, {
37822
+ subject: input.subject,
37823
+ ...input.deviceId !== void 0 ? { deviceId: input.deviceId } : {},
37824
+ series: input.series,
37825
+ scope,
37826
+ bucketStart,
37827
+ samples: 1,
37828
+ sum: input.value,
37829
+ min: input.value,
37830
+ max: input.value
37831
+ });
37832
+ return;
37833
+ }
37834
+ held.samples += 1;
37835
+ held.sum += input.value;
37836
+ if (input.value < held.min) held.min = input.value;
37837
+ if (input.value > held.max) held.max = input.value;
37838
+ }
37839
+ /** Buckets currently accumulating — diagnostics, and what a flush would write. */
37840
+ openBuckets() {
37841
+ return [...this.open.values()].map(toRow);
37842
+ }
37843
+ /**
37844
+ * Write every bucket that has CLOSED (its window ended at or before `now`)
37845
+ * and drop it from RAM. Returns the number of rows written.
37846
+ *
37847
+ * The current bucket is deliberately left alone: writing it early would mean
37848
+ * rewriting it on the next tick, which turns one row into up to sixty and
37849
+ * offers every one of them to the checkpoint lottery (D96).
37850
+ */
37851
+ async flushDue(now = this.nowFn()) {
37852
+ const currentBucket = ltsBucketStart(now, this.bucketMs);
37853
+ const due = [...this.open.values()].filter((b) => b.bucketStart < currentBucket);
37854
+ if (due.length === 0) {
37855
+ await this.maybeSweepCap(now);
37856
+ return 0;
37857
+ }
37858
+ let written = 0;
37859
+ for (const bucket of due) {
37860
+ const key = rowId(bucket.subject, bucket.series, bucket.scope, bucket.bucketStart);
37861
+ try {
37862
+ await this.store.set.mutate({
37863
+ collection: this.collection,
37864
+ key,
37865
+ value: {
37866
+ subject: bucket.subject,
37867
+ ...bucket.deviceId !== void 0 ? { deviceId: bucket.deviceId } : {},
37868
+ series: bucket.series,
37869
+ scope: bucket.scope,
37870
+ bucketStart: bucket.bucketStart,
37871
+ samples: bucket.samples,
37872
+ sum: bucket.sum,
37873
+ min: bucket.min,
37874
+ max: bucket.max
37875
+ }
37876
+ });
37877
+ written += 1;
37878
+ this.groups.add(groupKey(bucket.subject, bucket.series, bucket.scope));
37879
+ } catch (err) {
37880
+ this.logger.warn("lts bucket write failed — this interval will be missing", {
37881
+ ...bucket.deviceId !== void 0 ? { tags: { deviceId: bucket.deviceId } } : {},
37882
+ meta: {
37883
+ collection: this.collection,
37884
+ series: bucket.series,
37885
+ subject: bucket.subject,
37886
+ bucketStart: bucket.bucketStart,
37887
+ error: String(err)
37888
+ }
37889
+ });
37890
+ }
37891
+ this.open.delete(key);
37892
+ }
37893
+ await this.maybeSweepCap(now);
37894
+ return written;
37895
+ }
37896
+ /** Read closed buckets back. The read surface every chart will use. */
37897
+ async read(query = {}) {
37898
+ const where = {};
37899
+ if (query.series !== void 0) where["series"] = query.series;
37900
+ if (query.subject !== void 0) where["subject"] = query.subject;
37901
+ if (query.scope !== void 0) where["scope"] = query.scope;
37902
+ const records = await this.store.query.query({
37903
+ collection: this.collection,
37904
+ filter: {
37905
+ ...Object.keys(where).length > 0 ? { where } : {},
37906
+ ...query.from !== void 0 || query.to !== void 0 ? { whereBetween: { bucketStart: [query.from ?? 0, query.to ?? Number.MAX_SAFE_INTEGER] } } : {},
37907
+ orderBy: {
37908
+ field: "bucketStart",
37909
+ direction: "asc"
37910
+ },
37911
+ limit: query.limit ?? 5e3
37912
+ }
37913
+ });
37914
+ const rows = [];
37915
+ for (const record of records) {
37916
+ const row = recordToRow(record.data);
37917
+ if (row !== null) rows.push(row);
37918
+ }
37919
+ return rows;
37920
+ }
37921
+ /**
37922
+ * Enforce the per-(subject, series, scope) row cap, at most once every six
37923
+ * hours. Only groups this process has written to are examined: a group with
37924
+ * no new rows cannot have crossed a cap it was under.
37925
+ */
37926
+ async maybeSweepCap(now) {
37927
+ if (now - this.lastCapSweepAt < CAP_SWEEP_INTERVAL_MS) return;
37928
+ this.lastCapSweepAt = now;
37929
+ for (const group of this.groups) {
37930
+ const [subject, series, scope] = group.split("\0");
37931
+ if (subject === void 0 || series === void 0 || scope === void 0) continue;
37932
+ const where = {
37933
+ subject,
37934
+ series,
37935
+ scope
37936
+ };
37937
+ try {
37938
+ const excess = await this.store.count.query({
37939
+ collection: this.collection,
37940
+ filter: { where }
37941
+ }) - this.maxRows;
37942
+ if (excess <= 0) continue;
37943
+ const cutoff = (await this.store.query.query({
37944
+ collection: this.collection,
37945
+ filter: {
37946
+ where,
37947
+ orderBy: {
37948
+ field: "bucketStart",
37949
+ direction: "asc"
37950
+ },
37951
+ limit: excess
37952
+ }
37953
+ })).at(-1)?.data["bucketStart"];
37954
+ if (typeof cutoff !== "number") continue;
37955
+ const { deleted } = await this.store.deleteWhere.mutate({
37956
+ collection: this.collection,
37957
+ filter: {
37958
+ where,
37959
+ whereBetween: { bucketStart: [0, cutoff] }
37960
+ }
37961
+ });
37962
+ this.logger.info("lts row cap enforced", { meta: {
37963
+ collection: this.collection,
37964
+ series,
37965
+ subject,
37966
+ deleted,
37967
+ cap: this.maxRows
37968
+ } });
37969
+ } catch (err) {
37970
+ this.logger.warn("lts row cap sweep failed — the series keeps growing this cycle", { meta: {
37971
+ collection: this.collection,
37972
+ series,
37973
+ subject,
37974
+ error: String(err)
37975
+ } });
37976
+ }
37977
+ }
37978
+ }
37979
+ };
37980
+ function groupKey(subject, series, scope) {
37981
+ return `${subject}${series}${scope}`;
37982
+ }
37983
+ function rowId(subject, series, scope, bucketStart) {
37984
+ return `${subject}|${series}|${scope}|${bucketStart}`;
37985
+ }
37986
+ function toRow(bucket) {
37987
+ return {
37988
+ subject: bucket.subject,
37989
+ ...bucket.deviceId !== void 0 ? { deviceId: bucket.deviceId } : {},
37990
+ series: bucket.series,
37991
+ scope: bucket.scope,
37992
+ bucketStart: bucket.bucketStart,
37993
+ samples: bucket.samples,
37994
+ sum: bucket.sum,
37995
+ min: bucket.min,
37996
+ max: bucket.max
37997
+ };
37998
+ }
37999
+ /** Structural validation on read. A malformed row is skipped, never charted. */
38000
+ function recordToRow(data) {
38001
+ const subject = data["subject"];
38002
+ const series = data["series"];
38003
+ const scope = data["scope"];
38004
+ if (typeof subject !== "string" || typeof series !== "string") return null;
38005
+ const bucketStart = Number(data["bucketStart"]);
38006
+ const samples = Number(data["samples"]);
38007
+ const sum = Number(data["sum"]);
38008
+ const min = Number(data["min"]);
38009
+ const max = Number(data["max"]);
38010
+ if (![
38011
+ bucketStart,
38012
+ samples,
38013
+ sum,
38014
+ min,
38015
+ max
38016
+ ].every((n) => Number.isFinite(n))) return null;
38017
+ const rawDeviceId = data["deviceId"];
38018
+ const deviceId = typeof rawDeviceId === "number" && Number.isFinite(rawDeviceId) ? rawDeviceId : void 0;
38019
+ return {
38020
+ subject,
38021
+ ...deviceId !== void 0 ? { deviceId } : {},
38022
+ series,
38023
+ scope: typeof scope === "string" ? scope : "",
38024
+ bucketStart,
38025
+ samples,
38026
+ sum,
38027
+ min,
38028
+ max
38029
+ };
38030
+ }
38031
+ //#endregion
38032
+ //#region src/node-stress-lts.ts
38033
+ /**
38034
+ * @durable class=ledger owner=pipeline-orchestrator
38035
+ * write="one row per (node, series, 5-min bucket), written ONCE when the bucket closes; a node reporting no samples writes nothing"
38036
+ * retention="row CAP per (subject, series, scope) — 105,120 rows ≈ one year of 5-minute buckets. Not an age sweep: an LTS row summarises an interval and has no owner to be orphaned from."
38037
+ */
38038
+ var NODE_STRESS_LTS_COLLECTION = "pipeline-orchestrator:stats-5m";
38039
+ var NodeStressLts = class {
38040
+ lts;
38041
+ constructor(deps) {
38042
+ this.lts = new LtsAggregator({
38043
+ collection: NODE_STRESS_LTS_COLLECTION,
38044
+ store: deps.store,
38045
+ logger: deps.logger,
38046
+ ...deps.now !== void 0 ? { now: deps.now } : {}
38047
+ });
38048
+ }
38049
+ static declare(store) {
38050
+ return LtsAggregator.declare(store, NODE_STRESS_LTS_COLLECTION);
38051
+ }
38052
+ /** Fold one sweep's verdict for one node into the open buckets. */
38053
+ noteSignals(nodeId, signals, at) {
38054
+ this.lts.note({
38055
+ subject: nodeId,
38056
+ series: "node-score",
38057
+ value: signals.score,
38058
+ at
38059
+ });
38060
+ this.lts.note({
38061
+ subject: nodeId,
38062
+ series: "node-queue-pressure",
38063
+ value: signals.queuePressure,
38064
+ at
38065
+ });
38066
+ this.lts.note({
38067
+ subject: nodeId,
38068
+ series: "node-drop-ratio",
38069
+ value: signals.dropRatio,
38070
+ at
38071
+ });
38072
+ this.lts.note({
38073
+ subject: nodeId,
38074
+ series: "node-fps-deficit",
38075
+ value: signals.fpsDeficit,
38076
+ at
38077
+ });
38078
+ }
38079
+ flushDue(now) {
38080
+ return this.lts.flushDue(now);
38081
+ }
38082
+ read(query) {
38083
+ return this.lts.read(query);
38084
+ }
38085
+ openBuckets() {
38086
+ return this.lts.openBuckets();
38087
+ }
38088
+ };
38089
+ //#endregion
38090
+ //#region src/node-stress-move-ledger.ts
38091
+ /**
38092
+ * @durable class=ledger owner=pipeline-orchestrator
38093
+ * write="one row per APPLIED failover move (never per attempt); write-behind"
38094
+ * retention="pruned by the sweep once older than the longest guard window (2 h) — a move no guard can read is growth with no reader"
38095
+ */
38096
+ var NODE_STRESS_MOVES_COLLECTION = "pipeline-orchestrator:node-stress-moves";
38097
+ var NODE_STRESS_MOVES_COLUMNS = [
38098
+ (
38099
+ /** `<deviceId>:<at>` — one camera can be moved more than once, and each move
38100
+ * spends its own slice of the budget. */
38101
+ {
38102
+ name: "id",
38103
+ type: "TEXT",
38104
+ primaryKey: true,
38105
+ notNull: true
38106
+ }),
38107
+ (
38108
+ /** Indexed: every question about a move is asked per-camera. */
38109
+ {
38110
+ name: "deviceId",
38111
+ type: "INTEGER",
38112
+ notNull: true
38113
+ }),
38114
+ (
38115
+ /** The node the camera LEFT — the return ban is about coming back here. */
38116
+ {
38117
+ name: "fromNodeId",
38118
+ type: "TEXT",
38119
+ notNull: true
38120
+ }),
38121
+ {
38122
+ name: "at",
38123
+ type: "INTEGER",
38124
+ notNull: true
38125
+ }
38126
+ ];
38127
+ var NODE_STRESS_MOVES_INDEXES = [{
38128
+ name: "idx_node_stress_moves_device",
38129
+ columns: ["deviceId"]
38130
+ }];
38131
+ function moveId(entry) {
38132
+ return `${entry.deviceId}:${entry.at}`;
38133
+ }
38134
+ var NODE_STRESS_MOVES_SPEC = {
38135
+ collection: NODE_STRESS_MOVES_COLLECTION,
38136
+ columns: NODE_STRESS_MOVES_COLUMNS,
38137
+ indexes: NODE_STRESS_MOVES_INDEXES,
38138
+ writeMode: "write-behind",
38139
+ keyOf: (row) => row.id,
38140
+ toValue: (row) => ({
38141
+ deviceId: row.deviceId,
38142
+ fromNodeId: row.fromNodeId,
38143
+ at: row.at
38144
+ }),
38145
+ fromRecord: (id, data) => {
38146
+ const deviceId = Number(data["deviceId"]);
38147
+ const at = Number(data["at"]);
38148
+ const fromNodeId = data["fromNodeId"];
38149
+ if (!Number.isFinite(deviceId) || !Number.isFinite(at)) return null;
38150
+ if (typeof fromNodeId !== "string" || fromNodeId.length === 0) return null;
38151
+ return {
38152
+ id,
38153
+ deviceId,
38154
+ fromNodeId,
38155
+ at
38156
+ };
38157
+ },
38158
+ deviceIdOf: (row) => row.deviceId,
38159
+ loadLimit: 1e4
38160
+ };
38161
+ var NodeStressMoveLedger = class {
38162
+ ledger;
38163
+ constructor(deps) {
38164
+ this.ledger = new DurableLedger({
38165
+ spec: NODE_STRESS_MOVES_SPEC,
38166
+ store: deps.store,
38167
+ logger: deps.logger
38168
+ });
38169
+ }
38170
+ static declare(store) {
38171
+ return DurableLedger.declare(store, NODE_STRESS_MOVES_SPEC);
38172
+ }
38173
+ /** Boot reseed. Returns the row count so the caller can say out loud how much
38174
+ * budget it recovered — "moves recovered: 0" after a restart is the line that
38175
+ * explains a burst of relocations. */
38176
+ async load() {
38177
+ return (await this.ledger.load()).length;
38178
+ }
38179
+ /** The history the guards read. Pure RAM — a guard must never wait on I/O. */
38180
+ entries() {
38181
+ return this.ledger.snapshot().map(({ deviceId, fromNodeId, at }) => ({
38182
+ deviceId,
38183
+ fromNodeId,
38184
+ at
38185
+ }));
38186
+ }
38187
+ /** Record one APPLIED move. Mirror first; the durable write follows and its
38188
+ * failure is logged, never thrown at a relocation that already happened. */
38189
+ record(entry) {
38190
+ this.ledger.put({
38191
+ ...entry,
38192
+ id: moveId(entry)
38193
+ });
38194
+ }
38195
+ /** Drop moves older than `cutoff` — no guard can read them. Returns the count. */
38196
+ pruneOlderThan(cutoff) {
38197
+ const keep = new Set(this.ledger.snapshot().filter((row) => row.at >= cutoff).map((row) => row.id));
38198
+ return this.ledger.pruneExcept(keep);
38199
+ }
38200
+ };
38201
+ //#endregion
37193
38202
  //#region src/dispatch-reconcile.ts
37194
38203
  function runnerAttachmentKey(nodeId, deviceId) {
37195
38204
  return `${nodeId}:${deviceId}`;
@@ -42326,8 +43335,18 @@ async function buildOrchestratorControllers(deps) {
42326
43335
  readGlobalSettings: () => globalSettings,
42327
43336
  getInitTimestamp: () => deps.initTimestamp
42328
43337
  });
43338
+ const nodeStressMoves = new NodeStressMoveLedger({
43339
+ store: deps.ctx().api.settingsStore,
43340
+ logger: deps.ctx().logger.child("node-stress")
43341
+ });
43342
+ const nodeStressLts = new NodeStressLts({
43343
+ store: deps.ctx().api.settingsStore,
43344
+ logger: deps.ctx().logger.child("node-stress-lts")
43345
+ });
42329
43346
  const nodeStress = new NodeStressController({
42330
43347
  ledger,
43348
+ moves: nodeStressMoves,
43349
+ lts: nodeStressLts,
42331
43350
  topology,
42332
43351
  settingsStore,
42333
43352
  logger: deps.ctx().logger,
@@ -42336,6 +43355,17 @@ async function buildOrchestratorControllers(deps) {
42336
43355
  readPipelinePin: (deviceId) => deps.readPipelinePin(deviceId),
42337
43356
  readGlobalSettings: () => globalSettings
42338
43357
  });
43358
+ await NodeStressMoveLedger.declare(deps.ctx().api.settingsStore).then(() => nodeStress.hydrate()).catch((err) => {
43359
+ deps.ctx().logger.warn("node-stress move history unavailable — this boot starts cold", { meta: { error: errMsg(err) } });
43360
+ });
43361
+ await NodeStressLts.declare(deps.ctx().api.settingsStore).catch((err) => {
43362
+ deps.ctx().logger.warn("node-stress statistics unavailable — no baseline this boot", { meta: { error: errMsg(err) } });
43363
+ });
43364
+ const nodeStressLtsTimer = setInterval(() => {
43365
+ nodeStressLts.flushDue().catch((err) => {
43366
+ deps.ctx().logger.warn("node-stress statistics flush failed", { meta: { error: errMsg(err) } });
43367
+ });
43368
+ }, 6e4);
42339
43369
  nodeStress.start();
42340
43370
  const inferenceRotation = new RoundRobinInferenceDeviceRotation();
42341
43371
  /**
@@ -42679,6 +43709,7 @@ async function buildOrchestratorControllers(deps) {
42679
43709
  reconcile.scheduleReconcile();
42680
43710
  const detectionWiring = new DetectionWiringController({
42681
43711
  ctx: () => deps.ctx(),
43712
+ featuresStore: deps.ctx().api.settingsStore,
42682
43713
  ledger,
42683
43714
  placement,
42684
43715
  audio,
@@ -42703,10 +43734,15 @@ async function buildOrchestratorControllers(deps) {
42703
43734
  deviceHasOnboardMotionCap: (deviceId) => deps.deviceHasOnboardMotionCap(deviceId),
42704
43735
  deviceSettingsSchema: () => deps.deviceSettingsSchema()
42705
43736
  });
43737
+ await detectionWiring.hydrateFeaturesMirror().catch((err) => {
43738
+ deps.ctx().logger.warn("device-features mirror not restored — this boot starts cold", { meta: { error: errMsg(err) } });
43739
+ });
42706
43740
  return {
42707
43741
  ledger,
42708
43742
  topology,
42709
43743
  loadService,
43744
+ nodeStressLts,
43745
+ nodeStressLtsTimer,
42710
43746
  audio,
42711
43747
  settingsStore,
42712
43748
  loadShed,
@@ -43259,6 +44295,18 @@ function deriveRuntimeSettings(config) {
43259
44295
  }
43260
44296
  //#endregion
43261
44297
  //#region src/index.ts
44298
+ /**
44299
+ * The FULL action catalog, under the name the HUB HARVESTS.
44300
+ *
44301
+ * The hub's forked-addon harvest imports this entry module and reads the
44302
+ * `customActions` NAMED export (`loadForkedCustomActionCatalog`) — returning a
44303
+ * catalog from `onInitialize` is not enough. Without this line the bridge
44304
+ * answers *"no addon 'pipeline-orchestrator' registers custom actions"* for
44305
+ * every action here, which is what `dumpState` had been doing, silently, since
44306
+ * it was written: an admin diagnostic that 404s is worse than no diagnostic,
44307
+ * because nobody discovers it is missing until they need it.
44308
+ */
44309
+ var customActions = pipelineOrchestratorActions;
43262
44310
  var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddon {
43263
44311
  /** This node's Moleculer nodeId (from this.ctx.kernel.localNodeId). */
43264
44312
  localNodeId = "hub";
@@ -43476,6 +44524,10 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
43476
44524
  pendingRetryTimer = null;
43477
44525
  /** Periodic auto-rebalance sweep timer (drift correction under hysteresis). */
43478
44526
  autoRebalanceTimer = null;
44527
+ /** Node-stress five-minute statistics + its flush timer (see
44528
+ * `node-stress-lts.ts`). `observe` mode's first durable output. */
44529
+ nodeStressLts = null;
44530
+ nodeStressLtsTimer = null;
43479
44531
  initTimestamp = 0;
43480
44532
  /** Storage migration maintenance lease. It only gates dispatch; it does not
43481
44533
  * change any camera wrapper or persistent pipeline configuration. */
@@ -43569,6 +44621,8 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
43569
44621
  this.unsubOrchestratorSubscriptions = controllers.unsubOrchestratorSubscriptions;
43570
44622
  this.pendingRetryTimer = controllers.pendingRetryTimer;
43571
44623
  this.autoRebalanceTimer = controllers.autoRebalanceTimer;
44624
+ this.nodeStressLts = controllers.nodeStressLts;
44625
+ this.nodeStressLtsTimer = controllers.nodeStressLtsTimer;
43572
44626
  return {
43573
44627
  providers: [
43574
44628
  {
@@ -43597,7 +44651,23 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
43597
44651
  }
43598
44652
  ],
43599
44653
  customActions: pipelineOrchestratorActions,
43600
- actionHandlers: { dumpState: async () => this.dumpDiagnostics() }
44654
+ actionHandlers: {
44655
+ dumpState: async () => this.dumpDiagnostics(),
44656
+ nodeStressStats: async (input) => {
44657
+ const lts = this.nodeStressLts;
44658
+ const moves = this.nodeStress?.historyView() ?? [];
44659
+ if (!lts) return {
44660
+ rows: [],
44661
+ open: [],
44662
+ moves: [...moves]
44663
+ };
44664
+ return {
44665
+ rows: (await lts.read(input)).map(withStatsMean),
44666
+ open: lts.openBuckets().map(withStatsMean),
44667
+ moves: [...moves]
44668
+ };
44669
+ }
44670
+ }
43601
44671
  };
43602
44672
  }
43603
44673
  /**
@@ -43632,6 +44702,11 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
43632
44702
  clearInterval(this.autoRebalanceTimer);
43633
44703
  this.autoRebalanceTimer = null;
43634
44704
  }
44705
+ if (this.nodeStressLtsTimer !== null) {
44706
+ clearInterval(this.nodeStressLtsTimer);
44707
+ this.nodeStressLtsTimer = null;
44708
+ }
44709
+ this.nodeStressLts = null;
43635
44710
  this.unsubOrchestratorSubscriptions?.();
43636
44711
  this.unsubOrchestratorSubscriptions = null;
43637
44712
  this.reconcile?.dispose();
@@ -44585,5 +45660,12 @@ var PipelineOrchestratorAddon = class PipelineOrchestratorAddon extends BaseAddo
44585
45660
  return this.isSessionCamera(deviceId) && !this.session.hasActiveSession(deviceId);
44586
45661
  }
44587
45662
  };
45663
+ /** The derived mean for one statistics row — see `node-stress-lts.ts`. */
45664
+ function withStatsMean(row) {
45665
+ return {
45666
+ ...row,
45667
+ mean: row.samples > 0 ? row.sum / row.samples : 0
45668
+ };
45669
+ }
44588
45670
  //#endregion
44589
- export { balance, computeCapacityScore, PipelineOrchestratorAddon as default, pipelineOrchestratorActions };
45671
+ export { balance, computeCapacityScore, customActions, PipelineOrchestratorAddon as default, pipelineOrchestratorActions };