@camstack/server 1.2.892 → 1.2.894

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 (97) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/core/api-catalog.js +93 -0
  3. package/dist/api/core/api-catalog.router.js +74 -0
  4. package/dist/api/trpc/generated-cap-routers.js +10 -0
  5. package/dist/api/trpc/trpc.middleware.js +17 -0
  6. package/dist/api/trpc/trpc.router.js +10 -3
  7. package/package.json +16 -29
  8. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  9. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  10. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  11. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  12. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  13. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  14. package/system/dist/builtins/autotrack/index.js +1 -1
  15. package/system/dist/builtins/autotrack/index.mjs +1 -1
  16. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  17. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  18. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  19. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  20. package/system/dist/builtins/camera-grid/index.js +1 -1
  21. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  22. package/system/dist/builtins/composer/composer.addon.js +4 -4
  23. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  24. package/system/dist/builtins/console-logging/index.js +1 -1
  25. package/system/dist/builtins/console-logging/index.mjs +1 -1
  26. package/system/dist/builtins/core-blocks/core-blocks.addon.js +3 -3
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +3 -3
  28. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  29. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  30. package/system/dist/builtins/device-manager/device-identity-index.d.ts +73 -0
  31. package/system/dist/builtins/device-manager/device-manager.addon.js +308 -17
  32. package/system/dist/builtins/device-manager/device-manager.addon.mjs +308 -17
  33. package/system/dist/builtins/device-manager/device-provider-context.d.ts +5 -0
  34. package/system/dist/builtins/device-manager/device-row-store.d.ts +4 -1
  35. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +10 -0
  36. package/system/dist/builtins/device-manager/runtime-state-persist-gate.d.ts +20 -1
  37. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  38. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  39. package/system/dist/builtins/keychain/index.js +4 -4
  40. package/system/dist/builtins/keychain/index.mjs +4 -4
  41. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  42. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  43. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  44. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  45. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  46. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  47. package/system/dist/builtins/loki-logging/index.js +1 -1
  48. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  49. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  50. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  51. package/system/dist/builtins/platform-probe/index.js +1 -1
  52. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  53. package/system/dist/builtins/record-entries/index.js +1 -1
  54. package/system/dist/builtins/record-entries/index.mjs +1 -1
  55. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  56. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  57. package/system/dist/builtins/snapshot/index.js +1 -1
  58. package/system/dist/builtins/snapshot/index.mjs +1 -1
  59. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  60. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  61. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  62. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  63. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  64. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  65. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  66. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  67. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  68. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  69. package/system/dist/builtins/winston-logging/index.js +1 -1
  70. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  71. package/system/dist/{capture-engine-sl6e9f9S.mjs → capture-engine-6UsbHfRF.mjs} +1 -1
  72. package/system/dist/{capture-engine-DHmlkW_d.js → capture-engine-DhqkkOfH.js} +1 -1
  73. package/system/dist/{composition-sources-PqcZfe3j.js → composition-sources-AbyhP_uF.js} +1 -1
  74. package/system/dist/{composition-sources-CznD85Ri.mjs → composition-sources-DmDAqBqM.mjs} +1 -1
  75. package/system/dist/{constants-_2SOk0By.js → constants-CLyC9O9i.js} +1 -1
  76. package/system/dist/{constants-CHwj_mIM.mjs → constants-DMeh8SL7.mjs} +1 -1
  77. package/system/dist/{device-ca-D2H1EMUY.mjs → device-ca-BJ714blt.mjs} +1 -1
  78. package/system/dist/{device-ca-WIEO5ZcE.js → device-ca-C4odTE-a.js} +1 -1
  79. package/system/dist/{dist-yx2KHo3b.js → dist-BDciHA-9.js} +207 -25
  80. package/system/dist/{dist-DbAhCrHy.mjs → dist-DLp5CYDy.mjs} +196 -26
  81. package/system/dist/file-host-worker.js +1 -1
  82. package/system/dist/file-host-worker.mjs +1 -1
  83. package/system/dist/{hub-identity-Buegac-w.js → hub-identity-BLkehzWw.js} +1 -1
  84. package/system/dist/{hub-identity-BcvZqT0L.mjs → hub-identity-C6c6E6Xn.mjs} +1 -1
  85. package/system/dist/{hub-mdns-ciao-DcNPj7WJ.js → hub-mdns-ciao-ByOblmkT.js} +2 -2
  86. package/system/dist/{hub-mdns-ciao-B6K_dO2s.mjs → hub-mdns-ciao-oQtUklUf.mjs} +2 -2
  87. package/system/dist/index.js +8 -8
  88. package/system/dist/index.mjs +8 -8
  89. package/system/dist/{legacy-integration-rows-door-BsZyVNiR.js → legacy-integration-rows-door-CVwsY9u6.js} +1 -1
  90. package/system/dist/{legacy-integration-rows-door-DHOJeDPG.mjs → legacy-integration-rows-door-D_FBo1b1.mjs} +1 -1
  91. package/system/dist/{rename-composition-block-DcVS1LuC.mjs → rename-composition-block-CnA_Dslb.mjs} +1 -1
  92. package/system/dist/{rename-composition-block-BXMor7MR.js → rename-composition-block-_LotNQv9.js} +1 -1
  93. package/system/dist/{restore-archive-BURufVQd.js → restore-archive-CXPBPM61.js} +1 -1
  94. package/system/dist/{restore-archive-BG8VJ8Ar.mjs → restore-archive-WMuoi9Ve.mjs} +82 -82
  95. package/system/dist/{wal-maintenance-B4wGD6QR.mjs → wal-maintenance-COXWd5qA.mjs} +0 -0
  96. package/system/dist/{wal-maintenance-CeaJyKNT.js → wal-maintenance-h2cm6gDJ.js} +0 -0
  97. package/system/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import { Br as deviceHistoryCapability, Lc as RecordTooLargeError, Ol as isReadingQuantity, St as HISTORY_ITEM_CATALOG, U as DEVICE_HISTORY_ENERGY_KEY, Ur as deviceRemovalHookCapability, Wr as deviceRunsCapability, _c as DeviceTransitionSchema, bl as historyUnitFor, fl as defineRecordKinds, fu as EventCategory, lc as wattMillisecondsToKwh, lu as DeviceType, ml as emitReadiness, qr as deviceTransitionsCapability, rt as DeviceRunSchema, uc as BaseAddon, xc as InvalidRecordError, xt as HISTORY_CATALOG, zn as armRemovalReconcile } from "../../dist-DbAhCrHy.mjs";
2
- import { a as catalogMetrics, c as DeviceDirectory, d as identityOf, f as subjectIdOf, i as capSeriesKey, l as isRealDeviceType, n as CaptureEngine, o as readPath, r as capItemSeriesKey, s as readUnit, t as CAP_KEY_PREFIX, u as SeriesRegistry } from "../../capture-engine-sl6e9f9S.mjs";
1
+ import { Al as isReadingQuantity, Bn as armRemovalReconcile, Cc as InvalidRecordError, Ct as HISTORY_ITEM_CATALOG, Gr as deviceRunsCapability, Jr as deviceTransitionsCapability, Sl as historyUnitFor, St as HISTORY_CATALOG, U as DEVICE_HISTORY_ENERGY_KEY, Vr as deviceHistoryCapability, Wr as deviceRemovalHookCapability, dc as wattMillisecondsToKwh, du as DeviceType, fc as BaseAddon, gl as emitReadiness, it as DeviceRunSchema, ml as defineRecordKinds, mu as EventCategory, yc as DeviceTransitionSchema, zc as RecordTooLargeError } from "../../dist-DLp5CYDy.mjs";
2
+ import { a as catalogMetrics, c as DeviceDirectory, d as identityOf, f as subjectIdOf, i as capSeriesKey, l as isRealDeviceType, n as CaptureEngine, o as readPath, r as capItemSeriesKey, s as readUnit, t as CAP_KEY_PREFIX, u as SeriesRegistry } from "../../capture-engine-6UsbHfRF.mjs";
3
3
  import { a as FIVE_MINUTES_MS, c as bucketEndOf, i as DAY_MS, l as bucketStartOf, n as RetentionJob, o as HOUR_MS, r as DepartureTracker, s as ROLLUP_GRACE_MS, t as DEFAULT_RETENTION, u as floorTo } from "../../retention-CUOVI1p7.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  //#region src/builtins/device-history/capture/point-writer.ts
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The identifier INDEX (planning#593): identifier key → devices, so the
3
+ * device-manager can say which devices of DIFFERENT integrations share
4
+ * provider-declared identifiers (D1059) without reading the fleet per question.
5
+ *
6
+ * It is a PROJECTION of the device rows, never an authority: it holds, per
7
+ * device, only what the pair rule needs — owning addon, integration instance and
8
+ * the declared identifiers — and it moves with the rows, as the
9
+ * {@link DeviceRowObserver} of the one `DeviceRowStore`. Every write of a row
10
+ * passes through that store (`upsert`, `upsertRegistration`, `patch`, `remove`;
11
+ * `swapIds` is built of them), so a row that changes reaches the index on the
12
+ * same statement. A deleted device leaves the index on its row's DELETE — the
13
+ * statement `removeDevice` runs right before it records the tombstone (D865) —
14
+ * not on an event or on absence from a listing.
15
+ *
16
+ * It loads once, from the fleet listing the device-manager already reads at
17
+ * boot ({@link seed}). Until then it answers `unknown` (D315), never `[]`; a row
18
+ * write that lands while the snapshot is in flight is buffered and replayed over
19
+ * it, so the seed can never roll a newer write back.
20
+ *
21
+ * Read-only: it finds candidates, it links nothing (that is step 3).
22
+ */
23
+ import { type IdentityCandidates, type IdentityConfidence, type IdentityMatchedKey } from "@camstack/types";
24
+ import type { PersistedDeviceMeta } from "./device-meta-types.js";
25
+ import type { DeviceRegistrationRow, DeviceRow, DeviceRowPatch } from "./device-row-store.js";
26
+ /** What the row store tells its observer, after each statement succeeded. */
27
+ export interface DeviceRowObserver {
28
+ /** A whole row was written (`upsert`). */
29
+ rowWritten(meta: PersistedDeviceMeta): void;
30
+ /** The registration columns were written (`upsertRegistration`) — insert or update. */
31
+ registrationWritten(row: DeviceRegistrationRow): void;
32
+ /** Named columns of an existing row were written (`patch`). */
33
+ rowPatched(deviceId: number, patch: DeviceRowPatch): void;
34
+ /** The row was deleted (`remove`). */
35
+ rowRemoved(deviceId: number): void;
36
+ }
37
+ /**
38
+ * Grade the keys two devices share. `null` when they are no candidate at all
39
+ * (no strong key matched).
40
+ *
41
+ * | Matched keys | Confidence |
42
+ * | ----------------------------------------- | ------------ |
43
+ * | two strong KINDS (e.g. `mac` + `serial`) | `auto` |
44
+ * | `mac` + `ip` | `auto` |
45
+ * | exactly one strong kind | `proposal` |
46
+ * | weak keys only (`hostname`, `ip`) | no candidate |
47
+ *
48
+ * Strength counts distinct KINDS, not values: two MACs of one device matching
49
+ * the other's two MACs are one kind of evidence, so a proposal.
50
+ */
51
+ export declare function classifyIdentityMatch(keys: readonly IdentityMatchedKey[]): IdentityConfidence | null;
52
+ export declare class DeviceIdentityIndex implements DeviceRowObserver {
53
+ private readonly devices;
54
+ private readonly byKey;
55
+ /** `null` once seeded; until then, the writes to replay over the snapshot. */
56
+ private pending;
57
+ /** Load from a fleet snapshot, then replay every write that landed meanwhile. */
58
+ seed(rows: readonly DeviceRow[]): void;
59
+ rowWritten(meta: PersistedDeviceMeta): void;
60
+ registrationWritten(row: DeviceRegistrationRow): void;
61
+ rowPatched(deviceId: number, patch: DeviceRowPatch): void;
62
+ rowRemoved(deviceId: number): void;
63
+ /**
64
+ * Every cross-integration candidate pair, graded by `classifyIdentityMatch`,
65
+ * plus the devices whose identity is unknown (nothing declared).
66
+ */
67
+ candidates(): IdentityCandidates;
68
+ private pairOf;
69
+ /** True when the write was buffered for replay over a seed still in flight. */
70
+ private buffer;
71
+ private put;
72
+ private drop;
73
+ }
@@ -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-yx2KHo3b.js");
6
+ const require_dist = require("../../dist-BDciHA-9.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-BXMor7MR.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-_LotNQv9.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");
@@ -4744,7 +4744,7 @@ function compareUnranked(a, b) {
4744
4744
  if (a[2] !== b[2]) return a[2] < b[2] ? -1 : 1;
4745
4745
  return a[3] - b[3];
4746
4746
  }
4747
- function compareKeys(a, b) {
4747
+ function compareKeys$1(a, b) {
4748
4748
  if (a.length === 5 && b.length === 5) {
4749
4749
  if (a[0] !== b[0]) return a[0] - b[0];
4750
4750
  return compareUnranked([
@@ -4919,14 +4919,14 @@ async function searchDevices(deps, input) {
4919
4919
  const keyed = listed.map((c) => ({
4920
4920
  c,
4921
4921
  key: sortKeyOf(c)
4922
- })).sort((a, b) => compareKeys(a.key, b.key));
4922
+ })).sort((a, b) => compareKeys$1(a.key, b.key));
4923
4923
  const limit = Math.min(input.limit ?? 50, 200);
4924
4924
  let start = 0;
4925
4925
  if (input.cursor !== void 0 && input.cursor !== null) {
4926
4926
  const after = decodeCursor(input.cursor);
4927
4927
  if (after === null) deps.logger.warn("deviceManager.search: undecodable cursor — restarting from the first page");
4928
4928
  else {
4929
- const next = keyed.findIndex((k) => compareKeys(k.key, after) > 0);
4929
+ const next = keyed.findIndex((k) => compareKeys$1(k.key, after) > 0);
4930
4930
  start = next === -1 ? keyed.length : next;
4931
4931
  }
4932
4932
  }
@@ -8326,8 +8326,7 @@ async function loadRuntimeState(pctx, input) {
8326
8326
  const { deviceId } = input;
8327
8327
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) return {};
8328
8328
  const data = await pctx.settings.readDeviceRuntimeState(deviceId);
8329
- pctx.host.seedMirror(deviceId, pctx.host.withResetSessionProbe(data));
8330
- return splitRuntimeBlob(data).native;
8329
+ return splitRuntimeBlob(pctx.host.seedMirrorFromRow(deviceId, data, pctx.settings)).native;
8331
8330
  }
8332
8331
  /**
8333
8332
  * Union of (1) operator-curated location registry and (2) labels
@@ -8898,6 +8897,214 @@ async function setIdentifiers(pctx, input) {
8898
8897
  });
8899
8898
  }
8900
8899
  //#endregion
8900
+ //#region src/builtins/device-manager/device-identity-index.ts
8901
+ /**
8902
+ * The identifier INDEX (planning#593): identifier key → devices, so the
8903
+ * device-manager can say which devices of DIFFERENT integrations share
8904
+ * provider-declared identifiers (D1059) without reading the fleet per question.
8905
+ *
8906
+ * It is a PROJECTION of the device rows, never an authority: it holds, per
8907
+ * device, only what the pair rule needs — owning addon, integration instance and
8908
+ * the declared identifiers — and it moves with the rows, as the
8909
+ * {@link DeviceRowObserver} of the one `DeviceRowStore`. Every write of a row
8910
+ * passes through that store (`upsert`, `upsertRegistration`, `patch`, `remove`;
8911
+ * `swapIds` is built of them), so a row that changes reaches the index on the
8912
+ * same statement. A deleted device leaves the index on its row's DELETE — the
8913
+ * statement `removeDevice` runs right before it records the tombstone (D865) —
8914
+ * not on an event or on absence from a listing.
8915
+ *
8916
+ * It loads once, from the fleet listing the device-manager already reads at
8917
+ * boot ({@link seed}). Until then it answers `unknown` (D315), never `[]`; a row
8918
+ * write that lands while the snapshot is in flight is buffered and replayed over
8919
+ * it, so the seed can never roll a newer write back.
8920
+ *
8921
+ * Read-only: it finds candidates, it links nothing (that is step 3).
8922
+ */
8923
+ /** The `kind=value` keys of one declaration. */
8924
+ function keysOf(identifiers) {
8925
+ if (identifiers === null) return [];
8926
+ const out = [];
8927
+ for (const kind of require_dist.DEVICE_IDENTIFIER_KEYS) {
8928
+ const entry = identifiers[kind];
8929
+ if (entry === void 0) continue;
8930
+ for (const e of [entry].flat()) out.push(`${kind}=${e.value}`);
8931
+ }
8932
+ return out;
8933
+ }
8934
+ function isIdentifierKind(value) {
8935
+ return require_dist.DEVICE_IDENTIFIER_KEYS.some((k) => k === value);
8936
+ }
8937
+ function parseKey(key) {
8938
+ const at = key.indexOf("=");
8939
+ const kind = key.slice(0, at);
8940
+ return isIdentifierKind(kind) ? {
8941
+ key: kind,
8942
+ value: key.slice(at + 1)
8943
+ } : null;
8944
+ }
8945
+ /**
8946
+ * Same integration? The same instance when both carry one; otherwise — one side
8947
+ * was never stamped — the same addon. In doubt, the same: no candidate.
8948
+ */
8949
+ function sameIntegration(a, b) {
8950
+ if (a.integrationId !== null && b.integrationId !== null) return a.integrationId === b.integrationId;
8951
+ return a.addonId === b.addonId;
8952
+ }
8953
+ function sideOf(d) {
8954
+ return {
8955
+ deviceId: d.deviceId,
8956
+ addonId: d.addonId,
8957
+ integrationId: d.integrationId
8958
+ };
8959
+ }
8960
+ function compareKeys(x, y) {
8961
+ if (x.key !== y.key) return x.key < y.key ? -1 : 1;
8962
+ return x.value < y.value ? -1 : x.value > y.value ? 1 : 0;
8963
+ }
8964
+ /**
8965
+ * Grade the keys two devices share. `null` when they are no candidate at all
8966
+ * (no strong key matched).
8967
+ *
8968
+ * | Matched keys | Confidence |
8969
+ * | ----------------------------------------- | ------------ |
8970
+ * | two strong KINDS (e.g. `mac` + `serial`) | `auto` |
8971
+ * | `mac` + `ip` | `auto` |
8972
+ * | exactly one strong kind | `proposal` |
8973
+ * | weak keys only (`hostname`, `ip`) | no candidate |
8974
+ *
8975
+ * Strength counts distinct KINDS, not values: two MACs of one device matching
8976
+ * the other's two MACs are one kind of evidence, so a proposal.
8977
+ */
8978
+ function classifyIdentityMatch(keys) {
8979
+ const kinds = new Set(keys.map((k) => k.key));
8980
+ const strongKinds = [...kinds].filter((kind) => require_dist.identifierStrength(kind) === "strong");
8981
+ if (strongKinds.length === 0) return null;
8982
+ if (strongKinds.length >= 2) return "auto";
8983
+ if (kinds.has("mac") && kinds.has("ip")) return "auto";
8984
+ return "proposal";
8985
+ }
8986
+ var DeviceIdentityIndex = class {
8987
+ devices = /* @__PURE__ */ new Map();
8988
+ byKey = /* @__PURE__ */ new Map();
8989
+ /** `null` once seeded; until then, the writes to replay over the snapshot. */
8990
+ pending = [];
8991
+ /** Load from a fleet snapshot, then replay every write that landed meanwhile. */
8992
+ seed(rows) {
8993
+ const buffered = this.pending ?? [];
8994
+ this.pending = null;
8995
+ this.devices.clear();
8996
+ this.byKey.clear();
8997
+ for (const row of rows) this.rowWritten(row.meta);
8998
+ for (const write of buffered) write(this);
8999
+ }
9000
+ rowWritten(meta) {
9001
+ if (this.buffer((i) => i.rowWritten(meta))) return;
9002
+ this.put({
9003
+ deviceId: meta.id,
9004
+ addonId: meta.addonId,
9005
+ integrationId: meta.integrationId ?? null,
9006
+ identifiers: meta.identifiers ?? null
9007
+ });
9008
+ }
9009
+ registrationWritten(row) {
9010
+ if (this.buffer((i) => i.registrationWritten(row))) return;
9011
+ const existing = this.devices.get(row.deviceId);
9012
+ this.put({
9013
+ deviceId: row.deviceId,
9014
+ addonId: row.addonId,
9015
+ integrationId: existing?.integrationId ?? null,
9016
+ identifiers: existing?.identifiers ?? null
9017
+ });
9018
+ }
9019
+ rowPatched(deviceId, patch) {
9020
+ if (patch.identifiers === void 0 && patch.integrationId === void 0) return;
9021
+ if (this.buffer((i) => i.rowPatched(deviceId, patch))) return;
9022
+ const existing = this.devices.get(deviceId);
9023
+ if (existing === void 0) return;
9024
+ this.put({
9025
+ ...existing,
9026
+ ...patch.identifiers !== void 0 ? { identifiers: patch.identifiers } : {},
9027
+ ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {}
9028
+ });
9029
+ }
9030
+ rowRemoved(deviceId) {
9031
+ if (this.buffer((i) => i.rowRemoved(deviceId))) return;
9032
+ this.drop(deviceId);
9033
+ }
9034
+ /**
9035
+ * Every cross-integration candidate pair, graded by `classifyIdentityMatch`,
9036
+ * plus the devices whose identity is unknown (nothing declared).
9037
+ */
9038
+ candidates() {
9039
+ if (this.pending !== null) return {
9040
+ status: "unknown",
9041
+ reason: "the identifier index has not loaded yet"
9042
+ };
9043
+ const seen = /* @__PURE__ */ new Set();
9044
+ const pairs = [];
9045
+ for (const [key, members] of this.byKey) {
9046
+ const parsed = parseKey(key);
9047
+ if (parsed === null || require_dist.identifierStrength(parsed.key) !== "strong") continue;
9048
+ if (members.size < 2) continue;
9049
+ const sorted = [...members].sort((x, y) => x - y);
9050
+ for (let i = 0; i < sorted.length; i++) for (let j = i + 1; j < sorted.length; j++) {
9051
+ const pair = this.pairOf(sorted[i], sorted[j], seen);
9052
+ if (pair !== null) pairs.push(pair);
9053
+ }
9054
+ }
9055
+ pairs.sort((x, y) => x.a.deviceId - y.a.deviceId || x.b.deviceId - y.b.deviceId);
9056
+ return {
9057
+ status: "answered",
9058
+ pairs,
9059
+ undeclaredDeviceIds: [...this.devices.values()].filter((d) => d.identifiers === null).map((d) => d.deviceId).sort((x, y) => x - y)
9060
+ };
9061
+ }
9062
+ pairOf(idA, idB, seen) {
9063
+ if (idA === void 0 || idB === void 0) return null;
9064
+ const tag = `${idA}/${idB}`;
9065
+ if (seen.has(tag)) return null;
9066
+ seen.add(tag);
9067
+ const a = this.devices.get(idA);
9068
+ const b = this.devices.get(idB);
9069
+ if (a === void 0 || b === void 0 || sameIntegration(a, b)) return null;
9070
+ const bKeys = new Set(keysOf(b.identifiers));
9071
+ const keys = keysOf(a.identifiers).filter((k) => bKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9072
+ const confidence = classifyIdentityMatch(keys);
9073
+ return confidence === null ? null : {
9074
+ a: sideOf(a),
9075
+ b: sideOf(b),
9076
+ keys,
9077
+ confidence
9078
+ };
9079
+ }
9080
+ /** True when the write was buffered for replay over a seed still in flight. */
9081
+ buffer(write) {
9082
+ if (this.pending === null) return false;
9083
+ this.pending.push(write);
9084
+ return true;
9085
+ }
9086
+ put(device) {
9087
+ this.drop(device.deviceId);
9088
+ this.devices.set(device.deviceId, device);
9089
+ for (const key of keysOf(device.identifiers)) {
9090
+ const members = this.byKey.get(key) ?? /* @__PURE__ */ new Set();
9091
+ members.add(device.deviceId);
9092
+ this.byKey.set(key, members);
9093
+ }
9094
+ }
9095
+ drop(deviceId) {
9096
+ const existing = this.devices.get(deviceId);
9097
+ if (existing === void 0) return;
9098
+ this.devices.delete(deviceId);
9099
+ for (const key of keysOf(existing.identifiers)) {
9100
+ const members = this.byKey.get(key);
9101
+ if (members === void 0) continue;
9102
+ members.delete(deviceId);
9103
+ if (members.size === 0) this.byKey.delete(key);
9104
+ }
9105
+ }
9106
+ };
9107
+ //#endregion
8901
9108
  //#region src/builtins/device-manager/linked-devices-manual-backfill.ts
8902
9109
  var LINKED_MANUAL_BACKFILL_MARKER_KEY = "_linkedDevicesManualBackfillVersion";
8903
9110
  function planManualBackfill(params) {
@@ -10652,6 +10859,7 @@ function encodeDeviceRowPatch(patch) {
10652
10859
  var DeviceRowStore = class {
10653
10860
  backend;
10654
10861
  logger;
10862
+ observer;
10655
10863
  declared = null;
10656
10864
  /** Call-site attribution for fleet reads. Armed only by
10657
10865
  * `CAMSTACK_FLEET_READ_CENSUS_MS`; see `fleet-read-census.ts`. */
@@ -10666,9 +10874,10 @@ var DeviceRowStore = class {
10666
10874
  get censusArmed() {
10667
10875
  return this.census.armed;
10668
10876
  }
10669
- constructor(backend, logger, census) {
10877
+ constructor(backend, logger, census, observer) {
10670
10878
  this.backend = backend;
10671
10879
  this.logger = logger;
10880
+ this.observer = observer;
10672
10881
  this.census = census ?? new FleetReadCensus(process.env["CAMSTACK_FLEET_READ_CENSUS_MS"], Date.now());
10673
10882
  if (this.census.armed) {
10674
10883
  const startedAt = Date.now();
@@ -10943,6 +11152,7 @@ var DeviceRowStore = class {
10943
11152
  key: String(meta.id),
10944
11153
  value: encodeDeviceRow(meta, extra)
10945
11154
  });
11155
+ this.observer?.rowWritten(meta);
10946
11156
  }
10947
11157
  /**
10948
11158
  * Write the named columns of an EXISTING row and nothing else.
@@ -10964,10 +11174,14 @@ var DeviceRowStore = class {
10964
11174
  filter: { where: { id: String(deviceId) } },
10965
11175
  data: columns
10966
11176
  });
10967
- if (updated === 0) this.logger.warn("device row patch matched no row — the device was removed under it", {
10968
- tags: { deviceId },
10969
- meta: { columns: Object.keys(columns) }
10970
- });
11177
+ if (updated === 0) {
11178
+ this.logger.warn("device row patch matched no row — the device was removed under it", {
11179
+ tags: { deviceId },
11180
+ meta: { columns: Object.keys(columns) }
11181
+ });
11182
+ return;
11183
+ }
11184
+ this.observer?.rowPatched(deviceId, patch);
10971
11185
  }
10972
11186
  /**
10973
11187
  * Insert-or-update the registration columns. See {@link DeviceRegistrationRow}
@@ -10993,6 +11207,7 @@ var DeviceRowStore = class {
10993
11207
  exportFingerprint: row.exportFingerprint
10994
11208
  }
10995
11209
  });
11210
+ this.observer?.registrationWritten(row);
10996
11211
  }
10997
11212
  /** Drop the device's row. Idempotent. */
10998
11213
  /**
@@ -11092,6 +11307,7 @@ var DeviceRowStore = class {
11092
11307
  collection: DEVICE_ROWS_COLLECTION,
11093
11308
  key: String(deviceId)
11094
11309
  });
11310
+ this.observer?.rowRemoved(deviceId);
11095
11311
  }
11096
11312
  /**
11097
11313
  * The retirement door for the three blobs this collection replaced.
@@ -11376,17 +11592,62 @@ function persistableBlob(blob, policyFor) {
11376
11592
  /**
11377
11593
  * The part of a `restored` slice that may live on disk (D1024). A cap that
11378
11594
  * names `restoredFields` keeps only those; every other restored cap keeps the
11379
- * whole slice. One function for both directions — what is written and what the
11595
+ * whole slice; a renamed field is read under its new name. One function for both directions — what is written and what the
11380
11596
  * boot seed reads back — so the two cannot drift.
11381
11597
  */
11382
11598
  function restoredPart(slice, policy) {
11599
+ const current = withRenamedFields(slice, policy.renamedFields);
11383
11600
  const names = policy.restoredFields;
11384
- if (names === void 0) return { ...slice };
11601
+ if (names === void 0) return current;
11385
11602
  const out = {};
11386
- for (const name of names) if (name in slice) out[name] = slice[name];
11603
+ for (const name of names) if (name in current) out[name] = current[name];
11387
11604
  return out;
11388
11605
  }
11389
11606
  /**
11607
+ * A field the cap renamed (`restoredFieldRenames`, #459): a row persisted
11608
+ * before the rename carries the OLD key. It is read once into the new name —
11609
+ * only when the new one is absent, a value under the new name always wins — and
11610
+ * dropped, so no reader of the mirror ever meets the old key.
11611
+ */
11612
+ function withRenamedFields(slice, renames) {
11613
+ const out = { ...slice };
11614
+ if (renames === void 0) return out;
11615
+ for (const [from, to] of Object.entries(renames)) {
11616
+ if (!(from in out)) continue;
11617
+ if (!(to in out)) out[to] = out[from];
11618
+ delete out[from];
11619
+ }
11620
+ return out;
11621
+ }
11622
+ /**
11623
+ * Read a whole stored row under the current field names (`restoredFieldRenames`).
11624
+ * Only the renames are applied — nothing is trimmed — so the worker that loads
11625
+ * the row is handed the same fields it would have got, under their new names.
11626
+ * `renamed` names the slices that still carry an old key on disk: the row must
11627
+ * be rewritten once, or the rename could never be retired.
11628
+ */
11629
+ function upgradeRenamedFields(row, policyFor) {
11630
+ const blob = { ...row };
11631
+ const renamed = [];
11632
+ for (const [capName, slice] of Object.entries(row)) {
11633
+ if (capName === "$owned" || !isPlainRecord(slice)) continue;
11634
+ const renames = policyFor(capName).renamedFields;
11635
+ if (renames === void 0) continue;
11636
+ const legacy = {};
11637
+ for (const from of Object.keys(renames)) if (from in slice) legacy[from] = slice[from];
11638
+ if (Object.keys(legacy).length === 0) continue;
11639
+ blob[capName] = withRenamedFields(slice, renames);
11640
+ renamed.push({
11641
+ capName,
11642
+ legacy
11643
+ });
11644
+ }
11645
+ return {
11646
+ blob,
11647
+ renamed
11648
+ };
11649
+ }
11650
+ /**
11390
11651
  * Are two slices the same, ignoring the fields the cap declared volatile?
11391
11652
  *
11392
11653
  * A volatile field is still WRITTEN — it simply does not, on its own, justify
@@ -12216,7 +12477,7 @@ var DeviceStateMirror = class {
12216
12477
  const read = (async () => {
12217
12478
  try {
12218
12479
  const row = await settings.readDeviceRuntimeState(deviceId);
12219
- this.seedMirror(deviceId, this.withResetSessionProbe(row));
12480
+ this.seedMirrorFromRow(deviceId, row, settings);
12220
12481
  this.seedRefusalLogged.delete(deviceId);
12221
12482
  } catch (err) {
12222
12483
  if (!this.seedRefusalLogged.has(deviceId)) {
@@ -12336,6 +12597,32 @@ var DeviceStateMirror = class {
12336
12597
  this.writer.markPersisted(deviceId, persistableBlob(joinRuntimeBlob(split.native, split.owned, this.policyFor), this.policyFor));
12337
12598
  }
12338
12599
  /**
12600
+ * Seed from the device's STORED row (`fill`), and return the row read under
12601
+ * the current field names. A row that still carries a field under its
12602
+ * pre-rename name (`restoredFieldRenames`) is rewritten once: the baseline
12603
+ * keeps the old key — that is what disk holds — so the write is not skipped
12604
+ * as already persisted, and a write is armed even if nothing else changes.
12605
+ * Without it the old key would stay on disk and the rename could never be
12606
+ * retired.
12607
+ */
12608
+ seedMirrorFromRow(deviceId, row, settings) {
12609
+ const upgraded = upgradeRenamedFields(row, this.policyFor);
12610
+ this.seedMirror(deviceId, this.withResetSessionProbe(upgraded.blob));
12611
+ if (upgraded.renamed.length === 0) return upgraded.blob;
12612
+ const baseline = { ...this.writer.persisted(deviceId) };
12613
+ for (const { capName, legacy } of upgraded.renamed) baseline[capName] = {
12614
+ ...baseline[capName],
12615
+ ...legacy
12616
+ };
12617
+ this.writer.markPersisted(deviceId, baseline);
12618
+ this.ctx.logger.info("stored runtime state carries a renamed field — rewriting the row once", {
12619
+ tags: { deviceId },
12620
+ meta: { caps: upgraded.renamed.map((r) => r.capName) }
12621
+ });
12622
+ this.writer.armOrHold(deviceId, settings);
12623
+ return upgraded.blob;
12624
+ }
12625
+ /**
12339
12626
  * The hub mirror's `feature-probe.lastProbedAt` is a PER-SESSION liveness
12340
12627
  * signal — it means "this worker process completed a probe THIS session".
12341
12628
  * Persisted runtime state carries the PRE-RESTART timestamp, which is stale
@@ -13791,6 +14078,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
13791
14078
  },
13792
14079
  remoteNativeCaps: this.remoteNativeCaps,
13793
14080
  seedMirror: (deviceId, blob, mode) => this.stateMirror.seedMirror(deviceId, blob, mode),
14081
+ seedMirrorFromRow: (deviceId, row, settings) => this.stateMirror.seedMirrorFromRow(deviceId, row, settings),
13794
14082
  withResetSessionProbe: (blob) => this.stateMirror.withResetSessionProbe(blob),
13795
14083
  get fieldClaims() {
13796
14084
  return fieldClaims();
@@ -14028,7 +14316,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14028
14316
  };
14029
14317
  const settingsStoreApi = this.ctx.api?.settingsStore;
14030
14318
  if (!settingsStoreApi) throw new Error("[device-manager] settings-store API not available — refusing to serve a fleet it cannot persist");
14031
- const deviceRows = new DeviceRowStore(deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"));
14319
+ const identityIndex = new DeviceIdentityIndex();
14320
+ const deviceRows = new DeviceRowStore(deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
14032
14321
  await deviceRows.declare();
14033
14322
  this.deviceRows = deviceRows;
14034
14323
  const records = this.ctx.records;
@@ -14091,6 +14380,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14091
14380
  const idToAddonId = metaStore.idToAddonId;
14092
14381
  const bootRows = await deviceRows.listAll();
14093
14382
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
14383
+ identityIndex.seed(bootRows);
14094
14384
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
14095
14385
  const templates = this.makeTemplateActions();
14096
14386
  const pctx = {
@@ -14176,6 +14466,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14176
14466
  setRole: (input) => setRole(pctx, input),
14177
14467
  setDisplay: (input) => setDisplay(pctx, input),
14178
14468
  setIdentifiers: (input) => setIdentifiers(pctx, input),
14469
+ listIdentityCandidates: async () => identityIndex.candidates(),
14179
14470
  getRoleDisplayDefaults: (input) => getRoleDisplayDefaults(pctx, input),
14180
14471
  setRoleDisplayDefaults: (input) => setRoleDisplayDefaults(pctx, input),
14181
14472
  applyInitialMeta: (input) => applyInitialMeta(pctx, input),