@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
@@ -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-DEAjZE_-.js");
6
+ const require_dist = require("../../dist-BNrIzdrJ.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-BxzETYOf.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-gJ_4GdHr.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");
@@ -485,7 +485,8 @@ function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
485
485
  ...metaRow?.primaryChildPreference !== void 0 ? { primaryChildPreference: metaRow.primaryChildPreference } : {},
486
486
  ...metaRow?.tags !== void 0 ? { tags: metaRow.tags } : {},
487
487
  ...metaRow?.display !== void 0 ? { display: metaRow.display } : {},
488
- ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {}
488
+ ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {},
489
+ ...metaRow?.attachedIdentifiers !== void 0 ? { attachedIdentifiers: metaRow.attachedIdentifiers } : {}
489
490
  };
490
491
  }
491
492
  function resolveDeviceById(registry, deviceId) {
@@ -3070,6 +3071,7 @@ async function listAll(pctx, input) {
3070
3071
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3071
3072
  ...m.display !== void 0 ? { display: m.display } : {},
3072
3073
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3074
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3073
3075
  ...(() => {
3074
3076
  if (slim) return {};
3075
3077
  const si = projectSourceInfo(persistedConfig ?? {}, stableId, aid, metadata);
@@ -3124,6 +3126,7 @@ async function getDevice(pctx, input) {
3124
3126
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3125
3127
  ...m.display !== void 0 ? { display: m.display } : {},
3126
3128
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3129
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3127
3130
  ...sourceInfoGetDevice !== void 0 ? { sourceInfo: sourceInfoGetDevice } : {}
3128
3131
  };
3129
3132
  }
@@ -3205,6 +3208,7 @@ function projectChildren(pctx, parentDeviceId, ownerAddonId, childRows, liveChil
3205
3208
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3206
3209
  ...m.display !== void 0 ? { display: m.display } : {},
3207
3210
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3211
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3208
3212
  ...sourceInfoChild !== void 0 ? { sourceInfo: sourceInfoChild } : {}
3209
3213
  });
3210
3214
  }
@@ -7501,6 +7505,10 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
7501
7505
  return (await purge(deviceId)).length;
7502
7506
  }
7503
7507
  },
7508
+ {
7509
+ store: "identity-links",
7510
+ run: async () => pctx.identityLinks === void 0 ? 0 : pctx.identityLinks.removeDevice(deviceId)
7511
+ },
7504
7512
  {
7505
7513
  store: "device-config",
7506
7514
  run: async () => {
@@ -7649,7 +7657,8 @@ async function loadMeta(pctx, input) {
7649
7657
  ...m.integrationId !== void 0 ? { integrationId: m.integrationId } : {},
7650
7658
  ...m.linkDeviceId !== void 0 ? { linkDeviceId: m.linkDeviceId } : {},
7651
7659
  ...m.role !== void 0 ? { role: m.role } : {},
7652
- ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {}
7660
+ ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
7661
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {}
7653
7662
  };
7654
7663
  }
7655
7664
  /**
@@ -8838,20 +8847,41 @@ function stampedCaller(input) {
8838
8847
  const raw = Reflect.get(Object(input), "callerAddonId");
8839
8848
  return typeof raw === "string" && raw.length > 0 ? raw : null;
8840
8849
  }
8850
+ var METHOD_OF = {
8851
+ identifiers: "setIdentifiers",
8852
+ attachedIdentifiers: "setAttachedIdentifiers"
8853
+ };
8841
8854
  async function setIdentifiers(pctx, input) {
8855
+ return writeDeclaredIdentity(pctx, input, "identifiers");
8856
+ }
8857
+ /**
8858
+ * `device-manager.setAttachedIdentifiers` (D1063): the identity of the device at
8859
+ * the far end of this device's physical link. Same owner check, normalisation
8860
+ * and merge as {@link setIdentifiers}, its own column.
8861
+ */
8862
+ async function setAttachedIdentifiers(pctx, input) {
8863
+ return writeDeclaredIdentity(pctx, input, "attachedIdentifiers");
8864
+ }
8865
+ /** The unread keys the merged declaration still holds, sorted: kept, not seen now. */
8866
+ function retainedKeys(merged, unread) {
8867
+ if (merged === null) return [];
8868
+ return [...new Set(unread)].filter((key) => merged[key] !== void 0).sort();
8869
+ }
8870
+ async function writeDeclaredIdentity(pctx, input, column) {
8871
+ const method = METHOD_OF[column];
8842
8872
  const { deviceId } = input;
8843
8873
  const logger = pctx.host.ctx.logger;
8844
8874
  const caller = stampedCaller(input);
8845
8875
  const parsed = require_dist.DeviceIdentifiersSchema.nullable().safeParse(input.identifiers);
8846
8876
  if (!parsed.success) {
8847
- logger.warn("setIdentifiers refused — the declaration is not in its normalised form", {
8877
+ logger.warn(`${method} refused — the declaration is not in its normalised form`, {
8848
8878
  tags: { deviceId },
8849
8879
  meta: {
8850
8880
  caller,
8851
8881
  issues: parsed.error.issues.map((i) => i.path.join("."))
8852
8882
  }
8853
8883
  });
8854
- throw new SetIdentifiersRefusedError("invalid", `[device-manager] setIdentifiers: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8884
+ throw new SetIdentifiersRefusedError("invalid", `[device-manager] ${method}: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8855
8885
  }
8856
8886
  const next = parsed.data === null || require_dist.isEmptyIdentifiers(parsed.data) ? null : parsed.data;
8857
8887
  const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
@@ -8861,25 +8891,39 @@ async function setIdentifiers(pctx, input) {
8861
8891
  kind: "not-owner",
8862
8892
  owner: persisted.addonId
8863
8893
  };
8864
- const stored = persisted.meta.identifiers ?? null;
8894
+ const stored = persisted.meta[column] ?? null;
8865
8895
  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 });
8896
+ if (column === "identifiers") {
8897
+ if (require_dist.sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8898
+ await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8899
+ return {
8900
+ kind: "written",
8901
+ value: merged
8902
+ };
8903
+ }
8904
+ const retained = retainedKeys(merged, input.unread ?? []);
8905
+ const storedRetained = persisted.meta.attachedRetained ?? [];
8906
+ const sameRetained = retained.join(",") === storedRetained.join(",");
8907
+ if (require_dist.sameIdentifiers(stored, merged) && sameRetained) return { kind: "unchanged" };
8908
+ await pctx.metaStore.rows.patch(deviceId, {
8909
+ attachedIdentifiers: merged,
8910
+ attachedRetained: retained.length === 0 ? null : retained
8911
+ });
8868
8912
  return {
8869
8913
  kind: "written",
8870
8914
  value: merged
8871
8915
  };
8872
8916
  });
8873
- if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] setIdentifiers: unknown device id=${deviceId}`);
8917
+ if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] ${method}: unknown device id=${deviceId}`);
8874
8918
  if (outcome.kind === "not-owner") {
8875
- logger.warn("setIdentifiers refused — only the owning provider declares identifiers", {
8919
+ logger.warn(`${method} refused — only the owning provider declares identifiers`, {
8876
8920
  tags: { deviceId },
8877
8921
  meta: {
8878
8922
  caller,
8879
8923
  owner: outcome.owner
8880
8924
  }
8881
8925
  });
8882
- throw new SetIdentifiersRefusedError("not-owner", `[device-manager] setIdentifiers: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8926
+ throw new SetIdentifiersRefusedError("not-owner", `[device-manager] ${method}: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8883
8927
  }
8884
8928
  if (outcome.kind === "unchanged") return;
8885
8929
  pctx.host.ctx.eventBus.emit({
@@ -8892,12 +8936,396 @@ async function setIdentifiers(pctx, input) {
8892
8936
  category: require_dist.EventCategory.DeviceMetaChanged,
8893
8937
  data: {
8894
8938
  deviceId,
8895
- field: "identifiers",
8939
+ field: column,
8896
8940
  value: outcome.value
8897
8941
  }
8898
8942
  });
8899
8943
  }
8900
8944
  //#endregion
8945
+ //#region src/builtins/device-manager/identity-link-reconciler.ts
8946
+ /**
8947
+ * Turns the identity index's link candidates into `identity-links` records
8948
+ * (D1063), and serves the operator's decisions on them.
8949
+ *
8950
+ * | Situation | Result |
8951
+ * | ------------------------------------------- | ---------------------------------------------- |
8952
+ * | `auto` candidate, no row | `linked` / `auto`, `identity-link.created` |
8953
+ * | `proposal` candidate, no row | `proposed`, no event |
8954
+ * | `proposed` row, candidate now `auto` | `linked` / `auto`, created |
8955
+ * | `dismissed` row | stays dismissed: nothing re-proposes it |
8956
+ * | `linked`/`auto` row, evidence gone | row deleted, `identity-link.lost` evidence-gone |
8957
+ * | `linked`/`operator` row, evidence gone | kept, flagged `evidenceGone`, `lost` evidence-gone |
8958
+ * | `linked`/`operator` flagged, evidence back | flag cleared, `identity-link.created` |
8959
+ * | `proposed` row, evidence gone | row deleted, no event (it never linked) |
8960
+ *
8961
+ * "Evidence gone" is judged from the PERSISTED identifiers, which already keep
8962
+ * an unread value (D49): a camera rebooting, a port that read no client this
8963
+ * poll, change nothing. A flagged operator link never acts: `power-source`
8964
+ * refuses through it and core-blocks withdraws its contribution, so a fresh link
8965
+ * on another port can contribute. It waits for the operator (Unlink) or for its
8966
+ * evidence to return. A link whose side has no row right now is left alone —
8967
+ * a removed device is the `identity-links` removal step's, never a guess here.
8968
+ *
8969
+ * Runs after the seed and on every identity change the index reports,
8970
+ * coalesced: a pass already queued absorbs the next request. No timer. Every
8971
+ * write — a pass, an operator decision, a removal — runs on one chain.
8972
+ */
8973
+ var NOT_LOADED = "the identity links have not been read yet";
8974
+ function sameEvidence(x, y) {
8975
+ return JSON.stringify(x) === JSON.stringify(y);
8976
+ }
8977
+ function sameSide(x, y) {
8978
+ return x.deviceId === y.deviceId && x.addonId === y.addonId && x.stableId === y.stableId;
8979
+ }
8980
+ function payloadOf(link, reason) {
8981
+ return {
8982
+ linkId: link.id,
8983
+ kind: link.kind,
8984
+ aDeviceId: link.a.deviceId,
8985
+ bDeviceId: link.b.deviceId,
8986
+ origin: link.origin,
8987
+ ...reason !== void 0 ? { reason } : {}
8988
+ };
8989
+ }
8990
+ var IdentityLinkReconciler = class {
8991
+ deps;
8992
+ tail = Promise.resolve();
8993
+ passQueued = false;
8994
+ now;
8995
+ constructor(deps) {
8996
+ this.deps = deps;
8997
+ this.now = deps.now ?? (() => Date.now());
8998
+ }
8999
+ /** Queue one pass; a pass already queued (not started) absorbs this request. */
9000
+ requestPass() {
9001
+ if (this.passQueued) return;
9002
+ this.passQueued = true;
9003
+ this.serialized(async () => {
9004
+ this.passQueued = false;
9005
+ await this.pass();
9006
+ }).catch((err) => {
9007
+ this.deps.logger.warn("identity-link pass failed — the next identity change retries", { meta: { error: require_dist.errMsg(err) } });
9008
+ });
9009
+ }
9010
+ /** Resolves when every queued write has run (tests, boot). */
9011
+ async settled() {
9012
+ await this.serialized(async () => void 0);
9013
+ }
9014
+ list(deviceId) {
9015
+ const links = this.deps.store.list();
9016
+ if (links === null) return {
9017
+ status: "not-loaded",
9018
+ reason: NOT_LOADED
9019
+ };
9020
+ return {
9021
+ status: "answered",
9022
+ links: [...deviceId === void 0 ? links : links.filter((l) => l.a.deviceId === deviceId || l.b.deviceId === deviceId)].sort((x, y) => x.id.localeCompare(y.id))
9023
+ };
9024
+ }
9025
+ confirm(linkId) {
9026
+ return this.decide(linkId, "proposed", async (link) => {
9027
+ const next = {
9028
+ ...link,
9029
+ state: "linked",
9030
+ origin: "operator",
9031
+ decidedAt: this.now()
9032
+ };
9033
+ await this.deps.store.put(next);
9034
+ this.log("identity link confirmed by the operator", next);
9035
+ this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(next));
9036
+ return next;
9037
+ });
9038
+ }
9039
+ dismiss(linkId) {
9040
+ return this.decide(linkId, "proposed", async (link) => {
9041
+ const next = this.dismissed(link);
9042
+ await this.deps.store.put(next);
9043
+ this.log("identity link proposal dismissed by the operator", next);
9044
+ return next;
9045
+ });
9046
+ }
9047
+ unlink(linkId) {
9048
+ return this.decide(linkId, "linked", async (link) => {
9049
+ const next = this.dismissed(link);
9050
+ await this.deps.store.put(next);
9051
+ this.log("identity link unlinked by the operator", next);
9052
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(next, "operator-unlinked"));
9053
+ return next;
9054
+ });
9055
+ }
9056
+ /** The `identity-links` removal step (D864): every link naming the device goes. */
9057
+ removeDevice(deviceId) {
9058
+ return this.serialized(async () => {
9059
+ const links = this.deps.store.list();
9060
+ if (links === null) throw new Error(NOT_LOADED);
9061
+ let removed = 0;
9062
+ for (const link of links) {
9063
+ if (link.a.deviceId !== deviceId && link.b.deviceId !== deviceId) continue;
9064
+ await this.deps.store.delete(link.id);
9065
+ removed += 1;
9066
+ if (link.state === "linked") {
9067
+ this.log("identity link lost — a side was removed", link, deviceId);
9068
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(link, "device-removed"));
9069
+ }
9070
+ }
9071
+ return removed;
9072
+ });
9073
+ }
9074
+ /** One pass over every candidate and every stored link. */
9075
+ async pass() {
9076
+ const answer = this.deps.candidates();
9077
+ const links = this.deps.store.list();
9078
+ if (answer.status !== "answered" || links === null) return;
9079
+ const byId = new Map(links.map((l) => [l.id, l]));
9080
+ const seen = /* @__PURE__ */ new Set();
9081
+ for (const candidate of answer.candidates) {
9082
+ const id = require_dist.identityLinkId(candidate.kind, candidate.a, candidate.b);
9083
+ if (seen.has(id)) continue;
9084
+ seen.add(id);
9085
+ await this.applyCandidate(id, candidate, byId.get(id) ?? null);
9086
+ }
9087
+ for (const link of links) {
9088
+ if (seen.has(link.id)) continue;
9089
+ const aId = answer.deviceIdOf(link.a.addonId, link.a.stableId);
9090
+ const bId = answer.deviceIdOf(link.b.addonId, link.b.stableId);
9091
+ if (aId === null || bId === null) continue;
9092
+ await this.applyEvidenceGone(link);
9093
+ }
9094
+ }
9095
+ async applyCandidate(id, candidate, stored) {
9096
+ if (require_dist.identityLinkSidesRefusal(candidate.kind, candidate.aRole) !== null) {
9097
+ this.deps.logger.debug("identity candidate skipped — the attaching side has the wrong role", {
9098
+ tags: { deviceId: candidate.a.deviceId },
9099
+ meta: {
9100
+ kind: candidate.kind,
9101
+ role: candidate.aRole,
9102
+ other: candidate.b.deviceId
9103
+ }
9104
+ });
9105
+ return;
9106
+ }
9107
+ if (stored === null) {
9108
+ const auto = candidate.confidence === "auto";
9109
+ const link = {
9110
+ id,
9111
+ kind: candidate.kind,
9112
+ a: candidate.a,
9113
+ b: candidate.b,
9114
+ state: auto ? "linked" : "proposed",
9115
+ origin: "auto",
9116
+ evidence: candidate.keys,
9117
+ createdAt: this.now(),
9118
+ ...auto ? { decidedAt: this.now() } : {}
9119
+ };
9120
+ await this.deps.store.put(link);
9121
+ this.log(auto ? "identity link created on strong evidence" : "identity link proposed", link);
9122
+ if (auto) this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(link));
9123
+ return;
9124
+ }
9125
+ if (stored.state === "dismissed") return;
9126
+ const upgrade = stored.state === "proposed" && candidate.confidence === "auto";
9127
+ const moved = !sameSide(stored.a, candidate.a) || !sameSide(stored.b, candidate.b) || !sameEvidence(stored.evidence, candidate.keys) || stored.evidenceGone === true;
9128
+ if (!upgrade && !moved) return;
9129
+ const returned = stored.state === "linked" && stored.evidenceGone === true;
9130
+ const { evidenceGone: _dropped, ...rest } = stored;
9131
+ const next = {
9132
+ ...rest,
9133
+ a: candidate.a,
9134
+ b: candidate.b,
9135
+ evidence: candidate.keys,
9136
+ ...upgrade ? {
9137
+ state: "linked",
9138
+ origin: "auto",
9139
+ decidedAt: this.now()
9140
+ } : {}
9141
+ };
9142
+ await this.deps.store.put(next);
9143
+ if (upgrade) {
9144
+ this.log("identity link created — the proposal now has strong evidence", next);
9145
+ this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(next));
9146
+ }
9147
+ if (returned) {
9148
+ this.log("identity link acts again — the evidence of a confirmed link is back", next);
9149
+ this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(next));
9150
+ }
9151
+ }
9152
+ async applyEvidenceGone(link) {
9153
+ if (link.state === "dismissed") return;
9154
+ if (link.state === "proposed") {
9155
+ await this.deps.store.delete(link.id);
9156
+ this.log("identity link proposal withdrawn — its evidence is gone", link);
9157
+ return;
9158
+ }
9159
+ if (link.origin === "operator") {
9160
+ if (link.evidenceGone === true) return;
9161
+ await this.deps.store.put({
9162
+ ...link,
9163
+ evidenceGone: true
9164
+ });
9165
+ 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);
9166
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9167
+ return;
9168
+ }
9169
+ await this.deps.store.delete(link.id);
9170
+ this.log("identity link lost — its evidence is gone", link);
9171
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9172
+ }
9173
+ dismissed(link) {
9174
+ return {
9175
+ ...link,
9176
+ state: "dismissed",
9177
+ origin: "operator",
9178
+ decidedAt: this.now()
9179
+ };
9180
+ }
9181
+ decide(linkId, from, apply) {
9182
+ return this.serialized(async () => {
9183
+ if (!this.deps.store.isLoaded()) return {
9184
+ ok: false,
9185
+ reason: "not-loaded",
9186
+ message: NOT_LOADED
9187
+ };
9188
+ const link = this.deps.store.get(linkId);
9189
+ if (link === null) return {
9190
+ ok: false,
9191
+ reason: "unknown-link",
9192
+ message: `no identity link ${linkId}`
9193
+ };
9194
+ if (link.state !== from) return {
9195
+ ok: false,
9196
+ reason: "wrong-state",
9197
+ message: `identity link ${linkId} is ${link.state}, not ${from}`
9198
+ };
9199
+ return {
9200
+ ok: true,
9201
+ link: await apply(link)
9202
+ };
9203
+ });
9204
+ }
9205
+ /** One line per side, so each camera's log carries it (`tags.deviceId`). */
9206
+ log(message, link, only) {
9207
+ this.lines("info", message, link, only);
9208
+ }
9209
+ warn(message, link) {
9210
+ this.lines("warn", message, link);
9211
+ }
9212
+ lines(level, message, link, only) {
9213
+ for (const side of [link.a, link.b]) {
9214
+ if (only !== void 0 && side.deviceId === only) continue;
9215
+ this.deps.logger[level](message, {
9216
+ tags: { deviceId: side.deviceId },
9217
+ meta: {
9218
+ linkId: link.id,
9219
+ kind: link.kind,
9220
+ state: link.state,
9221
+ origin: link.origin,
9222
+ other: side === link.a ? link.b.deviceId : link.a.deviceId,
9223
+ evidence: link.evidence.map((k) => k.key)
9224
+ }
9225
+ });
9226
+ }
9227
+ }
9228
+ serialized(write) {
9229
+ const run = this.tail.then(write, write);
9230
+ this.tail = run.then(() => void 0, () => void 0);
9231
+ return run;
9232
+ }
9233
+ };
9234
+ //#endregion
9235
+ //#region src/builtins/device-manager/record-kinds.ts
9236
+ var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
9237
+ var DeviceTombstoneBodySchema = require_dist.DeviceTombstoneSchema.omit({ deviceId: true });
9238
+ var _deviceManagerRecordKinds = require_dist.defineRecordKinds({
9239
+ tombstones: {
9240
+ schema: DeviceTombstoneBodySchema,
9241
+ class: "ledger",
9242
+ writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
9243
+ device: "none",
9244
+ at: "required",
9245
+ indexes: [{
9246
+ name: "deleted_at",
9247
+ fields: ["deletedAt"]
9248
+ }],
9249
+ retention: {
9250
+ owner: "device-manager",
9251
+ reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
9252
+ }
9253
+ },
9254
+ "discovery-proposals": {
9255
+ schema: require_dist.DiscoveryProposalBodySchema,
9256
+ class: "config",
9257
+ writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
9258
+ device: "none",
9259
+ at: "required",
9260
+ indexes: [{
9261
+ name: "last_seen_at",
9262
+ fields: ["lastSeenAt"]
9263
+ }],
9264
+ retention: {
9265
+ ttlMs: 2160 * 60 * 60 * 1e3,
9266
+ from: "at"
9267
+ }
9268
+ },
9269
+ "identity-links": {
9270
+ schema: require_dist.IdentityLinkBodySchema,
9271
+ class: "config",
9272
+ writeTrigger: "the identity-link reconciler sees a candidate appear, upgrade or lose its evidence; the operator confirms, dismisses or unlinks (D1063)",
9273
+ device: "none",
9274
+ at: "none",
9275
+ indexes: [{
9276
+ name: "a_device",
9277
+ fields: ["a.deviceId"]
9278
+ }, {
9279
+ name: "b_device",
9280
+ fields: ["b.deviceId"]
9281
+ }],
9282
+ retention: { none: "a link lives as long as both its devices; a dismissal is sticky (operator intent)" }
9283
+ }
9284
+ });
9285
+ var deviceManagerRecordKinds = _deviceManagerRecordKinds;
9286
+ _deviceManagerRecordKinds.tombstones;
9287
+ //#endregion
9288
+ //#region src/builtins/device-manager/identity-links-store.ts
9289
+ var IdentityLinksStore = class IdentityLinksStore {
9290
+ kind;
9291
+ links = null;
9292
+ constructor(kind) {
9293
+ this.kind = kind;
9294
+ }
9295
+ static of(records) {
9296
+ return new IdentityLinksStore(records.kind(deviceManagerRecordKinds["identity-links"]));
9297
+ }
9298
+ async load() {
9299
+ const rows = await (0, import_read_all_rows.readAllRows)(this.kind);
9300
+ this.links = new Map(rows.map((row) => [row.id, {
9301
+ id: row.id,
9302
+ ...row.data
9303
+ }]));
9304
+ }
9305
+ isLoaded() {
9306
+ return this.links !== null;
9307
+ }
9308
+ /** Every link; `null` until loaded. */
9309
+ list() {
9310
+ return this.links === null ? null : [...this.links.values()];
9311
+ }
9312
+ get(id) {
9313
+ return this.links?.get(id) ?? null;
9314
+ }
9315
+ async put(link) {
9316
+ const { id, ...data } = link;
9317
+ await this.kind.put({
9318
+ id,
9319
+ data
9320
+ });
9321
+ this.links?.set(id, link);
9322
+ }
9323
+ async delete(id) {
9324
+ await this.kind.delete(id);
9325
+ this.links?.delete(id);
9326
+ }
9327
+ };
9328
+ //#endregion
8901
9329
  //#region src/builtins/device-manager/device-identity-index.ts
8902
9330
  /**
8903
9331
  * The identifier INDEX (planning#593): identifier key → devices, so the
@@ -8919,7 +9347,13 @@ async function setIdentifiers(pctx, input) {
8919
9347
  * write that lands while the snapshot is in flight is buffered and replayed over
8920
9348
  * it, so the seed can never roll a newer write back.
8921
9349
  *
8922
- * Read-only: it finds candidates, it links nothing (that is step 3).
9350
+ * It finds candidates and links nothing itself: the `IdentityLinkReconciler`
9351
+ * (D1063) turns {@link linkCandidates} into link records, and is told of every
9352
+ * change that can move a candidate through {@link onIdentityChanged}.
9353
+ *
9354
+ * Beside the same-device pairs it pairs a device's `attachedIdentifiers` — the
9355
+ * far end of its physical link, a PoE port's wired client — with another
9356
+ * device's `identifiers`, graded by the same {@link classifyIdentityMatch}.
8923
9357
  */
8924
9358
  /** The `kind=value` keys of one declaration. */
8925
9359
  function keysOf(identifiers) {
@@ -8958,6 +9392,18 @@ function sideOf(d) {
8958
9392
  integrationId: d.integrationId
8959
9393
  };
8960
9394
  }
9395
+ function linkSideOf(d) {
9396
+ return {
9397
+ addonId: d.addonId,
9398
+ stableId: d.stableId,
9399
+ deviceId: d.deviceId
9400
+ };
9401
+ }
9402
+ /** The keys both declarations carry, ordered by key then value. */
9403
+ function sharedKeys(x, y) {
9404
+ const yKeys = new Set(keysOf(y));
9405
+ return keysOf(x).filter((k) => yKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9406
+ }
8961
9407
  function compareKeys(x, y) {
8962
9408
  if (x.key !== y.key) return x.key < y.key ? -1 : 1;
8963
9409
  return x.value < y.value ? -1 : x.value > y.value ? 1 : 0;
@@ -8987,6 +9433,9 @@ function classifyIdentityMatch(keys) {
8987
9433
  var DeviceIdentityIndex = class {
8988
9434
  devices = /* @__PURE__ */ new Map();
8989
9435
  byKey = /* @__PURE__ */ new Map();
9436
+ listeners = /* @__PURE__ */ new Set();
9437
+ /** True while {@link seed} replays rows: one notification follows, not one per row. */
9438
+ seeding = false;
8990
9439
  /** `null` once seeded; until then, the writes to replay over the snapshot. */
8991
9440
  pending = [];
8992
9441
  /** Load from a fleet snapshot, then replay every write that landed meanwhile. */
@@ -8995,17 +9444,37 @@ var DeviceIdentityIndex = class {
8995
9444
  this.pending = null;
8996
9445
  this.devices.clear();
8997
9446
  this.byKey.clear();
8998
- for (const row of rows) this.rowWritten(row.meta);
8999
- for (const write of buffered) write(this);
9447
+ this.seeding = true;
9448
+ try {
9449
+ for (const row of rows) this.rowWritten(row.meta);
9450
+ for (const write of buffered) write(this);
9451
+ } finally {
9452
+ this.seeding = false;
9453
+ }
9454
+ this.changed();
9455
+ }
9456
+ /**
9457
+ * Called after every change that can move a candidate (identifiers, attached
9458
+ * identifiers, role, integration, a row written or removed) and after the
9459
+ * seed. Synchronous: the listener schedules its own work.
9460
+ */
9461
+ onIdentityChanged(listener) {
9462
+ this.listeners.add(listener);
9463
+ return () => this.listeners.delete(listener);
9000
9464
  }
9001
9465
  rowWritten(meta) {
9002
9466
  if (this.buffer((i) => i.rowWritten(meta))) return;
9003
9467
  this.put({
9004
9468
  deviceId: meta.id,
9005
9469
  addonId: meta.addonId,
9470
+ stableId: meta.stableId,
9006
9471
  integrationId: meta.integrationId ?? null,
9007
- identifiers: meta.identifiers ?? null
9472
+ role: meta.role ?? null,
9473
+ identifiers: meta.identifiers ?? null,
9474
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
9475
+ attachedRetained: meta.attachedRetained ?? []
9008
9476
  });
9477
+ this.changed();
9009
9478
  }
9010
9479
  registrationWritten(row) {
9011
9480
  if (this.buffer((i) => i.registrationWritten(row))) return;
@@ -9013,24 +9482,117 @@ var DeviceIdentityIndex = class {
9013
9482
  this.put({
9014
9483
  deviceId: row.deviceId,
9015
9484
  addonId: row.addonId,
9485
+ stableId: row.stableId,
9016
9486
  integrationId: existing?.integrationId ?? null,
9017
- identifiers: existing?.identifiers ?? null
9487
+ role: existing?.role ?? null,
9488
+ identifiers: existing?.identifiers ?? null,
9489
+ attachedIdentifiers: existing?.attachedIdentifiers ?? null,
9490
+ attachedRetained: existing?.attachedRetained ?? []
9018
9491
  });
9492
+ if (existing === void 0 || existing.stableId !== row.stableId) this.changed();
9019
9493
  }
9020
9494
  rowPatched(deviceId, patch) {
9021
- if (patch.identifiers === void 0 && patch.integrationId === void 0) return;
9495
+ if (patch.identifiers === void 0 && patch.attachedIdentifiers === void 0 && patch.attachedRetained === void 0 && patch.integrationId === void 0 && patch.role === void 0) return;
9022
9496
  if (this.buffer((i) => i.rowPatched(deviceId, patch))) return;
9023
9497
  const existing = this.devices.get(deviceId);
9024
9498
  if (existing === void 0) return;
9025
9499
  this.put({
9026
9500
  ...existing,
9027
9501
  ...patch.identifiers !== void 0 ? { identifiers: patch.identifiers } : {},
9028
- ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {}
9502
+ ...patch.attachedIdentifiers !== void 0 ? { attachedIdentifiers: patch.attachedIdentifiers } : {},
9503
+ ...patch.attachedRetained !== void 0 ? { attachedRetained: patch.attachedRetained ?? [] } : {},
9504
+ ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {},
9505
+ ...patch.role !== void 0 ? { role: patch.role } : {}
9029
9506
  });
9507
+ this.changed();
9030
9508
  }
9031
9509
  rowRemoved(deviceId) {
9032
9510
  if (this.buffer((i) => i.rowRemoved(deviceId))) return;
9033
9511
  this.drop(deviceId);
9512
+ this.changed();
9513
+ }
9514
+ /**
9515
+ * Every pair a link could be made of (D1063): the same-device pairs of
9516
+ * {@link candidates}, plus each device's attached identifiers paired with
9517
+ * another integration's device identifiers (`poe-power`).
9518
+ *
9519
+ * One link per port: when a port's attached keys reach several devices, or a
9520
+ * device is reached by several ports, every one of those attached pairs is
9521
+ * graded a `proposal` at most — the operator picks.
9522
+ *
9523
+ * Freshness first: a pair whose shared keys the port only RETAINS (declared
9524
+ * unread — no client now, D49) is no candidate when another port FRESHLY
9525
+ * reports the same device. A camera moved from port 7 to port 9 is port 9's;
9526
+ * port 7's auto link loses its evidence. Two fresh reports stay proposals.
9527
+ */
9528
+ linkCandidates() {
9529
+ const same = this.candidates();
9530
+ if (same.status !== "answered") return { status: "unknown" };
9531
+ const out = [];
9532
+ for (const pair of same.pairs) {
9533
+ const a = this.devices.get(pair.a.deviceId);
9534
+ const b = this.devices.get(pair.b.deviceId);
9535
+ if (a === void 0 || b === void 0) continue;
9536
+ out.push({
9537
+ kind: "same-device",
9538
+ a: linkSideOf(a),
9539
+ b: linkSideOf(b),
9540
+ aRole: a.role,
9541
+ keys: pair.keys,
9542
+ confidence: pair.confidence
9543
+ });
9544
+ }
9545
+ out.push(...this.attachedPairs());
9546
+ const byRef = /* @__PURE__ */ new Map();
9547
+ for (const d of this.devices.values()) byRef.set(`${d.addonId}/${d.stableId}`, d.deviceId);
9548
+ return {
9549
+ status: "answered",
9550
+ candidates: out,
9551
+ deviceIdOf: (addonId, stableId) => byRef.get(`${addonId}/${stableId}`) ?? null
9552
+ };
9553
+ }
9554
+ attachedPairs() {
9555
+ const all = [];
9556
+ for (const port of this.devices.values()) {
9557
+ if (port.attachedIdentifiers === null) continue;
9558
+ const reached = /* @__PURE__ */ new Set();
9559
+ for (const key of keysOf(port.attachedIdentifiers)) for (const id of this.byKey.get(key) ?? []) reached.add(id);
9560
+ for (const id of [...reached].sort((x, y) => x - y)) {
9561
+ const target = this.devices.get(id);
9562
+ if (target === void 0 || id === port.deviceId || sameIntegration(port, target)) continue;
9563
+ const keys = sharedKeys(port.attachedIdentifiers, target.identifiers);
9564
+ const confidence = classifyIdentityMatch(keys);
9565
+ if (confidence === null) continue;
9566
+ const retained = new Set(port.attachedRetained);
9567
+ all.push({
9568
+ pair: {
9569
+ kind: "poe-power",
9570
+ a: linkSideOf(port),
9571
+ b: linkSideOf(target),
9572
+ aRole: port.role,
9573
+ keys,
9574
+ confidence
9575
+ },
9576
+ fresh: keys.some((k) => !retained.has(k.key))
9577
+ });
9578
+ }
9579
+ }
9580
+ const freshlyReached = new Set(all.filter((p) => p.fresh).map((p) => p.pair.b.deviceId));
9581
+ const pairs = all.filter((p) => p.fresh || !freshlyReached.has(p.pair.b.deviceId)).map((p) => p.pair);
9582
+ const perPort = /* @__PURE__ */ new Map();
9583
+ const perTarget = /* @__PURE__ */ new Map();
9584
+ for (const p of pairs) {
9585
+ perPort.set(p.a.deviceId, (perPort.get(p.a.deviceId) ?? 0) + 1);
9586
+ perTarget.set(p.b.deviceId, (perTarget.get(p.b.deviceId) ?? 0) + 1);
9587
+ }
9588
+ return pairs.map((p) => (perPort.get(p.a.deviceId) ?? 0) > 1 || (perTarget.get(p.b.deviceId) ?? 0) > 1 ? {
9589
+ ...p,
9590
+ confidence: "proposal"
9591
+ } : p);
9592
+ }
9593
+ changed() {
9594
+ if (this.pending !== null || this.seeding) return;
9595
+ for (const listener of this.listeners) listener();
9034
9596
  }
9035
9597
  /**
9036
9598
  * Every cross-integration candidate pair, graded by `classifyIdentityMatch`,
@@ -9068,8 +9630,7 @@ var DeviceIdentityIndex = class {
9068
9630
  const a = this.devices.get(idA);
9069
9631
  const b = this.devices.get(idB);
9070
9632
  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);
9633
+ const keys = sharedKeys(a.identifiers, b.identifiers);
9073
9634
  const confidence = classifyIdentityMatch(keys);
9074
9635
  return confidence === null ? null : {
9075
9636
  a: sideOf(a),
@@ -10036,44 +10597,6 @@ var DeviceMetaStore = class {
10036
10597
  });
10037
10598
  };
10038
10599
  //#endregion
10039
- //#region src/builtins/device-manager/record-kinds.ts
10040
- var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
10041
- var DeviceTombstoneBodySchema = require_dist.DeviceTombstoneSchema.omit({ deviceId: true });
10042
- var _deviceManagerRecordKinds = require_dist.defineRecordKinds({
10043
- tombstones: {
10044
- schema: DeviceTombstoneBodySchema,
10045
- class: "ledger",
10046
- writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
10047
- device: "none",
10048
- at: "required",
10049
- indexes: [{
10050
- name: "deleted_at",
10051
- fields: ["deletedAt"]
10052
- }],
10053
- retention: {
10054
- owner: "device-manager",
10055
- reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
10056
- }
10057
- },
10058
- "discovery-proposals": {
10059
- schema: require_dist.DiscoveryProposalBodySchema,
10060
- class: "config",
10061
- writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
10062
- device: "none",
10063
- at: "required",
10064
- indexes: [{
10065
- name: "last_seen_at",
10066
- fields: ["lastSeenAt"]
10067
- }],
10068
- retention: {
10069
- ttlMs: 2160 * 60 * 60 * 1e3,
10070
- from: "at"
10071
- }
10072
- }
10073
- });
10074
- var deviceManagerRecordKinds = _deviceManagerRecordKinds;
10075
- _deviceManagerRecordKinds.tombstones;
10076
- //#endregion
10077
10600
  //#region src/builtins/device-manager/device-tombstone-store.ts
10078
10601
  /**
10079
10602
  * The tombstones of deleted devices (D865) — `tombstones` record kind (phase 4).
@@ -10648,6 +11171,14 @@ var DEVICE_ROWS_COLUMNS = [
10648
11171
  {
10649
11172
  name: "identifiers",
10650
11173
  type: "JSON"
11174
+ },
11175
+ {
11176
+ name: "attachedIdentifiers",
11177
+ type: "JSON"
11178
+ },
11179
+ {
11180
+ name: "attachedRetained",
11181
+ type: "JSON"
10651
11182
  }
10652
11183
  ];
10653
11184
  /**
@@ -10768,6 +11299,8 @@ function decodeDeviceRow(data) {
10768
11299
  const rawDisplay = data["display"];
10769
11300
  const rawMetadata = data["metadata"];
10770
11301
  const identifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["identifiers"]);
11302
+ const attachedIdentifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
11303
+ const attachedRetained = require_dist.DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
10771
11304
  return {
10772
11305
  meta: {
10773
11306
  id: deviceId,
@@ -10790,7 +11323,9 @@ function decodeDeviceRow(data) {
10790
11323
  ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
10791
11324
  ...role !== void 0 ? { role } : {},
10792
11325
  ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
10793
- ...identifiers.success ? { identifiers: identifiers.data } : {}
11326
+ ...identifiers.success ? { identifiers: identifiers.data } : {},
11327
+ ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
11328
+ ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
10794
11329
  },
10795
11330
  metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
10796
11331
  registered: readBoolean(data["registered"]) ?? false
@@ -10837,7 +11372,9 @@ function encodeDeviceRow(meta, extra = {}) {
10837
11372
  primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
10838
11373
  role: meta.role ?? null,
10839
11374
  display: meta.display ?? null,
10840
- identifiers: meta.identifiers ?? null
11375
+ identifiers: meta.identifiers ?? null,
11376
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
11377
+ attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
10841
11378
  };
10842
11379
  if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
10843
11380
  return row;
@@ -15319,6 +15856,23 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15319
15856
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
15320
15857
  await records.declare(deviceManagerRecordKinds);
15321
15858
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
15859
+ const identityLinksStore = IdentityLinksStore.of(records);
15860
+ await identityLinksStore.load();
15861
+ const identityLinks = new IdentityLinkReconciler({
15862
+ candidates: () => identityIndex.linkCandidates(),
15863
+ store: identityLinksStore,
15864
+ emit: (category, payload) => this.ctx.eventBus.emit({
15865
+ id: (0, node_crypto.randomUUID)(),
15866
+ timestamp: /* @__PURE__ */ new Date(),
15867
+ source: {
15868
+ type: "device",
15869
+ id: payload.bDeviceId
15870
+ },
15871
+ category,
15872
+ data: { ...payload }
15873
+ }),
15874
+ logger: this.ctx.logger.child("identity-links")
15875
+ });
15322
15876
  const discoveryProposals = new DiscoveryProposalService({
15323
15877
  store: DiscoveryProposalStore.of(records),
15324
15878
  orchestrator: this.discoveryDeps(),
@@ -15398,6 +15952,9 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15398
15952
  const bootRows = await deviceRows.listAll();
15399
15953
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
15400
15954
  identityIndex.seed(bootRows);
15955
+ for (const gone of await tombstones.listSince(0)) await identityLinks.removeDevice(gone.deviceId);
15956
+ identityIndex.onIdentityChanged(() => identityLinks.requestPass());
15957
+ identityLinks.requestPass();
15401
15958
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
15402
15959
  const templates = this.makeTemplateActions();
15403
15960
  const pctx = {
@@ -15410,6 +15967,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15410
15967
  removalFence: this.removalFence,
15411
15968
  removalCleanup: this.removalCleanup,
15412
15969
  tombstones,
15970
+ identityLinks,
15413
15971
  removalHooks: {
15414
15972
  api: this.ctx.api,
15415
15973
  logger: this.ctx.logger,
@@ -15484,6 +16042,11 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15484
16042
  setDisplay: (input) => setDisplay(pctx, input),
15485
16043
  setIdentifiers: (input) => setIdentifiers(pctx, input),
15486
16044
  listIdentityCandidates: async () => identityIndex.candidates(),
16045
+ setAttachedIdentifiers: (input) => setAttachedIdentifiers(pctx, input),
16046
+ listIdentityLinks: async (input) => identityLinks.list(input?.deviceId),
16047
+ confirmIdentityLink: ({ linkId }) => identityLinks.confirm(linkId),
16048
+ dismissIdentityLink: ({ linkId }) => identityLinks.dismiss(linkId),
16049
+ unlinkIdentity: ({ linkId }) => identityLinks.unlink(linkId),
15487
16050
  getRoleDisplayDefaults: (input) => getRoleDisplayDefaults(pctx, input),
15488
16051
  setRoleDisplayDefaults: (input) => setRoleDisplayDefaults(pctx, input),
15489
16052
  applyInitialMeta: (input) => applyInitialMeta(pctx, input),