@camstack/server 1.2.891 → 1.2.893

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 (118) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  3. package/dist/api/trpc/generated-cap-routers.js +204 -39
  4. package/dist/core/addon/addon-registry.service.js +47 -0
  5. package/dist/core/addon/retire-undeclared-fixed-integrations.js +57 -0
  6. package/package.json +14 -15
  7. package/system/dist/addon-runner.js +25 -9
  8. package/system/dist/addon-runner.mjs +25 -9
  9. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  11. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  14. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  15. package/system/dist/builtins/autotrack/index.js +1 -1
  16. package/system/dist/builtins/autotrack/index.mjs +1 -1
  17. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  18. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  19. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  20. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  21. package/system/dist/builtins/camera-grid/addon.d.ts +65 -41
  22. package/system/dist/builtins/camera-grid/grid-blocks.d.ts +51 -0
  23. package/system/dist/builtins/camera-grid/grid-camera-device.d.ts +4 -3
  24. package/system/dist/builtins/camera-grid/grid-layout-native-provider.d.ts +3 -1
  25. package/system/dist/builtins/camera-grid/grid-plan.d.ts +3 -3
  26. package/system/dist/builtins/camera-grid/index.d.ts +2 -6
  27. package/system/dist/builtins/camera-grid/index.js +431 -727
  28. package/system/dist/builtins/camera-grid/index.mjs +428 -719
  29. package/system/dist/builtins/composer/composed-device.d.ts +12 -2
  30. package/system/dist/builtins/composer/composer.addon.js +28 -10
  31. package/system/dist/builtins/composer/composer.addon.mjs +28 -10
  32. package/system/dist/builtins/composer/composition-declarations.d.ts +3 -1
  33. package/system/dist/builtins/console-logging/index.js +1 -1
  34. package/system/dist/builtins/console-logging/index.mjs +1 -1
  35. package/system/dist/builtins/core-blocks/core-blocks.addon.js +174 -39
  36. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +175 -40
  37. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +19 -1
  38. package/system/dist/builtins/core-blocks/power-source-devices.d.ts +9 -0
  39. package/system/dist/builtins/core-blocks/power-source-service.d.ts +39 -2
  40. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  41. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  42. package/system/dist/builtins/device-manager/device-identifiers-action.d.ts +9 -0
  43. package/system/dist/builtins/device-manager/device-identity-index.d.ts +73 -0
  44. package/system/dist/builtins/device-manager/device-manager.addon.js +401 -14
  45. package/system/dist/builtins/device-manager/device-manager.addon.mjs +401 -14
  46. package/system/dist/builtins/device-manager/device-meta-types.d.ts +5 -1
  47. package/system/dist/builtins/device-manager/device-row-store.d.ts +7 -3
  48. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +7 -0
  49. package/system/dist/builtins/device-manager/workload-transition.d.ts +23 -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 +3 -3
  59. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  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 +3 -3
  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-nmelnj-Y.mjs → capture-engine-CIVKm_jN.mjs} +1 -1
  85. package/system/dist/{capture-engine-DXz37Mjg.js → capture-engine-mZ2J-GD6.js} +1 -1
  86. package/system/dist/{composition-sources-BLn3cU74.js → composition-sources-CGP5ZUYo.js} +1 -1
  87. package/system/dist/{composition-sources-uphZtYtN.mjs → composition-sources-bJP8_Z2o.mjs} +1 -1
  88. package/system/dist/{constants-BAaGwvKn.js → constants-BD8oSQro.js} +1 -1
  89. package/system/dist/{constants-DWU46D02.mjs → constants-w-6vvTPp.mjs} +1 -1
  90. package/system/dist/{device-ca-jbH_rqZh.js → device-ca-CXxnQaff.js} +1 -1
  91. package/system/dist/{device-ca-CK6mLB2w.mjs → device-ca-DE_oetBE.mjs} +1 -1
  92. package/system/dist/{dist-m5beNMze.js → dist-B2-Uflhy.js} +2573 -443
  93. package/system/dist/{dist-Dgq9nuvh.mjs → dist-Be8yFd71.mjs} +2460 -444
  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-identity-CKCA89XP.js → hub-identity-BjYvJU_v.js} +1 -1
  97. package/system/dist/{hub-identity-DlBBoHJC.mjs → hub-identity-C3g7b58L.mjs} +1 -1
  98. package/system/dist/{hub-mdns-ciao-CqcCGPdi.js → hub-mdns-ciao-BRfv9GfW.js} +2 -2
  99. package/system/dist/{hub-mdns-ciao-B8uFW-RG.mjs → hub-mdns-ciao-v6X_SbWl.mjs} +2 -2
  100. package/system/dist/index.js +33 -19
  101. package/system/dist/index.mjs +33 -19
  102. package/system/dist/kernel/moleculer/child-cap-dispatch.d.ts +3 -6
  103. package/system/dist/kernel/moleculer/switch-toggle.d.ts +7 -2
  104. package/system/dist/{legacy-integration-rows-door-Co0gj1Lm.js → legacy-integration-rows-door-B0q34gh3.js} +1 -1
  105. package/system/dist/{legacy-integration-rows-door-HI4nmSe_.mjs → legacy-integration-rows-door-DG35DG06.mjs} +1 -1
  106. package/system/dist/{rename-composition-block-UeVUYCwx.js → rename-composition-block-DNte3Cs9.js} +1 -1
  107. package/system/dist/{rename-composition-block-BthBMrXA.mjs → rename-composition-block-LEbZ4oZE.mjs} +1 -1
  108. package/system/dist/{restore-archive-P-ICnU58.mjs → restore-archive--4ENkU5f.mjs} +1 -1
  109. package/system/dist/{restore-archive-CJLsfBwK.js → restore-archive-DpFPheMK.js} +1 -1
  110. package/system/dist/{wal-maintenance-CUtwx-2Z.js → wal-maintenance-BWUJktqT.js} +0 -0
  111. package/system/dist/{wal-maintenance-qWjb7_f2.mjs → wal-maintenance-DQVDhuVJ.mjs} +0 -0
  112. package/system/package.json +2 -5
  113. package/system/dist/builtins/camera-grid/grid-camera-declarations.d.ts +0 -59
  114. package/system/dist/builtins/camera-grid/grid-instances.d.ts +0 -40
  115. package/system/dist/builtins/camera-grid/grid-record-kinds.d.ts +0 -31
  116. package/system/dist/builtins/camera-grid/migrations/__fixtures__/seed.d.ts +0 -13
  117. package/system/dist/builtins/camera-grid/migrations/camera-grids-to-records.d.ts +0 -26
  118. package/system/dist/builtins/camera-grid/migrations/index.d.ts +0 -6
@@ -3,10 +3,10 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-m5beNMze.js");
6
+ const require_dist = require("../../dist-B2-Uflhy.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
9
- const require_rename_composition_block = require("../../rename-composition-block-UeVUYCwx.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-DNte3Cs9.js");
10
10
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
11
11
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
12
12
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
@@ -484,7 +484,8 @@ function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
484
484
  ...metaRow?.childLayout !== void 0 ? { childLayout: metaRow.childLayout } : {},
485
485
  ...metaRow?.primaryChildPreference !== void 0 ? { primaryChildPreference: metaRow.primaryChildPreference } : {},
486
486
  ...metaRow?.tags !== void 0 ? { tags: metaRow.tags } : {},
487
- ...metaRow?.display !== void 0 ? { display: metaRow.display } : {}
487
+ ...metaRow?.display !== void 0 ? { display: metaRow.display } : {},
488
+ ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {}
488
489
  };
489
490
  }
490
491
  function resolveDeviceById(registry, deviceId) {
@@ -3068,6 +3069,7 @@ async function listAll(pctx, input) {
3068
3069
  ...m.primaryChildPreference !== void 0 ? { primaryChildPreference: m.primaryChildPreference } : {},
3069
3070
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3070
3071
  ...m.display !== void 0 ? { display: m.display } : {},
3072
+ ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3071
3073
  ...(() => {
3072
3074
  if (slim) return {};
3073
3075
  const si = projectSourceInfo(persistedConfig ?? {}, stableId, aid, metadata);
@@ -3121,6 +3123,7 @@ async function getDevice(pctx, input) {
3121
3123
  ...m.primaryChildPreference !== void 0 ? { primaryChildPreference: m.primaryChildPreference } : {},
3122
3124
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3123
3125
  ...m.display !== void 0 ? { display: m.display } : {},
3126
+ ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3124
3127
  ...sourceInfoGetDevice !== void 0 ? { sourceInfo: sourceInfoGetDevice } : {}
3125
3128
  };
3126
3129
  }
@@ -3201,6 +3204,7 @@ function projectChildren(pctx, parentDeviceId, ownerAddonId, childRows, liveChil
3201
3204
  ...m.primaryChildPreference !== void 0 ? { primaryChildPreference: m.primaryChildPreference } : {},
3202
3205
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3203
3206
  ...m.display !== void 0 ? { display: m.display } : {},
3207
+ ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3204
3208
  ...sourceInfoChild !== void 0 ? { sourceInfo: sourceInfoChild } : {}
3205
3209
  });
3206
3210
  }
@@ -4740,7 +4744,7 @@ function compareUnranked(a, b) {
4740
4744
  if (a[2] !== b[2]) return a[2] < b[2] ? -1 : 1;
4741
4745
  return a[3] - b[3];
4742
4746
  }
4743
- function compareKeys(a, b) {
4747
+ function compareKeys$1(a, b) {
4744
4748
  if (a.length === 5 && b.length === 5) {
4745
4749
  if (a[0] !== b[0]) return a[0] - b[0];
4746
4750
  return compareUnranked([
@@ -4915,14 +4919,14 @@ async function searchDevices(deps, input) {
4915
4919
  const keyed = listed.map((c) => ({
4916
4920
  c,
4917
4921
  key: sortKeyOf(c)
4918
- })).sort((a, b) => compareKeys(a.key, b.key));
4922
+ })).sort((a, b) => compareKeys$1(a.key, b.key));
4919
4923
  const limit = Math.min(input.limit ?? 50, 200);
4920
4924
  let start = 0;
4921
4925
  if (input.cursor !== void 0 && input.cursor !== null) {
4922
4926
  const after = decodeCursor(input.cursor);
4923
4927
  if (after === null) deps.logger.warn("deviceManager.search: undecodable cursor — restarting from the first page");
4924
4928
  else {
4925
- const next = keyed.findIndex((k) => compareKeys(k.key, after) > 0);
4929
+ const next = keyed.findIndex((k) => compareKeys$1(k.key, after) > 0);
4926
4930
  start = next === -1 ? keyed.length : next;
4927
4931
  }
4928
4932
  }
@@ -8801,6 +8805,307 @@ async function removeLocation(pctx, input) {
8801
8805
  });
8802
8806
  }
8803
8807
  //#endregion
8808
+ //#region src/builtins/device-manager/device-identifiers-action.ts
8809
+ /**
8810
+ * `device-manager.setIdentifiers` — the ONE writer of a device's provider-declared
8811
+ * identifiers (D1059).
8812
+ *
8813
+ * Who may write: the provider that OWNS the device, and nobody else. Ownership is
8814
+ * the caller stamp the transport sets (`callerAddonId`, never in an input schema,
8815
+ * so a session cannot supply it — `CALLER_STAMPED_CAPABILITIES` lists
8816
+ * `device-manager`) compared with the row's `addonId`. An operator session carries
8817
+ * no stamp and is refused; so is another addon. The operator reads identifiers, it
8818
+ * never edits them: the free-form, editable blob is `metadata`.
8819
+ *
8820
+ * The stored value is `mergeIdentifiers(stored, declared, unread)`: each kind the
8821
+ * declaration carries replaces the stored one, each kind it lacks is removed,
8822
+ * except the kinds in `unread` (the provider's read FAILED), which keep what was
8823
+ * stored — a failed read never erases a fact (D49). An entry whose value and
8824
+ * origin are unchanged keeps its stored `readAt` (when that value was first read),
8825
+ * so a provider re-declaring the same values on every boot writes nothing and
8826
+ * emits nothing. `null` clears every kind not in `unread`.
8827
+ */
8828
+ var SetIdentifiersRefusedError = class extends Error {
8829
+ reason;
8830
+ constructor(reason, message) {
8831
+ super(message);
8832
+ this.reason = reason;
8833
+ this.name = "SetIdentifiersRefusedError";
8834
+ }
8835
+ };
8836
+ /** The caller the transport stamped; `null` when the call carries none. */
8837
+ function stampedCaller(input) {
8838
+ const raw = Reflect.get(Object(input), "callerAddonId");
8839
+ return typeof raw === "string" && raw.length > 0 ? raw : null;
8840
+ }
8841
+ async function setIdentifiers(pctx, input) {
8842
+ const { deviceId } = input;
8843
+ const logger = pctx.host.ctx.logger;
8844
+ const caller = stampedCaller(input);
8845
+ const parsed = require_dist.DeviceIdentifiersSchema.nullable().safeParse(input.identifiers);
8846
+ if (!parsed.success) {
8847
+ logger.warn("setIdentifiers refused — the declaration is not in its normalised form", {
8848
+ tags: { deviceId },
8849
+ meta: {
8850
+ caller,
8851
+ issues: parsed.error.issues.map((i) => i.path.join("."))
8852
+ }
8853
+ });
8854
+ throw new SetIdentifiersRefusedError("invalid", `[device-manager] setIdentifiers: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8855
+ }
8856
+ const next = parsed.data === null || require_dist.isEmptyIdentifiers(parsed.data) ? null : parsed.data;
8857
+ const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
8858
+ const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
8859
+ if (!persisted) return { kind: "unknown-device" };
8860
+ if (caller === null || caller !== persisted.addonId) return {
8861
+ kind: "not-owner",
8862
+ owner: persisted.addonId
8863
+ };
8864
+ const stored = persisted.meta.identifiers ?? null;
8865
+ const merged = require_dist.mergeIdentifiers(stored, next, input.unread ?? []);
8866
+ if (require_dist.sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8867
+ await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8868
+ return {
8869
+ kind: "written",
8870
+ value: merged
8871
+ };
8872
+ });
8873
+ if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] setIdentifiers: unknown device id=${deviceId}`);
8874
+ if (outcome.kind === "not-owner") {
8875
+ logger.warn("setIdentifiers refused — only the owning provider declares identifiers", {
8876
+ tags: { deviceId },
8877
+ meta: {
8878
+ caller,
8879
+ owner: outcome.owner
8880
+ }
8881
+ });
8882
+ throw new SetIdentifiersRefusedError("not-owner", `[device-manager] setIdentifiers: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8883
+ }
8884
+ if (outcome.kind === "unchanged") return;
8885
+ pctx.host.ctx.eventBus.emit({
8886
+ id: (0, node_crypto.randomUUID)(),
8887
+ timestamp: /* @__PURE__ */ new Date(),
8888
+ source: {
8889
+ type: "device",
8890
+ id: deviceId
8891
+ },
8892
+ category: require_dist.EventCategory.DeviceMetaChanged,
8893
+ data: {
8894
+ deviceId,
8895
+ field: "identifiers",
8896
+ value: outcome.value
8897
+ }
8898
+ });
8899
+ }
8900
+ //#endregion
8901
+ //#region src/builtins/device-manager/device-identity-index.ts
8902
+ /**
8903
+ * The identifier INDEX (planning#593): identifier key → devices, so the
8904
+ * device-manager can say which devices of DIFFERENT integrations share
8905
+ * provider-declared identifiers (D1059) without reading the fleet per question.
8906
+ *
8907
+ * It is a PROJECTION of the device rows, never an authority: it holds, per
8908
+ * device, only what the pair rule needs — owning addon, integration instance and
8909
+ * the declared identifiers — and it moves with the rows, as the
8910
+ * {@link DeviceRowObserver} of the one `DeviceRowStore`. Every write of a row
8911
+ * passes through that store (`upsert`, `upsertRegistration`, `patch`, `remove`;
8912
+ * `swapIds` is built of them), so a row that changes reaches the index on the
8913
+ * same statement. A deleted device leaves the index on its row's DELETE — the
8914
+ * statement `removeDevice` runs right before it records the tombstone (D865) —
8915
+ * not on an event or on absence from a listing.
8916
+ *
8917
+ * It loads once, from the fleet listing the device-manager already reads at
8918
+ * boot ({@link seed}). Until then it answers `unknown` (D315), never `[]`; a row
8919
+ * write that lands while the snapshot is in flight is buffered and replayed over
8920
+ * it, so the seed can never roll a newer write back.
8921
+ *
8922
+ * Read-only: it finds candidates, it links nothing (that is step 3).
8923
+ */
8924
+ /** The `kind=value` keys of one declaration. */
8925
+ function keysOf(identifiers) {
8926
+ if (identifiers === null) return [];
8927
+ const out = [];
8928
+ for (const kind of require_dist.DEVICE_IDENTIFIER_KEYS) {
8929
+ const entry = identifiers[kind];
8930
+ if (entry === void 0) continue;
8931
+ for (const e of [entry].flat()) out.push(`${kind}=${e.value}`);
8932
+ }
8933
+ return out;
8934
+ }
8935
+ function isIdentifierKind(value) {
8936
+ return require_dist.DEVICE_IDENTIFIER_KEYS.some((k) => k === value);
8937
+ }
8938
+ function parseKey(key) {
8939
+ const at = key.indexOf("=");
8940
+ const kind = key.slice(0, at);
8941
+ return isIdentifierKind(kind) ? {
8942
+ key: kind,
8943
+ value: key.slice(at + 1)
8944
+ } : null;
8945
+ }
8946
+ /**
8947
+ * Same integration? The same instance when both carry one; otherwise — one side
8948
+ * was never stamped — the same addon. In doubt, the same: no candidate.
8949
+ */
8950
+ function sameIntegration(a, b) {
8951
+ if (a.integrationId !== null && b.integrationId !== null) return a.integrationId === b.integrationId;
8952
+ return a.addonId === b.addonId;
8953
+ }
8954
+ function sideOf(d) {
8955
+ return {
8956
+ deviceId: d.deviceId,
8957
+ addonId: d.addonId,
8958
+ integrationId: d.integrationId
8959
+ };
8960
+ }
8961
+ function compareKeys(x, y) {
8962
+ if (x.key !== y.key) return x.key < y.key ? -1 : 1;
8963
+ return x.value < y.value ? -1 : x.value > y.value ? 1 : 0;
8964
+ }
8965
+ /**
8966
+ * Grade the keys two devices share. `null` when they are no candidate at all
8967
+ * (no strong key matched).
8968
+ *
8969
+ * | Matched keys | Confidence |
8970
+ * | ----------------------------------------- | ------------ |
8971
+ * | two strong KINDS (e.g. `mac` + `serial`) | `auto` |
8972
+ * | `mac` + `ip` | `auto` |
8973
+ * | exactly one strong kind | `proposal` |
8974
+ * | weak keys only (`hostname`, `ip`) | no candidate |
8975
+ *
8976
+ * Strength counts distinct KINDS, not values: two MACs of one device matching
8977
+ * the other's two MACs are one kind of evidence, so a proposal.
8978
+ */
8979
+ function classifyIdentityMatch(keys) {
8980
+ const kinds = new Set(keys.map((k) => k.key));
8981
+ const strongKinds = [...kinds].filter((kind) => require_dist.identifierStrength(kind) === "strong");
8982
+ if (strongKinds.length === 0) return null;
8983
+ if (strongKinds.length >= 2) return "auto";
8984
+ if (kinds.has("mac") && kinds.has("ip")) return "auto";
8985
+ return "proposal";
8986
+ }
8987
+ var DeviceIdentityIndex = class {
8988
+ devices = /* @__PURE__ */ new Map();
8989
+ byKey = /* @__PURE__ */ new Map();
8990
+ /** `null` once seeded; until then, the writes to replay over the snapshot. */
8991
+ pending = [];
8992
+ /** Load from a fleet snapshot, then replay every write that landed meanwhile. */
8993
+ seed(rows) {
8994
+ const buffered = this.pending ?? [];
8995
+ this.pending = null;
8996
+ this.devices.clear();
8997
+ this.byKey.clear();
8998
+ for (const row of rows) this.rowWritten(row.meta);
8999
+ for (const write of buffered) write(this);
9000
+ }
9001
+ rowWritten(meta) {
9002
+ if (this.buffer((i) => i.rowWritten(meta))) return;
9003
+ this.put({
9004
+ deviceId: meta.id,
9005
+ addonId: meta.addonId,
9006
+ integrationId: meta.integrationId ?? null,
9007
+ identifiers: meta.identifiers ?? null
9008
+ });
9009
+ }
9010
+ registrationWritten(row) {
9011
+ if (this.buffer((i) => i.registrationWritten(row))) return;
9012
+ const existing = this.devices.get(row.deviceId);
9013
+ this.put({
9014
+ deviceId: row.deviceId,
9015
+ addonId: row.addonId,
9016
+ integrationId: existing?.integrationId ?? null,
9017
+ identifiers: existing?.identifiers ?? null
9018
+ });
9019
+ }
9020
+ rowPatched(deviceId, patch) {
9021
+ if (patch.identifiers === void 0 && patch.integrationId === void 0) return;
9022
+ if (this.buffer((i) => i.rowPatched(deviceId, patch))) return;
9023
+ const existing = this.devices.get(deviceId);
9024
+ if (existing === void 0) return;
9025
+ this.put({
9026
+ ...existing,
9027
+ ...patch.identifiers !== void 0 ? { identifiers: patch.identifiers } : {},
9028
+ ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {}
9029
+ });
9030
+ }
9031
+ rowRemoved(deviceId) {
9032
+ if (this.buffer((i) => i.rowRemoved(deviceId))) return;
9033
+ this.drop(deviceId);
9034
+ }
9035
+ /**
9036
+ * Every cross-integration candidate pair, graded by `classifyIdentityMatch`,
9037
+ * plus the devices whose identity is unknown (nothing declared).
9038
+ */
9039
+ candidates() {
9040
+ if (this.pending !== null) return {
9041
+ status: "unknown",
9042
+ reason: "the identifier index has not loaded yet"
9043
+ };
9044
+ const seen = /* @__PURE__ */ new Set();
9045
+ const pairs = [];
9046
+ for (const [key, members] of this.byKey) {
9047
+ const parsed = parseKey(key);
9048
+ if (parsed === null || require_dist.identifierStrength(parsed.key) !== "strong") continue;
9049
+ if (members.size < 2) continue;
9050
+ const sorted = [...members].sort((x, y) => x - y);
9051
+ for (let i = 0; i < sorted.length; i++) for (let j = i + 1; j < sorted.length; j++) {
9052
+ const pair = this.pairOf(sorted[i], sorted[j], seen);
9053
+ if (pair !== null) pairs.push(pair);
9054
+ }
9055
+ }
9056
+ pairs.sort((x, y) => x.a.deviceId - y.a.deviceId || x.b.deviceId - y.b.deviceId);
9057
+ return {
9058
+ status: "answered",
9059
+ pairs,
9060
+ undeclaredDeviceIds: [...this.devices.values()].filter((d) => d.identifiers === null).map((d) => d.deviceId).sort((x, y) => x - y)
9061
+ };
9062
+ }
9063
+ pairOf(idA, idB, seen) {
9064
+ if (idA === void 0 || idB === void 0) return null;
9065
+ const tag = `${idA}/${idB}`;
9066
+ if (seen.has(tag)) return null;
9067
+ seen.add(tag);
9068
+ const a = this.devices.get(idA);
9069
+ const b = this.devices.get(idB);
9070
+ if (a === void 0 || b === void 0 || sameIntegration(a, b)) return null;
9071
+ const bKeys = new Set(keysOf(b.identifiers));
9072
+ const keys = keysOf(a.identifiers).filter((k) => bKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9073
+ const confidence = classifyIdentityMatch(keys);
9074
+ return confidence === null ? null : {
9075
+ a: sideOf(a),
9076
+ b: sideOf(b),
9077
+ keys,
9078
+ confidence
9079
+ };
9080
+ }
9081
+ /** True when the write was buffered for replay over a seed still in flight. */
9082
+ buffer(write) {
9083
+ if (this.pending === null) return false;
9084
+ this.pending.push(write);
9085
+ return true;
9086
+ }
9087
+ put(device) {
9088
+ this.drop(device.deviceId);
9089
+ this.devices.set(device.deviceId, device);
9090
+ for (const key of keysOf(device.identifiers)) {
9091
+ const members = this.byKey.get(key) ?? /* @__PURE__ */ new Set();
9092
+ members.add(device.deviceId);
9093
+ this.byKey.set(key, members);
9094
+ }
9095
+ }
9096
+ drop(deviceId) {
9097
+ const existing = this.devices.get(deviceId);
9098
+ if (existing === void 0) return;
9099
+ this.devices.delete(deviceId);
9100
+ for (const key of keysOf(existing.identifiers)) {
9101
+ const members = this.byKey.get(key);
9102
+ if (members === void 0) continue;
9103
+ members.delete(deviceId);
9104
+ if (members.size === 0) this.byKey.delete(key);
9105
+ }
9106
+ }
9107
+ };
9108
+ //#endregion
8804
9109
  //#region src/builtins/device-manager/linked-devices-manual-backfill.ts
8805
9110
  var LINKED_MANUAL_BACKFILL_MARKER_KEY = "_linkedDevicesManualBackfillVersion";
8806
9111
  function planManualBackfill(params) {
@@ -10339,6 +10644,10 @@ var DEVICE_ROWS_COLUMNS = [
10339
10644
  {
10340
10645
  name: "metadata",
10341
10646
  type: "JSON"
10647
+ },
10648
+ {
10649
+ name: "identifiers",
10650
+ type: "JSON"
10342
10651
  }
10343
10652
  ];
10344
10653
  /**
@@ -10458,6 +10767,7 @@ function decodeDeviceRow(data) {
10458
10767
  const primaryChildPreference = readStringArray(data["primaryChildPreference"]);
10459
10768
  const rawDisplay = data["display"];
10460
10769
  const rawMetadata = data["metadata"];
10770
+ const identifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["identifiers"]);
10461
10771
  return {
10462
10772
  meta: {
10463
10773
  id: deviceId,
@@ -10479,7 +10789,8 @@ function decodeDeviceRow(data) {
10479
10789
  ...isChildLayout(rawChildLayout) ? { childLayout: rawChildLayout } : {},
10480
10790
  ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
10481
10791
  ...role !== void 0 ? { role } : {},
10482
- ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {}
10792
+ ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
10793
+ ...identifiers.success ? { identifiers: identifiers.data } : {}
10483
10794
  },
10484
10795
  metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
10485
10796
  registered: readBoolean(data["registered"]) ?? false
@@ -10525,7 +10836,8 @@ function encodeDeviceRow(meta, extra = {}) {
10525
10836
  childLayout: meta.childLayout ?? null,
10526
10837
  primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
10527
10838
  role: meta.role ?? null,
10528
- display: meta.display ?? null
10839
+ display: meta.display ?? null,
10840
+ identifiers: meta.identifiers ?? null
10529
10841
  };
10530
10842
  if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
10531
10843
  return row;
@@ -10548,6 +10860,7 @@ function encodeDeviceRowPatch(patch) {
10548
10860
  var DeviceRowStore = class {
10549
10861
  backend;
10550
10862
  logger;
10863
+ observer;
10551
10864
  declared = null;
10552
10865
  /** Call-site attribution for fleet reads. Armed only by
10553
10866
  * `CAMSTACK_FLEET_READ_CENSUS_MS`; see `fleet-read-census.ts`. */
@@ -10562,9 +10875,10 @@ var DeviceRowStore = class {
10562
10875
  get censusArmed() {
10563
10876
  return this.census.armed;
10564
10877
  }
10565
- constructor(backend, logger, census) {
10878
+ constructor(backend, logger, census, observer) {
10566
10879
  this.backend = backend;
10567
10880
  this.logger = logger;
10881
+ this.observer = observer;
10568
10882
  this.census = census ?? new FleetReadCensus(process.env["CAMSTACK_FLEET_READ_CENSUS_MS"], Date.now());
10569
10883
  if (this.census.armed) {
10570
10884
  const startedAt = Date.now();
@@ -10839,6 +11153,7 @@ var DeviceRowStore = class {
10839
11153
  key: String(meta.id),
10840
11154
  value: encodeDeviceRow(meta, extra)
10841
11155
  });
11156
+ this.observer?.rowWritten(meta);
10842
11157
  }
10843
11158
  /**
10844
11159
  * Write the named columns of an EXISTING row and nothing else.
@@ -10860,10 +11175,14 @@ var DeviceRowStore = class {
10860
11175
  filter: { where: { id: String(deviceId) } },
10861
11176
  data: columns
10862
11177
  });
10863
- if (updated === 0) this.logger.warn("device row patch matched no row — the device was removed under it", {
10864
- tags: { deviceId },
10865
- meta: { columns: Object.keys(columns) }
10866
- });
11178
+ if (updated === 0) {
11179
+ this.logger.warn("device row patch matched no row — the device was removed under it", {
11180
+ tags: { deviceId },
11181
+ meta: { columns: Object.keys(columns) }
11182
+ });
11183
+ return;
11184
+ }
11185
+ this.observer?.rowPatched(deviceId, patch);
10867
11186
  }
10868
11187
  /**
10869
11188
  * Insert-or-update the registration columns. See {@link DeviceRegistrationRow}
@@ -10889,6 +11208,7 @@ var DeviceRowStore = class {
10889
11208
  exportFingerprint: row.exportFingerprint
10890
11209
  }
10891
11210
  });
11211
+ this.observer?.registrationWritten(row);
10892
11212
  }
10893
11213
  /** Drop the device's row. Idempotent. */
10894
11214
  /**
@@ -10988,6 +11308,7 @@ var DeviceRowStore = class {
10988
11308
  collection: DEVICE_ROWS_COLLECTION,
10989
11309
  key: String(deviceId)
10990
11310
  });
11311
+ this.observer?.rowRemoved(deviceId);
10991
11312
  }
10992
11313
  /**
10993
11314
  * The retirement door for the three blobs this collection replaced.
@@ -11174,6 +11495,41 @@ var RunningFlipDetector = class {
11174
11495
  }
11175
11496
  };
11176
11497
  //#endregion
11498
+ //#region src/builtins/device-manager/workload-transition.ts
11499
+ function readState(slice) {
11500
+ const parsed = require_dist.WorkloadStateSchema.safeParse(slice["state"]);
11501
+ return parsed.success ? parsed.data : null;
11502
+ }
11503
+ /**
11504
+ * Remembers each workload's last SETTLED state (running, paused, stopped,
11505
+ * crashed) and turns a move away from it into the cap's events. `starting` /
11506
+ * `stopping` and an unknown state are never remembered, so stopped → starting →
11507
+ * running is one `started`, and crashed → starting → running one `recovered`.
11508
+ *
11509
+ * The first state seen for a device is a seed: it raises nothing, so a hub
11510
+ * restart does not announce every running container as started.
11511
+ */
11512
+ var WorkloadTransitionDetector = class {
11513
+ #settled = /* @__PURE__ */ new Map();
11514
+ note(deviceId, slice) {
11515
+ const state = readState(slice);
11516
+ const previous = this.#settled.get(deviceId);
11517
+ const kind = require_dist.workloadTransition(previous, state);
11518
+ if (state !== null && require_dist.isWorkloadSettled(state)) this.#settled.set(deviceId, state);
11519
+ if (kind === null || state === null || previous === void 0) return null;
11520
+ return {
11521
+ kind,
11522
+ deviceId,
11523
+ state,
11524
+ previous,
11525
+ since: typeof slice["since"] === "number" && Number.isFinite(slice["since"]) ? slice["since"] : null
11526
+ };
11527
+ }
11528
+ forget(deviceId) {
11529
+ this.#settled.delete(deviceId);
11530
+ }
11531
+ };
11532
+ //#endregion
11177
11533
  //#region src/builtins/device-manager/last-active-mode.ts
11178
11534
  /**
11179
11535
  * The last mode a climate device actually RAN (D224): "turn on" needs a mode to
@@ -11765,6 +12121,7 @@ var DeviceStateMirror = class {
11765
12121
  writer;
11766
12122
  /** Edge detector for `running-state` flip events (D933). */
11767
12123
  runningFlip = new RunningFlipDetector();
12124
+ workloadTransitions = new WorkloadTransitionDetector();
11768
12125
  constructor(ctx, policyFor = require_dist.runtimeStatePolicyFor, schemaFor = defaultSchemaFor) {
11769
12126
  this.ctx = ctx;
11770
12127
  this.policyFor = policyFor;
@@ -11997,6 +12354,7 @@ var DeviceStateMirror = class {
11997
12354
  await this.seeding.get(deviceId)?.catch(() => void 0);
11998
12355
  await this.writer.forget(deviceId);
11999
12356
  this.stateMirror.delete(deviceId);
12357
+ this.workloadTransitions.forget(deviceId);
12000
12358
  this.claims.clearDevice(deviceId);
12001
12359
  this.seeded.delete(deviceId);
12002
12360
  this.rowRead.delete(deviceId);
@@ -12297,6 +12655,30 @@ var DeviceStateMirror = class {
12297
12655
  for (const deviceId of deviceIds) out[String(deviceId)] = this.snapshotForDevice(deviceId);
12298
12656
  return out;
12299
12657
  }
12658
+ /**
12659
+ * The `workload` cap's events (#585): judged from the PUBLIC slice like the
12660
+ * running flip, so a provider only writes its state. The first state seen is
12661
+ * a seed and raises nothing.
12662
+ */
12663
+ emitWorkloadTransition(deviceId, slice) {
12664
+ const transition = this.workloadTransitions.note(deviceId, slice);
12665
+ if (transition === null) return;
12666
+ this.ctx.eventBus.emit({
12667
+ id: (0, node_crypto.randomUUID)(),
12668
+ timestamp: /* @__PURE__ */ new Date(),
12669
+ source: {
12670
+ type: "device",
12671
+ id: deviceId
12672
+ },
12673
+ category: require_dist.WORKLOAD_TRANSITION_CATEGORY[transition.kind],
12674
+ data: {
12675
+ deviceId,
12676
+ state: transition.state,
12677
+ previous: transition.previous,
12678
+ since: transition.since
12679
+ }
12680
+ });
12681
+ }
12300
12682
  /** Remember a restored running bit so the first public merge does not emit a flip. */
12301
12683
  seedRunningFlip(deviceId) {
12302
12684
  const slice = this.capSlice(deviceId, RUNNING_STATE_CAP);
@@ -12327,6 +12709,7 @@ var DeviceStateMirror = class {
12327
12709
  }
12328
12710
  });
12329
12711
  }
12712
+ if (capName === require_dist.workloadCapability.name) this.emitWorkloadTransition(deviceId, slice);
12330
12713
  this.ctx.eventBus.emit({
12331
12714
  id: (0, node_crypto.randomUUID)(),
12332
12715
  timestamp: /* @__PURE__ */ new Date(),
@@ -13862,7 +14245,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
13862
14245
  };
13863
14246
  const settingsStoreApi = this.ctx.api?.settingsStore;
13864
14247
  if (!settingsStoreApi) throw new Error("[device-manager] settings-store API not available — refusing to serve a fleet it cannot persist");
13865
- const deviceRows = new DeviceRowStore(deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"));
14248
+ const identityIndex = new DeviceIdentityIndex();
14249
+ const deviceRows = new DeviceRowStore(deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
13866
14250
  await deviceRows.declare();
13867
14251
  this.deviceRows = deviceRows;
13868
14252
  const records = this.ctx.records;
@@ -13925,6 +14309,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
13925
14309
  const idToAddonId = metaStore.idToAddonId;
13926
14310
  const bootRows = await deviceRows.listAll();
13927
14311
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
14312
+ identityIndex.seed(bootRows);
13928
14313
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
13929
14314
  const templates = this.makeTemplateActions();
13930
14315
  const pctx = {
@@ -14009,6 +14394,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14009
14394
  setPrimaryChildPreference: (input) => setPrimaryChildPreference(pctx, input),
14010
14395
  setRole: (input) => setRole(pctx, input),
14011
14396
  setDisplay: (input) => setDisplay(pctx, input),
14397
+ setIdentifiers: (input) => setIdentifiers(pctx, input),
14398
+ listIdentityCandidates: async () => identityIndex.candidates(),
14012
14399
  getRoleDisplayDefaults: (input) => getRoleDisplayDefaults(pctx, input),
14013
14400
  setRoleDisplayDefaults: (input) => setRoleDisplayDefaults(pctx, input),
14014
14401
  applyInitialMeta: (input) => applyInitialMeta(pctx, input),