@camstack/server 1.2.918 → 1.2.919

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 (93) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/package.json +11 -9
  3. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/system/dist/builtins/autotrack/index.js +1 -1
  10. package/system/dist/builtins/autotrack/index.mjs +1 -1
  11. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  12. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  13. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  14. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  15. package/system/dist/builtins/camera-grid/index.js +1 -1
  16. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  17. package/system/dist/builtins/composer/composer.addon.js +4 -4
  18. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  19. package/system/dist/builtins/console-logging/index.js +1 -1
  20. package/system/dist/builtins/console-logging/index.mjs +1 -1
  21. package/system/dist/builtins/core-blocks/core-blocks.addon.js +4 -4
  22. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +4 -4
  23. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  24. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  25. package/system/dist/builtins/device-manager/device-manager.addon.js +19 -1132
  26. package/system/dist/builtins/device-manager/device-manager.addon.mjs +11 -1123
  27. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  28. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  29. package/system/dist/builtins/keychain/index.js +4 -4
  30. package/system/dist/builtins/keychain/index.mjs +4 -4
  31. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  32. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  33. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  34. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  35. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  36. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  37. package/system/dist/builtins/loki-logging/index.js +1 -1
  38. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  39. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  40. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  41. package/system/dist/builtins/platform-probe/index.js +1 -1
  42. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  43. package/system/dist/builtins/record-entries/index.js +1 -1
  44. package/system/dist/builtins/record-entries/index.mjs +1 -1
  45. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  46. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  47. package/system/dist/builtins/snapshot/index.js +1 -1
  48. package/system/dist/builtins/snapshot/index.mjs +1 -1
  49. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  50. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  51. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  52. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  53. package/system/dist/builtins/sqlite-storage/migrations/migration-edits.d.ts +31 -5
  54. package/system/dist/builtins/sqlite-storage/migrations/migration-pass.d.ts +5 -5
  55. package/system/dist/builtins/sqlite-storage/migrations/migration-types.d.ts +15 -1
  56. package/system/dist/builtins/sqlite-storage/records/records-engine.d.ts +7 -0
  57. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +4 -4
  58. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +4 -4
  59. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  60. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  61. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  62. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  63. package/system/dist/builtins/winston-logging/index.js +1 -1
  64. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  65. package/system/dist/{capture-engine-CMZtj4AD.js → capture-engine-DLFzxSof.js} +1 -1
  66. package/system/dist/{capture-engine-CoefzcsI.mjs → capture-engine-lx-ggDqQ.mjs} +1 -1
  67. package/system/dist/{composition-sources-BVndKBya.mjs → composition-sources-BKA_EEb6.mjs} +1 -1
  68. package/system/dist/{composition-sources-Bq4EFdKT.js → composition-sources-BVQ2x2kp.js} +1 -1
  69. package/system/dist/{constants-VKa3Y_M7.mjs → constants-BpaM7LV9.mjs} +1 -1
  70. package/system/dist/{constants-DOBw7N2s.js → constants-TrK4tkaV.js} +1 -1
  71. package/system/dist/{device-ca-BYXNhG52.js → device-ca-BCURI4VN.js} +1 -1
  72. package/system/dist/{device-ca-C9a-1Q9D.mjs → device-ca-CR1WOAty.mjs} +1 -1
  73. package/system/dist/device-row-store-DIYmeeJf.mjs +1113 -0
  74. package/system/dist/device-row-store-ML0g2MYJ.js +1143 -0
  75. package/system/dist/{dist-DQGk7XcX.mjs → dist-B9QP5wIl.mjs} +691 -3
  76. package/system/dist/{dist-BvoilCmO.js → dist-UXAYr3HM.js} +702 -2
  77. package/system/dist/file-host-worker.js +2 -2
  78. package/system/dist/file-host-worker.mjs +2 -2
  79. package/system/dist/{hub-identity-CN6z_g2b.mjs → hub-identity-3gYSQdRz.mjs} +1 -1
  80. package/system/dist/{hub-identity-B_r524vf.js → hub-identity-CGsNqBks.js} +1 -1
  81. package/system/dist/{hub-mdns-ciao-Dmaledqs.mjs → hub-mdns-ciao-BvjAcyuD.mjs} +2 -2
  82. package/system/dist/{hub-mdns-ciao-5HHfcwfK.js → hub-mdns-ciao-CDHA875K.js} +2 -2
  83. package/system/dist/index.js +8 -8
  84. package/system/dist/index.mjs +8 -8
  85. package/system/dist/{legacy-integration-rows-door-BgMMdawG.mjs → legacy-integration-rows-door-D3V2leAn.mjs} +1 -1
  86. package/system/dist/{legacy-integration-rows-door-tRQ5ufny.js → legacy-integration-rows-door-DhQRTSPJ.js} +1 -1
  87. package/system/dist/{rename-composition-block-CMP2cY6o.js → rename-composition-block-BeC7EAMk.js} +1 -1
  88. package/system/dist/{rename-composition-block-D7WfspkB.mjs → rename-composition-block-Cz7yCW3Q.mjs} +1 -1
  89. package/system/dist/{restore-archive-DLJV-MXM.js → restore-archive-Dj81PTwm.js} +1 -1
  90. package/system/dist/{restore-archive-BDj4MPWq.mjs → restore-archive-oOjfUbB5.mjs} +1 -1
  91. package/system/dist/{wal-maintenance-CvVAKiFr.mjs → wal-maintenance-BhbA2ep5.mjs} +0 -0
  92. package/system/dist/{wal-maintenance-CIEBmJaJ.js → wal-maintenance-PtLQ5hgH.js} +0 -0
  93. package/system/package.json +1 -1
@@ -1,10 +1,11 @@
1
- import { $c as SECRET_CLEAR, $r as deviceStateCapability, A as ConditionMirror, Bo as sameIdentifiers, Cc as BaseAddon, Co as resolveCommandHold, Du as errMsg$1, Eu as DeviceType$1, Fa as normalizeUnit, Fo as resolveTemplateRef, Fs as workloadCapability, Ha as parseStreamParamsFormPatch, Hl as isKeychainStoredField, Is as workloadTransition, J as DEVICE_TEMPLATE_FILTERS, Jo as settleDeviceFeatures, Jr as deviceManagerCapability, Kl as isSecretMarker, Kr as deviceExtensionCapability, Ll as isCommand$1, Mi as identityLinkId, Mn as WORKLOAD_TRANSITION_CATEGORY, Ni as identityLinkSidesRefusal, Nn as WorkloadStateSchema, Nr as createDeviceExtensionProvider, Pa as normalizeTags, Q as DEVICE_TEMPLATE_VALUES_CAP, R as DAY_NAMES, Ro as runtimeFieldUnit, Sa as mergeIdentifiers, Si as formatMinutes, Ti as generateDeviceAlias, Tl as defineRecordKinds, Tu as DeviceRole, U as DEVICE_IDENTIFIER_KEYS, Vr as defineExtensionSlotProvider, Wl as isSecretClear, Wo as searchRank, X as DEVICE_TEMPLATE_MAX_OUTPUT, Xs as capAppliesToDeviceKind, Xt as PUSH_CONFIRM_WINDOW_MS, Y as DEVICE_TEMPLATE_MAX_LENGTH, Yi as isKernelDerivedFeature, Yr as deviceOffersActions, Ys as canonicalStoredDeviceType, _l as collectZodSecretPaths$1, _r as commandBurstOffsets, _u as toSecretFieldView, al as WELL_KNOWN_TAB_MAP, at as DeviceStatusSchema, bt as FieldClaimSchema, bu as vocabActionIdFor, dt as ExportNameRefusedError, du as secretTreeFromPaths, ea as isWorkloadSettled, ei as deviceStatusCapability, es as siteZoneKey, fi as extractSourceInfoFromMetadata, fl as auditedFields, ia as legacyAutoLinkIds, ii as enumerateSchemaFields, ji as identifierStrength, jl as expandCapMethods$1, jt as IdentityLinkBodySchema, ku as EventCategory$1, li as expandContainer, mu as sleep$2, ni as effectiveRefreshIntervalMs, nr as buildStreamParamsConfigSchema, nt as DeviceIdentifierKeySchema, or as canonicalIconKey, ot as DeviceTombstoneSchema, pn as STREAM_PROFILE_META, qi as isEmptyIdentifiers, ql as isSecretMarkerLike, ri as enumerateItemArrayFields, rt as DeviceIdentifiersSchema, s as ALL_CAPABILITY_DEFINITIONS, so as reconcileReportedFeatures, st as DiscoveryProposalBodySchema, su as resolveSecretMarkers, ua as locationIconKey, uc as implementedMethodsOf$1, ur as checkDeviceAlias, vl as commandEffect, vu as transformSecretWrite, wu as DeviceFeature, x as CAP_NAMES_WITH_STATUS, y as CAMERA_SWITCH_ORDER, yt as FieldClaimModeSchema, yu as userError, zl as isDeviceConfigCap, zo as runtimeStatePolicyFor, zt as MINUTES_PER_DAY } from "../../dist-DQGk7XcX.mjs";
1
+ import { A as ConditionMirror, Bl as isDeviceConfigCap, Bo as runtimeStatePolicyFor, Ca as mergeIdentifiers, Ci as formatMinutes, Du as DeviceRole, Ei as generateDeviceAlias, Eu as DeviceFeature, Fa as normalizeTags, Gl as isSecretClear, Go as searchRank, Ia as normalizeUnit, Io as resolveTemplateRef, Is as workloadCapability, J as DEVICE_TEMPLATE_FILTERS, Ji as isEmptyIdentifiers, Jl as isSecretMarkerLike, Kr as deviceExtensionCapability, Ls as workloadTransition, Mi as identifierStrength, Ml as expandCapMethods$1, Mn as WORKLOAD_TRANSITION_CATEGORY, Ni as identityLinkId, Nn as WorkloadStateSchema, Nr as createDeviceExtensionProvider, Ou as DeviceType$1, Pi as identityLinkSidesRefusal, Q as DEVICE_TEMPLATE_VALUES_CAP, R as DAY_NAMES, Rl as isCommand$1, Su as vocabActionIdFor, U as DEVICE_IDENTIFIER_KEYS, Ua as parseStreamParamsFormPatch, Ul as isKeychainStoredField, Vo as sameIdentifiers, Vr as defineExtensionSlotProvider, X as DEVICE_TEMPLATE_MAX_OUTPUT, Xi as isKernelDerivedFeature, Xr as deviceOffersActions, Xt as PUSH_CONFIRM_WINDOW_MS, Y as DEVICE_TEMPLATE_MAX_LENGTH, Yo as settleDeviceFeatures, Yr as deviceManagerCapability, Zs as capAppliesToDeviceKind, _r as commandBurstOffsets, aa as legacyAutoLinkIds, ai as enumerateSchemaFields, at as DeviceStatusSchema, bt as FieldClaimSchema, bu as transformSecretWrite, co as reconcileReportedFeatures, da as locationIconKey, dc as implementedMethodsOf$1, dt as ExportNameRefusedError, ei as deviceStateCapability, el as SECRET_CLEAR, gu as sleep$2, ii as enumerateItemArrayFields, ju as EventCategory$1, ku as errMsg$1, lu as resolveSecretMarkers, nr as buildStreamParamsConfigSchema, ol as WELL_KNOWN_TAB_MAP, or as canonicalIconKey, pi as extractSourceInfoFromMetadata, pl as auditedFields, pn as STREAM_PROFILE_META, pu as secretTreeFromPaths, ql as isSecretMarker, ri as effectiveRefreshIntervalMs, rt as DeviceIdentifiersSchema, s as ALL_CAPABILITY_DEFINITIONS, ta as isWorkloadSettled, ti as deviceStatusCapability, ts as siteZoneKey, ui as expandContainer, ur as checkDeviceAlias, vl as collectZodSecretPaths$1, wc as BaseAddon, wo as resolveCommandHold, x as CAP_NAMES_WITH_STATUS, xu as userError, y as CAMERA_SWITCH_ORDER, yl as commandEffect, yt as FieldClaimModeSchema, yu as toSecretFieldView, zo as runtimeFieldUnit, zt as MINUTES_PER_DAY } from "../../dist-B9QP5wIl.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-D7WfspkB.mjs";
4
+ import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-Cz7yCW3Q.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";
8
+ import { a as MigrationRefusedError, i as deviceManagerRecordKinds, n as DeviceRowStore, r as deviceRowBackendOf } from "../../device-row-store-DIYmeeJf.mjs";
8
9
  import { n as isRenderResponse, r as analyzeTemplate } from "../../template-protocol-SgPDx3Hw.mjs";
9
10
  import { s as normalizeServiceType } from "../../dns-wire-Dm3H_7ST.mjs";
10
11
  import { createRequire } from "node:module";
@@ -2616,14 +2617,14 @@ function buildRecordingOnboardConfigSchema(options, status) {
2616
2617
  ]
2617
2618
  }] };
2618
2619
  }
2619
- function readBoolean$1(patch, key) {
2620
+ function readBoolean(patch, key) {
2620
2621
  if (!(key in patch)) return void 0;
2621
2622
  const value = patch[key];
2622
2623
  if (typeof value === "boolean") return value;
2623
2624
  if (value === "true") return true;
2624
2625
  if (value === "false") return false;
2625
2626
  }
2626
- function readNumber$1(patch, key) {
2627
+ function readNumber(patch, key) {
2627
2628
  if (!(key in patch)) return void 0;
2628
2629
  const value = Number(patch[key]);
2629
2630
  return Number.isFinite(value) ? value : void 0;
@@ -2672,15 +2673,15 @@ function readWindowRow(row) {
2672
2673
  */
2673
2674
  function parseRecordingOnboardFormPatch(patch) {
2674
2675
  const out = {};
2675
- const enabled = readBoolean$1(patch, RECORDING_ONBOARD_KEYS.enabled);
2676
+ const enabled = readBoolean(patch, RECORDING_ONBOARD_KEYS.enabled);
2676
2677
  if (enabled !== void 0) out.enabled = enabled;
2677
- const overwrite = readBoolean$1(patch, RECORDING_ONBOARD_KEYS.overwriteWhenFull);
2678
+ const overwrite = readBoolean(patch, RECORDING_ONBOARD_KEYS.overwriteWhenFull);
2678
2679
  if (overwrite !== void 0) out.overwriteWhenFull = overwrite;
2679
- const pre = readNumber$1(patch, RECORDING_ONBOARD_KEYS.preRecordSec);
2680
+ const pre = readNumber(patch, RECORDING_ONBOARD_KEYS.preRecordSec);
2680
2681
  if (pre !== void 0) out.preRecordSec = pre;
2681
- const post = readNumber$1(patch, RECORDING_ONBOARD_KEYS.postRecordSec);
2682
+ const post = readNumber(patch, RECORDING_ONBOARD_KEYS.postRecordSec);
2682
2683
  if (post !== void 0) out.postRecordSec = post;
2683
- const segment = readNumber$1(patch, RECORDING_ONBOARD_KEYS.segmentMinutes);
2684
+ const segment = readNumber(patch, RECORDING_ONBOARD_KEYS.segmentMinutes);
2684
2685
  if (segment !== void 0) out.segmentMinutes = segment;
2685
2686
  if (RECORDING_ONBOARD_KEYS.windows in patch) {
2686
2687
  const raw = patch[RECORDING_ONBOARD_KEYS.windows];
@@ -6534,34 +6535,6 @@ async function runLocationBackfillAtBoot(pctx, bootRows) {
6534
6535
  }
6535
6536
  });
6536
6537
  }
6537
- //#endregion
6538
- //#region src/builtins/device-manager/migration-refused.ts
6539
- /**
6540
- * A migration step that REFUSED with nothing moved.
6541
- *
6542
- * `migrateDevice` distinguishes two kinds of failure after the disable phase,
6543
- * and they must never be confused (D663 task 5b ruling I-1):
6544
- *
6545
- * - **refused, nothing moved** — a precheck of `swapIds` (a row missing, the
6546
- * temp id taken), the mirror drain that runs before the rows move, or a
6547
- * claim found in the mirror after that drain (it landed while the migration
6548
- * was starting). Both cameras are switched back to exactly what they were,
6549
- * because nothing about either device changed.
6550
- * - **failed while moving** — any other throw from `swapIds` (rows partially
6551
- * moved), or from `swapHardwareState` (rows swapped, state not). The two
6552
- * devices may wear each other's identity; switching them back on would run
6553
- * pipelines against crossed identities, so they stay off and the operator is
6554
- * told to intervene.
6555
- *
6556
- * Only a step that KNOWS it wrote nothing may throw this. An unknown error is
6557
- * read as "may have moved" — the safe reading.
6558
- */
6559
- var MigrationRefusedError = class extends Error {
6560
- constructor(message, options) {
6561
- super(message, options);
6562
- this.name = "MigrationRefusedError";
6563
- }
6564
- };
6565
6538
  /** A refusal that names a switch the camera does not offer, rather than one it
6566
6539
  * could not be asked about. The cap documents rejecting the former; anything
6567
6540
  * else is treated as the camera being out of reach, which is the safe reading:
@@ -9226,59 +9199,8 @@ var IdentityLinkReconciler = class {
9226
9199
  }
9227
9200
  };
9228
9201
  //#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
9202
  //#region src/builtins/device-manager/identity-links-store.ts
9203
+ var import_read_all_rows = require_read_all_rows();
9282
9204
  var IdentityLinksStore = class IdentityLinksStore {
9283
9205
  kind;
9284
9206
  links = null;
@@ -10837,1040 +10759,6 @@ var DiscoveryProposalStore = class DiscoveryProposalStore {
10837
10759
  }
10838
10760
  };
10839
10761
  //#endregion
10840
- //#region src/builtins/device-manager/fleet-read-census.ts
10841
- /** How many stack frames identify a call site. One frame is a method; three are
10842
- * a cause — `listFleet < listAll < onDeviceRegistered` is the answer, `listAll`
10843
- * alone is not. Same choice, for the same reason, as `read-census.ts`. */
10844
- var CENSUS_STACK_FRAMES = 3;
10845
- function siteFromStack(stack) {
10846
- if (stack === void 0) return "unknown";
10847
- const frames = stack.split("\n").slice(1).map((line) => line.trim().replace(/^at\s+/, "")).filter((line) => line.length > 0).slice(0, CENSUS_STACK_FRAMES).map((line) => {
10848
- const open = line.indexOf(" (");
10849
- return (open > 0 ? line.slice(0, open) : line).replace(/^async\s+/, "");
10850
- });
10851
- return frames.length === 0 ? "unknown" : frames.join(" < ");
10852
- }
10853
- var FleetReadCensus = class FleetReadCensus {
10854
- /**
10855
- * Longest window the census may be armed for.
10856
- *
10857
- * Ten minutes covers a boot several times over and bounds what an operator
10858
- * pays if they set the variable and forget it. A diagnostic that can be left
10859
- * on becomes a tax nobody remembers enabling.
10860
- */
10861
- static MAX_WINDOW_MS = 10 * 6e4;
10862
- windowMs;
10863
- closesAt;
10864
- counts = /* @__PURE__ */ new Map();
10865
- reported = false;
10866
- constructor(rawEnv, nowMs) {
10867
- const parsed = rawEnv === void 0 ? NaN : Number(rawEnv);
10868
- const valid = Number.isFinite(parsed) && parsed > 0;
10869
- this.windowMs = valid ? Math.min(parsed, FleetReadCensus.MAX_WINDOW_MS) : 0;
10870
- this.closesAt = valid ? nowMs + this.windowMs : 0;
10871
- }
10872
- get armed() {
10873
- return this.windowMs > 0;
10874
- }
10875
- /** Test seam: pretend the window closed. Production reads the clock. */
10876
- closeAt(nowMs) {
10877
- if (nowMs >= this.closesAt) this.forceClosed = true;
10878
- }
10879
- forceClosed = false;
10880
- isOpen(nowMs) {
10881
- if (!this.armed || this.forceClosed) return false;
10882
- return nowMs < this.closesAt;
10883
- }
10884
- /**
10885
- * Capture the caller, or `null` when the window is shut.
10886
- *
10887
- * Called at the START of a read. A read that began inside the window belongs
10888
- * to it even if it lands after the close — otherwise the slow reads at the
10889
- * edge would be attributed to nobody, and the slow ones are the interesting
10890
- * ones.
10891
- *
10892
- * `callerAddonId`, when given, is formatted as the site VERBATIM instead of
10893
- * walking the local stack. A call that arrived over the cap channel — a
10894
- * forked addon's `ctx.api.deviceManager.listAll.query()`, routed through
10895
- * `LocalChildRegistry` → `onUnownedCall` → `CapRouteResolver` — carries its
10896
- * origin as DATA (the registered `childId` the parent captured off the UDS
10897
- * connection), and no amount of stack depth would ever recover it: every
10898
- * frame between the socket read and this call is the SAME generic
10899
- * dispatcher code (`onUnownedCall`, `dispatch`, `invoke`) regardless of
10900
- * which addon called — the 2026-08-25 boot census measured this directly,
10901
- * five thousand calls landing on `listAll` with nothing nameable above it.
10902
- *
10903
- * `isOpen` is checked FIRST, before the id is even looked at — a caller
10904
- * threading a (cheap, already-known) `callerAddonId` through on every
10905
- * request, armed or not, must not pay for the template string when
10906
- * disarmed. This is also why formatting lives HERE rather than at the call
10907
- * site: `DeviceRowStore` passes the raw id through unconditionally, and
10908
- * only this method — which already knows whether armed — decides whether
10909
- * to spend anything on it.
10910
- */
10911
- siteOf(callerAddonId, nowMs = Date.now()) {
10912
- if (!this.isOpen(nowMs)) return null;
10913
- if (callerAddonId !== void 0) return `addon:${callerAddonId}`;
10914
- const holder = {};
10915
- Error.captureStackTrace(holder, this.siteOf);
10916
- return siteFromStack(holder.stack);
10917
- }
10918
- /** Count one read at an already-captured site. A `null` site is not counted. */
10919
- record(site, rowCount) {
10920
- if (site === null) return;
10921
- const existing = this.counts.get(site);
10922
- if (existing === void 0) {
10923
- this.counts.set(site, {
10924
- site,
10925
- calls: 1,
10926
- rows: rowCount
10927
- });
10928
- return;
10929
- }
10930
- existing.calls += 1;
10931
- existing.rows += rowCount;
10932
- }
10933
- /** Attributed sites, busiest first. */
10934
- rows() {
10935
- return [...this.counts.values()].map((c) => ({
10936
- site: c.site,
10937
- calls: c.calls,
10938
- rows: c.rows
10939
- })).sort((a, b) => b.calls - a.calls);
10940
- }
10941
- /**
10942
- * Emit the report ONCE.
10943
- *
10944
- * `perMin` is included because the raw count is unreadable without the window
10945
- * it was taken over — "4 149" means nothing until you know it was 66 seconds.
10946
- */
10947
- report(logger, elapsedMs) {
10948
- if (this.reported || !this.armed) return;
10949
- this.reported = true;
10950
- const rows = this.rows();
10951
- const totalCalls = rows.reduce((acc, r) => acc + r.calls, 0);
10952
- logger.info("fleet read census", { meta: {
10953
- elapsedMs,
10954
- sites: rows.length,
10955
- totalCalls,
10956
- rows: rows.map((r) => ({
10957
- site: r.site,
10958
- calls: r.calls,
10959
- rows: r.rows,
10960
- perMin: elapsedMs === 0 ? 0 : Math.round(r.calls * 6e4 / elapsedMs)
10961
- }))
10962
- } });
10963
- }
10964
- };
10965
- //#endregion
10966
- //#region src/builtins/device-manager/device-row-store.ts
10967
- /**
10968
- * `device-manager:devices` — ONE ROW PER DEVICE.
10969
- *
10970
- * ## What this replaces
10971
- *
10972
- * The device-manager used to keep its whole fleet in three JSON blobs on the
10973
- * addon-settings row set (`deviceMeta`, `deviceMetadata`, `deviceIndex`).
10974
- * Measured on the live hub 2026-08-19: 467 KB + 87 KB + 70 KB = 625 KB of the
10975
- * table's 627 KB, and EVERY read of any of them read and `JSON.parse`d all
10976
- * three, synchronously, on hub-main's event loop — `ctx.settings.readAddonStore`
10977
- * lands in `SqliteSettingsBackend.getAllAddon`, which is prefix-scoped to the
10978
- * addon but not to the key. A V8 profile of that boot had hub-main's JS thread
10979
- * 99.9% busy for 76 s with 64% of it inside `getAllAddon`, ~89% of that entered
10980
- * through the meta store, and every runner's first store read queued behind it.
10981
- *
10982
- * Writing was worse than reading. `ConfigManager.createSettingsView`'s
10983
- * `writeAddonStore` is `setAllAddon(addonId, { ...existing, ...patch })`, and
10984
- * `setAllAddon` DELETEs and re-INSERTs every row of the addon — so renaming one
10985
- * camera rewrote 625 KB.
10986
- *
10987
- * A row per device makes the per-device question a primary-key lookup and the
10988
- * per-device write a single-row upsert touching only the columns named.
10989
- *
10990
- * ## Why `deviceIndex` has no column and no collection
10991
- *
10992
- * `deviceIndex` was `Record<addonId, stableId[]>` — pure derivation: `addonId`
10993
- * and `stableId` are fields of every row, so "this addon's devices" is
10994
- * `where: { addonId }`. It carried exactly one bit that is NOT derivable:
10995
- * membership meant "`registerDevice` has run at least once", which is how
10996
- * `registerDevice` tells a FIRST registration (emit `DeviceRegistered`) from a
10997
- * meta refresh. `allocateDeviceId` writes a row without registering, so row
10998
- * existence alone cannot answer it. That bit is the {@link registered} column,
10999
- * and nothing else of `deviceIndex` survives.
11000
- *
11001
- * ## Why metadata is a column and not a second collection
11002
- *
11003
- * `deviceMetadata` lived in its own blob for ONE reason: a blob write is
11004
- * whole-value, so a lifecycle writer (`registerDevice` / `setName` / …) that
11005
- * had to preserve a `metadata` field would eventually clobber a concurrent
11006
- * `setMetadata`. Single-writer-per-blob was the fix. Column writes have no such
11007
- * problem — `set` names its columns and leaves the rest of the row untouched —
11008
- * so the split has no reason to exist and metadata rides on the device's own
11009
- * row.
11010
- *
11011
- * ## Adding a column later
11012
- *
11013
- * `declareCollection` is additive ONLY when SQLite can `ALTER TABLE … ADD
11014
- * COLUMN` it. A new `NOT NULL` column without a `defaultValue` cannot be added
11015
- * to a populated table, so the backend counts it as non-additive and REBUILDS
11016
- * the collection — dropping every row. Any column added here after ship must
11017
- * either be nullable or carry a `defaultValue`.
11018
- */
11019
- /**
11020
- * @durable class=ledger owner=device-manager
11021
- * write="one row per device, written by `allocateDeviceId` (identity placeholder),
11022
- * `registerDevice` (full reconcile) and every meta setter (single-column patch);
11023
- * `setMetadata` patches the `metadata` column of the same row"
11024
- * retention="none — a row goes only when the operator removes the device
11025
- * (`removeDevice`), or when an integration is deleted and cascades. Bounded by the
11026
- * fleet an operator configures (974 rows on the reference hub)."
11027
- *
11028
- * ### Why `ledger` and not `config`
11029
- *
11030
- * This shipped as `class=registry`, a sixth class that does not exist —
11031
- * `DURABLE_CLASSES` is `ledger | mirror | ephemeral | config | audit`, so
11032
- * `check-durable-state-declared.ts` has failed since. `config` is the tempting
11033
- * answer, because a device's `name` and `location` ARE operator intent. It is
11034
- * the wrong one, and wrong in the dangerous direction: `config`'s rule is
11035
- * *"already durable everywhere"*, and that is exactly the premise that made the
11036
- * dead `devices` table look harmless right up to D183.
11037
- *
11038
- * Nothing else holds a device's NUMERIC id. `allocateDeviceId` mints it here
11039
- * and every other store in the system keys on it — `addon-device-settings`,
11040
- * `device-runtime-state`, every `pipeline-analytics:*` row, every recorder path.
11041
- * That is `ledger`'s definition verbatim ("a fact only this component ever
11042
- * held"), and `ledger`'s rule — *must not be pruned against a fallible read* —
11043
- * is precisely the rule this collection needs (D49): a `getBindings` or an
11044
- * integration listing that answers empty because it FAILED must never be
11045
- * allowed to retire a device row.
11046
- */
11047
- var DEVICE_ROWS_COLLECTION = "device-manager:devices";
11048
- /**
11049
- * Fleet reads pass this explicitly.
11050
- *
11051
- * `settings-store.query` applies a DEFAULT row cap of 2 000 when the caller
11052
- * names no `limit` (`query-bounds.ts`), and truncation there is silent to the
11053
- * caller — it warns in the engine's log and returns a short list that looks
11054
- * complete. The reference hub is already at 974 devices; half the default cap
11055
- * is not a margin worth betting the fleet listing on. 20 000 is the engine's
11056
- * hard ceiling, so this asks for everything the engine will ever serve in one
11057
- * call and any future need to page is a loud failure rather than a quiet one.
11058
- */
11059
- var DEVICE_ROWS_FLEET_LIMIT = 2e4;
11060
- var DEVICE_ROWS_COLUMNS = [
11061
- {
11062
- name: "id",
11063
- type: "TEXT",
11064
- primaryKey: true,
11065
- notNull: true
11066
- },
11067
- {
11068
- name: "deviceId",
11069
- type: "INTEGER",
11070
- notNull: true
11071
- },
11072
- {
11073
- name: "addonId",
11074
- type: "TEXT",
11075
- notNull: true
11076
- },
11077
- {
11078
- name: "stableId",
11079
- type: "TEXT",
11080
- notNull: true
11081
- },
11082
- {
11083
- name: "type",
11084
- type: "TEXT",
11085
- notNull: true
11086
- },
11087
- {
11088
- name: "name",
11089
- type: "TEXT",
11090
- notNull: true
11091
- },
11092
- {
11093
- name: "alias",
11094
- type: "TEXT"
11095
- },
11096
- {
11097
- name: "userNamed",
11098
- type: "BOOLEAN"
11099
- },
11100
- {
11101
- name: "location",
11102
- type: "TEXT"
11103
- },
11104
- {
11105
- name: "tags",
11106
- type: "JSON"
11107
- },
11108
- {
11109
- name: "disabled",
11110
- type: "BOOLEAN",
11111
- notNull: true,
11112
- defaultValue: false
11113
- },
11114
- {
11115
- name: "parentDeviceId",
11116
- type: "INTEGER"
11117
- },
11118
- {
11119
- name: "registered",
11120
- type: "BOOLEAN",
11121
- notNull: true,
11122
- defaultValue: false
11123
- },
11124
- {
11125
- name: "features",
11126
- type: "JSON"
11127
- },
11128
- {
11129
- name: "exportFingerprint",
11130
- type: "TEXT"
11131
- },
11132
- {
11133
- name: "integrationId",
11134
- type: "TEXT"
11135
- },
11136
- {
11137
- name: "linkDeviceId",
11138
- type: "INTEGER"
11139
- },
11140
- {
11141
- name: "primaryChildEntityId",
11142
- type: "TEXT"
11143
- },
11144
- {
11145
- name: "childLayout",
11146
- type: "JSON"
11147
- },
11148
- {
11149
- name: "primaryChildPreference",
11150
- type: "JSON"
11151
- },
11152
- {
11153
- name: "role",
11154
- type: "TEXT"
11155
- },
11156
- {
11157
- name: "display",
11158
- type: "JSON"
11159
- },
11160
- {
11161
- name: "metadata",
11162
- type: "JSON"
11163
- },
11164
- {
11165
- name: "identifiers",
11166
- type: "JSON"
11167
- },
11168
- {
11169
- name: "attachedIdentifiers",
11170
- type: "JSON"
11171
- },
11172
- {
11173
- name: "attachedRetained",
11174
- type: "JSON"
11175
- }
11176
- ];
11177
- /**
11178
- * The columns a SLIM fleet read selects: every declared column except the
11179
- * primary key (always returned) and `metadata`.
11180
- *
11181
- * ## Why this is a DENYLIST and must stay one
11182
- *
11183
- * `decodeDeviceRow` returns `null` when `deviceId`, `addonId`, `stableId`,
11184
- * `type` or `name` is missing, and `list()` then SKIPS the row with a warn. A
11185
- * hand-written allowlist that forgot one of the five would not make the fleet
11186
- * slower — it would make devices vanish from every listing, quietly, and the
11187
- * only trace would be a log line nobody is reading at the time. Deriving the
11188
- * list by subtraction means a column added tomorrow is carried by default and
11189
- * the only way to lose one is to name it here.
11190
- *
11191
- * `metadata` is the one slim provably discards: `device-queries.ts#listAll`
11192
- * sets `metadata: null` on every slim row. It is also the largest JSON column
11193
- * on the row, which is why this is worth doing at all.
11194
- *
11195
- * ## What is NOT here, and will not be
11196
- *
11197
- * There is no `where: { type: 'camera' }` companion to this. `isCameraDevice`
11198
- * is a method-presence check (`getStreamSources`), not the persisted `type`, so
11199
- * a doorbell with a camera answers YES while its row says `doorbell`. Filtering
11200
- * the rows by type would strip exactly those devices of their row — and
11201
- * `toDeviceInfo` reads `name` / `location` / `disabled` from the ROW precisely
11202
- * because the live device's copies are stale by construction. The fleet would
11203
- * keep working and start reporting pre-rename names on doorbells. The
11204
- * `isCamera` filter stays in JS.
11205
- */
11206
- var DEVICE_ROWS_SLIM_COLUMNS = DEVICE_ROWS_COLUMNS.map((c) => c.name).filter((name) => name !== "id" && name !== "metadata");
11207
- var DEVICE_ROWS_INDEXES = [
11208
- {
11209
- name: "idx_dm_devices_addon_stable",
11210
- columns: ["addonId", "stableId"]
11211
- },
11212
- {
11213
- name: "idx_dm_devices_parent",
11214
- columns: ["parentDeviceId"]
11215
- },
11216
- {
11217
- name: "idx_dm_devices_integration",
11218
- columns: ["integrationId"]
11219
- },
11220
- {
11221
- name: "idx_dm_devices_alias",
11222
- columns: ["alias"]
11223
- }
11224
- ];
11225
- /** Adapt `ctx.api.settingsStore` (tRPC namespace) to {@link DeviceRowBackend}. */
11226
- function deviceRowBackendOf(client) {
11227
- return {
11228
- declareCollection: async (input) => {
11229
- await client.declareCollection.mutate(input);
11230
- },
11231
- get: (input) => client.get.query(input),
11232
- set: async (input) => {
11233
- await client.set.mutate(input);
11234
- },
11235
- query: (input) => client.query.query(input),
11236
- updateWhere: (input) => client.updateWhere.mutate(input),
11237
- delete: async (input) => {
11238
- await client.delete.mutate(input);
11239
- },
11240
- count: (input) => client.count.query(input)
11241
- };
11242
- }
11243
- function isPlainObject$1(value) {
11244
- return value !== null && typeof value === "object" && !Array.isArray(value);
11245
- }
11246
- function readString(value) {
11247
- return typeof value === "string" ? value : void 0;
11248
- }
11249
- function readNumber(value) {
11250
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
11251
- }
11252
- function readBoolean(value) {
11253
- if (typeof value === "boolean") return value;
11254
- if (value === 1) return true;
11255
- if (value === 0) return false;
11256
- }
11257
- function readStringArray(value) {
11258
- if (!Array.isArray(value)) return void 0;
11259
- const out = [];
11260
- for (const entry of value) if (typeof entry === "string") out.push(entry);
11261
- return out;
11262
- }
11263
- /**
11264
- * Decode one stored row.
11265
- *
11266
- * Returns `null` for a row missing an identity field the rest of the system
11267
- * treats as an invariant (`deviceId` / `addonId` / `stableId` / `type` /
11268
- * `name`). A row like that cannot be projected into a `DeviceInfo` and taking
11269
- * the whole fleet read down for it would be worse — the caller logs the skip.
11270
- */
11271
- function decodeDeviceRow(data) {
11272
- const deviceId = readNumber(data["deviceId"]);
11273
- const addonId = readString(data["addonId"]);
11274
- const stableId = readString(data["stableId"]);
11275
- const storedType = readString(data["type"]);
11276
- const type = storedType === void 0 ? void 0 : canonicalStoredDeviceType(storedType);
11277
- const name = readString(data["name"]);
11278
- if (deviceId === void 0 || addonId === void 0 || stableId === void 0 || type === void 0 || name === void 0) return null;
11279
- const location = readString(data["location"]);
11280
- const tags = readStringArray(data["tags"]);
11281
- const parentDeviceId = readNumber(data["parentDeviceId"]);
11282
- const userNamed = readBoolean(data["userNamed"]);
11283
- const features = readStringArray(data["features"]);
11284
- const exportFingerprint = readString(data["exportFingerprint"]);
11285
- const integrationId = readString(data["integrationId"]);
11286
- const linkDeviceId = readNumber(data["linkDeviceId"]);
11287
- const primaryChildEntityId = readString(data["primaryChildEntityId"]);
11288
- const role = readString(data["role"]);
11289
- const alias = readString(data["alias"]);
11290
- const rawChildLayout = data["childLayout"];
11291
- const primaryChildPreference = readStringArray(data["primaryChildPreference"]);
11292
- const rawDisplay = data["display"];
11293
- const rawMetadata = data["metadata"];
11294
- const identifiers = DeviceIdentifiersSchema.safeParse(data["identifiers"]);
11295
- const attachedIdentifiers = DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
11296
- const attachedRetained = DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
11297
- return {
11298
- meta: {
11299
- id: deviceId,
11300
- addonId,
11301
- stableId,
11302
- type,
11303
- name,
11304
- location: location ?? null,
11305
- ...tags !== void 0 && tags.length > 0 ? { tags: [...tags] } : {},
11306
- disabled: readBoolean(data["disabled"]) ?? false,
11307
- parentDeviceId: parentDeviceId ?? null,
11308
- ...alias !== void 0 ? { alias } : {},
11309
- ...userNamed !== void 0 ? { userNamed } : {},
11310
- ...features !== void 0 ? { features } : {},
11311
- ...exportFingerprint !== void 0 ? { exportFingerprint } : {},
11312
- ...integrationId !== void 0 ? { integrationId } : {},
11313
- ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
11314
- ...primaryChildEntityId !== void 0 ? { primaryChildEntityId } : {},
11315
- ...isChildLayout(rawChildLayout) ? { childLayout: rawChildLayout } : {},
11316
- ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
11317
- ...role !== void 0 ? { role } : {},
11318
- ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
11319
- ...identifiers.success ? { identifiers: identifiers.data } : {},
11320
- ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
11321
- ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
11322
- },
11323
- metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
11324
- registered: readBoolean(data["registered"]) ?? false
11325
- };
11326
- }
11327
- /**
11328
- * `ChildLayout` is a JSON column: what comes back is whatever was written.
11329
- * The projection hands it to the UI untouched, so the only thing worth
11330
- * checking is that it is still the array shape the writer put in.
11331
- */
11332
- function isChildLayout(value) {
11333
- return Array.isArray(value);
11334
- }
11335
- /**
11336
- * `DeviceDisplayOverride` is likewise stored verbatim in a JSON column. It is
11337
- * an all-optional record, so any object round-trips; the write path
11338
- * (`normalizeDisplayOverride`) is what gives it shape.
11339
- */
11340
- function toDisplayOverride(value) {
11341
- return value;
11342
- }
11343
- /** Full-row value for an upsert: identity + every field of the meta record. */
11344
- function encodeDeviceRow(meta, extra = {}) {
11345
- const row = {
11346
- id: String(meta.id),
11347
- deviceId: meta.id,
11348
- addonId: meta.addonId,
11349
- stableId: meta.stableId,
11350
- type: meta.type,
11351
- name: meta.name,
11352
- alias: meta.alias ?? null,
11353
- userNamed: meta.userNamed ?? null,
11354
- location: meta.location,
11355
- tags: meta.tags === void 0 || meta.tags.length === 0 ? null : [...meta.tags],
11356
- disabled: meta.disabled,
11357
- parentDeviceId: meta.parentDeviceId,
11358
- registered: extra.registered ?? false,
11359
- features: meta.features === void 0 ? null : [...meta.features],
11360
- exportFingerprint: meta.exportFingerprint ?? null,
11361
- integrationId: meta.integrationId ?? null,
11362
- linkDeviceId: meta.linkDeviceId ?? null,
11363
- primaryChildEntityId: meta.primaryChildEntityId ?? null,
11364
- childLayout: meta.childLayout ?? null,
11365
- primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
11366
- role: meta.role ?? null,
11367
- display: meta.display ?? null,
11368
- identifiers: meta.identifiers ?? null,
11369
- attachedIdentifiers: meta.attachedIdentifiers ?? null,
11370
- attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
11371
- };
11372
- if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
11373
- return row;
11374
- }
11375
- /** Column map for a partial write — only the keys the caller actually named. */
11376
- function encodeDeviceRowPatch(patch) {
11377
- const row = {};
11378
- for (const [key, value] of Object.entries(patch)) {
11379
- if (value === void 0) continue;
11380
- row[key] = value;
11381
- }
11382
- return row;
11383
- }
11384
- /**
11385
- * Row access for the device fleet. Every method is a single statement against
11386
- * `device-manager:devices` — there is no in-memory copy of the fleet here and
11387
- * no cache: a per-device question is a primary-key lookup, a fleet question is
11388
- * one indexed scan.
11389
- */
11390
- var DeviceRowStore = class {
11391
- backend;
11392
- logger;
11393
- observer;
11394
- declared = null;
11395
- /** Call-site attribution for fleet reads. Armed only by
11396
- * `CAMSTACK_FLEET_READ_CENSUS_MS`; see `fleet-read-census.ts`. */
11397
- census;
11398
- /**
11399
- * Is the fleet-read census armed right now? Exposed so a caller ABOVE this
11400
- * store (`device-queries.ts`) can skip extracting a caller identity off its
11401
- * input entirely when nobody is measuring — "the boolean field read first"
11402
- * pattern this repo already uses elsewhere to keep a diagnostic seam at
11403
- * zero cost while disarmed.
11404
- */
11405
- get censusArmed() {
11406
- return this.census.armed;
11407
- }
11408
- constructor(backend, logger, census, observer) {
11409
- this.backend = backend;
11410
- this.logger = logger;
11411
- this.observer = observer;
11412
- this.census = census ?? new FleetReadCensus(process.env["CAMSTACK_FLEET_READ_CENSUS_MS"], Date.now());
11413
- if (this.census.armed) {
11414
- const startedAt = Date.now();
11415
- setTimeout(() => this.census.report(this.logger, Date.now() - startedAt), this.census.windowMs).unref?.();
11416
- }
11417
- }
11418
- /**
11419
- * Lazy, idempotent `declareCollection`, memoised on the PROMISE so N
11420
- * concurrent first-callers issue one declaration rather than N. A rejection
11421
- * is not latched — the slot is cleared so the next caller retries instead of
11422
- * inheriting a dead collection forever.
11423
- */
11424
- async declare() {
11425
- const existing = this.declared;
11426
- if (existing !== null) return existing;
11427
- const run = (async () => {
11428
- try {
11429
- await this.backend.declareCollection({
11430
- collection: DEVICE_ROWS_COLLECTION,
11431
- columns: DEVICE_ROWS_COLUMNS,
11432
- indexes: DEVICE_ROWS_INDEXES
11433
- });
11434
- } catch (err) {
11435
- this.declared = null;
11436
- throw err;
11437
- }
11438
- })();
11439
- this.declared = run;
11440
- return run;
11441
- }
11442
- /** One device, by numeric id. `null` when the fleet does not know it. */
11443
- async get(deviceId) {
11444
- await this.declare();
11445
- const raw = await this.backend.get({
11446
- collection: DEVICE_ROWS_COLLECTION,
11447
- key: String(deviceId)
11448
- });
11449
- if (!isPlainObject$1(raw)) return null;
11450
- const decoded = decodeDeviceRow(raw);
11451
- if (decoded === null) {
11452
- this.logger.warn("device row skipped — identity fields missing", { tags: { deviceId } });
11453
- return null;
11454
- }
11455
- return decoded;
11456
- }
11457
- /**
11458
- * Every device, ordered by numeric id.
11459
- *
11460
- * `callerAddonId`, when known, is the addon that ORIGINATED this call —
11461
- * captured off the cap-channel envelope (`CapCallInput.callerAddonId`, set
11462
- * by `LocalChildRegistry` from the registered `childId`), never guessed.
11463
- * Passed straight to the census; a stack walk can never name it (see
11464
- * `fleet-read-census.ts#siteOf`).
11465
- */
11466
- async listAll(callerAddonId) {
11467
- return this.list({
11468
- orderBy: {
11469
- field: "deviceId",
11470
- direction: "asc"
11471
- },
11472
- limit: DEVICE_ROWS_FLEET_LIMIT
11473
- }, void 0, callerAddonId);
11474
- }
11475
- /**
11476
- * The fleet, read as narrowly as the question allows.
11477
- *
11478
- * `listAll` is a full-table `SELECT … ORDER BY "deviceId"` — ~1 017 rows a
11479
- * call on the live hub, 14–54 calls a minute — and its callers then filtered
11480
- * the result in JS. The two filters that CAN be pushed down are here:
11481
- *
11482
- * - `deviceIds` becomes a `whereIn`. The viewer's linked-devices panel asks
11483
- * about ~8 named ids; it was answered by reading the whole ledger. An
11484
- * EMPTY set reads nothing at all rather than degrading to "everything" —
11485
- * a request for no devices is a request, not an omission.
11486
- * - `slim` becomes a column projection, {@link DEVICE_ROWS_SLIM_COLUMNS}.
11487
- *
11488
- * `isCamera` is deliberately NOT one of them — see that constant's note and
11489
- * `device-row-store-filtered.spec.ts`.
11490
- *
11491
- * `callerAddonId` — see {@link listAll}'s doc; same meaning here.
11492
- */
11493
- async listFleet(opts, callerAddonId) {
11494
- if (opts.deviceIds !== void 0 && opts.deviceIds.length === 0) return [];
11495
- return this.list({
11496
- ...opts.deviceIds !== void 0 ? { whereIn: { deviceId: [...new Set(opts.deviceIds)] } } : {},
11497
- orderBy: {
11498
- field: "deviceId",
11499
- direction: "asc"
11500
- },
11501
- limit: DEVICE_ROWS_FLEET_LIMIT
11502
- }, opts.slim === true ? DEVICE_ROWS_SLIM_COLUMNS : void 0, callerAddonId);
11503
- }
11504
- /**
11505
- * Many devices, by numeric id, in ONE query.
11506
- *
11507
- * `get(id)` called once per id in a loop is the primary-key lookup this
11508
- * store exists to make cheap, repeated until it isn't — measured on the
11509
- * live hub 2026-08-25: `get device-manager:devices` at 1 656 calls/min
11510
- * steady-state and 17 687 during boot, exactly one row per call. This
11511
- * collapses that into the same `whereIn` {@link listFleet} already does for
11512
- * a fleet read, keyed by id.
11513
- *
11514
- * A requested id the fleet does not know is simply ABSENT from the map —
11515
- * never a fabricated row, matching {@link get}'s `null`. An empty `ids`
11516
- * reads nothing at all, same as `listFleet({ deviceIds: [] })`.
11517
- */
11518
- async getMany(ids) {
11519
- const rows = await this.listFleet({ deviceIds: ids });
11520
- return new Map(rows.map((row) => [row.meta.id, row]));
11521
- }
11522
- /**
11523
- * The device an addon knows as `stableId`, or `null`.
11524
- *
11525
- * `(addonId, stableId)` is the addon-facing identity — unique by
11526
- * construction, since `allocateDeviceId` is the only thing that mints a row
11527
- * and it returns the existing id for a pair it already knows. A second row
11528
- * for the pair would be a corruption, so this takes the LOWEST id and says
11529
- * so rather than picking arbitrarily.
11530
- */
11531
- async findByStableId(addonId, stableId) {
11532
- const rows = await this.list({
11533
- where: {
11534
- addonId,
11535
- stableId
11536
- },
11537
- orderBy: {
11538
- field: "deviceId",
11539
- direction: "asc"
11540
- },
11541
- limit: 2
11542
- });
11543
- const first = rows[0];
11544
- if (first === void 0) return null;
11545
- if (rows.length > 1) this.logger.warn("duplicate device rows for one (addonId, stableId) — using the lowest id", {
11546
- tags: { deviceId: first.meta.id },
11547
- meta: {
11548
- addonId,
11549
- stableId,
11550
- ids: rows.map((r) => r.meta.id)
11551
- }
11552
- });
11553
- return first;
11554
- }
11555
- /**
11556
- * The device that owns a template alias, or `null`. Aliases are unique, so a
11557
- * second row for one alias would be a corruption: the LOWEST id is answered and
11558
- * the duplicate is said on the record.
11559
- */
11560
- async findByAlias(alias) {
11561
- const rows = await this.list({
11562
- where: { alias },
11563
- orderBy: {
11564
- field: "deviceId",
11565
- direction: "asc"
11566
- },
11567
- limit: 2
11568
- });
11569
- const first = rows[0];
11570
- if (first === void 0) return null;
11571
- if (rows.length > 1) this.logger.warn("duplicate device rows for one alias — using the lowest id", {
11572
- tags: { deviceId: first.meta.id },
11573
- meta: {
11574
- alias,
11575
- ids: rows.map((r) => r.meta.id)
11576
- }
11577
- });
11578
- return first;
11579
- }
11580
- /** Every device owned by one addon, ordered by numeric id. */
11581
- async listByAddon(addonId) {
11582
- return this.list({
11583
- where: { addonId },
11584
- orderBy: {
11585
- field: "deviceId",
11586
- direction: "asc"
11587
- },
11588
- limit: DEVICE_ROWS_FLEET_LIMIT
11589
- });
11590
- }
11591
- /** Every device an integration owns, ordered by numeric id. */
11592
- async listByIntegration(integrationId) {
11593
- return this.list({
11594
- where: { integrationId },
11595
- orderBy: {
11596
- field: "deviceId",
11597
- direction: "asc"
11598
- },
11599
- limit: DEVICE_ROWS_FLEET_LIMIT
11600
- });
11601
- }
11602
- /** Direct children of one device, ordered by numeric id. */
11603
- async listByParent(parentDeviceId) {
11604
- return this.list({
11605
- where: { parentDeviceId },
11606
- orderBy: {
11607
- field: "deviceId",
11608
- direction: "asc"
11609
- },
11610
- limit: DEVICE_ROWS_FLEET_LIMIT
11611
- });
11612
- }
11613
- /**
11614
- * Direct children of MANY devices, in ONE query.
11615
- *
11616
- * `listByParent` called once per parent is the same shape `get` was before
11617
- * {@link getMany}: an indexed lookup this store makes cheap, repeated until
11618
- * it isn't. Measured on the live hub 2026-08-27, 120-second boot window:
11619
- * `DeviceRowStore.list < DeviceRowStore.listByParent < getChildren` at
11620
- * **1 024 calls** — one per device — for 919 rows in total. The BFS in
11621
- * `device-meta-actions.ts#collectDescendants` walked a container tree the
11622
- * same way, one query per node.
11623
- *
11624
- * `whereIn` on the indexed `parentDeviceId` column collapses a level of that
11625
- * walk into a single statement. Contract, verbatim from {@link getMany}: an
11626
- * EMPTY `parentDeviceIds` reads nothing at all rather than degrading to
11627
- * "everything", and a parent with no children — or one the fleet does not
11628
- * know — is simply ABSENT from the map, never an invented empty row.
11629
- */
11630
- async listByParentMany(parentDeviceIds) {
11631
- const out = /* @__PURE__ */ new Map();
11632
- const unique = [...new Set(parentDeviceIds)];
11633
- if (unique.length === 0) return out;
11634
- const rows = await this.list({
11635
- whereIn: { parentDeviceId: unique },
11636
- orderBy: {
11637
- field: "deviceId",
11638
- direction: "asc"
11639
- },
11640
- limit: DEVICE_ROWS_FLEET_LIMIT
11641
- });
11642
- const byParent = /* @__PURE__ */ new Map();
11643
- for (const row of rows) {
11644
- const parent = row.meta.parentDeviceId;
11645
- if (parent === null || parent === void 0) continue;
11646
- const bucket = byParent.get(parent);
11647
- if (bucket === void 0) byParent.set(parent, [row]);
11648
- else bucket.push(row);
11649
- }
11650
- for (const [parent, bucket] of byParent) out.set(parent, bucket);
11651
- return out;
11652
- }
11653
- /** How many devices the fleet holds. Used to tell "empty store" from "gone device". */
11654
- async count() {
11655
- await this.declare();
11656
- return this.backend.count({ collection: DEVICE_ROWS_COLLECTION });
11657
- }
11658
- async list(filter, columns, callerAddonId) {
11659
- const site = this.census.siteOf(callerAddonId);
11660
- await this.declare();
11661
- const records = await this.backend.query({
11662
- collection: DEVICE_ROWS_COLLECTION,
11663
- filter,
11664
- ...columns === void 0 ? {} : { columns }
11665
- });
11666
- this.census.record(site, records.length);
11667
- const out = [];
11668
- for (const record of records) {
11669
- const decoded = decodeDeviceRow(record.data);
11670
- if (decoded === null) {
11671
- this.logger.warn("device row skipped — identity fields missing", { meta: { rowId: record.id } });
11672
- continue;
11673
- }
11674
- out.push(decoded);
11675
- }
11676
- return out;
11677
- }
11678
- /** Insert or replace the whole identity row. */
11679
- async upsert(meta, extra = {}) {
11680
- await this.declare();
11681
- await this.backend.set({
11682
- collection: DEVICE_ROWS_COLLECTION,
11683
- key: String(meta.id),
11684
- value: encodeDeviceRow(meta, extra)
11685
- });
11686
- this.observer?.rowWritten(meta);
11687
- }
11688
- /**
11689
- * Write the named columns of an EXISTING row and nothing else.
11690
- *
11691
- * An UPDATE, deliberately not an upsert: a partial upsert would try to INSERT
11692
- * a row carrying only the patched columns, and SQLite rejects that on the
11693
- * `NOT NULL` identity columns before the primary-key conflict can turn it
11694
- * into an update. Every caller resolves the row under the write lock and
11695
- * throws when it is gone, so matching zero rows means a device was removed
11696
- * between the resolve and the write — the patch is lost, and a lost write
11697
- * that says nothing reads as a write that happened.
11698
- */
11699
- async patch(deviceId, patch) {
11700
- const columns = encodeDeviceRowPatch(patch);
11701
- if (Object.keys(columns).length === 0) return;
11702
- await this.declare();
11703
- const { updated } = await this.backend.updateWhere({
11704
- collection: DEVICE_ROWS_COLLECTION,
11705
- filter: { where: { id: String(deviceId) } },
11706
- data: columns
11707
- });
11708
- if (updated === 0) {
11709
- this.logger.warn("device row patch matched no row — the device was removed under it", {
11710
- tags: { deviceId },
11711
- meta: { columns: Object.keys(columns) }
11712
- });
11713
- return;
11714
- }
11715
- this.observer?.rowPatched(deviceId, patch);
11716
- }
11717
- /**
11718
- * Insert-or-update the registration columns. See {@link DeviceRegistrationRow}
11719
- * for why this is a separate, fully-specified statement rather than a patch.
11720
- */
11721
- async upsertRegistration(row) {
11722
- await this.declare();
11723
- await this.backend.set({
11724
- collection: DEVICE_ROWS_COLLECTION,
11725
- key: String(row.deviceId),
11726
- value: {
11727
- deviceId: row.deviceId,
11728
- addonId: row.addonId,
11729
- stableId: row.stableId,
11730
- type: row.type,
11731
- name: row.name,
11732
- userNamed: row.userNamed,
11733
- location: row.location,
11734
- disabled: row.disabled,
11735
- parentDeviceId: row.parentDeviceId,
11736
- registered: row.registered,
11737
- features: [...row.features],
11738
- exportFingerprint: row.exportFingerprint
11739
- }
11740
- });
11741
- this.observer?.registrationWritten(row);
11742
- }
11743
- /** Drop the device's row. Idempotent. */
11744
- /**
11745
- * Exchange the ids of two devices, carrying their children with them.
11746
- *
11747
- * ## Why this exists as a primitive
11748
- *
11749
- * Replacing a camera means the new hardware has to become the device the rest
11750
- * of the system already knows. Everything general about a camera is keyed on
11751
- * the NUMERIC id and on nothing else — the recording path on disk is
11752
- * `<deviceId>/profile/…`, the hour ledger, the media store and zone ownership
11753
- * carry `deviceId` and not one `stableId` between them, and all four
11754
- * ecosystem exports (Home Assistant, Alexa, HomeKit, Google) key on it too.
11755
- * Moving that work is the expensive, lossy operation. Moving the NUMBER is
11756
- * two rows.
11757
- *
11758
- * ## Children are re-pointed, not renumbered
11759
- *
11760
- * A child keeps its own id and follows its parent: every row whose
11761
- * `parentDeviceId` was `a` now names `b`, and the reverse. Renumbering the
11762
- * children as well would move THEIR general work for no reason — the
11763
- * accessory's own recordings and rules are keyed on the child id, which is
11764
- * not the id being inherited.
11765
- *
11766
- * ## There are no transactions here, so the ORDER is the safety
11767
- *
11768
- * The backing store is a collection API (`set` / `delete` / `updateWhere`);
11769
- * there is no rollback to lean on. So the sequence is chosen to make every
11770
- * crash point LOUD rather than plausible: `a` first moves to a freshly
11771
- * allocated id, which the monotonic counter guarantees was never used and
11772
- * will never be reused. A crash before the end therefore leaves a device
11773
- * missing from its number and a stray at an unfamiliar one — visible in the
11774
- * device list at a glance. What it can never leave is two rows on one number,
11775
- * or a row that looks correct while its children point elsewhere.
11776
- *
11777
- * The caller holds {@link DeviceMetaStore.withMetaWriteLock}. This method does
11778
- * not take it: taking it here would deadlock the migration that has to disable
11779
- * functions on both devices in the same critical section.
11780
- */
11781
- async swapIds(a, b, tempId) {
11782
- const { rowA, rowB, childrenOfA, childrenOfB } = await this.planSwap(a, b, tempId).catch((err) => {
11783
- if (err instanceof MigrationRefusedError) throw err;
11784
- throw new MigrationRefusedError(`[device-manager] swapIds: precheck failed before any row moved — ${err instanceof Error ? err.message : String(err)}`, { cause: err });
11785
- });
11786
- await this.moveRow(rowA, tempId);
11787
- await this.moveRow(rowB, a);
11788
- await this.moveRow({
11789
- ...rowA,
11790
- meta: {
11791
- ...rowA.meta,
11792
- id: tempId
11793
- }
11794
- }, b);
11795
- for (const childId of childrenOfA) await this.patch(childId, { parentDeviceId: b });
11796
- for (const childId of childrenOfB) await this.patch(childId, { parentDeviceId: a });
11797
- this.logger.info("device ids swapped", {
11798
- tags: { deviceId: a },
11799
- meta: {
11800
- a,
11801
- b,
11802
- childrenOfA,
11803
- childrenOfB
11804
- }
11805
- });
11806
- }
11807
- /** The read-only half of {@link swapIds}: every refusal, every read, no write. */
11808
- async planSwap(a, b, tempId) {
11809
- if (a === b) throw new MigrationRefusedError(`[device-manager] swapIds: ${a} and ${b} are the same device`);
11810
- await this.declare();
11811
- const rowA = await this.get(a);
11812
- const rowB = await this.get(b);
11813
- if (rowA === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${a} does not exist`);
11814
- if (rowB === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${b} does not exist`);
11815
- if (await this.get(tempId) !== null) throw new MigrationRefusedError(`[device-manager] swapIds: temp id ${tempId} is taken`);
11816
- return {
11817
- rowA,
11818
- rowB,
11819
- childrenOfA: (await this.listByParent(a)).map((r) => r.meta.id),
11820
- childrenOfB: (await this.listByParent(b)).map((r) => r.meta.id)
11821
- };
11822
- }
11823
- /** Rewrite a row under a new id and drop the old key. Not exported: the only
11824
- * legitimate reason to move a row is {@link swapIds}. */
11825
- async moveRow(row, toId) {
11826
- await this.upsert({
11827
- ...row.meta,
11828
- id: toId
11829
- }, {
11830
- registered: row.registered,
11831
- metadata: row.metadata
11832
- });
11833
- await this.remove(row.meta.id);
11834
- }
11835
- async remove(deviceId) {
11836
- await this.declare();
11837
- await this.backend.delete({
11838
- collection: DEVICE_ROWS_COLLECTION,
11839
- key: String(deviceId)
11840
- });
11841
- this.observer?.rowRemoved(deviceId);
11842
- }
11843
- /**
11844
- * The retirement door for the three blobs this collection replaced.
11845
- *
11846
- * The purge is gated on THIS collection being non-empty, and the count has to
11847
- * be taken after `declare()` — which is why the owning addon runs it and the
11848
- * settings engine cannot: at the engine's own boot no addon has declared
11849
- * anything, so every successor would read as unreadable, forever.
11850
- */
11851
- retiredRowStore() {
11852
- return {
11853
- hasRow: async (spec) => {
11854
- const raw = await this.backend.get({
11855
- collection: spec.collection,
11856
- key: spec.row
11857
- });
11858
- return raw !== void 0 && raw !== null;
11859
- },
11860
- deleteRow: async (spec) => {
11861
- await this.backend.delete({
11862
- collection: spec.collection,
11863
- key: spec.row
11864
- });
11865
- },
11866
- countRows: async (collection) => {
11867
- await this.declare();
11868
- return this.backend.count({ collection });
11869
- }
11870
- };
11871
- }
11872
- };
11873
- //#endregion
11874
10762
  //#region src/builtins/device-manager/device-state-claims.ts
11875
10763
  function createDeviceStateClaimMethods(deps) {
11876
10764
  const { mirror, index, settings, logger } = deps;