@camstack/server 1.2.810 → 1.2.812

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 (116) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/api/trpc/cap-router-runtime.js +3 -0
  3. package/dist/api/trpc/generated-cap-mounts.js +3 -1
  4. package/dist/api/trpc/generated-cap-routers.js +1869 -1789
  5. package/dist/core/addon/hub-addon-api.js +8 -1
  6. package/dist/core/moleculer/moleculer.service.js +3 -0
  7. package/package.json +9 -42
  8. package/system/dist/addon-runner.js +4 -1
  9. package/system/dist/addon-runner.mjs +5 -2
  10. package/system/dist/{agent-https-B5cYxyQW.mjs → agent-https-CyEBY3RB.mjs} +1 -1
  11. package/system/dist/{agent-https-C0QE8tXs.js → agent-https-a3mE4PW4.js} +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  13. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  15. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.js +3 -101
  17. package/system/dist/builtins/alerts/alerts.addon.mjs +40 -134
  18. package/system/dist/builtins/autotrack/index.js +1 -1
  19. package/system/dist/builtins/autotrack/index.mjs +1 -1
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  21. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  22. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  23. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  24. package/system/dist/builtins/camera-grid/index.js +1 -1
  25. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  26. package/system/dist/builtins/composer/composer.addon.js +6 -5
  27. package/system/dist/builtins/composer/composer.addon.mjs +6 -5
  28. package/system/dist/builtins/console-logging/index.js +1 -1
  29. package/system/dist/builtins/console-logging/index.mjs +1 -1
  30. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +2 -0
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.js +358 -32
  32. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +361 -35
  33. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +42 -0
  34. package/system/dist/builtins/core-blocks/remote-call-redirect.d.ts +1 -1
  35. package/system/dist/builtins/core-blocks/remote-service.d.ts +38 -0
  36. package/system/dist/builtins/device-history/device-history.addon.d.ts +5 -0
  37. package/system/dist/builtins/device-history/device-history.addon.js +357 -18
  38. package/system/dist/builtins/device-history/device-history.addon.mjs +357 -18
  39. package/system/dist/builtins/device-history/retention/retention.d.ts +14 -1
  40. package/system/dist/builtins/device-history/transitions/device-transitions-record-kinds.d.ts +14 -0
  41. package/system/dist/builtins/device-history/transitions/transitions-service.d.ts +80 -0
  42. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +2 -0
  43. package/system/dist/builtins/device-manager/device-manager.addon.js +712 -18
  44. package/system/dist/builtins/device-manager/device-manager.addon.mjs +780 -95
  45. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +7 -0
  46. package/system/dist/builtins/device-manager/transitions/command-args.d.ts +4 -0
  47. package/system/dist/builtins/device-manager/transitions/transition-correlator.d.ts +68 -0
  48. package/system/dist/builtins/device-manager/transitions/transitions-sender.d.ts +37 -0
  49. package/system/dist/builtins/device-manager/transitions/transitions-wiring.d.ts +25 -0
  50. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  51. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  52. package/system/dist/builtins/keychain/index.js +4 -4
  53. package/system/dist/builtins/keychain/index.mjs +4 -4
  54. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  55. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  56. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  57. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  58. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  59. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  60. package/system/dist/builtins/loki-logging/index.js +1 -1
  61. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  62. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  63. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  64. package/system/dist/builtins/platform-probe/index.js +1 -1
  65. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  66. package/system/dist/builtins/record-entries/index.js +1 -1
  67. package/system/dist/builtins/record-entries/index.mjs +1 -1
  68. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  69. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  70. package/system/dist/builtins/snapshot/index.js +1 -1
  71. package/system/dist/builtins/snapshot/index.mjs +1 -1
  72. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  73. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  74. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  75. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  76. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  77. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  78. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  79. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  80. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  81. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  82. package/system/dist/builtins/winston-logging/index.js +1 -1
  83. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  84. package/system/dist/{capture-engine-DHvJXvuV.js → capture-engine-BO9mSlY-.js} +1 -1
  85. package/system/dist/{capture-engine-Ci4GwgjQ.mjs → capture-engine-ByF-6AFH.mjs} +1 -1
  86. package/system/dist/{composition-sources-CXJ0SzYJ.mjs → composition-sources-AziMFo7T.mjs} +1 -1
  87. package/system/dist/{composition-sources-B-WY9L7z.js → composition-sources-BMJUPUh2.js} +1 -1
  88. package/system/dist/{constants-DAuOjW5K.mjs → constants-CTikgsC_.mjs} +1 -1
  89. package/system/dist/{constants-DnJ2vuC7.js → constants-CjRlgRlu.js} +1 -1
  90. package/system/dist/{device-ca-D0HejZGK.mjs → device-ca-CNRlFqFC.mjs} +1 -1
  91. package/system/dist/{device-ca-BRpXm-B0.js → device-ca-Dxl6kVcJ.js} +1 -1
  92. package/system/dist/{dist-BLxWQm_m.mjs → dist-BPq13Y8j.mjs} +17392 -15506
  93. package/system/dist/{dist-DZQowBDF.js → dist-CkJnelZr.js} +17463 -15511
  94. package/system/dist/file-host-worker.js +1 -1
  95. package/system/dist/file-host-worker.mjs +1 -1
  96. package/system/dist/{hub-mdns-ciao-BJx5WmFx.mjs → hub-mdns-ciao-CrjItezp.mjs} +2 -2
  97. package/system/dist/{hub-mdns-ciao-ClSuN_QT.js → hub-mdns-ciao-Cx6yJBl9.js} +2 -2
  98. package/system/dist/index.js +67 -75
  99. package/system/dist/index.mjs +53 -68
  100. package/system/dist/kernel/cap-router-builder.d.ts +9 -0
  101. package/system/dist/kernel/command-observation.d.ts +76 -0
  102. package/system/dist/kernel/index.d.ts +2 -0
  103. package/system/dist/kernel/transport/child-cap-protocol.d.ts +10 -1
  104. package/system/dist/kernel/transport/local-child-registry.d.ts +15 -0
  105. package/system/dist/{legacy-integration-rows-door-BiNKE2zW.js → legacy-integration-rows-door-CKM-LxvL.js} +1 -1
  106. package/system/dist/{legacy-integration-rows-door-CN84_M7B.mjs → legacy-integration-rows-door-Dxcqwc-w.mjs} +1 -1
  107. package/system/dist/log-redactor-BhIEMaG9.js +149 -0
  108. package/system/dist/log-redactor-XLDrPzOi.mjs +120 -0
  109. package/system/dist/logging/log-redactor.d.ts +2 -0
  110. package/system/dist/{restore-archive-Co1yYMV3.js → restore-archive-BQWOdGAB.js} +1 -1
  111. package/system/dist/{restore-archive-gLW5oc1w.mjs → restore-archive-r3zTdLKr.mjs} +82 -82
  112. package/system/dist/{retention-BNONb5X_.js → retention-BcOSL6b9.js} +33 -2
  113. package/system/dist/{retention-B9l9TnGE.mjs → retention-CUOVI1p7.mjs} +33 -2
  114. package/system/dist/{wal-maintenance-BQaIM_cY.js → wal-maintenance-CiCgL4Hp.js} +0 -0
  115. package/system/dist/{wal-maintenance-Zji_8sLK.mjs → wal-maintenance-zJ4-ORo6.mjs} +0 -0
  116. package/system/package.json +7 -1
@@ -21,6 +21,14 @@
21
21
  * in history. A toggle power code is sent only when the current state
22
22
  * differs from the requested one; a discrete pair is always sent. A mute on
23
23
  * a device that does not report it is sent and marked assumed.
24
+ * - **Sources are declared** (planning#460). `availableSources` is the
25
+ * operator's declared sources, never the custom buttons. A source runs its
26
+ * steps in order under the device's lock (no other press interleaves),
27
+ * `stepDelayMs` apart; a refusal is typed (`unknown-source`,
28
+ * `unbound-step`, `undeclared-channel`) and a failed step stops the
29
+ * sequence and names itself. The source last sent is ASSUMED, and forgotten
30
+ * when the device is switched off, when the plug reads off and when a
31
+ * channel step moves the channel.
24
32
  * - **Precedence** (`sendMediaCommand`): a media-player command takes the
25
33
  * remote when its role is bound, else answers `not-routed` so the native
26
34
  * cap runs. The dispatch redirect asks this for every caller.
@@ -72,17 +80,24 @@ export interface RemoteServiceDeps {
72
80
  readonly now?: () => number;
73
81
  /** Waits between two sends of a repeat; a spec drives it. */
74
82
  readonly sleep?: (ms: number) => Promise<void>;
83
+ /** How long one press (or one whole source) may run under the device lock. */
84
+ readonly lockTimeoutMs?: number;
75
85
  }
86
+ /** A sequence is at most 16 steps of 3 s; a press that outlasts this is hung. */
87
+ export declare const REMOTE_LOCK_TIMEOUT_MS = 6e4;
76
88
  /** The pause between two full sends of a repeat — never stored, never a setting. */
77
89
  export declare const REMOTE_REPEAT_GAP_MS = 150;
78
90
  export declare class RemoteService implements IRemoteProvider {
79
91
  private readonly deps;
80
92
  private readonly now;
81
93
  private readonly sleep;
94
+ private readonly lockTimeoutMs;
82
95
  /** Remote devices seen so far, and the plug each one waits on: who an input event affects. */
83
96
  private readonly plugOf;
84
97
  private readonly sliceRuns;
85
98
  private readonly slicePending;
99
+ /** The tail of each device's presses: a sequence is never interleaved with another press. */
100
+ private readonly locks;
86
101
  constructor(deps: RemoteServiceDeps);
87
102
  readonly getConfig: IRemoteProvider["getConfig"];
88
103
  readonly setConfig: IRemoteProvider["setConfig"];
@@ -144,8 +159,31 @@ export declare class RemoteService implements IRemoteProvider {
144
159
  * including when the state was unknown, which is the only way it becomes known.
145
160
  */
146
161
  private setMute;
162
+ /**
163
+ * Runs `fn` after every earlier press of the device has finished. A press that
164
+ * does not finish within `lockTimeoutMs` is given up: the caller is told
165
+ * (`press-timeout`) and the lock is released, so one hung press never wedges
166
+ * the presses behind it.
167
+ */
168
+ private withLock;
169
+ private boundedPress;
147
170
  private run;
148
171
  /**
172
+ * `selectSource(name)`: the declared source a name (or its channel number)
173
+ * points at. A remote that declares none leaves the call to the native cap.
174
+ */
175
+ private selectSource;
176
+ /** `playMedia` of a channel: the `digits` source that declares the number, else a refusal. */
177
+ private playMedia;
178
+ /**
179
+ * Presses a source's steps in order, one lock for the whole sequence,
180
+ * `stepDelayMs` apart. Every step is checked bound BEFORE the first press, so
181
+ * a half-bound source sends nothing. A step that fails stops the sequence.
182
+ */
183
+ private runSource;
184
+ private forgetSource;
185
+ private runRole;
186
+ /**
149
187
  * The assumption moves only after a send landed. A bare `power` flips a KNOWN
150
188
  * state; a bare `mute` press flips a KNOWN mute and leaves an unknown one
151
189
  * unknown (the press alone does not say which way it went).
@@ -26,6 +26,8 @@ export interface DeviceHistoryConfig extends Record<string, unknown> {
26
26
  hourDays: number;
27
27
  /** `0` keeps the daily tier forever. */
28
28
  dayDays: number;
29
+ /** Days a device transition is kept. */
30
+ transitionDays: number;
29
31
  }
30
32
  /** The caller the transport stamped (never in an input schema); `null` when unstamped. */
31
33
  export declare function callerOf(input: unknown): string | null;
@@ -35,6 +37,7 @@ export declare class DeviceHistoryAddon extends BaseAddon<DeviceHistoryConfig> {
35
37
  private removalHook;
36
38
  private runsProvider;
37
39
  private runs;
40
+ private transitions;
38
41
  /** This instance's readiness generation (the base class keeps its own private). */
39
42
  private readonly readinessGeneration;
40
43
  constructor();
@@ -47,9 +50,11 @@ export declare class DeviceHistoryAddon extends BaseAddon<DeviceHistoryConfig> {
47
50
  private legacyScales;
48
51
  private requireRuntime;
49
52
  private requireRuns;
53
+ private requireTransitions;
50
54
  protected onInitialize(): Promise<ProviderRegistration[]>;
51
55
  override onHubReachable(): Promise<void>;
52
56
  private openRuns;
57
+ private openTransitions;
53
58
  private stopRuntime;
54
59
  protected override onShutdown(): Promise<void>;
55
60
  protected override scopedSettingsCapabilities(): readonly string[];
@@ -3,9 +3,9 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-DZQowBDF.js");
7
- const require_capture_engine = require("../../capture-engine-DHvJXvuV.js");
8
- const require_retention = require("../../retention-BNONb5X_.js");
6
+ const require_dist = require("../../dist-CkJnelZr.js");
7
+ const require_capture_engine = require("../../capture-engine-BO9mSlY-.js");
8
+ const require_retention = require("../../retention-BcOSL6b9.js");
9
9
  let node_crypto = require("node:crypto");
10
10
  //#region src/builtins/device-history/capture/point-writer.ts
11
11
  var FLUSH_INTERVAL_MS = 1e4;
@@ -3282,6 +3282,291 @@ var DeviceRunsService = class {
3282
3282
  return out;
3283
3283
  }
3284
3284
  };
3285
+ var deviceTransitionsRecordKinds = require_dist.defineRecordKinds({ "device-transitions": {
3286
+ schema: require_dist.DeviceTransitionSchema,
3287
+ class: "audit",
3288
+ database: "events",
3289
+ writeTrigger: "the hub kernel delivers a batch of correlated device transitions (commands matched to slice changes, or unmatched)",
3290
+ device: "required",
3291
+ at: "required",
3292
+ indexes: [
3293
+ {
3294
+ name: "device_cap_at",
3295
+ fields: [
3296
+ "deviceId",
3297
+ "capName",
3298
+ "at"
3299
+ ]
3300
+ },
3301
+ {
3302
+ name: "device_actor_at",
3303
+ fields: [
3304
+ "deviceId",
3305
+ "actor.kind",
3306
+ "at"
3307
+ ]
3308
+ },
3309
+ {
3310
+ name: "device_outcome_at",
3311
+ fields: [
3312
+ "deviceId",
3313
+ "outcome",
3314
+ "at"
3315
+ ]
3316
+ },
3317
+ {
3318
+ name: "actor_at",
3319
+ fields: ["actor.kind", "at"]
3320
+ },
3321
+ {
3322
+ name: "outcome_at",
3323
+ fields: ["outcome", "at"]
3324
+ }
3325
+ ],
3326
+ retention: {
3327
+ owner: "device-history",
3328
+ reason: "swept by the device-history retention pass under the transitionDays setting (default 365 days)"
3329
+ },
3330
+ deviceRemoval: "delete"
3331
+ } });
3332
+ var yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
3333
+ function rangeOf(window) {
3334
+ const range = {
3335
+ ...window.atFrom !== void 0 ? { gte: window.atFrom } : {},
3336
+ ...window.atTo !== void 0 ? { lt: window.atTo } : {}
3337
+ };
3338
+ return Object.keys(range).length > 0 ? { at: range } : {};
3339
+ }
3340
+ /** One equality filter per call: each is served by its own declared index. */
3341
+ function assertOneFilter(filters) {
3342
+ const named = Object.entries(filters).filter(([, value]) => value !== void 0).map(([key]) => key);
3343
+ if (named.length > 1) throw new Error(`filter by one of ${Object.keys(filters).join(", ")} per call (got ${named.join(" and ")})`);
3344
+ }
3345
+ function isRejectedRow(err) {
3346
+ return err instanceof require_dist.InvalidRecordError || err instanceof require_dist.RecordTooLargeError;
3347
+ }
3348
+ var TransitionsService = class {
3349
+ deps;
3350
+ handle = null;
3351
+ lastWriteAt = null;
3352
+ refused = /* @__PURE__ */ new Map();
3353
+ constructor(deps) {
3354
+ this.deps = deps;
3355
+ }
3356
+ /** Declare the kind. */
3357
+ async open() {
3358
+ await this.deps.records.declare(deviceTransitionsRecordKinds);
3359
+ this.handle = this.deps.records.kind(deviceTransitionsRecordKinds["device-transitions"]);
3360
+ }
3361
+ kind() {
3362
+ if (this.handle === null) throw new Error("the transition ledger is not open yet");
3363
+ return this.handle;
3364
+ }
3365
+ count(reason, by) {
3366
+ this.refused.set(reason, (this.refused.get(reason) ?? 0) + by);
3367
+ }
3368
+ /**
3369
+ * Write a batch. Only the kernel may: a forked addon is stamped by the
3370
+ * transport and an HTTP session's stamp is stripped, so anything but the
3371
+ * kernel's own id is refused, counted and logged. A storage failure throws,
3372
+ * so the sender keeps the batch (D49).
3373
+ */
3374
+ async record(callerAddonId, transitions) {
3375
+ if (callerAddonId !== "device-manager") {
3376
+ this.count("not-kernel", transitions.length);
3377
+ this.deps.logger.warn("device-transitions: refused a batch from a caller that is not the kernel (not-kernel)", { meta: {
3378
+ caller: callerAddonId,
3379
+ rows: transitions.length
3380
+ } });
3381
+ return {
3382
+ written: 0,
3383
+ refused: transitions.map((t) => ({
3384
+ id: t.id,
3385
+ reason: "not-kernel"
3386
+ }))
3387
+ };
3388
+ }
3389
+ if (transitions.length === 0) return {
3390
+ written: 0,
3391
+ refused: []
3392
+ };
3393
+ const handle = this.kind();
3394
+ const puts = transitions.map((t) => ({
3395
+ id: t.id,
3396
+ deviceId: t.deviceId,
3397
+ at: t.at,
3398
+ data: t
3399
+ }));
3400
+ try {
3401
+ await handle.putMany(puts);
3402
+ this.lastWriteAt = this.deps.clock();
3403
+ return {
3404
+ written: transitions.length,
3405
+ refused: []
3406
+ };
3407
+ } catch (err) {
3408
+ if (!isRejectedRow(err)) throw err;
3409
+ }
3410
+ let written = 0;
3411
+ const refused = [];
3412
+ for (const put of puts) try {
3413
+ await handle.put(put);
3414
+ written += 1;
3415
+ } catch (err) {
3416
+ if (!isRejectedRow(err)) throw err;
3417
+ refused.push({
3418
+ id: put.id,
3419
+ reason: "invalid"
3420
+ });
3421
+ this.count("invalid", 1);
3422
+ this.deps.logger.warn("device-transitions: a transition was rejected by the ledger (invalid)", {
3423
+ tags: { deviceId: put.deviceId },
3424
+ meta: {
3425
+ id: put.id,
3426
+ error: err instanceof Error ? err.message : String(err)
3427
+ }
3428
+ });
3429
+ }
3430
+ if (written > 0) this.lastWriteAt = this.deps.clock();
3431
+ return {
3432
+ written,
3433
+ refused
3434
+ };
3435
+ }
3436
+ async list(input) {
3437
+ assertOneFilter({
3438
+ capName: input.capName,
3439
+ actorKind: input.actorKind,
3440
+ outcome: input.outcome
3441
+ });
3442
+ const paging = {
3443
+ desc: true,
3444
+ limit: input.limit,
3445
+ ...input.cursor !== void 0 ? { cursor: input.cursor } : {}
3446
+ };
3447
+ const range = rangeOf(input);
3448
+ const handle = this.kind();
3449
+ const page = input.capName !== void 0 ? await handle.query({
3450
+ where: {
3451
+ deviceId: input.deviceId,
3452
+ capName: input.capName,
3453
+ ...range
3454
+ },
3455
+ ...paging
3456
+ }) : input.actorKind !== void 0 ? await handle.query({
3457
+ where: {
3458
+ deviceId: input.deviceId,
3459
+ "actor.kind": input.actorKind,
3460
+ ...range
3461
+ },
3462
+ ...paging
3463
+ }) : input.outcome !== void 0 ? await handle.query({
3464
+ where: {
3465
+ deviceId: input.deviceId,
3466
+ outcome: input.outcome,
3467
+ ...range
3468
+ },
3469
+ ...paging
3470
+ }) : await handle.query({
3471
+ deviceId: input.deviceId,
3472
+ ...input.atFrom !== void 0 ? { atFrom: input.atFrom } : {},
3473
+ ...input.atTo !== void 0 ? { atTo: input.atTo } : {},
3474
+ ...paging
3475
+ });
3476
+ return {
3477
+ transitions: page.records.map((row) => row.data),
3478
+ nextCursor: page.nextCursor
3479
+ };
3480
+ }
3481
+ async listRecent(input) {
3482
+ assertOneFilter({
3483
+ actorKind: input.actorKind,
3484
+ outcome: input.outcome
3485
+ });
3486
+ const paging = {
3487
+ desc: true,
3488
+ limit: input.limit,
3489
+ ...input.cursor !== void 0 ? { cursor: input.cursor } : {}
3490
+ };
3491
+ const range = rangeOf(input);
3492
+ const handle = this.kind();
3493
+ const where = input.actorKind !== void 0 ? {
3494
+ "actor.kind": input.actorKind,
3495
+ ...range
3496
+ } : input.outcome !== void 0 ? {
3497
+ outcome: input.outcome,
3498
+ ...range
3499
+ } : null;
3500
+ const page = where !== null ? await handle.query({
3501
+ where,
3502
+ ...paging
3503
+ }) : await handle.query({
3504
+ ...input.atFrom !== void 0 ? { atFrom: input.atFrom } : {},
3505
+ ...input.atTo !== void 0 ? { atTo: input.atTo } : {},
3506
+ ...paging
3507
+ });
3508
+ return {
3509
+ transitions: page.records.map((row) => row.data),
3510
+ nextCursor: page.nextCursor
3511
+ };
3512
+ }
3513
+ async get(input) {
3514
+ const row = await this.kind().get(input.id);
3515
+ return row !== null && row.data.deviceId === input.deviceId ? row.data : null;
3516
+ }
3517
+ async status() {
3518
+ let rows = null;
3519
+ try {
3520
+ rows = await this.kind().count({});
3521
+ } catch (err) {
3522
+ this.deps.logger.warn("device-transitions: the row count failed - reported as unknown", { meta: { error: err instanceof Error ? err.message : String(err) } });
3523
+ }
3524
+ return {
3525
+ rows,
3526
+ lastWriteAt: this.lastWriteAt,
3527
+ refused: Object.fromEntries(this.refused)
3528
+ };
3529
+ }
3530
+ /**
3531
+ * Delete every row older than `cutoff` (a row AT the cutoff is kept), in
3532
+ * day-wide slices from the oldest row, yielding between them. Answers the
3533
+ * rows deleted.
3534
+ */
3535
+ async sweep(cutoff) {
3536
+ const handle = this.kind();
3537
+ const first = (await handle.query({
3538
+ desc: false,
3539
+ limit: 1
3540
+ })).records[0]?.at;
3541
+ if (first === void 0 || first === null || first >= cutoff) return 0;
3542
+ const yieldNow = this.deps.yieldNow ?? yieldToEventLoop;
3543
+ let deleted = 0;
3544
+ for (let lo = first; lo < cutoff; lo += require_retention.DAY_MS) {
3545
+ deleted += await handle.deleteWhere({ atBefore: Math.min(lo + require_retention.DAY_MS, cutoff) });
3546
+ await yieldNow();
3547
+ }
3548
+ return deleted;
3549
+ }
3550
+ /** The D865 hook body: how many transition rows the removal deleted. */
3551
+ async removeDevice(deviceId) {
3552
+ return (await this.deps.records.deleteDevice(deviceId, { kinds: ["device-transitions"] }))["device-transitions"] ?? 0;
3553
+ }
3554
+ /** Rows per device, for the admin clean-up listing. */
3555
+ async countByDevice() {
3556
+ const handle = this.handle;
3557
+ if (handle === null) return [];
3558
+ const rows = await handle.aggregate({
3559
+ op: "count",
3560
+ groupBy: "deviceId"
3561
+ });
3562
+ const out = [];
3563
+ for (const row of rows) if (typeof row.group === "number" && row.value !== null) out.push({
3564
+ deviceId: row.group,
3565
+ count: row.value
3566
+ });
3567
+ return out;
3568
+ }
3569
+ };
3285
3570
  //#endregion
3286
3571
  //#region src/builtins/device-history/device-history.addon.ts
3287
3572
  /**
@@ -3309,7 +3594,8 @@ var DEFAULT_CONFIG = {
3309
3594
  rawDays: require_retention.DEFAULT_RETENTION.rawDays,
3310
3595
  fiveMinuteDays: require_retention.DEFAULT_RETENTION.fiveMinuteDays,
3311
3596
  hourDays: require_retention.DEFAULT_RETENTION.hourDays,
3312
- dayDays: 0
3597
+ dayDays: 0,
3598
+ transitionDays: require_retention.DEFAULT_RETENTION.transitionDays
3313
3599
  };
3314
3600
  function isRecord(value) {
3315
3601
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -3329,6 +3615,7 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3329
3615
  removalHook = null;
3330
3616
  runsProvider = null;
3331
3617
  runs = null;
3618
+ transitions = null;
3332
3619
  /** This instance's readiness generation (the base class keeps its own private). */
3333
3620
  readinessGeneration = `device-history-${Date.now().toString(36)}`;
3334
3621
  constructor() {
@@ -3347,6 +3634,7 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3347
3634
  for (const capName of [
3348
3635
  require_dist.deviceHistoryCapability.name,
3349
3636
  require_dist.deviceRunsCapability.name,
3637
+ require_dist.deviceTransitionsCapability.name,
3350
3638
  require_dist.deviceRemovalHookCapability.name
3351
3639
  ]) try {
3352
3640
  require_dist.emitReadiness(ctx.eventBus, {
@@ -3373,7 +3661,8 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3373
3661
  rawDays: positiveOr(c.rawDays, require_retention.DEFAULT_RETENTION.rawDays),
3374
3662
  fiveMinuteDays: positiveOr(c.fiveMinuteDays, require_retention.DEFAULT_RETENTION.fiveMinuteDays),
3375
3663
  hourDays: positiveOr(c.hourDays, require_retention.DEFAULT_RETENTION.hourDays),
3376
- dayDays: positiveOr(c.dayDays, 0) > 0 ? c.dayDays : null
3664
+ dayDays: positiveOr(c.dayDays, 0) > 0 ? c.dayDays : null,
3665
+ transitionDays: positiveOr(c.transitionDays, require_retention.DEFAULT_RETENTION.transitionDays)
3377
3666
  };
3378
3667
  }
3379
3668
  /** Unraid array counters still stored in GiB. A failed listing throws to the caller. */
@@ -3397,6 +3686,10 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3397
3686
  if (this.runsProvider === null) throw new Error("device-runs is starting — the run ledger is not open yet");
3398
3687
  return this.runsProvider;
3399
3688
  }
3689
+ requireTransitions() {
3690
+ if (this.transitions === null) throw new Error("device-transitions is starting — the transition ledger is not open yet");
3691
+ return this.transitions;
3692
+ }
3400
3693
  async onInitialize() {
3401
3694
  const provider = {
3402
3695
  listSeries: async (input) => this.requireRuntime().query.listSeries({
@@ -3436,36 +3729,54 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3436
3729
  getRun: async (input) => this.requireRuns().getRun(input),
3437
3730
  getCurrentRun: async (input) => this.requireRuns().getCurrentRun(input)
3438
3731
  };
3732
+ const transitionsFacade = {
3733
+ listTransitions: async (input) => this.requireTransitions().list(input),
3734
+ getTransition: async (input) => this.requireTransitions().get(input),
3735
+ listRecentTransitions: async (input) => this.requireTransitions().listRecent(input),
3736
+ record: async (input) => this.requireTransitions().record(callerOf(input), input.transitions),
3737
+ getStatus: async () => this.requireTransitions().status()
3738
+ };
3439
3739
  this.emitStoreReadiness("starting");
3440
3740
  this.ctx.logger.info("Initialized — device-history provider registered (store opens on hub link)");
3441
3741
  const removalHook = {
3442
3742
  onDeviceRemoved: async (input) => {
3443
3743
  const { series } = await this.requireRuntime().removeDevice(input.deviceId);
3444
3744
  const deviceRuns = await this.runs?.removeDevice(input.deviceId) ?? 0;
3445
- if (series > 0 || deviceRuns > 0) this.ctx.logger.info("device-history: removed the history of a deleted device", {
3745
+ const deviceTransitions = await this.transitions?.removeDevice(input.deviceId) ?? 0;
3746
+ if (series > 0 || deviceRuns > 0 || deviceTransitions > 0) this.ctx.logger.info("device-history: removed the history of a deleted device", {
3446
3747
  tags: { deviceId: input.deviceId },
3447
3748
  meta: {
3448
3749
  counts: {
3449
3750
  series,
3450
- deviceRuns
3751
+ deviceRuns,
3752
+ deviceTransitions
3451
3753
  },
3452
3754
  deletedAt: input.deletedAt
3453
3755
  }
3454
3756
  });
3455
3757
  return { counts: {
3456
3758
  series,
3457
- deviceRuns
3759
+ deviceRuns,
3760
+ deviceTransitions
3458
3761
  } };
3459
3762
  },
3460
- listDeviceData: async () => [...[...this.requireRuntime().seriesByDevice()].map(([deviceId, count]) => ({
3461
- store: "series",
3462
- deviceId,
3463
- count
3464
- })), ...(await this.runs?.countByDevice() ?? []).map(({ deviceId, count }) => ({
3465
- store: "runs",
3466
- deviceId,
3467
- count
3468
- }))]
3763
+ listDeviceData: async () => [
3764
+ ...[...this.requireRuntime().seriesByDevice()].map(([deviceId, count]) => ({
3765
+ store: "series",
3766
+ deviceId,
3767
+ count
3768
+ })),
3769
+ ...(await this.runs?.countByDevice() ?? []).map(({ deviceId, count }) => ({
3770
+ store: "runs",
3771
+ deviceId,
3772
+ count
3773
+ })),
3774
+ ...(await this.transitions?.countByDevice() ?? []).map(({ deviceId, count }) => ({
3775
+ store: "transitions",
3776
+ deviceId,
3777
+ count
3778
+ }))
3779
+ ]
3469
3780
  };
3470
3781
  this.removalHook = removalHook;
3471
3782
  return [
@@ -3477,6 +3788,10 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3477
3788
  capability: require_dist.deviceRunsCapability,
3478
3789
  provider: runsFacade
3479
3790
  },
3791
+ {
3792
+ capability: require_dist.deviceTransitionsCapability,
3793
+ provider: transitionsFacade
3794
+ },
3480
3795
  {
3481
3796
  capability: require_dist.deviceRemovalHookCapability,
3482
3797
  provider: removalHook
@@ -3523,6 +3838,9 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3523
3838
  const runsOpened = await runs.open();
3524
3839
  this.runsProvider = runsOpened.provider;
3525
3840
  this.runs = runs;
3841
+ const transitions = await this.openTransitions();
3842
+ this.transitions = transitions;
3843
+ runtime.retentionJob.attachTransitions(transitions);
3526
3844
  this.unsubscribe = this.ctx.eventBus.subscribe({ category: require_dist.EventCategory.DeviceStateChanged }, (event) => {
3527
3845
  const data = event.data;
3528
3846
  if (!isRecord(data)) return;
@@ -3576,6 +3894,18 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3576
3894
  clock: () => Date.now()
3577
3895
  });
3578
3896
  }
3897
+ async openTransitions() {
3898
+ const { ctx } = this;
3899
+ const records = ctx.records;
3900
+ if (records === void 0) throw new Error("device-history needs ctx.records on the hub for the transition ledger");
3901
+ const transitions = new TransitionsService({
3902
+ records,
3903
+ logger: ctx.logger,
3904
+ clock: () => Date.now()
3905
+ });
3906
+ await transitions.open();
3907
+ return transitions;
3908
+ }
3579
3909
  async stopRuntime() {
3580
3910
  this.unsubscribe?.();
3581
3911
  this.unsubscribe = null;
@@ -3588,6 +3918,7 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3588
3918
  this.runtime = null;
3589
3919
  this.runs = null;
3590
3920
  this.runsProvider = null;
3921
+ this.transitions = null;
3591
3922
  }
3592
3923
  scopedSettingsCapabilities() {
3593
3924
  return ["device-history"];
@@ -3597,7 +3928,7 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3597
3928
  return this.schema({ sections: [{
3598
3929
  id: "retention",
3599
3930
  title: "Retention",
3600
- description: "How long each tier is kept. The raw points feed the 5-minute rollup; the 1-day tier is kept forever unless a number of days is set.",
3931
+ description: "How long each tier is kept. The raw points feed the 5-minute rollup; the 1-day tier is kept forever unless a number of days is set. Device transitions (who changed what) are kept for their own number of days.",
3601
3932
  columns: 2,
3602
3933
  fields: [
3603
3934
  {
@@ -3631,6 +3962,14 @@ var DeviceHistoryAddon = class extends require_dist.BaseAddon {
3631
3962
  min: 0,
3632
3963
  max: 36500,
3633
3964
  step: 1
3965
+ },
3966
+ {
3967
+ type: "number",
3968
+ key: "transitionDays",
3969
+ label: "Device transitions (days)",
3970
+ min: 7,
3971
+ max: 3650,
3972
+ step: 1
3634
3973
  }
3635
3974
  ]
3636
3975
  }] });