@camstack/server 1.2.899 → 1.2.900

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 (100) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/api/trpc/generated-cap-routers.js +50 -0
  3. package/package.json +10 -9
  4. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  5. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  6. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  7. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  8. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  9. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  10. package/system/dist/builtins/autotrack/index.js +1 -1
  11. package/system/dist/builtins/autotrack/index.mjs +1 -1
  12. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  13. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  14. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  15. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  16. package/system/dist/builtins/camera-grid/index.js +1 -1
  17. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  18. package/system/dist/builtins/composer/composer.addon.js +4 -4
  19. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  20. package/system/dist/builtins/console-logging/index.js +1 -1
  21. package/system/dist/builtins/console-logging/index.mjs +1 -1
  22. package/system/dist/builtins/core-blocks/composition-api.d.ts +37 -1
  23. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +14 -0
  24. package/system/dist/builtins/core-blocks/core-blocks.addon.js +516 -7
  25. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +516 -7
  26. package/system/dist/builtins/core-blocks/link-contributions.d.ts +85 -0
  27. package/system/dist/builtins/core-blocks/power-source-service.d.ts +25 -1
  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-identifiers-action.d.ts +8 -0
  31. package/system/dist/builtins/device-manager/device-identity-index.d.ts +56 -2
  32. package/system/dist/builtins/device-manager/device-manager.addon.js +625 -62
  33. package/system/dist/builtins/device-manager/device-manager.addon.mjs +624 -61
  34. package/system/dist/builtins/device-manager/device-meta-types.d.ts +9 -1
  35. package/system/dist/builtins/device-manager/device-provider-context.d.ts +3 -0
  36. package/system/dist/builtins/device-manager/device-row-store.d.ts +4 -2
  37. package/system/dist/builtins/device-manager/identity-link-reconciler.d.ts +66 -0
  38. package/system/dist/builtins/device-manager/identity-links-store.d.ts +22 -0
  39. package/system/dist/builtins/device-manager/record-kinds.d.ts +2 -1
  40. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  41. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  42. package/system/dist/builtins/keychain/index.js +4 -4
  43. package/system/dist/builtins/keychain/index.mjs +4 -4
  44. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  45. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  46. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  47. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  48. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  49. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  50. package/system/dist/builtins/loki-logging/index.js +1 -1
  51. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  52. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  53. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  54. package/system/dist/builtins/platform-probe/index.js +1 -1
  55. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  56. package/system/dist/builtins/record-entries/index.js +1 -1
  57. package/system/dist/builtins/record-entries/index.mjs +1 -1
  58. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  59. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  60. package/system/dist/builtins/snapshot/index.js +1 -1
  61. package/system/dist/builtins/snapshot/index.mjs +1 -1
  62. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  63. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  64. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  65. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  67. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  68. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  69. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  70. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  71. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  72. package/system/dist/builtins/winston-logging/index.js +1 -1
  73. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  74. package/system/dist/{capture-engine-LHKTf-nM.js → capture-engine-B3csK2sW.js} +1 -1
  75. package/system/dist/{capture-engine-BcD6iCZM.mjs → capture-engine-CCAzcezv.mjs} +1 -1
  76. package/system/dist/{composition-sources-C3ARJk2g.mjs → composition-sources-BX7u-Hdf.mjs} +1 -1
  77. package/system/dist/{composition-sources-DNUDbuXy.js → composition-sources-Bkbk5Oh5.js} +1 -1
  78. package/system/dist/{constants-dL8fl9aI.js → constants-BqxCksdV.js} +1 -1
  79. package/system/dist/{constants-er38mZOb.mjs → constants-_bOm_ae5.mjs} +1 -1
  80. package/system/dist/{device-ca-Ccz5olgH.mjs → device-ca-DRqN1P5Y.mjs} +1 -1
  81. package/system/dist/{device-ca-KWa6uJRU.js → device-ca-KNx_DazP.js} +1 -1
  82. package/system/dist/{dist-DEAjZE_-.js → dist-BNrIzdrJ.js} +351 -7
  83. package/system/dist/{dist-DBanWvHF.mjs → dist-S-zGcCEr.mjs} +310 -8
  84. package/system/dist/file-host-worker.js +1 -1
  85. package/system/dist/file-host-worker.mjs +1 -1
  86. package/system/dist/{hub-identity-CVv79TVO.mjs → hub-identity-DSdbZxeR.mjs} +1 -1
  87. package/system/dist/{hub-identity-Dy8ZSUuq.js → hub-identity-pN0LtUhx.js} +1 -1
  88. package/system/dist/{hub-mdns-ciao-C_XjO7YI.js → hub-mdns-ciao-GafEbDm8.js} +2 -2
  89. package/system/dist/{hub-mdns-ciao-DtmIyWDL.mjs → hub-mdns-ciao-wAcv5VBY.mjs} +2 -2
  90. package/system/dist/index.js +8 -8
  91. package/system/dist/index.mjs +8 -8
  92. package/system/dist/{legacy-integration-rows-door-BL8T4lya.mjs → legacy-integration-rows-door--186Wij_.mjs} +1 -1
  93. package/system/dist/{legacy-integration-rows-door-DPInWtE6.js → legacy-integration-rows-door-B1swGb0r.js} +1 -1
  94. package/system/dist/{rename-composition-block-Dgo-9-Ts.mjs → rename-composition-block-Cf5syiM4.mjs} +1 -1
  95. package/system/dist/{rename-composition-block-BxzETYOf.js → rename-composition-block-gJ_4GdHr.js} +1 -1
  96. package/system/dist/{restore-archive-BUtuNTe1.mjs → restore-archive-D7UwwT1L.mjs} +1 -1
  97. package/system/dist/{restore-archive-Zvx9sHZP.js → restore-archive-DXi9iBay.js} +1 -1
  98. package/system/dist/{wal-maintenance-DS2IKwtK.js → wal-maintenance-BA9XNPvt.js} +0 -0
  99. package/system/dist/{wal-maintenance-cASt_sYy.mjs → wal-maintenance-s3KdED98.mjs} +0 -0
  100. package/system/package.json +1 -1
@@ -1,7 +1,7 @@
1
- import { $ as DEVICE_TEMPLATE_VALUES_CAP, $i as legacyAutoLinkIds, Al as isCommand$1, An as WORKLOAD_TRANSITION_CATEGORY, As as workloadCapability, Bl as isSecretMarkerLike, C as COMMAND_BURST_OFFSETS_MS, Fl as isKeychainStoredField, Gr as deviceOffersActions, Gs as capAppliesToDeviceKind, Hi as isEmptyIdentifiers, Ho as settleDeviceFeatures, Hr as deviceExtensionCapability, Ia as parseStreamParamsFormPatch, Jc as SECRET_CLEAR, Jo as siteZoneKey, Jt as PUSH_CONFIRM_WINDOW_MS, Ll as isSecretClear, Lr as defineExtensionSlotProvider, Lt as MINUTES_PER_DAY, Ml as isDeviceConfigCap, Mo as runtimeStatePolicyFor, No as sameIdentifiers, Oa as normalizeTags, Oi as identifierStrength, Oo as resolveTemplateRef, Qr as effectiveRefreshIntervalMs, Ro as searchRank, Si as generateDeviceAlias, W as DEVICE_IDENTIFIER_KEYS, Wi as isKernelDerivedFeature, Wr as deviceManagerCapability, Ws as canonicalStoredDeviceType, X as DEVICE_TEMPLATE_MAX_LENGTH, Xr as deviceStatusCapability, Y as DEVICE_TEMPLATE_FILTERS, Yi as isWorkloadSettled, Yr as deviceStateCapability, Z as DEVICE_TEMPLATE_MAX_OUTPUT, _a as mergeIdentifiers, _u as DeviceType$1, aa as locationIconKey, ac as implementedMethodsOf$1, at as DeviceStatusSchema, bl as defineRecordKinds, bt as FieldClaimSchema, bu as EventCategory$1, cr as checkDeviceAlias, cu as toSecretFieldView, dn as STREAM_PROFILE_META, dt as ExportNameRefusedError, du as vocabActionIdFor, ei as enumerateItemArrayFields, el as WELL_KNOWN_TAB_MAP, er as buildStreamParamsConfigSchema, eu as resolveSecretMarkers, fl as collectZodSecretPaths$1, go as resolveCommandHold, gu as DeviceRole, hu as DeviceFeature, ir as canonicalIconKey, j as ConditionMirror, jn as WorkloadStateSchema, jo as runtimeFieldUnit, js as workloadTransition, ka as normalizeUnit, kr as createDeviceExtensionProvider, li as extractSourceInfoFromMetadata, lu as transformSecretWrite, oi as expandContainer, ot as DeviceTombstoneSchema, ou as sleep$2, pl as commandEffect, rt as DeviceIdentifiersSchema, ru as secretTreeFromPaths, s as ALL_CAPABILITY_DEFINITIONS, sl as auditedFields, st as DiscoveryProposalBodySchema, ti as enumerateSchemaFields, to as reconcileReportedFeatures, uu as userError, vc as BaseAddon, vu as errMsg$1, wl as expandCapMethods$1, x as CAP_NAMES_WITH_STATUS, y as CAMERA_SWITCH_ORDER, yi as formatMinutes, yt as FieldClaimModeSchema, z as DAY_NAMES, zl as isSecretMarker } from "../../dist-DBanWvHF.mjs";
1
+ import { $ as DEVICE_TEMPLATE_VALUES_CAP, $r as deviceStatusCapability, Bo as sameIdentifiers, Br as defineExtensionSlotProvider, Bt as MINUTES_PER_DAY, C as COMMAND_BURST_OFFSETS_MS, Co as resolveCommandHold, Cu as DeviceRole, Dl as defineRecordKinds, Du as EventCategory$1, Fa as normalizeUnit, Fo as resolveTemplateRef, Go as searchRank, Gr as deviceExtensionCapability, Ha as parseStreamParamsFormPatch, Hl as isKeychainStoredField, Jr as deviceOffersActions, Kl as isSecretMarker, Ll as isCommand$1, Ls as workloadCapability, Mi as identityLinkId, Mr as createDeviceExtensionProvider, Mt as IdentityLinkBodySchema, Ni as identityLinkSidesRefusal, Nn as WORKLOAD_TRANSITION_CATEGORY, Pa as normalizeTags, Pn as WorkloadStateSchema, Qr as deviceStateCapability, Qs as capAppliesToDeviceKind, Ro as runtimeFieldUnit, Rs as workloadTransition, Sa as mergeIdentifiers, Si as formatMinutes, Su as DeviceFeature, Tc as BaseAddon, Ti as generateDeviceAlias, Tu as errMsg$1, W as DEVICE_IDENTIFIER_KEYS, Wl as isSecretClear, X as DEVICE_TEMPLATE_MAX_LENGTH, Y as DEVICE_TEMPLATE_FILTERS, Yi as isKernelDerivedFeature, Yo as settleDeviceFeatures, Z as DEVICE_TEMPLATE_MAX_OUTPUT, Zs as canonicalStoredDeviceType, Zt as PUSH_CONFIRM_WINDOW_MS, _u as userError, bl as commandEffect, bt as FieldClaimModeSchema, ct as DiscoveryProposalBodySchema, dr as checkDeviceAlias, ea as isWorkloadSettled, fc as implementedMethodsOf$1, fi as extractSourceInfoFromMetadata, ft as ExportNameRefusedError, gu as transformSecretWrite, hu as toSecretFieldView, ia as legacyAutoLinkIds, ii as enumerateSchemaFields, it as DeviceIdentifiersSchema, j as ConditionMirror, ji as identifierStrength, jl as expandCapMethods$1, li as expandContainer, ml as auditedFields, mn as STREAM_PROFILE_META, ot as DeviceStatusSchema, pu as sleep$2, qi as isEmptyIdentifiers, ql as isSecretMarkerLike, qr as deviceManagerCapability, ri as enumerateItemArrayFields, rr as buildStreamParamsConfigSchema, rt as DeviceIdentifierKeySchema, s as ALL_CAPABILITY_DEFINITIONS, sl as WELL_KNOWN_TAB_MAP, so as reconcileReportedFeatures, sr as canonicalIconKey, st as DeviceTombstoneSchema, su as resolveSecretMarkers, ti as effectiveRefreshIntervalMs, tl as SECRET_CLEAR, ts as siteZoneKey, ua as locationIconKey, uu as secretTreeFromPaths, vu as vocabActionIdFor, wu as DeviceType$1, x as CAP_NAMES_WITH_STATUS, xt as FieldClaimSchema, y as CAMERA_SWITCH_ORDER, yl as collectZodSecretPaths$1, z as DAY_NAMES, zl as isDeviceConfigCap, zo as runtimeStatePolicyFor } from "../../dist-S-zGcCEr.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
3
  import { a as redactLogText, i as redactLogMeta, n as isSecretArgumentKey } from "../../log-redactor-XLDrPzOi.mjs";
4
- import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-Dgo-9-Ts.mjs";
4
+ import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-Cf5syiM4.mjs";
5
5
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
6
6
  import { t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
7
7
  import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-u6xQA6r7.mjs";
@@ -479,7 +479,8 @@ function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
479
479
  ...metaRow?.primaryChildPreference !== void 0 ? { primaryChildPreference: metaRow.primaryChildPreference } : {},
480
480
  ...metaRow?.tags !== void 0 ? { tags: metaRow.tags } : {},
481
481
  ...metaRow?.display !== void 0 ? { display: metaRow.display } : {},
482
- ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {}
482
+ ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {},
483
+ ...metaRow?.attachedIdentifiers !== void 0 ? { attachedIdentifiers: metaRow.attachedIdentifiers } : {}
483
484
  };
484
485
  }
485
486
  function resolveDeviceById(registry, deviceId) {
@@ -3064,6 +3065,7 @@ async function listAll(pctx, input) {
3064
3065
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3065
3066
  ...m.display !== void 0 ? { display: m.display } : {},
3066
3067
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3068
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3067
3069
  ...(() => {
3068
3070
  if (slim) return {};
3069
3071
  const si = projectSourceInfo(persistedConfig ?? {}, stableId, aid, metadata);
@@ -3118,6 +3120,7 @@ async function getDevice(pctx, input) {
3118
3120
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3119
3121
  ...m.display !== void 0 ? { display: m.display } : {},
3120
3122
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3123
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3121
3124
  ...sourceInfoGetDevice !== void 0 ? { sourceInfo: sourceInfoGetDevice } : {}
3122
3125
  };
3123
3126
  }
@@ -3199,6 +3202,7 @@ function projectChildren(pctx, parentDeviceId, ownerAddonId, childRows, liveChil
3199
3202
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3200
3203
  ...m.display !== void 0 ? { display: m.display } : {},
3201
3204
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3205
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3202
3206
  ...sourceInfoChild !== void 0 ? { sourceInfo: sourceInfoChild } : {}
3203
3207
  });
3204
3208
  }
@@ -7495,6 +7499,10 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
7495
7499
  return (await purge(deviceId)).length;
7496
7500
  }
7497
7501
  },
7502
+ {
7503
+ store: "identity-links",
7504
+ run: async () => pctx.identityLinks === void 0 ? 0 : pctx.identityLinks.removeDevice(deviceId)
7505
+ },
7498
7506
  {
7499
7507
  store: "device-config",
7500
7508
  run: async () => {
@@ -7643,7 +7651,8 @@ async function loadMeta(pctx, input) {
7643
7651
  ...m.integrationId !== void 0 ? { integrationId: m.integrationId } : {},
7644
7652
  ...m.linkDeviceId !== void 0 ? { linkDeviceId: m.linkDeviceId } : {},
7645
7653
  ...m.role !== void 0 ? { role: m.role } : {},
7646
- ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {}
7654
+ ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
7655
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {}
7647
7656
  };
7648
7657
  }
7649
7658
  /**
@@ -8832,20 +8841,41 @@ function stampedCaller(input) {
8832
8841
  const raw = Reflect.get(Object(input), "callerAddonId");
8833
8842
  return typeof raw === "string" && raw.length > 0 ? raw : null;
8834
8843
  }
8844
+ var METHOD_OF = {
8845
+ identifiers: "setIdentifiers",
8846
+ attachedIdentifiers: "setAttachedIdentifiers"
8847
+ };
8835
8848
  async function setIdentifiers(pctx, input) {
8849
+ return writeDeclaredIdentity(pctx, input, "identifiers");
8850
+ }
8851
+ /**
8852
+ * `device-manager.setAttachedIdentifiers` (D1063): the identity of the device at
8853
+ * the far end of this device's physical link. Same owner check, normalisation
8854
+ * and merge as {@link setIdentifiers}, its own column.
8855
+ */
8856
+ async function setAttachedIdentifiers(pctx, input) {
8857
+ return writeDeclaredIdentity(pctx, input, "attachedIdentifiers");
8858
+ }
8859
+ /** The unread keys the merged declaration still holds, sorted: kept, not seen now. */
8860
+ function retainedKeys(merged, unread) {
8861
+ if (merged === null) return [];
8862
+ return [...new Set(unread)].filter((key) => merged[key] !== void 0).sort();
8863
+ }
8864
+ async function writeDeclaredIdentity(pctx, input, column) {
8865
+ const method = METHOD_OF[column];
8836
8866
  const { deviceId } = input;
8837
8867
  const logger = pctx.host.ctx.logger;
8838
8868
  const caller = stampedCaller(input);
8839
8869
  const parsed = DeviceIdentifiersSchema.nullable().safeParse(input.identifiers);
8840
8870
  if (!parsed.success) {
8841
- logger.warn("setIdentifiers refused — the declaration is not in its normalised form", {
8871
+ logger.warn(`${method} refused — the declaration is not in its normalised form`, {
8842
8872
  tags: { deviceId },
8843
8873
  meta: {
8844
8874
  caller,
8845
8875
  issues: parsed.error.issues.map((i) => i.path.join("."))
8846
8876
  }
8847
8877
  });
8848
- throw new SetIdentifiersRefusedError("invalid", `[device-manager] setIdentifiers: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8878
+ throw new SetIdentifiersRefusedError("invalid", `[device-manager] ${method}: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8849
8879
  }
8850
8880
  const next = parsed.data === null || isEmptyIdentifiers(parsed.data) ? null : parsed.data;
8851
8881
  const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
@@ -8855,25 +8885,39 @@ async function setIdentifiers(pctx, input) {
8855
8885
  kind: "not-owner",
8856
8886
  owner: persisted.addonId
8857
8887
  };
8858
- const stored = persisted.meta.identifiers ?? null;
8888
+ const stored = persisted.meta[column] ?? null;
8859
8889
  const merged = mergeIdentifiers(stored, next, input.unread ?? []);
8860
- if (sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8861
- await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8890
+ if (column === "identifiers") {
8891
+ if (sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8892
+ await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8893
+ return {
8894
+ kind: "written",
8895
+ value: merged
8896
+ };
8897
+ }
8898
+ const retained = retainedKeys(merged, input.unread ?? []);
8899
+ const storedRetained = persisted.meta.attachedRetained ?? [];
8900
+ const sameRetained = retained.join(",") === storedRetained.join(",");
8901
+ if (sameIdentifiers(stored, merged) && sameRetained) return { kind: "unchanged" };
8902
+ await pctx.metaStore.rows.patch(deviceId, {
8903
+ attachedIdentifiers: merged,
8904
+ attachedRetained: retained.length === 0 ? null : retained
8905
+ });
8862
8906
  return {
8863
8907
  kind: "written",
8864
8908
  value: merged
8865
8909
  };
8866
8910
  });
8867
- if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] setIdentifiers: unknown device id=${deviceId}`);
8911
+ if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] ${method}: unknown device id=${deviceId}`);
8868
8912
  if (outcome.kind === "not-owner") {
8869
- logger.warn("setIdentifiers refused — only the owning provider declares identifiers", {
8913
+ logger.warn(`${method} refused — only the owning provider declares identifiers`, {
8870
8914
  tags: { deviceId },
8871
8915
  meta: {
8872
8916
  caller,
8873
8917
  owner: outcome.owner
8874
8918
  }
8875
8919
  });
8876
- throw new SetIdentifiersRefusedError("not-owner", `[device-manager] setIdentifiers: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8920
+ throw new SetIdentifiersRefusedError("not-owner", `[device-manager] ${method}: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8877
8921
  }
8878
8922
  if (outcome.kind === "unchanged") return;
8879
8923
  pctx.host.ctx.eventBus.emit({
@@ -8886,12 +8930,395 @@ async function setIdentifiers(pctx, input) {
8886
8930
  category: EventCategory$1.DeviceMetaChanged,
8887
8931
  data: {
8888
8932
  deviceId,
8889
- field: "identifiers",
8933
+ field: column,
8890
8934
  value: outcome.value
8891
8935
  }
8892
8936
  });
8893
8937
  }
8894
8938
  //#endregion
8939
+ //#region src/builtins/device-manager/identity-link-reconciler.ts
8940
+ /**
8941
+ * Turns the identity index's link candidates into `identity-links` records
8942
+ * (D1063), and serves the operator's decisions on them.
8943
+ *
8944
+ * | Situation | Result |
8945
+ * | ------------------------------------------- | ---------------------------------------------- |
8946
+ * | `auto` candidate, no row | `linked` / `auto`, `identity-link.created` |
8947
+ * | `proposal` candidate, no row | `proposed`, no event |
8948
+ * | `proposed` row, candidate now `auto` | `linked` / `auto`, created |
8949
+ * | `dismissed` row | stays dismissed: nothing re-proposes it |
8950
+ * | `linked`/`auto` row, evidence gone | row deleted, `identity-link.lost` evidence-gone |
8951
+ * | `linked`/`operator` row, evidence gone | kept, flagged `evidenceGone`, `lost` evidence-gone |
8952
+ * | `linked`/`operator` flagged, evidence back | flag cleared, `identity-link.created` |
8953
+ * | `proposed` row, evidence gone | row deleted, no event (it never linked) |
8954
+ *
8955
+ * "Evidence gone" is judged from the PERSISTED identifiers, which already keep
8956
+ * an unread value (D49): a camera rebooting, a port that read no client this
8957
+ * poll, change nothing. A flagged operator link never acts: `power-source`
8958
+ * refuses through it and core-blocks withdraws its contribution, so a fresh link
8959
+ * on another port can contribute. It waits for the operator (Unlink) or for its
8960
+ * evidence to return. A link whose side has no row right now is left alone —
8961
+ * a removed device is the `identity-links` removal step's, never a guess here.
8962
+ *
8963
+ * Runs after the seed and on every identity change the index reports,
8964
+ * coalesced: a pass already queued absorbs the next request. No timer. Every
8965
+ * write — a pass, an operator decision, a removal — runs on one chain.
8966
+ */
8967
+ var NOT_LOADED = "the identity links have not been read yet";
8968
+ function sameEvidence(x, y) {
8969
+ return JSON.stringify(x) === JSON.stringify(y);
8970
+ }
8971
+ function sameSide(x, y) {
8972
+ return x.deviceId === y.deviceId && x.addonId === y.addonId && x.stableId === y.stableId;
8973
+ }
8974
+ function payloadOf(link, reason) {
8975
+ return {
8976
+ linkId: link.id,
8977
+ kind: link.kind,
8978
+ aDeviceId: link.a.deviceId,
8979
+ bDeviceId: link.b.deviceId,
8980
+ origin: link.origin,
8981
+ ...reason !== void 0 ? { reason } : {}
8982
+ };
8983
+ }
8984
+ var IdentityLinkReconciler = class {
8985
+ deps;
8986
+ tail = Promise.resolve();
8987
+ passQueued = false;
8988
+ now;
8989
+ constructor(deps) {
8990
+ this.deps = deps;
8991
+ this.now = deps.now ?? (() => Date.now());
8992
+ }
8993
+ /** Queue one pass; a pass already queued (not started) absorbs this request. */
8994
+ requestPass() {
8995
+ if (this.passQueued) return;
8996
+ this.passQueued = true;
8997
+ this.serialized(async () => {
8998
+ this.passQueued = false;
8999
+ await this.pass();
9000
+ }).catch((err) => {
9001
+ this.deps.logger.warn("identity-link pass failed — the next identity change retries", { meta: { error: errMsg$1(err) } });
9002
+ });
9003
+ }
9004
+ /** Resolves when every queued write has run (tests, boot). */
9005
+ async settled() {
9006
+ await this.serialized(async () => void 0);
9007
+ }
9008
+ list(deviceId) {
9009
+ const links = this.deps.store.list();
9010
+ if (links === null) return {
9011
+ status: "not-loaded",
9012
+ reason: NOT_LOADED
9013
+ };
9014
+ return {
9015
+ status: "answered",
9016
+ links: [...deviceId === void 0 ? links : links.filter((l) => l.a.deviceId === deviceId || l.b.deviceId === deviceId)].sort((x, y) => x.id.localeCompare(y.id))
9017
+ };
9018
+ }
9019
+ confirm(linkId) {
9020
+ return this.decide(linkId, "proposed", async (link) => {
9021
+ const next = {
9022
+ ...link,
9023
+ state: "linked",
9024
+ origin: "operator",
9025
+ decidedAt: this.now()
9026
+ };
9027
+ await this.deps.store.put(next);
9028
+ this.log("identity link confirmed by the operator", next);
9029
+ this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(next));
9030
+ return next;
9031
+ });
9032
+ }
9033
+ dismiss(linkId) {
9034
+ return this.decide(linkId, "proposed", async (link) => {
9035
+ const next = this.dismissed(link);
9036
+ await this.deps.store.put(next);
9037
+ this.log("identity link proposal dismissed by the operator", next);
9038
+ return next;
9039
+ });
9040
+ }
9041
+ unlink(linkId) {
9042
+ return this.decide(linkId, "linked", async (link) => {
9043
+ const next = this.dismissed(link);
9044
+ await this.deps.store.put(next);
9045
+ this.log("identity link unlinked by the operator", next);
9046
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(next, "operator-unlinked"));
9047
+ return next;
9048
+ });
9049
+ }
9050
+ /** The `identity-links` removal step (D864): every link naming the device goes. */
9051
+ removeDevice(deviceId) {
9052
+ return this.serialized(async () => {
9053
+ const links = this.deps.store.list();
9054
+ if (links === null) throw new Error(NOT_LOADED);
9055
+ let removed = 0;
9056
+ for (const link of links) {
9057
+ if (link.a.deviceId !== deviceId && link.b.deviceId !== deviceId) continue;
9058
+ await this.deps.store.delete(link.id);
9059
+ removed += 1;
9060
+ if (link.state === "linked") {
9061
+ this.log("identity link lost — a side was removed", link, deviceId);
9062
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(link, "device-removed"));
9063
+ }
9064
+ }
9065
+ return removed;
9066
+ });
9067
+ }
9068
+ /** One pass over every candidate and every stored link. */
9069
+ async pass() {
9070
+ const answer = this.deps.candidates();
9071
+ const links = this.deps.store.list();
9072
+ if (answer.status !== "answered" || links === null) return;
9073
+ const byId = new Map(links.map((l) => [l.id, l]));
9074
+ const seen = /* @__PURE__ */ new Set();
9075
+ for (const candidate of answer.candidates) {
9076
+ const id = identityLinkId(candidate.kind, candidate.a, candidate.b);
9077
+ if (seen.has(id)) continue;
9078
+ seen.add(id);
9079
+ await this.applyCandidate(id, candidate, byId.get(id) ?? null);
9080
+ }
9081
+ for (const link of links) {
9082
+ if (seen.has(link.id)) continue;
9083
+ const aId = answer.deviceIdOf(link.a.addonId, link.a.stableId);
9084
+ const bId = answer.deviceIdOf(link.b.addonId, link.b.stableId);
9085
+ if (aId === null || bId === null) continue;
9086
+ await this.applyEvidenceGone(link);
9087
+ }
9088
+ }
9089
+ async applyCandidate(id, candidate, stored) {
9090
+ if (identityLinkSidesRefusal(candidate.kind, candidate.aRole) !== null) {
9091
+ this.deps.logger.debug("identity candidate skipped — the attaching side has the wrong role", {
9092
+ tags: { deviceId: candidate.a.deviceId },
9093
+ meta: {
9094
+ kind: candidate.kind,
9095
+ role: candidate.aRole,
9096
+ other: candidate.b.deviceId
9097
+ }
9098
+ });
9099
+ return;
9100
+ }
9101
+ if (stored === null) {
9102
+ const auto = candidate.confidence === "auto";
9103
+ const link = {
9104
+ id,
9105
+ kind: candidate.kind,
9106
+ a: candidate.a,
9107
+ b: candidate.b,
9108
+ state: auto ? "linked" : "proposed",
9109
+ origin: "auto",
9110
+ evidence: candidate.keys,
9111
+ createdAt: this.now(),
9112
+ ...auto ? { decidedAt: this.now() } : {}
9113
+ };
9114
+ await this.deps.store.put(link);
9115
+ this.log(auto ? "identity link created on strong evidence" : "identity link proposed", link);
9116
+ if (auto) this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(link));
9117
+ return;
9118
+ }
9119
+ if (stored.state === "dismissed") return;
9120
+ const upgrade = stored.state === "proposed" && candidate.confidence === "auto";
9121
+ const moved = !sameSide(stored.a, candidate.a) || !sameSide(stored.b, candidate.b) || !sameEvidence(stored.evidence, candidate.keys) || stored.evidenceGone === true;
9122
+ if (!upgrade && !moved) return;
9123
+ const returned = stored.state === "linked" && stored.evidenceGone === true;
9124
+ const { evidenceGone: _dropped, ...rest } = stored;
9125
+ const next = {
9126
+ ...rest,
9127
+ a: candidate.a,
9128
+ b: candidate.b,
9129
+ evidence: candidate.keys,
9130
+ ...upgrade ? {
9131
+ state: "linked",
9132
+ origin: "auto",
9133
+ decidedAt: this.now()
9134
+ } : {}
9135
+ };
9136
+ await this.deps.store.put(next);
9137
+ if (upgrade) {
9138
+ this.log("identity link created — the proposal now has strong evidence", next);
9139
+ this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(next));
9140
+ }
9141
+ if (returned) {
9142
+ this.log("identity link acts again — the evidence of a confirmed link is back", next);
9143
+ this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(next));
9144
+ }
9145
+ }
9146
+ async applyEvidenceGone(link) {
9147
+ if (link.state === "dismissed") return;
9148
+ if (link.state === "proposed") {
9149
+ await this.deps.store.delete(link.id);
9150
+ this.log("identity link proposal withdrawn — its evidence is gone", link);
9151
+ return;
9152
+ }
9153
+ if (link.origin === "operator") {
9154
+ if (link.evidenceGone === true) return;
9155
+ await this.deps.store.put({
9156
+ ...link,
9157
+ evidenceGone: true
9158
+ });
9159
+ this.warn("identity link no longer acts — confirmed by the operator, but its evidence is gone; Unlink it, or it acts again when the evidence returns", link);
9160
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9161
+ return;
9162
+ }
9163
+ await this.deps.store.delete(link.id);
9164
+ this.log("identity link lost — its evidence is gone", link);
9165
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9166
+ }
9167
+ dismissed(link) {
9168
+ return {
9169
+ ...link,
9170
+ state: "dismissed",
9171
+ origin: "operator",
9172
+ decidedAt: this.now()
9173
+ };
9174
+ }
9175
+ decide(linkId, from, apply) {
9176
+ return this.serialized(async () => {
9177
+ if (!this.deps.store.isLoaded()) return {
9178
+ ok: false,
9179
+ reason: "not-loaded",
9180
+ message: NOT_LOADED
9181
+ };
9182
+ const link = this.deps.store.get(linkId);
9183
+ if (link === null) return {
9184
+ ok: false,
9185
+ reason: "unknown-link",
9186
+ message: `no identity link ${linkId}`
9187
+ };
9188
+ if (link.state !== from) return {
9189
+ ok: false,
9190
+ reason: "wrong-state",
9191
+ message: `identity link ${linkId} is ${link.state}, not ${from}`
9192
+ };
9193
+ return {
9194
+ ok: true,
9195
+ link: await apply(link)
9196
+ };
9197
+ });
9198
+ }
9199
+ /** One line per side, so each camera's log carries it (`tags.deviceId`). */
9200
+ log(message, link, only) {
9201
+ this.lines("info", message, link, only);
9202
+ }
9203
+ warn(message, link) {
9204
+ this.lines("warn", message, link);
9205
+ }
9206
+ lines(level, message, link, only) {
9207
+ for (const side of [link.a, link.b]) {
9208
+ if (only !== void 0 && side.deviceId === only) continue;
9209
+ this.deps.logger[level](message, {
9210
+ tags: { deviceId: side.deviceId },
9211
+ meta: {
9212
+ linkId: link.id,
9213
+ kind: link.kind,
9214
+ state: link.state,
9215
+ origin: link.origin,
9216
+ other: side === link.a ? link.b.deviceId : link.a.deviceId,
9217
+ evidence: link.evidence.map((k) => k.key)
9218
+ }
9219
+ });
9220
+ }
9221
+ }
9222
+ serialized(write) {
9223
+ const run = this.tail.then(write, write);
9224
+ this.tail = run.then(() => void 0, () => void 0);
9225
+ return run;
9226
+ }
9227
+ };
9228
+ //#endregion
9229
+ //#region src/builtins/device-manager/record-kinds.ts
9230
+ var import_read_all_rows = require_read_all_rows();
9231
+ var _deviceManagerRecordKinds = defineRecordKinds({
9232
+ tombstones: {
9233
+ schema: DeviceTombstoneSchema.omit({ deviceId: true }),
9234
+ class: "ledger",
9235
+ writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
9236
+ device: "none",
9237
+ at: "required",
9238
+ indexes: [{
9239
+ name: "deleted_at",
9240
+ fields: ["deletedAt"]
9241
+ }],
9242
+ retention: {
9243
+ owner: "device-manager",
9244
+ reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
9245
+ }
9246
+ },
9247
+ "discovery-proposals": {
9248
+ schema: DiscoveryProposalBodySchema,
9249
+ class: "config",
9250
+ writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
9251
+ device: "none",
9252
+ at: "required",
9253
+ indexes: [{
9254
+ name: "last_seen_at",
9255
+ fields: ["lastSeenAt"]
9256
+ }],
9257
+ retention: {
9258
+ ttlMs: 2160 * 60 * 60 * 1e3,
9259
+ from: "at"
9260
+ }
9261
+ },
9262
+ "identity-links": {
9263
+ schema: IdentityLinkBodySchema,
9264
+ class: "config",
9265
+ writeTrigger: "the identity-link reconciler sees a candidate appear, upgrade or lose its evidence; the operator confirms, dismisses or unlinks (D1063)",
9266
+ device: "none",
9267
+ at: "none",
9268
+ indexes: [{
9269
+ name: "a_device",
9270
+ fields: ["a.deviceId"]
9271
+ }, {
9272
+ name: "b_device",
9273
+ fields: ["b.deviceId"]
9274
+ }],
9275
+ retention: { none: "a link lives as long as both its devices; a dismissal is sticky (operator intent)" }
9276
+ }
9277
+ });
9278
+ var deviceManagerRecordKinds = _deviceManagerRecordKinds;
9279
+ _deviceManagerRecordKinds.tombstones;
9280
+ //#endregion
9281
+ //#region src/builtins/device-manager/identity-links-store.ts
9282
+ var IdentityLinksStore = class IdentityLinksStore {
9283
+ kind;
9284
+ links = null;
9285
+ constructor(kind) {
9286
+ this.kind = kind;
9287
+ }
9288
+ static of(records) {
9289
+ return new IdentityLinksStore(records.kind(deviceManagerRecordKinds["identity-links"]));
9290
+ }
9291
+ async load() {
9292
+ const rows = await (0, import_read_all_rows.readAllRows)(this.kind);
9293
+ this.links = new Map(rows.map((row) => [row.id, {
9294
+ id: row.id,
9295
+ ...row.data
9296
+ }]));
9297
+ }
9298
+ isLoaded() {
9299
+ return this.links !== null;
9300
+ }
9301
+ /** Every link; `null` until loaded. */
9302
+ list() {
9303
+ return this.links === null ? null : [...this.links.values()];
9304
+ }
9305
+ get(id) {
9306
+ return this.links?.get(id) ?? null;
9307
+ }
9308
+ async put(link) {
9309
+ const { id, ...data } = link;
9310
+ await this.kind.put({
9311
+ id,
9312
+ data
9313
+ });
9314
+ this.links?.set(id, link);
9315
+ }
9316
+ async delete(id) {
9317
+ await this.kind.delete(id);
9318
+ this.links?.delete(id);
9319
+ }
9320
+ };
9321
+ //#endregion
8895
9322
  //#region src/builtins/device-manager/device-identity-index.ts
8896
9323
  /**
8897
9324
  * The identifier INDEX (planning#593): identifier key → devices, so the
@@ -8913,7 +9340,13 @@ async function setIdentifiers(pctx, input) {
8913
9340
  * write that lands while the snapshot is in flight is buffered and replayed over
8914
9341
  * it, so the seed can never roll a newer write back.
8915
9342
  *
8916
- * Read-only: it finds candidates, it links nothing (that is step 3).
9343
+ * It finds candidates and links nothing itself: the `IdentityLinkReconciler`
9344
+ * (D1063) turns {@link linkCandidates} into link records, and is told of every
9345
+ * change that can move a candidate through {@link onIdentityChanged}.
9346
+ *
9347
+ * Beside the same-device pairs it pairs a device's `attachedIdentifiers` — the
9348
+ * far end of its physical link, a PoE port's wired client — with another
9349
+ * device's `identifiers`, graded by the same {@link classifyIdentityMatch}.
8917
9350
  */
8918
9351
  /** The `kind=value` keys of one declaration. */
8919
9352
  function keysOf(identifiers) {
@@ -8952,6 +9385,18 @@ function sideOf(d) {
8952
9385
  integrationId: d.integrationId
8953
9386
  };
8954
9387
  }
9388
+ function linkSideOf(d) {
9389
+ return {
9390
+ addonId: d.addonId,
9391
+ stableId: d.stableId,
9392
+ deviceId: d.deviceId
9393
+ };
9394
+ }
9395
+ /** The keys both declarations carry, ordered by key then value. */
9396
+ function sharedKeys(x, y) {
9397
+ const yKeys = new Set(keysOf(y));
9398
+ return keysOf(x).filter((k) => yKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9399
+ }
8955
9400
  function compareKeys(x, y) {
8956
9401
  if (x.key !== y.key) return x.key < y.key ? -1 : 1;
8957
9402
  return x.value < y.value ? -1 : x.value > y.value ? 1 : 0;
@@ -8981,6 +9426,9 @@ function classifyIdentityMatch(keys) {
8981
9426
  var DeviceIdentityIndex = class {
8982
9427
  devices = /* @__PURE__ */ new Map();
8983
9428
  byKey = /* @__PURE__ */ new Map();
9429
+ listeners = /* @__PURE__ */ new Set();
9430
+ /** True while {@link seed} replays rows: one notification follows, not one per row. */
9431
+ seeding = false;
8984
9432
  /** `null` once seeded; until then, the writes to replay over the snapshot. */
8985
9433
  pending = [];
8986
9434
  /** Load from a fleet snapshot, then replay every write that landed meanwhile. */
@@ -8989,17 +9437,37 @@ var DeviceIdentityIndex = class {
8989
9437
  this.pending = null;
8990
9438
  this.devices.clear();
8991
9439
  this.byKey.clear();
8992
- for (const row of rows) this.rowWritten(row.meta);
8993
- for (const write of buffered) write(this);
9440
+ this.seeding = true;
9441
+ try {
9442
+ for (const row of rows) this.rowWritten(row.meta);
9443
+ for (const write of buffered) write(this);
9444
+ } finally {
9445
+ this.seeding = false;
9446
+ }
9447
+ this.changed();
9448
+ }
9449
+ /**
9450
+ * Called after every change that can move a candidate (identifiers, attached
9451
+ * identifiers, role, integration, a row written or removed) and after the
9452
+ * seed. Synchronous: the listener schedules its own work.
9453
+ */
9454
+ onIdentityChanged(listener) {
9455
+ this.listeners.add(listener);
9456
+ return () => this.listeners.delete(listener);
8994
9457
  }
8995
9458
  rowWritten(meta) {
8996
9459
  if (this.buffer((i) => i.rowWritten(meta))) return;
8997
9460
  this.put({
8998
9461
  deviceId: meta.id,
8999
9462
  addonId: meta.addonId,
9463
+ stableId: meta.stableId,
9000
9464
  integrationId: meta.integrationId ?? null,
9001
- identifiers: meta.identifiers ?? null
9465
+ role: meta.role ?? null,
9466
+ identifiers: meta.identifiers ?? null,
9467
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
9468
+ attachedRetained: meta.attachedRetained ?? []
9002
9469
  });
9470
+ this.changed();
9003
9471
  }
9004
9472
  registrationWritten(row) {
9005
9473
  if (this.buffer((i) => i.registrationWritten(row))) return;
@@ -9007,24 +9475,117 @@ var DeviceIdentityIndex = class {
9007
9475
  this.put({
9008
9476
  deviceId: row.deviceId,
9009
9477
  addonId: row.addonId,
9478
+ stableId: row.stableId,
9010
9479
  integrationId: existing?.integrationId ?? null,
9011
- identifiers: existing?.identifiers ?? null
9480
+ role: existing?.role ?? null,
9481
+ identifiers: existing?.identifiers ?? null,
9482
+ attachedIdentifiers: existing?.attachedIdentifiers ?? null,
9483
+ attachedRetained: existing?.attachedRetained ?? []
9012
9484
  });
9485
+ if (existing === void 0 || existing.stableId !== row.stableId) this.changed();
9013
9486
  }
9014
9487
  rowPatched(deviceId, patch) {
9015
- if (patch.identifiers === void 0 && patch.integrationId === void 0) return;
9488
+ if (patch.identifiers === void 0 && patch.attachedIdentifiers === void 0 && patch.attachedRetained === void 0 && patch.integrationId === void 0 && patch.role === void 0) return;
9016
9489
  if (this.buffer((i) => i.rowPatched(deviceId, patch))) return;
9017
9490
  const existing = this.devices.get(deviceId);
9018
9491
  if (existing === void 0) return;
9019
9492
  this.put({
9020
9493
  ...existing,
9021
9494
  ...patch.identifiers !== void 0 ? { identifiers: patch.identifiers } : {},
9022
- ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {}
9495
+ ...patch.attachedIdentifiers !== void 0 ? { attachedIdentifiers: patch.attachedIdentifiers } : {},
9496
+ ...patch.attachedRetained !== void 0 ? { attachedRetained: patch.attachedRetained ?? [] } : {},
9497
+ ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {},
9498
+ ...patch.role !== void 0 ? { role: patch.role } : {}
9023
9499
  });
9500
+ this.changed();
9024
9501
  }
9025
9502
  rowRemoved(deviceId) {
9026
9503
  if (this.buffer((i) => i.rowRemoved(deviceId))) return;
9027
9504
  this.drop(deviceId);
9505
+ this.changed();
9506
+ }
9507
+ /**
9508
+ * Every pair a link could be made of (D1063): the same-device pairs of
9509
+ * {@link candidates}, plus each device's attached identifiers paired with
9510
+ * another integration's device identifiers (`poe-power`).
9511
+ *
9512
+ * One link per port: when a port's attached keys reach several devices, or a
9513
+ * device is reached by several ports, every one of those attached pairs is
9514
+ * graded a `proposal` at most — the operator picks.
9515
+ *
9516
+ * Freshness first: a pair whose shared keys the port only RETAINS (declared
9517
+ * unread — no client now, D49) is no candidate when another port FRESHLY
9518
+ * reports the same device. A camera moved from port 7 to port 9 is port 9's;
9519
+ * port 7's auto link loses its evidence. Two fresh reports stay proposals.
9520
+ */
9521
+ linkCandidates() {
9522
+ const same = this.candidates();
9523
+ if (same.status !== "answered") return { status: "unknown" };
9524
+ const out = [];
9525
+ for (const pair of same.pairs) {
9526
+ const a = this.devices.get(pair.a.deviceId);
9527
+ const b = this.devices.get(pair.b.deviceId);
9528
+ if (a === void 0 || b === void 0) continue;
9529
+ out.push({
9530
+ kind: "same-device",
9531
+ a: linkSideOf(a),
9532
+ b: linkSideOf(b),
9533
+ aRole: a.role,
9534
+ keys: pair.keys,
9535
+ confidence: pair.confidence
9536
+ });
9537
+ }
9538
+ out.push(...this.attachedPairs());
9539
+ const byRef = /* @__PURE__ */ new Map();
9540
+ for (const d of this.devices.values()) byRef.set(`${d.addonId}/${d.stableId}`, d.deviceId);
9541
+ return {
9542
+ status: "answered",
9543
+ candidates: out,
9544
+ deviceIdOf: (addonId, stableId) => byRef.get(`${addonId}/${stableId}`) ?? null
9545
+ };
9546
+ }
9547
+ attachedPairs() {
9548
+ const all = [];
9549
+ for (const port of this.devices.values()) {
9550
+ if (port.attachedIdentifiers === null) continue;
9551
+ const reached = /* @__PURE__ */ new Set();
9552
+ for (const key of keysOf(port.attachedIdentifiers)) for (const id of this.byKey.get(key) ?? []) reached.add(id);
9553
+ for (const id of [...reached].sort((x, y) => x - y)) {
9554
+ const target = this.devices.get(id);
9555
+ if (target === void 0 || id === port.deviceId || sameIntegration(port, target)) continue;
9556
+ const keys = sharedKeys(port.attachedIdentifiers, target.identifiers);
9557
+ const confidence = classifyIdentityMatch(keys);
9558
+ if (confidence === null) continue;
9559
+ const retained = new Set(port.attachedRetained);
9560
+ all.push({
9561
+ pair: {
9562
+ kind: "poe-power",
9563
+ a: linkSideOf(port),
9564
+ b: linkSideOf(target),
9565
+ aRole: port.role,
9566
+ keys,
9567
+ confidence
9568
+ },
9569
+ fresh: keys.some((k) => !retained.has(k.key))
9570
+ });
9571
+ }
9572
+ }
9573
+ const freshlyReached = new Set(all.filter((p) => p.fresh).map((p) => p.pair.b.deviceId));
9574
+ const pairs = all.filter((p) => p.fresh || !freshlyReached.has(p.pair.b.deviceId)).map((p) => p.pair);
9575
+ const perPort = /* @__PURE__ */ new Map();
9576
+ const perTarget = /* @__PURE__ */ new Map();
9577
+ for (const p of pairs) {
9578
+ perPort.set(p.a.deviceId, (perPort.get(p.a.deviceId) ?? 0) + 1);
9579
+ perTarget.set(p.b.deviceId, (perTarget.get(p.b.deviceId) ?? 0) + 1);
9580
+ }
9581
+ return pairs.map((p) => (perPort.get(p.a.deviceId) ?? 0) > 1 || (perTarget.get(p.b.deviceId) ?? 0) > 1 ? {
9582
+ ...p,
9583
+ confidence: "proposal"
9584
+ } : p);
9585
+ }
9586
+ changed() {
9587
+ if (this.pending !== null || this.seeding) return;
9588
+ for (const listener of this.listeners) listener();
9028
9589
  }
9029
9590
  /**
9030
9591
  * Every cross-integration candidate pair, graded by `classifyIdentityMatch`,
@@ -9062,8 +9623,7 @@ var DeviceIdentityIndex = class {
9062
9623
  const a = this.devices.get(idA);
9063
9624
  const b = this.devices.get(idB);
9064
9625
  if (a === void 0 || b === void 0 || sameIntegration(a, b)) return null;
9065
- const bKeys = new Set(keysOf(b.identifiers));
9066
- const keys = keysOf(a.identifiers).filter((k) => bKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9626
+ const keys = sharedKeys(a.identifiers, b.identifiers);
9067
9627
  const confidence = classifyIdentityMatch(keys);
9068
9628
  return confidence === null ? null : {
9069
9629
  a: sideOf(a),
@@ -10030,43 +10590,6 @@ var DeviceMetaStore = class {
10030
10590
  });
10031
10591
  };
10032
10592
  //#endregion
10033
- //#region src/builtins/device-manager/record-kinds.ts
10034
- var import_read_all_rows = require_read_all_rows();
10035
- var _deviceManagerRecordKinds = defineRecordKinds({
10036
- tombstones: {
10037
- schema: DeviceTombstoneSchema.omit({ deviceId: true }),
10038
- class: "ledger",
10039
- writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
10040
- device: "none",
10041
- at: "required",
10042
- indexes: [{
10043
- name: "deleted_at",
10044
- fields: ["deletedAt"]
10045
- }],
10046
- retention: {
10047
- owner: "device-manager",
10048
- reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
10049
- }
10050
- },
10051
- "discovery-proposals": {
10052
- schema: DiscoveryProposalBodySchema,
10053
- class: "config",
10054
- writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
10055
- device: "none",
10056
- at: "required",
10057
- indexes: [{
10058
- name: "last_seen_at",
10059
- fields: ["lastSeenAt"]
10060
- }],
10061
- retention: {
10062
- ttlMs: 2160 * 60 * 60 * 1e3,
10063
- from: "at"
10064
- }
10065
- }
10066
- });
10067
- var deviceManagerRecordKinds = _deviceManagerRecordKinds;
10068
- _deviceManagerRecordKinds.tombstones;
10069
- //#endregion
10070
10593
  //#region src/builtins/device-manager/device-tombstone-store.ts
10071
10594
  /**
10072
10595
  * The tombstones of deleted devices (D865) — `tombstones` record kind (phase 4).
@@ -10641,6 +11164,14 @@ var DEVICE_ROWS_COLUMNS = [
10641
11164
  {
10642
11165
  name: "identifiers",
10643
11166
  type: "JSON"
11167
+ },
11168
+ {
11169
+ name: "attachedIdentifiers",
11170
+ type: "JSON"
11171
+ },
11172
+ {
11173
+ name: "attachedRetained",
11174
+ type: "JSON"
10644
11175
  }
10645
11176
  ];
10646
11177
  /**
@@ -10761,6 +11292,8 @@ function decodeDeviceRow(data) {
10761
11292
  const rawDisplay = data["display"];
10762
11293
  const rawMetadata = data["metadata"];
10763
11294
  const identifiers = DeviceIdentifiersSchema.safeParse(data["identifiers"]);
11295
+ const attachedIdentifiers = DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
11296
+ const attachedRetained = DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
10764
11297
  return {
10765
11298
  meta: {
10766
11299
  id: deviceId,
@@ -10783,7 +11316,9 @@ function decodeDeviceRow(data) {
10783
11316
  ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
10784
11317
  ...role !== void 0 ? { role } : {},
10785
11318
  ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
10786
- ...identifiers.success ? { identifiers: identifiers.data } : {}
11319
+ ...identifiers.success ? { identifiers: identifiers.data } : {},
11320
+ ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
11321
+ ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
10787
11322
  },
10788
11323
  metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
10789
11324
  registered: readBoolean(data["registered"]) ?? false
@@ -10830,7 +11365,9 @@ function encodeDeviceRow(meta, extra = {}) {
10830
11365
  primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
10831
11366
  role: meta.role ?? null,
10832
11367
  display: meta.display ?? null,
10833
- identifiers: meta.identifiers ?? null
11368
+ identifiers: meta.identifiers ?? null,
11369
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
11370
+ attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
10834
11371
  };
10835
11372
  if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
10836
11373
  return row;
@@ -15312,6 +15849,23 @@ var DeviceManagerAddon = class extends BaseAddon {
15312
15849
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
15313
15850
  await records.declare(deviceManagerRecordKinds);
15314
15851
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
15852
+ const identityLinksStore = IdentityLinksStore.of(records);
15853
+ await identityLinksStore.load();
15854
+ const identityLinks = new IdentityLinkReconciler({
15855
+ candidates: () => identityIndex.linkCandidates(),
15856
+ store: identityLinksStore,
15857
+ emit: (category, payload) => this.ctx.eventBus.emit({
15858
+ id: randomUUID(),
15859
+ timestamp: /* @__PURE__ */ new Date(),
15860
+ source: {
15861
+ type: "device",
15862
+ id: payload.bDeviceId
15863
+ },
15864
+ category,
15865
+ data: { ...payload }
15866
+ }),
15867
+ logger: this.ctx.logger.child("identity-links")
15868
+ });
15315
15869
  const discoveryProposals = new DiscoveryProposalService({
15316
15870
  store: DiscoveryProposalStore.of(records),
15317
15871
  orchestrator: this.discoveryDeps(),
@@ -15391,6 +15945,9 @@ var DeviceManagerAddon = class extends BaseAddon {
15391
15945
  const bootRows = await deviceRows.listAll();
15392
15946
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
15393
15947
  identityIndex.seed(bootRows);
15948
+ for (const gone of await tombstones.listSince(0)) await identityLinks.removeDevice(gone.deviceId);
15949
+ identityIndex.onIdentityChanged(() => identityLinks.requestPass());
15950
+ identityLinks.requestPass();
15394
15951
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
15395
15952
  const templates = this.makeTemplateActions();
15396
15953
  const pctx = {
@@ -15403,6 +15960,7 @@ var DeviceManagerAddon = class extends BaseAddon {
15403
15960
  removalFence: this.removalFence,
15404
15961
  removalCleanup: this.removalCleanup,
15405
15962
  tombstones,
15963
+ identityLinks,
15406
15964
  removalHooks: {
15407
15965
  api: this.ctx.api,
15408
15966
  logger: this.ctx.logger,
@@ -15477,6 +16035,11 @@ var DeviceManagerAddon = class extends BaseAddon {
15477
16035
  setDisplay: (input) => setDisplay(pctx, input),
15478
16036
  setIdentifiers: (input) => setIdentifiers(pctx, input),
15479
16037
  listIdentityCandidates: async () => identityIndex.candidates(),
16038
+ setAttachedIdentifiers: (input) => setAttachedIdentifiers(pctx, input),
16039
+ listIdentityLinks: async (input) => identityLinks.list(input?.deviceId),
16040
+ confirmIdentityLink: ({ linkId }) => identityLinks.confirm(linkId),
16041
+ dismissIdentityLink: ({ linkId }) => identityLinks.dismiss(linkId),
16042
+ unlinkIdentity: ({ linkId }) => identityLinks.unlink(linkId),
15480
16043
  getRoleDisplayDefaults: (input) => getRoleDisplayDefaults(pctx, input),
15481
16044
  setRoleDisplayDefaults: (input) => setRoleDisplayDefaults(pctx, input),
15482
16045
  applyInitialMeta: (input) => applyInitialMeta(pctx, input),