@camstack/system 1.2.313 → 1.2.314

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 (106) hide show
  1. package/dist/addon-runner.js +1 -1
  2. package/dist/addon-runner.mjs +1 -1
  3. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/dist/builtins/autotrack/index.js +1 -1
  10. package/dist/builtins/autotrack/index.mjs +1 -1
  11. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  12. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  13. package/dist/builtins/camera-grid/index.js +1 -1
  14. package/dist/builtins/camera-grid/index.mjs +1 -1
  15. package/dist/builtins/composer/claim-gate.d.ts +32 -0
  16. package/dist/builtins/composer/composed-device-set.d.ts +38 -0
  17. package/dist/builtins/composer/composed-device.d.ts +4 -3
  18. package/dist/builtins/composer/composer-grafts.d.ts +54 -0
  19. package/dist/builtins/composer/composer-plan.d.ts +89 -0
  20. package/dist/builtins/composer/composer-verdict.d.ts +19 -0
  21. package/dist/builtins/composer/composer.addon.js +2500 -422
  22. package/dist/builtins/composer/composer.addon.mjs +2493 -415
  23. package/dist/builtins/composer/composer.d.ts +66 -51
  24. package/dist/builtins/composer/composition-runtime.d.ts +84 -9
  25. package/dist/builtins/composer/confirmed-seed.d.ts +32 -0
  26. package/dist/builtins/composer/existing-target.d.ts +87 -0
  27. package/dist/builtins/composer/field-record.d.ts +41 -0
  28. package/dist/builtins/composer/graft-host.d.ts +47 -0
  29. package/dist/builtins/composer/held-claims.d.ts +12 -0
  30. package/dist/builtins/composer/owned-fields-target.d.ts +55 -0
  31. package/dist/builtins/composer/slice-assembler.d.ts +10 -0
  32. package/dist/builtins/composer/source-readings.d.ts +122 -0
  33. package/dist/builtins/composer/source-tracker.d.ts +35 -42
  34. package/dist/builtins/console-logging/index.js +1 -1
  35. package/dist/builtins/console-logging/index.mjs +1 -1
  36. package/dist/builtins/core-blocks/composition-api.d.ts +7 -4
  37. package/dist/builtins/core-blocks/composition-peers.d.ts +9 -0
  38. package/dist/builtins/core-blocks/composition-sources.d.ts +14 -3
  39. package/dist/builtins/core-blocks/core-block-store.d.ts +8 -1
  40. package/dist/builtins/core-blocks/core-blocks.addon.d.ts +4 -3
  41. package/dist/builtins/core-blocks/core-blocks.addon.js +326 -50
  42. package/dist/builtins/core-blocks/core-blocks.addon.mjs +326 -50
  43. package/dist/builtins/device-manager/claimed-status-overlay.d.ts +12 -0
  44. package/dist/builtins/device-manager/device-manager.addon.d.ts +16 -0
  45. package/dist/builtins/device-manager/device-manager.addon.js +1825 -317
  46. package/dist/builtins/device-manager/device-manager.addon.mjs +1825 -317
  47. package/dist/builtins/device-manager/device-provider-context.d.ts +24 -2
  48. package/dist/builtins/device-manager/device-row-store.d.ts +2 -0
  49. package/dist/builtins/device-manager/device-state-claim-views.d.ts +77 -0
  50. package/dist/builtins/device-manager/device-state-claims.d.ts +43 -0
  51. package/dist/builtins/device-manager/device-state-mirror.d.ts +145 -61
  52. package/dist/builtins/device-manager/field-claims-index.d.ts +69 -0
  53. package/dist/builtins/device-manager/field-ownership.d.ts +53 -0
  54. package/dist/builtins/device-manager/migrate-device.d.ts +27 -0
  55. package/dist/builtins/device-manager/migrate-guard.d.ts +7 -0
  56. package/dist/builtins/device-manager/migrate-hardware-state.d.ts +55 -0
  57. package/dist/builtins/device-manager/migration-refused.d.ts +23 -0
  58. package/dist/builtins/device-manager/mirror-row-writer.d.ts +138 -0
  59. package/dist/builtins/device-manager/runtime-state-persist-gate.d.ts +4 -0
  60. package/dist/builtins/doorbell/virtual-doorbell.addon.js +1 -3
  61. package/dist/builtins/doorbell/virtual-doorbell.addon.mjs +1 -3
  62. package/dist/builtins/hub-forwarder/index.js +1 -1
  63. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  64. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  65. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  66. package/dist/builtins/local-auth/local-auth.addon.js +1 -1
  67. package/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  68. package/dist/builtins/local-network/local-network.addon.js +1 -1
  69. package/dist/builtins/local-network/local-network.addon.mjs +1 -1
  70. package/dist/builtins/loki-logging/index.js +1 -1
  71. package/dist/builtins/loki-logging/index.mjs +1 -1
  72. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  73. package/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  74. package/dist/builtins/platform-probe/index.js +1 -1
  75. package/dist/builtins/platform-probe/index.mjs +1 -1
  76. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  77. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  78. package/dist/builtins/snapshot/index.js +1 -1
  79. package/dist/builtins/snapshot/index.mjs +1 -1
  80. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  81. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  82. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +0 -0
  83. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +0 -0
  84. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  85. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  86. package/dist/builtins/system-config/system-config.addon.js +1 -1
  87. package/dist/builtins/system-config/system-config.addon.mjs +1 -1
  88. package/dist/builtins/winston-logging/index.js +1 -1
  89. package/dist/builtins/winston-logging/index.mjs +1 -1
  90. package/dist/{child-cap-dispatch-CHTiHbsv.mjs → child-cap-dispatch-AAltfBUH.mjs} +1484 -1417
  91. package/dist/{child-cap-dispatch-Dyn_7ezH.js → child-cap-dispatch-DzcUd_ct.js} +1503 -1424
  92. package/dist/{dist-CkRwnhbo.js → dist-BtNkk3Qz.js} +4577 -3824
  93. package/dist/{dist-Cj7pJmXq.mjs → dist-cH4t1ZEm.mjs} +4541 -3824
  94. package/dist/index.js +137 -8
  95. package/dist/index.mjs +133 -8
  96. package/dist/kernel/capability-registry.d.ts +43 -1
  97. package/dist/kernel/index.d.ts +3 -1
  98. package/dist/kernel/moleculer/device-cap-proxy.d.ts +0 -10
  99. package/dist/kernel/status-overlay.d.ts +18 -0
  100. package/dist/kernel/transport/claimed-get-status.d.ts +15 -0
  101. package/dist/kernel/transport/index.d.ts +2 -0
  102. package/dist/kernel/transport/local-child-registry.d.ts +23 -0
  103. package/dist/kernel/transport/parent-unowned-call.d.ts +25 -0
  104. package/dist/{retired-settings-keys-CGSuXhP8.js → retired-settings-keys-B7imb-qH.js} +1 -1
  105. package/dist/{retired-settings-keys-C1duPikd.mjs → retired-settings-keys-DQYHfZ0S.mjs} +1 -1
  106. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import { $ as compositionSliceKey, K as buildCapabilityLookup, Ln as DeviceType, Q as composerCapability, Sn as toExpressionValue, Z as composedDeviceStableId, c as COMPOSER_ADDON_ID, et as compositionSourceKey, g as DeclaredDevices, i as BaseDevice, ir as EventCategory, jn as BaseAddon, kn as errMsg, t as ALL_CAPABILITY_DEFINITIONS, tn as planComposition, xt as evaluateCompositionField } from "../../dist-Cj7pJmXq.mjs";
2
- import { n as parseDeviceStateChanged, t as isRecord } from "../../device-state-changed-DoBbkyEI.mjs";
1
+ import { $ as compositionFieldKey, Bn as BaseAddon, Fn as toExpressionValue, J as buildCapabilityLookup, Mn as compositionItemFieldPath, Nn as compositionSliceKey, On as COMPOSER_ADDON_ID, Pn as compositionSourceKey, Q as composerCapability, Rn as DeviceType, bt as evaluateCompositionField, c as COMPOSED_ITEM_FIXED_FIELDS, en as planComposition, g as DeclaredDevices, i as BaseDevice, jn as composedDeviceStableId, t as ALL_CAPABILITY_DEFINITIONS, ur as EventCategory, zn as errMsg } from "../../dist-cH4t1ZEm.mjs";
2
+ import { n as parseDeviceStateChanged, t as isRecord$1 } from "../../device-state-changed-DoBbkyEI.mjs";
3
3
  import { z } from "zod";
4
4
  //#region src/builtins/composer/composed-device.ts
5
5
  /**
@@ -80,6 +80,217 @@ function isComposedDevice(device) {
80
80
  return device instanceof ComposedDevice;
81
81
  }
82
82
  //#endregion
83
+ //#region src/builtins/composer/claim-gate.ts
84
+ function claimKey(k) {
85
+ return `${k.owner}@${k.deviceId}#${k.capName}`;
86
+ }
87
+ var RELEASE_CONFIRMATIONS = 2;
88
+ function entryOf$1(key) {
89
+ return {
90
+ key,
91
+ misses: 0,
92
+ attempts: 0
93
+ };
94
+ }
95
+ var ClaimGate = class {
96
+ logger;
97
+ known = /* @__PURE__ */ new Map();
98
+ constructor(logger) {
99
+ this.logger = logger;
100
+ }
101
+ /**
102
+ * The claims the hub holds before this process applied anything. Called once
103
+ * at boot, before the first `filter`. A claim the gate already knows keeps its
104
+ * entry and its miss count.
105
+ */
106
+ seed(claims) {
107
+ const fresh = claims.filter((c) => !this.known.has(claimKey(c)));
108
+ this.known = new Map([...this.known, ...fresh.map((c) => [claimKey(c), entryOf$1({
109
+ deviceId: c.deviceId,
110
+ capName: c.capName,
111
+ owner: c.owner
112
+ })])]);
113
+ }
114
+ /** Every claim known under one owner — what a block whose plan is held keeps (D659 placeholder rule). */
115
+ claimsOf(owner) {
116
+ return [...this.known.values()].filter((e) => e.key.owner === owner).map((e) => e.key);
117
+ }
118
+ /**
119
+ * Learn `wanted` and answer the claims to release NOW: those absent from
120
+ * `wanted` on two consecutive calls, plus those whose earlier release the hub
121
+ * has not confirmed yet. A claim wanted again starts from zero misses.
122
+ */
123
+ filter(wanted) {
124
+ const present = new Map(wanted.map((k) => [claimKey(k), k]));
125
+ const next = /* @__PURE__ */ new Map();
126
+ const releases = [];
127
+ for (const [key, entry] of this.known) {
128
+ if (present.has(key)) {
129
+ next.set(key, {
130
+ ...entry,
131
+ misses: 0,
132
+ attempts: 0
133
+ });
134
+ continue;
135
+ }
136
+ const misses = Math.min(entry.misses + 1, RELEASE_CONFIRMATIONS);
137
+ if (misses < RELEASE_CONFIRMATIONS) this.logger.warn("a claim vanished from one apply — it is kept until a second apply agrees", {
138
+ tags: this.tagsOf(entry.key),
139
+ meta: {
140
+ ...this.metaOf(entry.key),
141
+ misses
142
+ }
143
+ });
144
+ else {
145
+ if (entry.misses < RELEASE_CONFIRMATIONS) this.logger.info("a claim is unwanted on two consecutive applies — it is released to the native provider", {
146
+ tags: this.tagsOf(entry.key),
147
+ meta: this.metaOf(entry.key)
148
+ });
149
+ releases.push(entry.key);
150
+ }
151
+ next.set(key, {
152
+ ...entry,
153
+ misses
154
+ });
155
+ }
156
+ for (const [key, k] of present) if (!next.has(key)) next.set(key, entryOf$1(k));
157
+ this.known = next;
158
+ return releases;
159
+ }
160
+ /** The hub confirmed the release (or held nothing of ours): forgotten. */
161
+ released(key, how) {
162
+ const k = claimKey(key);
163
+ const attempts = this.known.get(k)?.attempts ?? 0;
164
+ this.known = new Map([...this.known].filter(([other]) => other !== k));
165
+ this.logger.info(attempts > 0 ? "claim release landed after failed attempts" : "claim release confirmed by the hub", {
166
+ tags: this.tagsOf(key),
167
+ meta: {
168
+ ...this.metaOf(key),
169
+ outcome: how,
170
+ ...attempts > 0 ? { attempts } : {}
171
+ }
172
+ });
173
+ }
174
+ /** The release did not land: kept, and returned by every later `filter` until it does. Never given up. */
175
+ releaseFailed(key, error) {
176
+ const k = claimKey(key);
177
+ const entry = this.known.get(k);
178
+ if (entry === void 0) return;
179
+ const attempts = entry.attempts + 1;
180
+ this.known = new Map([...this.known, [k, {
181
+ ...entry,
182
+ attempts
183
+ }]]);
184
+ if (attempts > 1) return;
185
+ this.logger.warn("claim release did not land — retried on every apply until it does", {
186
+ tags: this.tagsOf(key),
187
+ meta: {
188
+ ...this.metaOf(key),
189
+ error
190
+ }
191
+ });
192
+ }
193
+ tagsOf(key) {
194
+ return { deviceId: key.deviceId };
195
+ }
196
+ metaOf(key) {
197
+ return {
198
+ owner: key.owner,
199
+ cap: key.capName
200
+ };
201
+ }
202
+ };
203
+ //#endregion
204
+ //#region src/builtins/composer/composed-device-set.ts
205
+ /**
206
+ * The composed devices the composer DECLARED (D659): one row per `new`-target
207
+ * block, hung off the shared Blocks integration, adopted or built by
208
+ * `DeclaredDevices.reconcile`. This is the only place a composed row is created,
209
+ * kept or swept — a composition on an EXISTING device never enters it (D663).
210
+ *
211
+ * - `rows` is the set of stableIds whose row exists: seeded from the persisted
212
+ * rows at boot, then what every declare kept. Planning asks it to decide
213
+ * whether a block that stopped planning has a row to hold as a placeholder.
214
+ * - A changed shape (type, role, cap set, placeholder or not) needs a NEW device
215
+ * object: decommission, and let the reconcile adopt it with the new class. A
216
+ * failure keeps the old device and is retried on the next apply.
217
+ * - A failed reconcile changes nothing (D49): the devices already live stay.
218
+ */
219
+ var ComposedDeviceSet = class {
220
+ deps;
221
+ devices = /* @__PURE__ */ new Map();
222
+ existingRows = /* @__PURE__ */ new Set();
223
+ declaredFingerprint = null;
224
+ constructor(deps) {
225
+ this.deps = deps;
226
+ }
227
+ /** StableIds whose row exists. */
228
+ get rows() {
229
+ return this.existingRows;
230
+ }
231
+ seedRows(rows) {
232
+ this.existingRows = new Set(rows.map((r) => r.stableId));
233
+ }
234
+ get(stableId) {
235
+ return this.devices.get(stableId) ?? null;
236
+ }
237
+ idOf(stableId) {
238
+ return this.devices.get(stableId)?.id ?? null;
239
+ }
240
+ async rebuildShapes(planned, previousOf) {
241
+ const errors = /* @__PURE__ */ new Map();
242
+ for (const p of planned) {
243
+ const previous = previousOf(p.block.id);
244
+ const device = previous?.device ?? null;
245
+ if (previous === void 0 || device === null || p.shape === null) continue;
246
+ if (previous.shape === p.shape) continue;
247
+ try {
248
+ this.deps.logger.info("composition shape changed — rebuilding its device", {
249
+ tags: { deviceId: device.id },
250
+ meta: {
251
+ blockId: p.block.id,
252
+ from: previous.shape,
253
+ to: p.shape
254
+ }
255
+ });
256
+ if (p.spec !== null) await this.deps.devices.applyDerivedSpec(device.id, p.spec);
257
+ await this.deps.devices.decommission(device.id);
258
+ const stableId = composedDeviceStableId(p.block.id);
259
+ this.devices = new Map([...this.devices].filter(([s]) => s !== stableId));
260
+ this.declaredFingerprint = null;
261
+ } catch (err) {
262
+ const error = errMsg(err);
263
+ errors.set(p.block.id, error);
264
+ this.deps.logger.warn("rebuilding a composed device failed — the old one is kept", {
265
+ tags: { deviceId: device.id },
266
+ meta: {
267
+ blockId: p.block.id,
268
+ error
269
+ }
270
+ });
271
+ }
272
+ }
273
+ return errors;
274
+ }
275
+ async reconcile(integrationId, declarations, planned) {
276
+ const shapes = new Map(planned.flatMap((p) => p.declaration === null ? [] : [[p.declaration.stableId, p.shape]]));
277
+ const fingerprint = JSON.stringify(declarations.map((d) => [d.stableId, shapes.get(d.stableId) ?? null]).toSorted());
278
+ const allLive = declarations.every((d) => this.devices.has(d.stableId));
279
+ if (fingerprint === this.declaredFingerprint && allLive) return;
280
+ try {
281
+ const result = await this.deps.declare(integrationId, declarations);
282
+ this.devices = result.devices;
283
+ this.existingRows = new Set(declarations.map((d) => d.stableId).filter((s) => this.existingRows.has(s) || result.devices.has(s)));
284
+ this.declaredFingerprint = fingerprint;
285
+ } catch (err) {
286
+ this.deps.logger.warn("composer: the device declaration failed — keeping the devices already live", { meta: {
287
+ error: errMsg(err),
288
+ declarations: declarations.length
289
+ } });
290
+ }
291
+ }
292
+ };
293
+ //#endregion
83
294
  //#region src/builtins/composer/composition-declarations.ts
84
295
  /**
85
296
  * Which composed devices exist (D659): one declaration per composition block,
@@ -187,6 +398,373 @@ var WithdrawalGate = class {
187
398
  }
188
399
  };
189
400
  //#endregion
401
+ //#region src/builtins/composer/composer-plan.ts
402
+ /**
403
+ * What one apply PLANS for a block, before anything is declared, claimed or
404
+ * run (D659, D663). Pure over its inputs: the composer hands in what it knows
405
+ * (its rows, the previous plan, the tracker) and gets a `PlannedBlock` back.
406
+ *
407
+ * - A `new` target plans as in slice 1: a declaration, a shape, a placeholder
408
+ * when the composition stopped planning but its row exists.
409
+ * - An `existing` target declares NOTHING (the row is not the composer's). It
410
+ * is resolved through the tracker's path, described with one bindings read
411
+ * per plan change, and planned against that description. A settled plan is
412
+ * kept until the OPERATOR acts (edit, restart): a bindings change alone never
413
+ * re-plans (Task 10 rule 2, D659). While the claims index is unseeded or the
414
+ * target is unresolved or undescribed, the block WAITS by name and claims
415
+ * nothing (D49). A target gone on two agreeing index reads is `gone`.
416
+ * - An unreadable row names no target: whatever it holds is held (D49).
417
+ */
418
+ /** The shape of a placeholder: no caps, so no plan to take a shape from. */
419
+ var PLACEHOLDER_SHAPE = "placeholder";
420
+ var NO_PLAN = {
421
+ fields: [],
422
+ problems: [],
423
+ declaration: null,
424
+ shape: null,
425
+ spec: null
426
+ };
427
+ /**
428
+ * A row that exists but does not parse is held exactly like a composition
429
+ * that stopped planning: its device (if it has a row) stays as an offline
430
+ * placeholder, its claims (if any) are kept, and the block fails naming the
431
+ * parse error. Absent, it would be withdrawn on the second apply that omitted
432
+ * it (D49).
433
+ */
434
+ function planUnreadable(block, rows) {
435
+ const stableId = composedDeviceStableId(block.id);
436
+ const hasRow = rows.has(stableId);
437
+ return {
438
+ ...NO_PLAN,
439
+ block: {
440
+ id: block.id,
441
+ name: block.name,
442
+ enabled: false,
443
+ updatedAt: 0
444
+ },
445
+ problems: [`the stored block does not parse — ${block.error}`],
446
+ declaration: hasRow ? placeholderDeclaration(stableId) : null,
447
+ shape: hasRow ? PLACEHOLDER_SHAPE : null,
448
+ target: { kind: "unreadable" }
449
+ };
450
+ }
451
+ /** `target` is the block's own `new` target, narrowed by the caller: this path never sees an existing one (M-5). */
452
+ function planNew(block, target, lookupCap, rows) {
453
+ const plan = planComposition(block.composition, lookupCap);
454
+ const planned = { kind: "new" };
455
+ if (plan.problems.length > 0) {
456
+ const stableId = composedDeviceStableId(block.id);
457
+ const hasRow = rows.has(stableId);
458
+ return {
459
+ ...NO_PLAN,
460
+ block,
461
+ problems: plan.problems.map((p) => `${p.path}: ${p.message}`),
462
+ declaration: hasRow ? placeholderDeclaration(stableId) : null,
463
+ shape: hasRow ? PLACEHOLDER_SHAPE : null,
464
+ target: planned
465
+ };
466
+ }
467
+ const caps = block.composition.features.flatMap((f) => {
468
+ const def = lookupCap(f.cap);
469
+ return def === null ? [] : [def];
470
+ });
471
+ const declarationInput = {
472
+ blockId: block.id,
473
+ name: block.name,
474
+ target,
475
+ caps
476
+ };
477
+ return {
478
+ block,
479
+ fields: plan.fields,
480
+ problems: [],
481
+ declaration: declarationFor(declarationInput),
482
+ shape: shapeOf(declarationInput),
483
+ spec: {
484
+ type: target.type,
485
+ ...target.role === void 0 ? {} : { role: target.role }
486
+ },
487
+ target: planned
488
+ };
489
+ }
490
+ async function planExisting(input) {
491
+ const { block, previous, operatorAction } = input;
492
+ const prior = previous?.target;
493
+ if (!operatorAction && previous !== void 0 && prior?.kind === "existing" && prior.waiting === null) return {
494
+ ...previous,
495
+ block
496
+ };
497
+ const ref = input.target.device;
498
+ const key = compositionSourceKey(ref);
499
+ const knownId = prior?.kind === "existing" ? prior.deviceId : null;
500
+ if (input.claimsWait !== null) return waitingPlan(block, ref, knownId, input.claimsWait);
501
+ const resolution = await input.tracker.resolve(ref, operatorAction);
502
+ if (resolution.kind === "unknown") return waitingPlan(block, ref, knownId, `the target device \`${key}\` could not be resolved (${resolution.error}) — nothing is claimed until it is; retried on the next apply`);
503
+ const existing = {
504
+ kind: "existing",
505
+ ref,
506
+ deviceId: resolution.kind === "found" ? resolution.deviceId : knownId,
507
+ waiting: null,
508
+ gone: null,
509
+ features: [],
510
+ nativeCaps: /* @__PURE__ */ new Map()
511
+ };
512
+ if (resolution.kind === "missing") return {
513
+ ...NO_PLAN,
514
+ block,
515
+ target: {
516
+ ...existing,
517
+ gone: `${resolution.reason} — two index reads agreed`
518
+ }
519
+ };
520
+ const description = await input.targets.describe(ref, resolution.deviceId, resolution.type, operatorAction);
521
+ if (description === null) return waitingPlan(block, ref, resolution.deviceId, `the target device \`${key}\` could not be described (its bindings did not read) — nothing is claimed until it is; retried on the next apply`);
522
+ const plan = planComposition(block.composition, input.lookupCap, description);
523
+ return {
524
+ ...NO_PLAN,
525
+ block,
526
+ fields: plan.problems.length > 0 ? [] : plan.fields,
527
+ problems: plan.problems.map((p) => `${p.path}: ${p.message}`),
528
+ target: {
529
+ ...existing,
530
+ features: plan.features,
531
+ nativeCaps: description.nativeCaps
532
+ }
533
+ };
534
+ }
535
+ function waitingPlan(block, ref, deviceId, waiting) {
536
+ return {
537
+ ...NO_PLAN,
538
+ block,
539
+ target: {
540
+ kind: "existing",
541
+ ref,
542
+ deviceId,
543
+ waiting,
544
+ gone: null,
545
+ features: [],
546
+ nativeCaps: /* @__PURE__ */ new Map()
547
+ }
548
+ };
549
+ }
550
+ /** What `logPlanTransition` compares: problems, and for an existing target its wait or its loss. */
551
+ function planSummary(p) {
552
+ const target = p.target;
553
+ return (target.kind === "existing" ? [
554
+ p.problems.join("; "),
555
+ target.waiting ?? "",
556
+ target.gone ?? ""
557
+ ] : [p.problems.join("; ")]).filter((part) => part !== "").join(" | ");
558
+ }
559
+ /**
560
+ * Rule 5 on the PLAN path: `device.unregistered` is telemetry and may be
561
+ * dropped (D8), so a target is often found gone by the operator's next edit or
562
+ * restart. The previous live target is what must be ungrafted — exactly as on
563
+ * the event path. Null when nothing was lost by THIS plan.
564
+ */
565
+ function lostTarget(p, previous) {
566
+ const now = p.target;
567
+ const before = previous?.target;
568
+ if (now.kind !== "existing" || now.gone === null || before?.kind !== "existing") return null;
569
+ if (before.deviceId === null || before.gone !== null) return null;
570
+ return {
571
+ target: before,
572
+ deviceId: before.deviceId
573
+ };
574
+ }
575
+ /** Two plans write the same place: both new, or the very same existing-target plan (reused until the operator acts). */
576
+ function sameTarget(a, b) {
577
+ return a === b || a.kind === "new" && b.kind === "new";
578
+ }
579
+ /** One line when a block starts or stops planning (or waiting, or loses its target) — never one per apply. */
580
+ function logPlanTransition(logger, previous, p, liveTags) {
581
+ if (previous !== void 0 && planSummary(previous) === planSummary(p)) return;
582
+ if (previous === void 0 && planSummary(p) === "") return;
583
+ const target = p.target;
584
+ const extras = {
585
+ tags: target.kind === "existing" && target.deviceId !== null ? { deviceId: target.deviceId } : liveTags,
586
+ meta: {
587
+ blockId: p.block.id,
588
+ problems: p.problems,
589
+ placeholder: p.declaration !== null
590
+ }
591
+ };
592
+ if (target.kind === "existing" && target.gone !== null) logger.error("customization target device is gone — the block failed; only the operator ends this (edit or restart the block)", {
593
+ ...extras,
594
+ meta: {
595
+ ...extras.meta,
596
+ target: compositionSourceKey(target.ref)
597
+ }
598
+ });
599
+ else if (target.kind === "existing" && target.waiting !== null) logger.warn("customization waits — nothing is claimed or released until it plans", {
600
+ ...extras,
601
+ meta: {
602
+ ...extras.meta,
603
+ reason: target.waiting
604
+ }
605
+ });
606
+ else if (p.problems.length === 0) logger.info("composition plans again", extras);
607
+ else logger.warn(p.declaration === null ? "composition does not plan — no device is declared for it" : "composition no longer plans — its device is kept offline with no capabilities", extras);
608
+ }
609
+ //#endregion
610
+ //#region src/builtins/composer/slice-assembler.ts
611
+ /**
612
+ * From the runtime's flat field values to the slice a target takes (D663).
613
+ *
614
+ * A top-level field is written under its path. An item leaf
615
+ * (`consumables.items[desiccant].remaining.value`) is one entry of an ARRAY:
616
+ * every leaf of one item is grouped by `(cap, arrayPath, key)` and set, by
617
+ * path segment, onto the cap's OWN `status.itemArray.emptyItem` — so an
618
+ * unsourced nullable leaf is `null` because the cap says so, not because this
619
+ * module guessed. The key, the label and {@link COMPOSED_ITEM_FIXED_FIELDS}
620
+ * are the composer's; items are sorted by key so two writes of the same
621
+ * values are one slice.
622
+ *
623
+ * A cap the lookup does not know as an item array cannot be assembled: that
624
+ * is thrown by name, and the runtime's write path turns a throw into a named,
625
+ * retried failure — never a half-built array.
626
+ */
627
+ function isRecord(value) {
628
+ return typeof value === "object" && value !== null && !Array.isArray(value);
629
+ }
630
+ /** `setPath(item, ['remaining', 'value'], 0)` → `{ ...item, remaining: { ...item.remaining, value: 0 } }`. */
631
+ function setPath(record, segments, value) {
632
+ const [head, ...rest] = segments;
633
+ if (head === void 0) return record;
634
+ if (rest.length === 0) return {
635
+ ...record,
636
+ [head]: value
637
+ };
638
+ const current = record[head];
639
+ return {
640
+ ...record,
641
+ [head]: setPath(isRecord(current) ? current : {}, rest, value)
642
+ };
643
+ }
644
+ function itemArrayOf(group, lookupCap) {
645
+ const itemArray = lookupCap(group.cap)?.status?.itemArray;
646
+ if (itemArray === void 0 || itemArray.path !== group.arrayPath) throw new Error(`\`${group.cap}\` has no item array at \`${group.arrayPath}\` — \`${compositionItemFieldPath(group.arrayPath, group.key, "*")}\` cannot be assembled`);
647
+ return itemArray;
648
+ }
649
+ function assembleItem(group, lookupCap) {
650
+ const itemArray = itemArrayOf(group, lookupCap);
651
+ const base = {
652
+ ...itemArray.emptyItem,
653
+ [itemArray.keyField]: group.key,
654
+ ...itemArray.labelField === void 0 ? {} : { [itemArray.labelField]: group.label },
655
+ ...COMPOSED_ITEM_FIXED_FIELDS
656
+ };
657
+ return group.leaves.reduce((item, leaf) => setPath(item, leaf.plan.path.split("."), leaf.value), base);
658
+ }
659
+ function groupItems(entries) {
660
+ const groups = /* @__PURE__ */ new Map();
661
+ for (const entry of entries) {
662
+ const item = entry.plan.item;
663
+ if (item === void 0) continue;
664
+ const id = `${entry.plan.cap}\u0000${item.arrayPath}\u0000${item.key}`;
665
+ const group = groups.get(id) ?? {
666
+ cap: entry.plan.cap,
667
+ arrayPath: item.arrayPath,
668
+ key: item.key,
669
+ label: item.label,
670
+ leaves: []
671
+ };
672
+ groups.set(id, {
673
+ ...group,
674
+ leaves: [...group.leaves, entry]
675
+ });
676
+ }
677
+ return [...groups.values()];
678
+ }
679
+ function compareKeys(a, b) {
680
+ return a < b ? -1 : a > b ? 1 : 0;
681
+ }
682
+ function assembleSlice(entries, lookupCap) {
683
+ const top = Object.fromEntries(entries.filter((e) => e.plan.item === void 0).map((e) => [e.plan.path, e.value]));
684
+ const groups = groupItems(entries);
685
+ const arrays = [...new Set(groups.map((g) => g.arrayPath))].map((arrayPath) => [arrayPath, groups.filter((g) => g.arrayPath === arrayPath).toSorted((a, b) => compareKeys(a.key, b.key)).map((g) => assembleItem(g, lookupCap))]);
686
+ return {
687
+ ...top,
688
+ ...Object.fromEntries(arrays)
689
+ };
690
+ }
691
+ //#endregion
692
+ //#region src/builtins/composer/field-record.ts
693
+ /**
694
+ * One composed field's record and the pure judgements over it (D659, D663):
695
+ * what it may write, whether it is released (a CONFIRMED unavailability of a
696
+ * `release`-mode field, S1b) or HELD (no answer yet, D49), and how a report or a
697
+ * log line names it. Split from `composition-runtime.ts`, which holds the
698
+ * behaviour.
699
+ */
700
+ var NO_FIELDS = /* @__PURE__ */ new Set();
701
+ function fieldKey(plan) {
702
+ return compositionFieldKey(plan);
703
+ }
704
+ /** The top-level field a record writes: an item leaf writes its whole array. */
705
+ function topLevelField(plan) {
706
+ return plan.item === void 0 ? plan.path : plan.item.arrayPath;
707
+ }
708
+ /** The field as a report or a log line names it: `items[desiccant].status` for an item leaf. */
709
+ function fieldPath(plan) {
710
+ return plan.item === void 0 ? plan.path : compositionItemFieldPath(plan.item.arrayPath, plan.item.key, plan.path);
711
+ }
712
+ function itemOf(plan) {
713
+ return plan.item === void 0 ? {} : { item: plan.item };
714
+ }
715
+ function sameSet(a, b) {
716
+ return a.size === b.size && [...a].every((x) => b.has(x));
717
+ }
718
+ function valueOf(outcome) {
719
+ return outcome === null || outcome.state === "unavailable" ? void 0 : outcome.value;
720
+ }
721
+ function reasonOf(outcome) {
722
+ if (outcome === null) return "not evaluated yet";
723
+ return outcome.reason;
724
+ }
725
+ /** State, value and reason — what a write or a log line is about. NEVER the deadline (R1). */
726
+ function sameOutcome(a, b) {
727
+ return a !== null && a.state === b.state && valueOf(a) === valueOf(b) && reasonOf(a) === reasonOf(b);
728
+ }
729
+ /** A source is GONE: the outcome that must never be masked by a non-fatal one. */
730
+ function isFatal(outcome) {
731
+ return outcome !== null && outcome.state === "unavailable" && outcome.fatal;
732
+ }
733
+ /** A `release`-mode field whose source is CONFIRMED unavailable: not the composition's to write (S1b). Stale is a value (D49). */
734
+ function isReleased(record) {
735
+ const outcome = record.outcome;
736
+ return record.plan.unavailable === "release" && outcome?.state === "unavailable" && outcome.confirmed === true;
737
+ }
738
+ /** A `release`-mode field with no value and no ANSWER yet (a failed, first or empty read): held on its last value, never released (D49). */
739
+ function isHeld(record) {
740
+ const outcome = record.outcome;
741
+ return record.plan.unavailable === "release" && outcome?.state === "unavailable" && outcome.confirmed !== true;
742
+ }
743
+ function namedField(r) {
744
+ return {
745
+ cap: r.plan.cap,
746
+ path: r.plan.path,
747
+ ...itemOf(r.plan),
748
+ reason: reasonOf(r.outcome) ?? "unavailable"
749
+ };
750
+ }
751
+ function writable(record) {
752
+ const outcome = record.outcome;
753
+ if (outcome === null) return void 0;
754
+ if (outcome.state !== "unavailable") return outcome.value;
755
+ switch (record.plan.unavailable) {
756
+ case "null": return null;
757
+ case "unknown": return "unknown";
758
+ default: return;
759
+ }
760
+ }
761
+ function errorText(error) {
762
+ return error instanceof Error ? error.message : String(error);
763
+ }
764
+ function pendingReason(cap, pending) {
765
+ return pending.kind === "refused" ? `the \`${cap}\` capability refused the value: ${pending.error}` : `writing the \`${cap}\` capability threw: ${pending.error}`;
766
+ }
767
+ //#endregion
190
768
  //#region src/builtins/composer/composition-runtime.ts
191
769
  /**
192
770
  * One running composition: per-field state, writes to the composed device, and
@@ -217,37 +795,35 @@ var WithdrawalGate = class {
217
795
  * - Nothing escapes: a pass that throws is logged, and the timer is re-armed
218
796
  * from the stored deadlines regardless.
219
797
  * - `stop()` is terminal: every entry point is a no-op afterwards.
798
+ *
799
+ * Slice 2 (D663):
800
+ * - Records are keyed by `compositionFieldKey`: two items' `status` are two
801
+ * records. An item-array cap is written WHOLE — a change to one item leaf
802
+ * re-sends every item, assembled by `assembleSlice` on the cap's `emptyItem`.
803
+ * A required item leaf with no fallback holds the array, named once.
804
+ * - `'unknown'` unavailable mode writes the enum's own word.
805
+ * - `'release'` unavailable mode hands the field BACK (ruling S1b): the target
806
+ * is told to `withhold` it, the field's record forgets what it wrote, and the
807
+ * source returning re-widens and writes it again. Stale is a value (D49),
808
+ * never a release — and neither is an UNCONFIRMED unavailability (a failed,
809
+ * first or empty read): the field is HELD on its last value, not written,
810
+ * not withheld, its claim kept, until the source answers (D49, fix round 2).
811
+ * `state().released` / `state().held` name every such field for the report.
812
+ * - A target whose writes are asynchronous (claims on the hub) reports what did
813
+ * not land through `onAsyncFailure`: the cap is marked write-pending by name
814
+ * and re-written whole on the next pass — no retry timer (D3).
220
815
  */
221
- function errorText(error) {
222
- return error instanceof Error ? error.message : String(error);
223
- }
224
- function pendingReason(cap, pending) {
225
- return pending.kind === "refused" ? `the \`${cap}\` capability refused the value: ${pending.error}` : `writing the \`${cap}\` capability threw: ${pending.error}`;
226
- }
227
- function fieldKey(plan) {
228
- return `${plan.cap}.${plan.path}`;
229
- }
230
- function valueOf(outcome) {
231
- return outcome === null || outcome.state === "unavailable" ? void 0 : outcome.value;
232
- }
233
- function reasonOf(outcome) {
234
- if (outcome === null) return "not evaluated yet";
235
- return outcome.reason;
236
- }
237
- /** State, value and reason — what a write or a log line is about. NEVER the deadline (R1). */
238
- function sameOutcome(a, b) {
239
- return a !== null && a.state === b.state && valueOf(a) === valueOf(b) && reasonOf(a) === reasonOf(b);
240
- }
241
- /** A source is GONE: the outcome that must never be masked by a non-fatal one. */
242
- function isFatal(outcome) {
243
- return outcome !== null && outcome.state === "unavailable" && outcome.fatal;
244
- }
245
- function writable(record) {
246
- const outcome = record.outcome;
247
- if (outcome === null) return void 0;
248
- if (outcome.state !== "unavailable") return outcome.value;
249
- return record.plan.unavailable === "null" ? null : void 0;
250
- }
816
+ /**
817
+ * A refusal nothing on this side can retry away: another owner holds the
818
+ * field, the slice is invalid for the cap, the device is not known. Every
819
+ * other outcome — a throw, an unreadable row, a migration in flight, a lost
820
+ * claim — is transient and retried on the next pass (D6: bounded, never a loop).
821
+ */
822
+ var TERMINAL_REFUSALS = new Set([
823
+ "owned-by-other",
824
+ "invalid-slice",
825
+ "unknown-device"
826
+ ]);
251
827
  var CompositionRuntime = class {
252
828
  deps;
253
829
  records;
@@ -260,6 +836,16 @@ var CompositionRuntime = class {
260
836
  lastPassError = null;
261
837
  pending = /* @__PURE__ */ new Map();
262
838
  heldBack = /* @__PURE__ */ new Set();
839
+ /** Caps whose item array is not written because a required leaf has no value. */
840
+ itemsHeld = /* @__PURE__ */ new Set();
841
+ /** Record keys currently released (S1b), for transition logs and the report. */
842
+ released = /* @__PURE__ */ new Set();
843
+ /** Per cap, the top-level fields the target last accepted as withheld; absent = none. */
844
+ withheld = /* @__PURE__ */ new Map();
845
+ /** Per record key, how many times the field has been released — churn the transition line reports (D391). */
846
+ releaseFlaps = /* @__PURE__ */ new Map();
847
+ /** Caps the target refused for good (`TERMINAL_REFUSALS`): never written again by this runtime. */
848
+ terminal = /* @__PURE__ */ new Map();
263
849
  constructor(deps) {
264
850
  this.deps = deps;
265
851
  this.records = new Map(deps.fields.map((plan) => [fieldKey(plan), {
@@ -267,6 +853,7 @@ var CompositionRuntime = class {
267
853
  outcome: null,
268
854
  written: void 0
269
855
  }]));
856
+ deps.target.onAsyncFailure?.((cap, failure) => this.onTargetWriteFailed(cap, failure));
270
857
  }
271
858
  start() {
272
859
  if (this.disabledReason !== null) return;
@@ -288,7 +875,8 @@ var CompositionRuntime = class {
288
875
  state: "unavailable",
289
876
  value: null,
290
877
  reason,
291
- fatal: false
878
+ fatal: false,
879
+ confirmed: true
292
880
  };
293
881
  const touched = [...this.records.values()].filter((r) => !isFatal(r.outcome) && !sameOutcome(r.outcome, outcome));
294
882
  for (const r of touched) this.logTransition(r, outcome);
@@ -310,10 +898,20 @@ var CompositionRuntime = class {
310
898
  failure: this.failure,
311
899
  available: this.available === true,
312
900
  fields: [...this.records.values()].map((r) => {
901
+ const terminal = this.terminal.get(r.plan.cap);
902
+ if (terminal !== void 0 && !isFatal(r.outcome)) return {
903
+ cap: r.plan.cap,
904
+ path: r.plan.path,
905
+ ...itemOf(r.plan),
906
+ state: "unavailable",
907
+ value: null,
908
+ reason: terminal
909
+ };
313
910
  const pending = this.pending.get(r.plan.cap);
314
911
  if (pending !== void 0 && !isFatal(r.outcome)) return {
315
912
  cap: r.plan.cap,
316
913
  path: r.plan.path,
914
+ ...itemOf(r.plan),
317
915
  state: "unavailable",
318
916
  value: null,
319
917
  reason: pendingReason(r.plan.cap, pending)
@@ -323,20 +921,69 @@ var CompositionRuntime = class {
323
921
  return {
324
922
  cap: r.plan.cap,
325
923
  path: r.plan.path,
924
+ ...itemOf(r.plan),
326
925
  state: r.outcome?.state ?? "unavailable",
327
926
  value: value === void 0 ? null : value,
328
927
  ...reason === null ? {} : { reason }
329
928
  };
330
- })
929
+ }),
930
+ released: [...this.records.values()].filter(isReleased).map(namedField),
931
+ held: [...this.records.values()].filter(isHeld).map(namedField)
331
932
  };
332
933
  }
333
934
  /**
334
- * Every entry point runs here: a no-op once stopped, nothing thrown escapes,
335
- * and the one timer is re-armed from the stored deadlines whatever happened.
935
+ * The target's enqueued write of `cap` did not land: the cap is write-pending
936
+ * by name and re-written WHOLE on the next pass that evaluates it (or the next
937
+ * deadline pass). A withhold sent to that target is forgotten too, so it is
938
+ * re-sent. No retry timer (D3).
336
939
  */
337
- guarded(during, rearm, body) {
338
- if (this.stopped) return;
339
- let threw = false;
940
+ onTargetWriteFailed(cap, failure) {
941
+ this.guarded("target-failure", false, () => {
942
+ if (!this.deps.fields.some((f) => f.cap === cap) || this.terminal.has(cap)) return;
943
+ if (failure.kind === "refused" && TERMINAL_REFUSALS.has(failure.code)) {
944
+ this.markTerminal(cap, failure.code, failure.message);
945
+ return;
946
+ }
947
+ this.withheld = new Map([...this.withheld].filter(([c]) => c !== cap));
948
+ this.markPending(cap, this.seeded.has(cap) ? "patch" : "seed", failure.kind === "threw" ? {
949
+ kind: "threw",
950
+ error: failure.error
951
+ } : {
952
+ kind: "refused",
953
+ error: `${failure.code}: ${failure.message}`
954
+ });
955
+ this.updateAvailability();
956
+ });
957
+ }
958
+ /**
959
+ * The target refused this cap for good: nothing on this side can retry it
960
+ * away (I-3). The cap is never written again by this runtime, its fields
961
+ * report the refusal, and the block fails naming it — only the operator ends
962
+ * this (edit or delete the block, or the competing one), like a gone source.
963
+ */
964
+ markTerminal(cap, code, message) {
965
+ const reason = `the \`${cap}\` capability was refused for good: ${code}: ${message} — only the operator ends this (edit or delete the block)`;
966
+ this.terminal = new Map([...this.terminal, [cap, reason]]);
967
+ this.pending = new Map([...this.pending].filter(([c]) => c !== cap));
968
+ if (this.failure === null) this.failure = `composed write refused for good — ${cap}: ${code}: ${message}`;
969
+ this.deps.logger.error("composed capability refused for good — it is not written again until the operator edits or deletes the block", {
970
+ tags: { deviceId: this.deps.target.id },
971
+ meta: {
972
+ blockId: this.deps.blockId,
973
+ cap,
974
+ code,
975
+ error: message
976
+ }
977
+ });
978
+ this.updateAvailability();
979
+ }
980
+ /**
981
+ * Every entry point runs here: a no-op once stopped, nothing thrown escapes,
982
+ * and the one timer is re-armed from the stored deadlines whatever happened.
983
+ */
984
+ guarded(during, rearm, body) {
985
+ if (this.stopped) return;
986
+ let threw = false;
340
987
  try {
341
988
  body();
342
989
  this.lastPassError = null;
@@ -415,35 +1062,153 @@ var CompositionRuntime = class {
415
1062
  const cap = this.records.get(k)?.plan.cap;
416
1063
  return cap === void 0 ? [] : [cap];
417
1064
  }), ...retry]);
418
- for (const cap of caps) if (!this.seeded.has(cap)) this.seedCap(cap);
419
- else if (this.pending.has(cap)) this.patchWholeCap(cap);
420
- else this.patchCap(cap, touched);
1065
+ for (const cap of caps) {
1066
+ if (this.terminal.has(cap)) continue;
1067
+ const sync = this.syncReleased(cap);
1068
+ if (sync === "failed") continue;
1069
+ if (!this.seeded.has(cap)) this.seedCap(cap);
1070
+ else if (this.pending.has(cap) || sync === "changed") this.patchWholeCap(cap, sync === "changed");
1071
+ else this.patchCap(cap, touched);
1072
+ }
1073
+ }
1074
+ /**
1075
+ * S1b: tell the target which fields of `cap` are released, when that set
1076
+ * changed since it last accepted one. A released record forgets what it wrote,
1077
+ * so the source returning writes it again. False when the target refused or
1078
+ * threw: the cap is write-pending and the withhold is re-sent next pass.
1079
+ */
1080
+ syncReleased(cap) {
1081
+ const records = this.recordsOf(cap);
1082
+ this.logReleaseTransitions(cap, records);
1083
+ const releasedRecords = records.filter(isReleased);
1084
+ this.records = new Map([...this.records].map(([k, r]) => releasedRecords.includes(r) && r.written !== void 0 ? [k, {
1085
+ ...r,
1086
+ written: void 0
1087
+ }] : [k, r]));
1088
+ const withhold = this.deps.target.withhold;
1089
+ if (withhold === void 0) return "unchanged";
1090
+ const fields = new Set(releasedRecords.map((r) => topLevelField(r.plan)));
1091
+ if (sameSet(fields, this.withheld.get(cap) ?? NO_FIELDS)) return "unchanged";
1092
+ let failed;
1093
+ try {
1094
+ const outcome = withhold.call(this.deps.target, cap, [...fields].toSorted());
1095
+ failed = outcome.ok ? null : {
1096
+ kind: "refused",
1097
+ error: outcome.error
1098
+ };
1099
+ } catch (error) {
1100
+ failed = {
1101
+ kind: "threw",
1102
+ error: errorText(error)
1103
+ };
1104
+ }
1105
+ if (failed !== null) {
1106
+ this.markPending(cap, this.seeded.has(cap) ? "patch" : "seed", failed);
1107
+ return "failed";
1108
+ }
1109
+ this.withheld = new Map([...this.withheld.entries()].filter(([c]) => c !== cap).concat(fields.size === 0 ? [] : [[cap, fields]]));
1110
+ return "changed";
1111
+ }
1112
+ /** One info line per field per direction, never one per pass. */
1113
+ logReleaseTransitions(cap, records) {
1114
+ const now = new Set(records.filter(isReleased).map((r) => fieldKey(r.plan)));
1115
+ const before = new Set(records.filter((r) => this.released.has(fieldKey(r.plan))).map((r) => fieldKey(r.plan)));
1116
+ for (const r of records) {
1117
+ const key = fieldKey(r.plan);
1118
+ const direction = now.has(key) && !before.has(key) ? "released" : !now.has(key) && before.has(key) ? "reclaimed" : null;
1119
+ if (direction === null) continue;
1120
+ const flaps = (this.releaseFlaps.get(key) ?? 0) + (direction === "released" ? 1 : 0);
1121
+ this.releaseFlaps = new Map([...this.releaseFlaps, [key, flaps]]);
1122
+ this.deps.logger.info(direction === "released" ? "composed field released to the native provider — its source is unavailable" : "composed field reclaimed from the native provider — its source is back", {
1123
+ tags: { deviceId: this.deps.target.id },
1124
+ meta: {
1125
+ blockId: this.deps.blockId,
1126
+ cap,
1127
+ field: fieldPath(r.plan),
1128
+ direction,
1129
+ reason: reasonOf(r.outcome) ?? "value available again",
1130
+ flaps
1131
+ }
1132
+ });
1133
+ }
1134
+ this.released = new Set([...[...this.released].filter((k) => !before.has(k)), ...now]);
421
1135
  }
422
1136
  seedCap(cap) {
423
1137
  const records = this.recordsOf(cap);
424
- const missing = records.filter((r) => r.plan.required && writable(r) === void 0).map((r) => r.plan.path);
1138
+ const missing = records.filter((r) => (r.plan.required || isHeld(r)) && writable(r) === void 0 && !isReleased(r)).map((r) => fieldPath(r.plan));
425
1139
  if (missing.length > 0) return this.holdBackSeed(cap, missing);
426
1140
  this.heldBack = new Set([...this.heldBack].filter((c) => c !== cap));
427
- const entries = this.writableEntries(records);
1141
+ const entries = this.entriesFor(cap, records);
428
1142
  if (!this.write(cap, "seed", entries)) return;
429
1143
  this.seeded = new Set([...this.seeded, cap]);
430
1144
  this.markWritten(cap, entries);
431
1145
  }
432
1146
  patchCap(cap, touched) {
433
- const entries = this.writableEntries(this.recordsOf(cap).filter((r) => touched.has(fieldKey(r.plan)) && writable(r) !== r.written));
1147
+ const entries = this.entriesFor(cap, this.recordsOf(cap).filter((r) => touched.has(fieldKey(r.plan)) && writable(r) !== r.written));
434
1148
  if (entries.length === 0) return;
435
1149
  if (this.write(cap, "patch", entries)) this.markWritten(cap, entries);
436
1150
  }
437
- /** After a failed write nothing is known about what landed: send every current value. */
438
- patchWholeCap(cap) {
439
- const entries = this.writableEntries(this.recordsOf(cap));
440
- if (entries.length === 0) return;
1151
+ /**
1152
+ * After a failed write nothing is known about what landed, and after a
1153
+ * changed withhold the claim must be re-stated: send every current value.
1154
+ * `afterWithhold` with nothing left to write means the cap was released
1155
+ * whole — a pending write is moot then, not retried (M-2).
1156
+ */
1157
+ patchWholeCap(cap, afterWithhold = false) {
1158
+ const entries = this.entriesFor(cap, this.recordsOf(cap));
1159
+ if (entries.length === 0) {
1160
+ if (afterWithhold && this.pending.has(cap)) this.dropPending(cap);
1161
+ return;
1162
+ }
441
1163
  if (this.write(cap, "patch", entries)) this.markWritten(cap, entries);
442
1164
  }
1165
+ dropPending(cap) {
1166
+ this.pending = new Map([...this.pending].filter(([c]) => c !== cap));
1167
+ this.deps.logger.info("composed capability released whole — its pending write is moot, nothing is left to write", {
1168
+ tags: { deviceId: this.deps.target.id },
1169
+ meta: {
1170
+ blockId: this.deps.blockId,
1171
+ cap
1172
+ }
1173
+ });
1174
+ }
1175
+ /**
1176
+ * What one write of `cap` carries: the writable `candidates` — and, when any
1177
+ * of them is an item leaf, EVERY item leaf of the cap, because the array is
1178
+ * written whole (a patch of `items` replaces it). A required item leaf with
1179
+ * no value holds the whole array (its top-level siblings still go out).
1180
+ */
1181
+ entriesFor(cap, candidates) {
1182
+ const top = candidates.filter((r) => r.plan.item === void 0);
1183
+ if (!candidates.some((r) => r.plan.item !== void 0)) return this.writableEntries(top);
1184
+ const items = this.recordsOf(cap).filter((r) => r.plan.item !== void 0);
1185
+ const missing = items.filter((r) => r.plan.required && writable(r) === void 0).map((r) => fieldPath(r.plan));
1186
+ if (missing.length > 0) {
1187
+ this.holdItems(cap, missing);
1188
+ return this.writableEntries(top);
1189
+ }
1190
+ this.itemsHeld = new Set([...this.itemsHeld].filter((c) => c !== cap));
1191
+ return this.writableEntries([...top, ...items]);
1192
+ }
443
1193
  writableEntries(records) {
444
1194
  return records.flatMap((r) => {
445
- const v = writable(r);
446
- return v === void 0 ? [] : [[r.plan.path, v]];
1195
+ const value = writable(r);
1196
+ return value === void 0 ? [] : [{
1197
+ plan: r.plan,
1198
+ value
1199
+ }];
1200
+ });
1201
+ }
1202
+ holdItems(cap, missing) {
1203
+ if (this.itemsHeld.has(cap)) return;
1204
+ this.itemsHeld = new Set([...this.itemsHeld, cap]);
1205
+ this.deps.logger.warn("composed items held — a required item field has no value; the array is not written until it does", {
1206
+ tags: { deviceId: this.deps.target.id },
1207
+ meta: {
1208
+ blockId: this.deps.blockId,
1209
+ cap,
1210
+ missing
1211
+ }
447
1212
  });
448
1213
  }
449
1214
  holdBackSeed(cap, missing) {
@@ -458,11 +1223,11 @@ var CompositionRuntime = class {
458
1223
  }
459
1224
  });
460
1225
  }
461
- /** One write. A refusal or a throw marks the cap write-pending; true when it landed. */
1226
+ /** One write. A refusal or a throw marks the cap write-pending; true when the target took it. */
462
1227
  write(cap, op, entries) {
463
- const values = Object.fromEntries(entries);
464
1228
  let failed;
465
1229
  try {
1230
+ const values = assembleSlice(entries, this.deps.lookupCap);
466
1231
  const outcome = op === "seed" ? this.deps.target.seed(cap, values) : this.deps.target.patch(cap, values);
467
1232
  failed = outcome.ok ? null : {
468
1233
  kind: "refused",
@@ -508,10 +1273,10 @@ var CompositionRuntime = class {
508
1273
  });
509
1274
  }
510
1275
  markWritten(cap, entries) {
511
- const written = new Map(entries);
512
- this.records = new Map([...this.records].map(([k, r]) => r.plan.cap === cap && written.has(r.plan.path) ? [k, {
1276
+ const written = new Map(entries.map((e) => [fieldKey(e.plan), e.value]));
1277
+ this.records = new Map([...this.records].map(([k, r]) => r.plan.cap === cap && written.has(k) ? [k, {
513
1278
  ...r,
514
- written: written.get(r.plan.path)
1279
+ written: written.get(k)
515
1280
  }] : [k, r]));
516
1281
  }
517
1282
  updateAvailability() {
@@ -586,6 +1351,724 @@ var CompositionRuntime = class {
586
1351
  }
587
1352
  };
588
1353
  //#endregion
1354
+ //#region src/builtins/composer/confirmed-seed.ts
1355
+ var ConfirmedSeed = class {
1356
+ deps;
1357
+ seeded = false;
1358
+ /** The previous read answered `[]`: one more `[]` confirms it (D49). */
1359
+ emptySeen = false;
1360
+ /** Consecutive applies whose read did not answer: warned once per run. */
1361
+ waitApplies = 0;
1362
+ constructor(deps) {
1363
+ this.deps = deps;
1364
+ }
1365
+ get done() {
1366
+ return this.seeded;
1367
+ }
1368
+ /** Null once seeded, else why this apply must wait. */
1369
+ async ensure() {
1370
+ if (this.seeded) return null;
1371
+ const read = await this.deps.read();
1372
+ if (read.kind === "unknown") {
1373
+ this.emptySeen = false;
1374
+ this.waitApplies += 1;
1375
+ if (this.waitApplies === 1) this.deps.logger.warn(`composer: the ${this.deps.subject} could not be read — nothing is declared, withdrawn, claimed or released from them; retried on the next apply`, { meta: {
1376
+ subject: this.deps.subject,
1377
+ error: read.error
1378
+ } });
1379
+ return this.deps.unreadReason;
1380
+ }
1381
+ if (read.items.length === 0 && !this.emptySeen) {
1382
+ this.emptySeen = true;
1383
+ this.deps.logger.warn(`composer: the ${this.deps.subject} read empty — waiting for the next apply's read to agree before trusting it`, { meta: { subject: this.deps.subject } });
1384
+ return this.deps.emptyUnconfirmedReason;
1385
+ }
1386
+ this.deps.onSeeded(read.items);
1387
+ this.seeded = true;
1388
+ this.deps.logger.info(`composer: seeded from the ${this.deps.subject}`, { meta: {
1389
+ subject: this.deps.subject,
1390
+ items: read.items.length,
1391
+ confirmedEmpty: read.items.length === 0,
1392
+ appliesRefused: this.waitApplies
1393
+ } });
1394
+ return null;
1395
+ }
1396
+ };
1397
+ //#endregion
1398
+ //#region src/builtins/composer/existing-target.ts
1399
+ /**
1400
+ * What the composer needs to run a composition on an EXISTING device (D663)
1401
+ * besides the runtime and the claim-backed target: the target's description,
1402
+ * the claim shapes derived from the plan, and the block report's words.
1403
+ *
1404
+ * - The target is DESCRIBED (bound caps → native addon, row type) with ONE
1405
+ * `getBindings` per plan change, cached until `device.bindings-changed` for
1406
+ * that device. A read that fails keeps the previous description; with none,
1407
+ * the block waits and nothing is claimed (D49).
1408
+ * - A claim's field set is the PLAN's (S5): the top-level fields of the cap, an
1409
+ * item leaf contributing its whole array. Its mode is the feature's.
1410
+ * - A self-read of the target (rule 6) is served from the NATIVE view unless it
1411
+ * reads an ADDED cap — that is the composition's own output. Whether a native
1412
+ * cap's `device.state-changed` is the native or the composition's own merge
1413
+ * is NOT decided here from the plan: it follows whether the claim has landed
1414
+ * (`HeldClaims`, C-1).
1415
+ */
1416
+ /** The reason every ungraft of a gone target carries (Task 9 rule 5 / Task 10 rule 2). */
1417
+ var TARGET_GONE_UNGRAFT_REASON = "target device gone";
1418
+ /**
1419
+ * Rule 5, on either path that finds the target gone (`device.unregistered`, or
1420
+ * a later plan when that event was dropped): ungraft every cap the block ADDED
1421
+ * on that id, with the one ERROR that says so.
1422
+ */
1423
+ function ungraftGoneTarget(input) {
1424
+ const { grafts, deviceId } = input;
1425
+ const added = addedCapsOf(input.features);
1426
+ for (const cap of added) grafts?.ungraft(deviceId, cap, TARGET_GONE_UNGRAFT_REASON);
1427
+ input.logger.error("customization target device is gone — the block failed and its grafts are removed; only the operator ends this (edit or restart the block)", {
1428
+ tags: { deviceId },
1429
+ meta: {
1430
+ blockId: input.blockId,
1431
+ target: compositionSourceKey(input.ref),
1432
+ ungrafted: added,
1433
+ graftHost: grafts !== void 0
1434
+ }
1435
+ });
1436
+ }
1437
+ var TargetDescriptions = class {
1438
+ logger;
1439
+ readBoundCaps;
1440
+ cache = /* @__PURE__ */ new Map();
1441
+ constructor(logger, readBoundCaps) {
1442
+ this.logger = logger;
1443
+ this.readBoundCaps = readBoundCaps;
1444
+ }
1445
+ /** `device.bindings-changed` for this device: the next read is a real read. */
1446
+ invalidate(deviceId) {
1447
+ this.cache = new Map([...this.cache].filter(([, d]) => d.deviceId !== deviceId));
1448
+ }
1449
+ /**
1450
+ * The description of `ref`, resolved to `deviceId`. Served from the cache
1451
+ * unless `force` (the block's plan changed) or nothing is cached. A read that
1452
+ * fails keeps the previous description of the SAME device id, and answers
1453
+ * null when there is none: the caller waits, and claims nothing.
1454
+ */
1455
+ async describe(ref, deviceId, type, force) {
1456
+ const key = compositionSourceKey(ref);
1457
+ const cached = this.cache.get(key);
1458
+ const previous = cached !== void 0 && cached.deviceId === deviceId ? cached : null;
1459
+ if (!force && previous !== null) return previous;
1460
+ const read = await this.readBoundCaps(deviceId);
1461
+ if (read.kind === "unreadable") {
1462
+ this.logger.warn(previous === null ? "customization target: its bindings could not be read — nothing is claimed until they are; retried on the next apply" : "customization target: its bindings could not be read — the previous description is kept", {
1463
+ tags: { deviceId },
1464
+ meta: {
1465
+ target: key,
1466
+ error: read.error
1467
+ }
1468
+ });
1469
+ return previous;
1470
+ }
1471
+ const found = {
1472
+ kind: "found",
1473
+ deviceId,
1474
+ type,
1475
+ nativeCaps: read.caps
1476
+ };
1477
+ this.cache = new Map([...this.cache, [key, found]]);
1478
+ return found;
1479
+ }
1480
+ };
1481
+ /** The PLANNED field set a claim carries for `cap` (S5): an item leaf claims its whole array. */
1482
+ function claimFieldsOf(fields, cap) {
1483
+ return [...new Set(fields.filter((f) => f.cap === cap).map((f) => f.item === void 0 ? f.path : f.item.arrayPath))];
1484
+ }
1485
+ /** The claim mode of `cap`: `replace` for a cap the device serves natively, else `add`. */
1486
+ function claimModeOf(features, cap) {
1487
+ return features.find((f) => f.cap === cap)?.mode === "replace" ? "replace" : "add";
1488
+ }
1489
+ /** The caps a customization ADDS to its target — the ones it grafts a native for (Task 10). */
1490
+ function addedCapsOf(features) {
1491
+ return features.filter((f) => f.mode === "add").map((f) => f.cap);
1492
+ }
1493
+ function selfReadCaps(fields, target, features) {
1494
+ const targetKey = compositionSourceKey(target);
1495
+ const read = new Set(fields.flatMap((f) => f.reads.filter((r) => compositionSourceKey(r.source) === targetKey).map((r) => r.cap)));
1496
+ const added = new Set(addedCapsOf(features));
1497
+ return {
1498
+ effective: [...read].filter((cap) => added.has(cap)),
1499
+ native: [...read].filter((cap) => !added.has(cap))
1500
+ };
1501
+ }
1502
+ /** The `degraded` reason (rule 8): one entry per released field, the source's own reason after the dash. */
1503
+ function degradedReason(released) {
1504
+ return released.map((r) => {
1505
+ const path = r.item === void 0 ? r.path : compositionItemFieldPath(r.item.arrayPath, r.item.key, r.path);
1506
+ return `released to the native provider: ${r.cap}.${path} — ${r.reason}`;
1507
+ }).join("; ");
1508
+ }
1509
+ /** The `starting` reason of a block with HELD fields: each keeps its last value and claim until its source answers (D49). */
1510
+ function heldReason(held) {
1511
+ return held.map((r) => {
1512
+ const path = r.item === void 0 ? r.path : compositionItemFieldPath(r.item.arrayPath, r.item.key, r.path);
1513
+ return `held on its last value until its source answers (D49): ${r.cap}.${path} — ${r.reason}`;
1514
+ }).join("; ");
1515
+ }
1516
+ /**
1517
+ * Rule 4: a customization whose row exists but whose plan failed keeps its
1518
+ * claims, so its owned fields stay at their last value on the hub. The report
1519
+ * says so — each field that had a value is `stale`, with the reason.
1520
+ */
1521
+ function heldFieldsOf(fields, reason) {
1522
+ return fields.map((f) => f.state === "unavailable" ? f : {
1523
+ ...f,
1524
+ state: "stale",
1525
+ reason
1526
+ });
1527
+ }
1528
+ //#endregion
1529
+ //#region src/builtins/composer/composer-grafts.ts
1530
+ /**
1531
+ * The composer's side of grafts (D663, Task 10): WHEN a cap a customization
1532
+ * ADDS is grafted, removed or refused — `GraftHost` is only the how. Split from
1533
+ * `composer.ts`.
1534
+ *
1535
+ * - Decided at PLAN time only (rule 2): every added cap is grafted; a grafted
1536
+ * cap the plan now finds native is ungrafted (its event was dropped, D8).
1537
+ * - NATIVE ALWAYS WINS (I-2). A foreign `native-registered` on a grafted cap
1538
+ * ungrafts it (the claim stays). One that lands while a plan is in flight —
1539
+ * after the target's description was read, before the graft — is remembered
1540
+ * per described device, so that plan never grafts over it. A foreign
1541
+ * `native-unregistered` never re-grafts (D659).
1542
+ * - A cap no graft serves is NAMED for the block verdict (I-1): refused by the
1543
+ * host, or taken by a native. Every added cap unserved → the block fails.
1544
+ * - A binding a PREVIOUS composer process left (a respawn, D5) is retracted
1545
+ * when a settled plan does not want it (I-3), or when the gate releases the
1546
+ * add claim of a block that is gone — after reading that the binding IS the
1547
+ * composer's; a read that fails retracts nothing (D49).
1548
+ */
1549
+ /** A foreign native now serves the grafted cap: the claim stays (Task 10 rule 2). */
1550
+ var NATIVE_APPEARED_UNGRAFT_REASON = "a native provider appeared";
1551
+ /** The block's add claim was released by the D49 gate (deleted, disabled, feature removed): its graft goes with it. */
1552
+ var NO_LONGER_ADDED_UNGRAFT_REASON = "the block no longer adds this cap";
1553
+ /** A binding a previous composer process left, that nothing wants any more (I-3). */
1554
+ var STALE_GRAFT_RETRACT_REASON = "a graft left by a previous composer process that no plan wants";
1555
+ function withEntry(map, key, value) {
1556
+ return new Map([...map, [key, value]]);
1557
+ }
1558
+ function nativeTakenReason(addonId, when) {
1559
+ return `a native provider (${addonId}) ${when} — the cap is not grafted and its claim is kept; edit or restart the block to replace the native instead`;
1560
+ }
1561
+ var ComposerGrafts = class {
1562
+ ports;
1563
+ logger;
1564
+ readBindings;
1565
+ /** Per device: the added caps no graft serves, and why. Reset by each plan of that device. */
1566
+ unserved = /* @__PURE__ */ new Map();
1567
+ /** Per DESCRIBED device: foreign natives registered since its description was read (cap → addonId). */
1568
+ foreignSince = /* @__PURE__ */ new Map();
1569
+ constructor(ports, logger, readBindings) {
1570
+ this.ports = ports;
1571
+ this.logger = logger;
1572
+ this.readBindings = readBindings;
1573
+ }
1574
+ /** A description of `deviceId` is about to be read: it covers every registration before now. */
1575
+ describing(deviceId) {
1576
+ this.foreignSince = withEntry(this.foreignSince, deviceId, /* @__PURE__ */ new Map());
1577
+ }
1578
+ onBindingsChanged(data) {
1579
+ if (data.addonId === "composer") return;
1580
+ this.remember(data);
1581
+ const ports = this.ports;
1582
+ if (data.reason !== "native-registered" || ports === void 0) return;
1583
+ if (!ports.grafted(data.deviceId).has(data.capName)) return;
1584
+ this.logger.info("a native provider appeared on a grafted cap — the graft is removed; the claim stays", {
1585
+ tags: { deviceId: data.deviceId },
1586
+ meta: {
1587
+ cap: data.capName,
1588
+ addonId: data.addonId
1589
+ }
1590
+ });
1591
+ ports.ungraft(data.deviceId, data.capName, NATIVE_APPEARED_UNGRAFT_REASON);
1592
+ this.setUnserved(data.deviceId, data.capName, nativeTakenReason(data.addonId, "appeared"));
1593
+ }
1594
+ /** Rule 2, at plan time only: graft what the plan adds; ungraft what it finds native; retract what a previous process left. */
1595
+ plan(input) {
1596
+ const ports = this.ports;
1597
+ if (ports === void 0) return;
1598
+ const { deviceId } = input;
1599
+ const added = input.enabled && input.settled ? addedCapsOf(input.features) : [];
1600
+ const replaced = new Set(input.features.filter((f) => f.mode === "replace").map((f) => f.cap));
1601
+ for (const cap of ports.grafted(deviceId)) {
1602
+ if (!replaced.has(cap)) continue;
1603
+ this.logger.info("a native provider serves a grafted cap — the graft is removed; the claim stays", {
1604
+ tags: { deviceId },
1605
+ meta: { cap }
1606
+ });
1607
+ ports.ungraft(deviceId, cap, NATIVE_APPEARED_UNGRAFT_REASON);
1608
+ }
1609
+ if (input.settled) this.retractUnwanted(input, new Set(added));
1610
+ const foreign = this.foreignSince.get(deviceId) ?? /* @__PURE__ */ new Map();
1611
+ const unserved = /* @__PURE__ */ new Map();
1612
+ for (const cap of added) {
1613
+ const other = foreign.get(cap);
1614
+ if (other !== void 0) {
1615
+ const reason = nativeTakenReason(other, "registered while the block was planning");
1616
+ this.logger.warn("graft skipped — a native provider serves the cap (native always wins)", {
1617
+ tags: { deviceId },
1618
+ meta: {
1619
+ cap,
1620
+ addonId: other
1621
+ }
1622
+ });
1623
+ unserved.set(cap, reason);
1624
+ continue;
1625
+ }
1626
+ const outcome = ports.graft(deviceId, input.ref.stableId, cap);
1627
+ if (outcome.kind === "refused") unserved.set(cap, `graft refused: ${outcome.reason}`);
1628
+ }
1629
+ this.unserved = withEntry(this.unserved, deviceId, unserved);
1630
+ }
1631
+ /** The gate released a claim: a graft of that cap goes with it; a previous process's binding is retracted once read as the composer's. */
1632
+ async released(deviceId, capName) {
1633
+ const ports = this.ports;
1634
+ if (ports === void 0) return;
1635
+ this.setUnserved(deviceId, capName, null);
1636
+ if (ports.grafted(deviceId).has(capName)) {
1637
+ ports.ungraft(deviceId, capName, NO_LONGER_ADDED_UNGRAFT_REASON);
1638
+ return;
1639
+ }
1640
+ let read;
1641
+ try {
1642
+ read = await this.readBindings(deviceId);
1643
+ } catch (err) {
1644
+ read = {
1645
+ kind: "unreadable",
1646
+ error: errMsg(err)
1647
+ };
1648
+ }
1649
+ if (read.kind === "unreadable") {
1650
+ this.logger.warn("a released claim: the bindings could not be read — a graft left by a previous process, if any, is not retracted (D49)", {
1651
+ tags: { deviceId },
1652
+ meta: {
1653
+ cap: capName,
1654
+ error: read.error
1655
+ }
1656
+ });
1657
+ return;
1658
+ }
1659
+ if (read.caps.get(capName) === "composer") ports.retractStale(deviceId, capName, STALE_GRAFT_RETRACT_REASON);
1660
+ }
1661
+ /** The target row is gone: nothing about it is reported any more. */
1662
+ gone(deviceId) {
1663
+ this.unserved = new Map([...this.unserved].filter(([id]) => id !== deviceId));
1664
+ }
1665
+ verdict(deviceId, features) {
1666
+ const added = addedCapsOf(features);
1667
+ const unserved = this.unserved.get(deviceId) ?? /* @__PURE__ */ new Map();
1668
+ const named = added.flatMap((cap) => {
1669
+ const reason = unserved.get(cap);
1670
+ return reason === void 0 ? [] : [`${cap}: ${reason}`];
1671
+ });
1672
+ if (named.length === 0) return null;
1673
+ return {
1674
+ allUnserved: named.length === added.length && added.length === features.length,
1675
+ reason: `added caps no graft serves — ${named.join("; ")}`
1676
+ };
1677
+ }
1678
+ retractUnwanted(input, wanted) {
1679
+ const ports = this.ports;
1680
+ if (ports === void 0) return;
1681
+ const own = ports.grafted(input.deviceId);
1682
+ for (const [cap, addonId] of input.nativeCaps) {
1683
+ if (addonId !== "composer" || own.has(cap) || wanted.has(cap)) continue;
1684
+ this.logger.info("a graft left by a previous composer process is retracted", {
1685
+ tags: { deviceId: input.deviceId },
1686
+ meta: { cap }
1687
+ });
1688
+ ports.retractStale(input.deviceId, cap, STALE_GRAFT_RETRACT_REASON);
1689
+ }
1690
+ }
1691
+ remember(data) {
1692
+ const seen = this.foreignSince.get(data.deviceId);
1693
+ if (seen === void 0) return;
1694
+ if (data.reason === "native-registered") this.foreignSince = withEntry(this.foreignSince, data.deviceId, new Map([...seen, [data.capName, data.addonId]]));
1695
+ else if (data.reason === "native-unregistered" && seen.get(data.capName) === data.addonId) this.foreignSince = withEntry(this.foreignSince, data.deviceId, new Map([...seen].filter(([cap]) => cap !== data.capName)));
1696
+ }
1697
+ setUnserved(deviceId, cap, reason) {
1698
+ const current = this.unserved.get(deviceId) ?? /* @__PURE__ */ new Map();
1699
+ const next = new Map([...current].filter(([c]) => c !== cap));
1700
+ if (reason !== null) next.set(cap, reason);
1701
+ this.unserved = withEntry(this.unserved, deviceId, next);
1702
+ }
1703
+ };
1704
+ //#endregion
1705
+ //#region src/builtins/composer/composer-verdict.ts
1706
+ /** A runtime built by an apply, before the apply's sync decides whether it may start. */
1707
+ var NOT_STARTED = "the runtime has not started yet";
1708
+ function verdictOf(blockId, entry, unsynced, grafts = null) {
1709
+ if (entry === void 0) return {
1710
+ blockId,
1711
+ status: "starting",
1712
+ reason: "not applied yet"
1713
+ };
1714
+ if (entry.rebuildError !== null) return {
1715
+ blockId,
1716
+ status: "failed",
1717
+ reason: `rebuilding the composed device for its new shape failed: ${entry.rebuildError}`
1718
+ };
1719
+ if (entry.planned.problems.length > 0) {
1720
+ const kept = entry.planned.declaration === null ? "" : " — its device is kept offline with no capabilities";
1721
+ return {
1722
+ blockId,
1723
+ status: "failed",
1724
+ reason: `the composition does not validate: ${entry.planned.problems.join("; ")}${kept}`
1725
+ };
1726
+ }
1727
+ if (!entry.planned.block.enabled) return {
1728
+ blockId,
1729
+ status: "stopped"
1730
+ };
1731
+ const target = entry.planned.target;
1732
+ if (target.kind === "existing") {
1733
+ if (target.gone !== null) return {
1734
+ blockId,
1735
+ status: "failed",
1736
+ reason: `the target device is gone: ${target.gone}`
1737
+ };
1738
+ if (target.waiting !== null) return {
1739
+ blockId,
1740
+ status: "starting",
1741
+ reason: target.waiting
1742
+ };
1743
+ } else if (entry.device === null) return {
1744
+ blockId,
1745
+ status: "starting",
1746
+ reason: "the composed device has not been constructed yet"
1747
+ };
1748
+ const runtime = entry.runtime;
1749
+ if (runtime === null) return target.kind === "existing" ? {
1750
+ blockId,
1751
+ status: "starting",
1752
+ reason: NOT_STARTED
1753
+ } : {
1754
+ blockId,
1755
+ status: "running"
1756
+ };
1757
+ if (unsynced) return {
1758
+ blockId,
1759
+ status: "starting",
1760
+ reason: NOT_STARTED
1761
+ };
1762
+ const state = runtime.state();
1763
+ if (state.failure !== null) return {
1764
+ blockId,
1765
+ status: "failed",
1766
+ reason: state.failure
1767
+ };
1768
+ if (grafts?.allUnserved === true) return {
1769
+ blockId,
1770
+ status: "failed",
1771
+ reason: grafts.reason
1772
+ };
1773
+ const degraded = [...state.released.length > 0 ? [degradedReason(state.released)] : [], ...grafts === null ? [] : [grafts.reason]];
1774
+ if (degraded.length > 0) return {
1775
+ blockId,
1776
+ status: "degraded",
1777
+ reason: degraded.join("; ")
1778
+ };
1779
+ if (state.held.length > 0) return {
1780
+ blockId,
1781
+ status: "starting",
1782
+ reason: heldReason(state.held)
1783
+ };
1784
+ return {
1785
+ blockId,
1786
+ status: "running"
1787
+ };
1788
+ }
1789
+ //#endregion
1790
+ //#region src/builtins/composer/owned-fields-target.ts
1791
+ /**
1792
+ * The write target of a composition on an EXISTING device (D663): its fields
1793
+ * are CLAIMED on the hub (`deviceState.claimFields`), then patched
1794
+ * (`patchOwnedFields`). The runtime's `seed`/`patch` are synchronous and never
1795
+ * fail here — the RPC is enqueued — so what did not land is reported through
1796
+ * `onAsyncFailure`, and the runtime marks the cap write-pending and re-writes
1797
+ * it whole on its next pass. No retry timer (D3).
1798
+ *
1799
+ * - **The claim is re-sent until it has LANDED (ruling S5).** A cap enters
1800
+ * `landed` only on an `ok` claim answer. Every write of a cap not in `landed`
1801
+ * is a claim carrying the FULL planned field set (`fieldsOf`, never inferred
1802
+ * from the values). `not-claimed` / `field-not-claimed` — the hub lost or
1803
+ * never had the claim — drop the cap from `landed` and are escalated by
1804
+ * name, so the next write claims again.
1805
+ * - **Concurrent partial patches are MERGED, never dropped (S5).** One chain
1806
+ * per cap: while an RPC is in flight, later patches fold into one pending
1807
+ * value set (later keys win; a seed replaces it wholly), and the landing log
1808
+ * says how many were absorbed (D391).
1809
+ * - **A released field is withheld (S1b).** `withhold(cap, fields)` narrows the
1810
+ * next claim to the rest and omits their values; nothing left → the claim is
1811
+ * released at once. `[]` re-widens.
1812
+ * - **Every claim RPC of a `replace` cap is reported** (`onClaim`, C-1/N-1):
1813
+ * `claiming` when it goes out, then `held` on an `ok`, `free` on a confirmed
1814
+ * release or `not-claimed`, `unsettled` on a throw or any other refusal (D49:
1815
+ * changes nothing). `field-not-claimed` on a patch drops `landed` so the next
1816
+ * write claims again, but the hub still holds the claim: `held` stays (N-3).
1817
+ * The tracker follows this — never the plan — to know whether
1818
+ * `device.state-changed` of the cap is the provider's native, the
1819
+ * composition's own merge, or (while a claim is in flight) neither.
1820
+ * - `setAvailable` is a no-op: `device-status` is the native device's.
1821
+ */
1822
+ var ACCEPTED = { ok: true };
1823
+ /** The hub has no claim to patch: the next write must claim again. */
1824
+ var CLAIM_LOST_CODES = new Set(["not-claimed", "field-not-claimed"]);
1825
+ /**
1826
+ * Later keys win; a seed replaces the pending values wholly; a release
1827
+ * supersedes any pending values (nothing is left to write) and is itself
1828
+ * superseded by a later write (a claim REPLACES the hub's field set anyway).
1829
+ */
1830
+ function fold(current, next) {
1831
+ if (current === void 0 || next.kind === "release" || current.kind === "release") return next;
1832
+ if (next.op === "seed") return {
1833
+ ...next,
1834
+ merged: current.merged + 1
1835
+ };
1836
+ return {
1837
+ kind: "write",
1838
+ op: current.op,
1839
+ values: {
1840
+ ...current.values,
1841
+ ...next.values
1842
+ },
1843
+ merged: current.merged + 1
1844
+ };
1845
+ }
1846
+ function omitKeys(values, keys) {
1847
+ if (keys === void 0 || keys.size === 0) return values;
1848
+ return Object.fromEntries(Object.entries(values).filter(([key]) => !keys.has(key)));
1849
+ }
1850
+ var OwnedFieldsTarget = class {
1851
+ deps;
1852
+ id;
1853
+ landed = /* @__PURE__ */ new Set();
1854
+ withheld = /* @__PURE__ */ new Map();
1855
+ inFlight = /* @__PURE__ */ new Set();
1856
+ pending = /* @__PURE__ */ new Map();
1857
+ listeners = [];
1858
+ /** Per cap, bumped by every `withhold`: a claim that settles under another epoch claimed a stale field set and does not land (I-2). */
1859
+ epoch = /* @__PURE__ */ new Map();
1860
+ constructor(deps) {
1861
+ this.deps = deps;
1862
+ this.id = deps.deviceId;
1863
+ }
1864
+ seed(cap, slice) {
1865
+ this.enqueue(cap, {
1866
+ kind: "write",
1867
+ op: "seed",
1868
+ values: slice,
1869
+ merged: 0
1870
+ });
1871
+ return ACCEPTED;
1872
+ }
1873
+ patch(cap, patch) {
1874
+ this.enqueue(cap, {
1875
+ kind: "write",
1876
+ op: "patch",
1877
+ values: patch,
1878
+ merged: 0
1879
+ });
1880
+ return ACCEPTED;
1881
+ }
1882
+ /** `device-status` belongs to the native device; availability lives in the block report only. */
1883
+ setAvailable(_available) {}
1884
+ onAsyncFailure(listener) {
1885
+ this.listeners = [...this.listeners, listener];
1886
+ }
1887
+ withhold(cap, fields) {
1888
+ this.withheld = new Map([...this.withheld.entries()].filter(([c]) => c !== cap).concat(fields.length === 0 ? [] : [[cap, new Set(fields)]]));
1889
+ this.landed = new Set([...this.landed].filter((c) => c !== cap));
1890
+ this.epoch = new Map([...this.epoch, [cap, (this.epoch.get(cap) ?? 0) + 1]]);
1891
+ if (this.claimableFields(cap).length === 0) this.enqueue(cap, { kind: "release" });
1892
+ return ACCEPTED;
1893
+ }
1894
+ claimableFields(cap) {
1895
+ const held = this.withheld.get(cap);
1896
+ return this.deps.fieldsOf(cap).filter((f) => held === void 0 || !held.has(f));
1897
+ }
1898
+ enqueue(cap, op) {
1899
+ if (!this.inFlight.has(cap)) {
1900
+ this.send(cap, op);
1901
+ return;
1902
+ }
1903
+ this.pending = new Map([...this.pending, [cap, fold(this.pending.get(cap), op)]]);
1904
+ }
1905
+ send(cap, op) {
1906
+ this.inFlight = new Set([...this.inFlight, cap]);
1907
+ (op.kind === "release" ? this.sendRelease(cap) : this.sendWrite(cap, op)).then(() => this.settled(cap), (err) => {
1908
+ this.deps.logger.error("composed write chain threw past its handlers — the chain continues", {
1909
+ tags: { deviceId: this.deps.deviceId },
1910
+ meta: {
1911
+ cap,
1912
+ owner: this.deps.owner,
1913
+ error: errMsg(err)
1914
+ }
1915
+ });
1916
+ this.settled(cap);
1917
+ });
1918
+ }
1919
+ settled(cap) {
1920
+ this.inFlight = new Set([...this.inFlight].filter((c) => c !== cap));
1921
+ const next = this.pending.get(cap);
1922
+ if (next === void 0) return;
1923
+ this.pending = new Map([...this.pending].filter(([c]) => c !== cap));
1924
+ this.send(cap, next);
1925
+ }
1926
+ async sendWrite(cap, op) {
1927
+ const values = omitKeys(op.values, this.withheld.get(cap));
1928
+ const claim = !this.landed.has(cap);
1929
+ const fields = this.claimableFields(cap);
1930
+ const epoch = this.epoch.get(cap) ?? 0;
1931
+ if (claim && fields.length === 0) {
1932
+ this.deps.logger.debug("composed write skipped — every field of the capability is withheld", {
1933
+ tags: { deviceId: this.deps.deviceId },
1934
+ meta: {
1935
+ cap,
1936
+ owner: this.deps.owner,
1937
+ op: op.op
1938
+ }
1939
+ });
1940
+ return;
1941
+ }
1942
+ if (!claim && Object.keys(values).length === 0) return;
1943
+ if (claim) this.report(cap, "claiming");
1944
+ let outcome;
1945
+ try {
1946
+ outcome = claim ? await this.deps.api.claimFields({
1947
+ deviceId: this.deps.deviceId,
1948
+ capName: cap,
1949
+ owner: this.deps.owner,
1950
+ mode: this.deps.modeOf(cap),
1951
+ fields: [...fields],
1952
+ values
1953
+ }) : await this.deps.api.patchOwnedFields({
1954
+ deviceId: this.deps.deviceId,
1955
+ capName: cap,
1956
+ owner: this.deps.owner,
1957
+ values
1958
+ });
1959
+ } catch (err) {
1960
+ if (claim) this.report(cap, "unsettled");
1961
+ this.fail(cap, {
1962
+ kind: "threw",
1963
+ error: errMsg(err)
1964
+ });
1965
+ return;
1966
+ }
1967
+ if (outcome.ok) {
1968
+ if (claim) this.report(cap, "held");
1969
+ const current = (this.epoch.get(cap) ?? 0) === epoch;
1970
+ if (claim && current) this.landed = new Set([...this.landed, cap]);
1971
+ if (claim && !current) this.deps.logger.info("composed claim landed with a field set a withhold has since changed — the next write claims again", {
1972
+ tags: { deviceId: this.deps.deviceId },
1973
+ meta: {
1974
+ cap,
1975
+ owner: this.deps.owner,
1976
+ fields
1977
+ }
1978
+ });
1979
+ this.logLanded(cap, op, claim, fields);
1980
+ return;
1981
+ }
1982
+ if (CLAIM_LOST_CODES.has(outcome.code)) this.landed = new Set([...this.landed].filter((c) => c !== cap));
1983
+ if (outcome.code === "not-claimed") this.report(cap, "free");
1984
+ else if (claim) this.report(cap, "unsettled");
1985
+ this.fail(cap, {
1986
+ kind: "refused",
1987
+ code: outcome.code,
1988
+ message: outcome.message
1989
+ });
1990
+ }
1991
+ async sendRelease(cap) {
1992
+ const extras = {
1993
+ tags: { deviceId: this.deps.deviceId },
1994
+ meta: {
1995
+ cap,
1996
+ owner: this.deps.owner
1997
+ }
1998
+ };
1999
+ let outcome;
2000
+ try {
2001
+ outcome = await this.deps.api.releaseClaim({
2002
+ deviceId: this.deps.deviceId,
2003
+ capName: cap,
2004
+ owner: this.deps.owner
2005
+ });
2006
+ } catch (err) {
2007
+ this.fail(cap, {
2008
+ kind: "threw",
2009
+ error: errMsg(err)
2010
+ });
2011
+ return;
2012
+ }
2013
+ if (outcome.ok) {
2014
+ this.report(cap, "free");
2015
+ this.deps.logger.info("composed claim released — every field of the capability is handed back to the native provider", extras);
2016
+ return;
2017
+ }
2018
+ if (outcome.code === "not-claimed") {
2019
+ this.report(cap, "free");
2020
+ this.deps.logger.debug("composed claim release found nothing to hand back", extras);
2021
+ return;
2022
+ }
2023
+ this.fail(cap, {
2024
+ kind: "refused",
2025
+ code: outcome.code,
2026
+ message: outcome.message
2027
+ });
2028
+ }
2029
+ logLanded(cap, op, claim, fields) {
2030
+ const tags = { deviceId: this.deps.deviceId };
2031
+ if (op.merged > 0) this.deps.logger.info("composed write landed after absorbing merged patches", {
2032
+ tags,
2033
+ meta: {
2034
+ cap,
2035
+ owner: this.deps.owner,
2036
+ op: op.op,
2037
+ claim,
2038
+ merged: op.merged
2039
+ }
2040
+ });
2041
+ if (claim) this.deps.logger.info("composed claim landed", {
2042
+ tags,
2043
+ meta: {
2044
+ cap,
2045
+ owner: this.deps.owner,
2046
+ mode: this.deps.modeOf(cap),
2047
+ fields
2048
+ }
2049
+ });
2050
+ }
2051
+ /** Only a `replace` cap has a native the tracker must tell apart from the merge (N-7). */
2052
+ report(cap, event) {
2053
+ if (this.deps.modeOf(cap) === "replace") this.deps.onClaim?.(cap, event);
2054
+ }
2055
+ /** Escalated to the runtime; a failure nobody listens to is logged — never silent (D391). */
2056
+ fail(cap, failure) {
2057
+ if (this.listeners.length === 0) this.deps.logger.warn("composed write did not land and no runtime listens for it", {
2058
+ tags: { deviceId: this.deps.deviceId },
2059
+ meta: {
2060
+ cap,
2061
+ owner: this.deps.owner,
2062
+ ...failure.kind === "threw" ? { error: failure.error } : {
2063
+ code: failure.code,
2064
+ error: failure.message
2065
+ }
2066
+ }
2067
+ });
2068
+ for (const listener of this.listeners) listener(cap, failure);
2069
+ }
2070
+ };
2071
+ //#endregion
589
2072
  //#region src/builtins/composer/composer.ts
590
2073
  /**
591
2074
  * The composer: every declarative composition on this hub, in one runner
@@ -602,38 +2085,139 @@ var CompositionRuntime = class {
602
2085
  * (`WithdrawalGate.seed`). A block whose row exists but whose composition no
603
2086
  * longer plans (a cap renamed by a release) keeps its device as an offline
604
2087
  * placeholder with no capabilities, and reports `failed` naming why.
2088
+ *
2089
+ * Slice 2 (D663) — a composition on an EXISTING device declares nothing: the
2090
+ * row is not the composer's, `DeclaredDevices` never sees it, and the owner
2091
+ * filter in `composer.addon.ts` stays load-bearing. Its fields are CLAIMED on
2092
+ * the hub under the block id (`OwnedFieldsTarget`), and released through the
2093
+ * `ClaimGate` — two applies must agree, seeded at boot from the claims index —
2094
+ * when the block is gone, disabled, or lost the feature. Its own replaced
2095
+ * fields are read in the NATIVE view (rule 6). Its target row gone on two
2096
+ * agreeing index reads fails the block by name and ungrafts what it added —
2097
+ * whether the loss was seen on `device.unregistered` or on a later plan; its
2098
+ * claims die with the row. Nothing is claimed or released while the claims
2099
+ * index has not loaded (`CLAIMS_NOT_LOADED`). Planning is `composer-plan.ts`.
2100
+ *
2101
+ * A cap the customization ADDS is GRAFTED (`GraftHost`, Task 10): a
2102
+ * method-serving native on the target, decided at plan time only; when and why
2103
+ * is `composer-grafts.ts` (native always wins; an unserved cap is named in the
2104
+ * verdict; a previous process's leftover is retracted).
2105
+ *
2106
+ * A replaced field is handed back only on a CONFIRMED unavailability of its
2107
+ * source (D49, fix round 2): a failed, first or empty read HOLDS it on its last
2108
+ * value with its claim kept — the runtime's `held`, reported `starting` by name.
2109
+ * A runtime built by an apply starts in that apply's sync, never earlier from
2110
+ * an event (N-5).
605
2111
  */
606
2112
  var INTEGRATION_WAIT = "waiting for the shared Blocks integration to reconcile";
607
2113
  var STORE_NOT_LOADED = "the core_blocks store has not loaded — nothing is declared or withdrawn until it does (D49)";
608
2114
  var ROWS_UNREAD = "the composer's own device rows could not be read — nothing is declared or withdrawn until they are (D49)";
609
2115
  var ROWS_EMPTY_UNCONFIRMED = "the composer's own device rows read empty once — a cold registry answers the same, so nothing is declared or withdrawn until the next apply's read agrees (D49)";
610
- /** The shape of a placeholder: no caps, so no plan to take a shape from. */
611
- var PLACEHOLDER_SHAPE = "placeholder";
2116
+ var CLAIMS_NOT_LOADED = "the claims index has not loaded — nothing is claimed or released until it does (D49)";
2117
+ var CLAIMS_EMPTY_UNCONFIRMED = "the claims index read empty once — nothing is claimed or released until the next apply's read agrees (D49)";
2118
+ /** A release answered with one of these hands back nothing of ours: the gate forgets the claim. */
2119
+ var RELEASE_SETTLED_CODES = new Set([
2120
+ "not-claimed",
2121
+ "unknown-device",
2122
+ "owned-by-other"
2123
+ ]);
612
2124
  var Composer = class {
613
2125
  deps;
614
2126
  live = /* @__PURE__ */ new Map();
615
- devices = /* @__PURE__ */ new Map();
616
- /** StableIds whose row exists: the seeded persisted rows, then what every declare kept. */
617
- rows = /* @__PURE__ */ new Set();
618
- seeded = false;
619
- /** The previous seed read answered `[]`: one more `[]` confirms it (D49). */
620
- emptySeedSeen = false;
2127
+ /** The composed devices of `new`-target blocks, and the rows that exist. */
2128
+ composed;
621
2129
  /** Consecutive applies refused because `core_blocks` had not loaded: warned once per run. */
622
2130
  storeWaitApplies = 0;
623
2131
  /** Consecutive applies refused because the Blocks integration had not reconciled: warned once per run. */
624
2132
  integrationWaitApplies = 0;
625
- declaredFingerprint = null;
626
2133
  gate;
2134
+ claimGate;
2135
+ targets;
2136
+ grafts;
2137
+ /** The rows the composer owns, read ONCE before its first withdrawal decision. */
2138
+ rowSeed;
2139
+ /**
2140
+ * The claims the hub holds, read ONCE before the first release decision (rule
2141
+ * 3). Every owner in it is a composer block id — the Task 6 guard lets nothing
2142
+ * else claim. `not-loaded` is UNKNOWN (D315), never empty. Until seeded, every
2143
+ * existing-target block waits by name; new-target blocks are not held.
2144
+ */
2145
+ claimSeed;
627
2146
  /** Applies never interleave: each one reads and replaces the whole live set. */
628
2147
  applyChain = Promise.resolve();
2148
+ /**
2149
+ * Runtimes built by an apply and not started yet: that apply's sync starts
2150
+ * them, with their sources tracked. An event in between never does (N-5) —
2151
+ * it would start one on sources "not tracked yet".
2152
+ */
2153
+ unsynced = /* @__PURE__ */ new Set();
629
2154
  constructor(deps) {
630
2155
  this.deps = deps;
631
- this.gate = new WithdrawalGate(deps.logger.child("withdrawal"), (stableId) => this.devices.get(stableId)?.id ?? null);
2156
+ this.composed = new ComposedDeviceSet({
2157
+ logger: deps.logger,
2158
+ declare: deps.declare,
2159
+ devices: deps.devices
2160
+ });
2161
+ this.gate = new WithdrawalGate(deps.logger.child("withdrawal"), (stableId) => this.composed.idOf(stableId));
2162
+ this.claimGate = new ClaimGate(deps.logger.child("claims"));
2163
+ this.grafts = new ComposerGrafts(deps.grafts, deps.logger.child("graft"), deps.describeTarget);
2164
+ this.targets = new TargetDescriptions(deps.logger.child("target"), (deviceId) => {
2165
+ this.grafts.describing(deviceId);
2166
+ return deps.describeTarget(deviceId);
2167
+ });
2168
+ this.rowSeed = new ConfirmedSeed({
2169
+ logger: deps.logger,
2170
+ subject: "composer's own device rows",
2171
+ read: async () => {
2172
+ try {
2173
+ return {
2174
+ kind: "items",
2175
+ items: await deps.readPersisted()
2176
+ };
2177
+ } catch (err) {
2178
+ return {
2179
+ kind: "unknown",
2180
+ error: errMsg(err)
2181
+ };
2182
+ }
2183
+ },
2184
+ onSeeded: (rows) => {
2185
+ this.gate.seed(rows);
2186
+ this.composed.seedRows(rows);
2187
+ },
2188
+ unreadReason: ROWS_UNREAD,
2189
+ emptyUnconfirmedReason: ROWS_EMPTY_UNCONFIRMED
2190
+ });
2191
+ this.claimSeed = new ConfirmedSeed({
2192
+ logger: deps.logger,
2193
+ subject: "claims index",
2194
+ read: async () => {
2195
+ try {
2196
+ const listing = await deps.claims.listClaims({ ownerPrefix: "" });
2197
+ return listing.state === "loaded" ? {
2198
+ kind: "items",
2199
+ items: listing.claims
2200
+ } : {
2201
+ kind: "unknown",
2202
+ error: listing.reason
2203
+ };
2204
+ } catch (err) {
2205
+ return {
2206
+ kind: "unknown",
2207
+ error: errMsg(err)
2208
+ };
2209
+ }
2210
+ },
2211
+ onSeeded: (claims) => {
2212
+ this.claimGate.seed(claims);
2213
+ this.deps.tracker.seedClaims(claims);
2214
+ },
2215
+ unreadReason: CLAIMS_NOT_LOADED,
2216
+ emptyUnconfirmedReason: CLAIMS_EMPTY_UNCONFIRMED
2217
+ });
632
2218
  }
633
2219
  apply(input) {
634
- const run = this.applyChain.then(() => this.applyNow(input), () => this.applyNow(input));
635
- this.applyChain = run.then(() => void 0, () => void 0);
636
- return run;
2220
+ return this.chained(() => this.applyNow(input));
637
2221
  }
638
2222
  getStates(blockIds) {
639
2223
  return blockIds.flatMap((blockId) => {
@@ -642,10 +2226,10 @@ var Composer = class {
642
2226
  const verdict = this.verdict(blockId);
643
2227
  return [{
644
2228
  blockId,
645
- deviceId: entry.device?.id ?? null,
2229
+ deviceId: this.deviceIdOf(entry),
646
2230
  status: verdict.status,
647
2231
  ...verdict.reason === void 0 ? {} : { reason: verdict.reason },
648
- fields: entry.runtime?.state().fields.map((f) => ({ ...f })) ?? []
2232
+ fields: entry.runtime?.state().fields.map((f) => ({ ...f })) ?? [...entry.heldFields]
649
2233
  }];
650
2234
  });
651
2235
  }
@@ -653,15 +2237,28 @@ var Composer = class {
653
2237
  async onStateChanged(data) {
654
2238
  this.dispatch(await this.deps.tracker.onStateChanged(data.deviceId, data.capName, data.slice));
655
2239
  }
2240
+ async onNativeChanged(data) {
2241
+ this.dispatch(await this.deps.tracker.onNativeChanged(data.deviceId, data.capName, data.native));
2242
+ }
656
2243
  async onDeviceUnregistered(deviceId) {
657
- this.dispatch(await this.deps.tracker.onDeviceUnregistered(deviceId));
2244
+ const changed = await this.deps.tracker.onDeviceUnregistered(deviceId);
2245
+ await this.chained(() => this.failGoneTargets(deviceId));
2246
+ this.dispatch(changed);
658
2247
  }
659
2248
  async onBindingsChanged(data) {
2249
+ this.targets.invalidate(data.deviceId);
2250
+ this.grafts.onBindingsChanged(data);
660
2251
  this.dispatch(await this.deps.tracker.onBindingsChanged(data.deviceId, data.capName, data.reason));
661
2252
  }
662
2253
  shutdown() {
663
2254
  for (const entry of this.live.values()) entry.runtime?.stop();
664
2255
  }
2256
+ /** Run `work` after every apply already queued, whether that settled or failed. */
2257
+ chained(work) {
2258
+ const run = this.applyChain.then(work, work);
2259
+ this.applyChain = run.then(() => void 0, () => void 0);
2260
+ return run;
2261
+ }
665
2262
  async applyNow(input) {
666
2263
  const ids = [...input.blocks.map((b) => b.id), ...input.unreadableBlocks.map((u) => u.id)];
667
2264
  if (!input.storeLoaded) {
@@ -685,15 +2282,26 @@ var Composer = class {
685
2282
  this.deps.logger.info("composer: the shared Blocks integration has reconciled — applying again", { meta: { appliesRefused: this.integrationWaitApplies } });
686
2283
  this.integrationWaitApplies = 0;
687
2284
  }
688
- const unseeded = await this.ensureSeeded();
2285
+ const unseeded = await this.rowSeed.ensure();
689
2286
  if (unseeded !== null) return this.waiting(ids, unseeded);
690
- const planned = [...input.blocks.map((block) => this.plan(block)), ...input.unreadableBlocks.map((block) => this.planUnreadable(block))];
691
- this.logPlanTransitions(planned);
2287
+ const claimsWait = await this.claimSeed.ensure();
2288
+ const restart = new Set(input.restartBlockIds);
2289
+ const planned = [];
2290
+ for (const block of input.blocks) planned.push(await this.plan(block, restart, claimsWait));
2291
+ for (const block of input.unreadableBlocks) planned.push(planUnreadable(block, this.composed.rows));
2292
+ for (const p of planned) logPlanTransition(this.deps.logger, this.live.get(p.block.id)?.planned, p, this.tagsOf(p.block.id));
692
2293
  const declarations = this.gate.filter(planned.flatMap((p) => p.declaration === null ? [] : [p.declaration]));
693
- const rebuildErrors = await this.rebuildShapes(planned);
694
- await this.reconcileDevices(input.integrationId, declarations, planned);
695
- const rebuilt = await this.rebuildRuntimes(planned, declarations, new Set(input.restartBlockIds), rebuildErrors);
2294
+ const rebuildErrors = await this.composed.rebuildShapes(planned, (blockId) => {
2295
+ const previous = this.live.get(blockId);
2296
+ return previous === void 0 ? void 0 : {
2297
+ device: previous.device,
2298
+ shape: previous.planned.shape
2299
+ };
2300
+ });
2301
+ await this.composed.reconcile(input.integrationId, declarations, planned);
2302
+ const rebuilt = await this.rebuildRuntimes(planned, declarations, restart, rebuildErrors);
696
2303
  await this.syncSources(rebuilt);
2304
+ await this.reconcileClaims();
697
2305
  return {
698
2306
  blocks: planned.map((p) => this.verdict(p.block.id)),
699
2307
  acted: true
@@ -709,177 +2317,20 @@ var Composer = class {
709
2317
  acted: false
710
2318
  };
711
2319
  }
712
- /**
713
- * Seed the withdrawal gate with the rows that exist, ONCE, before its first
714
- * `filter`; answers null once seeded, else why this apply must wait.
715
- *
716
- * An EMPTY answer is the destroying direction: a cold registry answers `[]`
717
- * too, and `DeclaredDevices.reconcile` sweeps from its OWN later read — so a
718
- * cold seed followed by a warm sweep would delete the row of a block that no
719
- * longer plans, with no placeholder to hold it. `[]` is therefore trusted
720
- * only when the next apply's read agrees (D49); that apply comes from the
721
- * supervisor's existing converge, never a timer here (D3). A failed read
722
- * changes nothing and breaks the agreement.
723
- */
724
- async ensureSeeded() {
725
- if (this.seeded) return null;
726
- let rows;
727
- try {
728
- rows = await this.deps.readPersisted();
729
- } catch (err) {
730
- this.emptySeedSeen = false;
731
- this.deps.logger.warn("composer: reading its own device rows failed — nothing is declared or withdrawn; retried on the next apply", { meta: { error: errMsg(err) } });
732
- return ROWS_UNREAD;
733
- }
734
- if (rows.length === 0 && !this.emptySeedSeen) {
735
- this.emptySeedSeen = true;
736
- this.deps.logger.warn("composer: its own device rows read empty — waiting for the next apply to confirm before declaring or withdrawing anything");
737
- return ROWS_EMPTY_UNCONFIRMED;
738
- }
739
- this.gate.seed(rows);
740
- this.rows = new Set(rows.map((r) => r.stableId));
741
- this.seeded = true;
742
- this.deps.logger.info("composer: seeded the withdrawal gate from the persisted rows", { meta: {
743
- rows: rows.length,
744
- confirmedEmpty: rows.length === 0
745
- } });
746
- return null;
747
- }
748
- /**
749
- * A row that exists but does not parse is held exactly like a composition
750
- * that stopped planning: its device (if it has a row) stays as an offline
751
- * placeholder, and the block fails naming the parse error. Absent, it would
752
- * be withdrawn on the second apply that omitted it (D49).
753
- */
754
- planUnreadable(block) {
755
- const stableId = composedDeviceStableId(block.id);
756
- const hasRow = this.rows.has(stableId);
757
- return {
758
- block: {
759
- id: block.id,
760
- name: block.name,
761
- enabled: false,
762
- updatedAt: 0
763
- },
764
- fields: [],
765
- problems: [`the stored block does not parse — ${block.error}`],
766
- declaration: hasRow ? placeholderDeclaration(stableId) : null,
767
- shape: hasRow ? PLACEHOLDER_SHAPE : null,
768
- spec: null
769
- };
770
- }
771
- plan(block) {
772
- const plan = planComposition(block.composition, this.deps.lookupCap);
2320
+ plan(block, restart, claimsWait) {
773
2321
  const target = block.composition.target;
774
- if (plan.problems.length > 0 || target.kind !== "new") {
775
- const problems = plan.problems.length > 0 ? plan.problems.map((p) => `${p.path}: ${p.message}`) : [`target: a \`${target.kind}\` target is not composable in this release`];
776
- const stableId = composedDeviceStableId(block.id);
777
- const hasRow = this.rows.has(stableId);
778
- return {
779
- block,
780
- fields: [],
781
- problems,
782
- declaration: hasRow ? placeholderDeclaration(stableId) : null,
783
- shape: hasRow ? PLACEHOLDER_SHAPE : null,
784
- spec: null
785
- };
786
- }
787
- const caps = block.composition.features.flatMap((f) => {
788
- const def = this.deps.lookupCap(f.cap);
789
- return def === null ? [] : [def];
790
- });
791
- const declarationInput = {
792
- blockId: block.id,
793
- name: block.name,
794
- target,
795
- caps
796
- };
797
- return {
2322
+ if (target.kind === "new") return Promise.resolve(planNew(block, target, this.deps.lookupCap, this.composed.rows));
2323
+ const previous = this.live.get(block.id)?.planned;
2324
+ return planExisting({
798
2325
  block,
799
- fields: plan.fields,
800
- problems: [],
801
- declaration: declarationFor(declarationInput),
802
- shape: shapeOf(declarationInput),
803
- spec: {
804
- type: target.type,
805
- ...target.role === void 0 ? {} : { role: target.role }
806
- }
807
- };
808
- }
809
- /** One line when a block starts or stops planning — never one per apply. */
810
- logPlanTransitions(planned) {
811
- for (const p of planned) {
812
- const before = this.live.get(p.block.id)?.planned.problems.join("; ") ?? "";
813
- const now = p.problems.join("; ");
814
- if (before === now) continue;
815
- const extras = {
816
- tags: this.tagsOf(p.block.id),
817
- meta: {
818
- blockId: p.block.id,
819
- problems: p.problems,
820
- placeholder: p.declaration !== null
821
- }
822
- };
823
- if (now === "") this.deps.logger.info("composition plans again", extras);
824
- else this.deps.logger.warn(p.declaration === null ? "composition does not plan — no device is declared for it" : "composition no longer plans — its device is kept offline with no capabilities", extras);
825
- }
826
- }
827
- /**
828
- * A changed type/role/cap set (or a switch to or from a placeholder) needs a
829
- * NEW device object: decommission, and let the reconcile adopt it with the
830
- * new class. A failure keeps the old device and is retried next apply.
831
- */
832
- async rebuildShapes(planned) {
833
- const errors = /* @__PURE__ */ new Map();
834
- for (const p of planned) {
835
- const previous = this.live.get(p.block.id);
836
- const device = previous?.device ?? null;
837
- if (previous === void 0 || device === null || p.shape === null) continue;
838
- if (previous.planned.shape === p.shape) continue;
839
- try {
840
- this.deps.logger.info("composition shape changed — rebuilding its device", {
841
- tags: { deviceId: device.id },
842
- meta: {
843
- blockId: p.block.id,
844
- from: previous.planned.shape,
845
- to: p.shape
846
- }
847
- });
848
- if (p.spec !== null) await this.deps.devices.applyDerivedSpec(device.id, p.spec);
849
- await this.deps.devices.decommission(device.id);
850
- const stableId = composedDeviceStableId(p.block.id);
851
- this.devices = new Map([...this.devices].filter(([s]) => s !== stableId));
852
- this.declaredFingerprint = null;
853
- } catch (err) {
854
- const error = errMsg(err);
855
- errors.set(p.block.id, error);
856
- this.deps.logger.warn("rebuilding a composed device failed — the old one is kept", {
857
- tags: { deviceId: device.id },
858
- meta: {
859
- blockId: p.block.id,
860
- error
861
- }
862
- });
863
- }
864
- }
865
- return errors;
866
- }
867
- async reconcileDevices(integrationId, declarations, planned) {
868
- const shapes = new Map(planned.flatMap((p) => p.declaration === null ? [] : [[p.declaration.stableId, p.shape]]));
869
- const fingerprint = JSON.stringify(declarations.map((d) => [d.stableId, shapes.get(d.stableId) ?? null]).toSorted());
870
- const allLive = declarations.every((d) => this.devices.has(d.stableId));
871
- if (fingerprint === this.declaredFingerprint && allLive) return;
872
- try {
873
- const result = await this.deps.declare(integrationId, declarations);
874
- this.devices = result.devices;
875
- this.rows = new Set(declarations.map((d) => d.stableId).filter((s) => this.rows.has(s) || result.devices.has(s)));
876
- this.declaredFingerprint = fingerprint;
877
- } catch (err) {
878
- this.deps.logger.warn("composer: the device declaration failed — keeping the devices already live", { meta: {
879
- error: errMsg(err),
880
- declarations: declarations.length
881
- } });
882
- }
2326
+ target,
2327
+ previous,
2328
+ operatorAction: previous === void 0 || restart.has(block.id) || previous.block.updatedAt !== block.updatedAt,
2329
+ claimsWait,
2330
+ tracker: this.deps.tracker,
2331
+ targets: this.targets,
2332
+ lookupCap: this.deps.lookupCap
2333
+ });
883
2334
  }
884
2335
  async rebuildRuntimes(planned, declarations, restart, rebuildErrors) {
885
2336
  const reset = /* @__PURE__ */ new Set();
@@ -887,6 +2338,8 @@ var Composer = class {
887
2338
  const next = /* @__PURE__ */ new Map();
888
2339
  for (const p of planned) {
889
2340
  const previous = this.live.get(p.block.id);
2341
+ const lost = lostTarget(p, previous?.planned);
2342
+ if (lost !== null) this.ungraftGone(p.block.id, lost.target, lost.deviceId);
890
2343
  const rebuildError = rebuildErrors.get(p.block.id) ?? null;
891
2344
  if (previous !== void 0 && rebuildError !== null) {
892
2345
  next.set(p.block.id, {
@@ -895,28 +2348,45 @@ var Composer = class {
895
2348
  });
896
2349
  continue;
897
2350
  }
898
- const device = this.devices.get(composedDeviceStableId(p.block.id)) ?? null;
2351
+ const device = p.target.kind === "existing" ? null : this.composed.get(composedDeviceStableId(p.block.id));
899
2352
  const appliedName = device === null ? null : p.block.name === null ? previous?.appliedName ?? device.name : await this.applyName(device, p.block.name, previous?.appliedName ?? null);
900
- if (previous?.runtime != null && previous.device === device && previous.planned.block.updatedAt === p.block.updatedAt && previous.planned.block.enabled === p.block.enabled && !restart.has(p.block.id)) {
2353
+ if (previous?.runtime != null && previous.device === device && sameTarget(previous.planned.target, p.target) && previous.planned.block.updatedAt === p.block.updatedAt && previous.planned.block.enabled === p.block.enabled && !restart.has(p.block.id)) {
901
2354
  next.set(p.block.id, {
902
2355
  planned: p,
903
2356
  device,
904
2357
  runtime: previous.runtime,
905
2358
  appliedName,
906
- rebuildError: null
2359
+ rebuildError: null,
2360
+ heldFields: []
907
2361
  });
908
2362
  continue;
909
2363
  }
2364
+ const heldFields = this.heldFieldsFor(p, previous);
910
2365
  previous?.runtime?.stop();
911
- if (previous === void 0 || restart.has(p.block.id) || previous.planned.block.updatedAt !== p.block.updatedAt) for (const f of p.fields) for (const r of f.reads) reset.add(compositionSourceKey(r.source));
912
- const runtime = device === null || p.fields.length === 0 ? null : this.newRuntime(p, device);
2366
+ const operatorAction = previous === void 0 || restart.has(p.block.id) || previous.planned.block.updatedAt !== p.block.updatedAt;
2367
+ const targetKey = p.target.kind === "existing" ? compositionSourceKey(p.target.ref) : null;
2368
+ if (operatorAction) for (const f of p.fields) for (const r of f.reads) {
2369
+ const key = compositionSourceKey(r.source);
2370
+ if (key !== targetKey) reset.add(key);
2371
+ }
2372
+ const writer = this.writerFor(p, device);
2373
+ if (writer !== null && p.target.kind === "existing" && p.target.deviceId !== null) this.grafts.plan({
2374
+ deviceId: p.target.deviceId,
2375
+ ref: p.target.ref,
2376
+ features: p.target.features,
2377
+ nativeCaps: p.target.nativeCaps,
2378
+ enabled: p.block.enabled,
2379
+ settled: p.problems.length === 0
2380
+ });
2381
+ const runtime = writer === null || p.fields.length === 0 ? null : this.newRuntime(p, writer);
913
2382
  if (runtime !== null) fresh.add(runtime);
914
2383
  next.set(p.block.id, {
915
2384
  planned: p,
916
2385
  device,
917
2386
  runtime,
918
2387
  appliedName,
919
- rebuildError: null
2388
+ rebuildError: null,
2389
+ heldFields
920
2390
  });
921
2391
  }
922
2392
  const held = new Set(declarations.map((d) => d.stableId));
@@ -926,17 +2396,69 @@ var Composer = class {
926
2396
  else entry.runtime?.stop();
927
2397
  }
928
2398
  this.live = next;
929
- return {
930
- reset,
931
- fresh
932
- };
2399
+ const liveRuntimes = new Set([...next.values()].map((e) => e.runtime));
2400
+ this.unsynced = new Set([...[...this.unsynced].filter((r) => liveRuntimes.has(r)), ...fresh]);
2401
+ return { reset };
2402
+ }
2403
+ ungraftGone(blockId, target, deviceId) {
2404
+ this.grafts.gone(deviceId);
2405
+ ungraftGoneTarget({
2406
+ grafts: this.deps.grafts,
2407
+ logger: this.deps.logger,
2408
+ blockId,
2409
+ deviceId,
2410
+ ref: target.ref,
2411
+ features: target.features
2412
+ });
933
2413
  }
934
- newRuntime(p, device) {
2414
+ /** Where a block's runtime writes: its composed device, or a claim-backed target on the existing device. */
2415
+ writerFor(p, device) {
2416
+ const target = p.target;
2417
+ if (target.kind !== "existing") return device;
2418
+ if (target.deviceId === null || target.waiting !== null || target.gone !== null) return null;
2419
+ const deviceId = target.deviceId;
2420
+ const owner = p.block.id;
2421
+ return new OwnedFieldsTarget({
2422
+ deviceId,
2423
+ owner,
2424
+ modeOf: (cap) => claimModeOf(target.features, cap),
2425
+ fieldsOf: (cap) => claimFieldsOf(p.fields, cap),
2426
+ api: this.deps.claims,
2427
+ logger: this.deps.logger.child("owned"),
2428
+ onClaim: (cap, event) => void this.onClaimEvent(deviceId, cap, owner, event)
2429
+ });
2430
+ }
2431
+ /** C-1/N-1: the tracker follows the block's OWN claim as the hub answers it; every answer re-reads the native once. */
2432
+ async onClaimEvent(deviceId, cap, owner, event) {
2433
+ try {
2434
+ this.dispatch(await this.deps.tracker.claimEvent(deviceId, cap, owner, event));
2435
+ } catch (err) {
2436
+ this.deps.logger.warn("composer: following a claim transition failed", {
2437
+ tags: { deviceId },
2438
+ meta: {
2439
+ cap,
2440
+ owner,
2441
+ event,
2442
+ error: errMsg(err)
2443
+ }
2444
+ });
2445
+ }
2446
+ }
2447
+ heldFieldsFor(p, previous) {
2448
+ if (p.target.kind !== "existing" || p.problems.length === 0 || previous === void 0) return [];
2449
+ if (previous.runtime === null) return previous.heldFields;
2450
+ return heldFieldsOf(previous.runtime.state().fields, `the composition no longer plans — the field keeps its last value on the device: ${p.problems.join("; ")}`);
2451
+ }
2452
+ newRuntime(p, target) {
2453
+ const self = p.target.kind === "existing" ? selfReadCaps(p.fields, p.target.ref, p.target.features) : null;
2454
+ const targetKey = p.target.kind === "existing" ? compositionSourceKey(p.target.ref) : null;
2455
+ const nativeCaps = new Set(self?.native ?? []);
935
2456
  return new CompositionRuntime({
936
2457
  blockId: p.block.id,
937
2458
  fields: p.fields,
938
- target: device,
939
- read: (read) => this.deps.tracker.read(read),
2459
+ target,
2460
+ lookupCap: this.deps.lookupCap,
2461
+ read: (read) => this.deps.tracker.read(read, compositionSourceKey(read.source) === targetKey && nativeCaps.has(read.cap) ? "native" : "effective"),
940
2462
  now: this.deps.now,
941
2463
  timer: this.deps.newTimer(),
942
2464
  logger: this.deps.logger.child("runtime")
@@ -963,16 +2485,35 @@ var Composer = class {
963
2485
  }
964
2486
  }
965
2487
  async syncSources(rebuilt) {
966
- const requests = [...this.live.values()].filter((e) => e.runtime !== null && e.planned.block.enabled).flatMap((e) => e.planned.fields.flatMap((f) => f.reads.map((r) => ({
967
- ref: r.source,
968
- caps: [r.cap]
969
- }))));
2488
+ const requests = [];
2489
+ for (const e of this.live.values()) {
2490
+ const target = e.planned.target;
2491
+ const running = e.runtime !== null && e.planned.block.enabled;
2492
+ let targetKey = null;
2493
+ if (target.kind === "existing") {
2494
+ targetKey = compositionSourceKey(target.ref);
2495
+ const self = running ? selfReadCaps(e.planned.fields, target.ref, target.features) : null;
2496
+ requests.push({
2497
+ ref: target.ref,
2498
+ caps: self?.effective ?? [],
2499
+ nativeCaps: self?.native ?? [],
2500
+ nativeOwner: e.planned.block.id
2501
+ });
2502
+ }
2503
+ if (!running) continue;
2504
+ for (const f of e.planned.fields) for (const r of f.reads) if (compositionSourceKey(r.source) !== targetKey) requests.push({
2505
+ ref: r.source,
2506
+ caps: [r.cap]
2507
+ });
2508
+ }
970
2509
  const changed = await this.syncTracker(requests, rebuilt.reset);
971
2510
  for (const entry of this.live.values()) {
972
2511
  const runtime = entry.runtime;
973
2512
  if (runtime === null) continue;
2513
+ const fresh = this.unsynced.has(runtime);
2514
+ this.unsynced = new Set([...this.unsynced].filter((r) => r !== runtime));
974
2515
  if (!entry.planned.block.enabled) runtime.disable("the block is disabled");
975
- else if (rebuilt.fresh.has(runtime)) runtime.start();
2516
+ else if (fresh) runtime.start();
976
2517
  else runtime.onSourcesChanged(changed);
977
2518
  }
978
2519
  }
@@ -988,53 +2529,105 @@ var Composer = class {
988
2529
  return /* @__PURE__ */ new Set();
989
2530
  }
990
2531
  }
2532
+ /**
2533
+ * Rule 3: the claims every live customization WANTS this apply; everything
2534
+ * else the gate knows is a release candidate, handed back once two applies
2535
+ * agree. A block that cannot plan — waiting, unreadable, failed, or with its
2536
+ * target gone — HOLDS its claims (rule 4, rule 5): they are wanted as they
2537
+ * are. A disabled block wants none (rule 7).
2538
+ */
2539
+ async reconcileClaims() {
2540
+ if (!this.claimSeed.done) return;
2541
+ const wanted = [];
2542
+ const held = [];
2543
+ for (const [blockId, entry] of this.live) {
2544
+ const target = entry.planned.target;
2545
+ if (target.kind === "new") continue;
2546
+ if (target.kind === "unreadable" || entry.planned.problems.length > 0 || target.waiting !== null || target.gone !== null || target.deviceId === null) {
2547
+ held.push(blockId);
2548
+ continue;
2549
+ }
2550
+ if (!entry.planned.block.enabled) continue;
2551
+ const deviceId = target.deviceId;
2552
+ for (const f of target.features) wanted.push({
2553
+ deviceId,
2554
+ capName: f.cap,
2555
+ owner: blockId
2556
+ });
2557
+ }
2558
+ for (const owner of held) wanted.push(...this.claimGate.claimsOf(owner));
2559
+ for (const key of this.claimGate.filter(wanted)) await this.release(key);
2560
+ }
2561
+ async release(key) {
2562
+ let outcome;
2563
+ try {
2564
+ outcome = await this.deps.claims.releaseClaim(key);
2565
+ } catch (err) {
2566
+ this.claimGate.releaseFailed(key, errMsg(err));
2567
+ return;
2568
+ }
2569
+ if (!outcome.ok && !RELEASE_SETTLED_CODES.has(outcome.code)) {
2570
+ this.claimGate.releaseFailed(key, `${outcome.code}: ${outcome.message}`);
2571
+ return;
2572
+ }
2573
+ this.claimGate.released(key, outcome.ok ? "released" : outcome.code);
2574
+ await this.grafts.released(key.deviceId, key.capName);
2575
+ await this.onClaimEvent(key.deviceId, key.capName, key.owner, "free");
2576
+ }
2577
+ /**
2578
+ * Rule 5: a customization whose target row is gone — the tracker's two
2579
+ * agreeing reads — fails naming it, stops writing, and ungrafts every cap it
2580
+ * added on that id (Task 10's seam). Its claims are left as they are: the row
2581
+ * and its `$owned` died with the device. No auto-repair: an operator edit or
2582
+ * restart re-resolves the target.
2583
+ */
2584
+ failGoneTargets(deviceId) {
2585
+ const next = new Map(this.live);
2586
+ for (const [blockId, entry] of this.live) {
2587
+ const target = entry.planned.target;
2588
+ if (target.kind !== "existing" || target.deviceId !== deviceId || target.gone !== null) continue;
2589
+ const resolution = this.deps.tracker.resolution(target.ref);
2590
+ if (resolution.kind !== "missing") continue;
2591
+ entry.runtime?.stop();
2592
+ this.unsynced = new Set([...this.unsynced].filter((r) => r !== entry.runtime));
2593
+ this.ungraftGone(blockId, target, deviceId);
2594
+ next.set(blockId, {
2595
+ ...entry,
2596
+ runtime: null,
2597
+ planned: {
2598
+ ...entry.planned,
2599
+ target: {
2600
+ ...target,
2601
+ gone: `${resolution.reason} — two index reads agreed`
2602
+ }
2603
+ }
2604
+ });
2605
+ }
2606
+ this.live = next;
2607
+ }
991
2608
  dispatch(changed) {
992
2609
  if (changed.size === 0) return;
993
- for (const entry of this.live.values()) if (entry.planned.block.enabled) entry.runtime?.onSourcesChanged(changed);
2610
+ for (const entry of this.live.values()) {
2611
+ const runtime = entry.runtime;
2612
+ if (runtime === null || !entry.planned.block.enabled) continue;
2613
+ if (!this.unsynced.has(runtime)) runtime.onSourcesChanged(changed);
2614
+ }
2615
+ }
2616
+ deviceIdOf(entry) {
2617
+ if (entry.device !== null) return entry.device.id;
2618
+ return entry.planned.target.kind === "existing" ? entry.planned.target.deviceId : null;
994
2619
  }
995
2620
  tagsOf(blockId) {
996
- const deviceId = this.devices.get(composedDeviceStableId(blockId))?.id ?? null;
2621
+ const entry = this.live.get(blockId);
2622
+ const deviceId = this.composed.idOf(composedDeviceStableId(blockId)) ?? (entry === void 0 ? null : this.deviceIdOf(entry));
997
2623
  return deviceId === null ? {} : { deviceId };
998
2624
  }
999
2625
  verdict(blockId) {
1000
2626
  const entry = this.live.get(blockId);
1001
- if (entry === void 0) return {
1002
- blockId,
1003
- status: "starting",
1004
- reason: "not applied yet"
1005
- };
1006
- if (entry.rebuildError !== null) return {
1007
- blockId,
1008
- status: "failed",
1009
- reason: `rebuilding the composed device for its new shape failed: ${entry.rebuildError}`
1010
- };
1011
- if (entry.planned.problems.length > 0) {
1012
- const kept = entry.planned.declaration === null ? "" : " — its device is kept offline with no capabilities";
1013
- return {
1014
- blockId,
1015
- status: "failed",
1016
- reason: `the composition does not validate: ${entry.planned.problems.join("; ")}${kept}`
1017
- };
1018
- }
1019
- if (!entry.planned.block.enabled) return {
1020
- blockId,
1021
- status: "stopped"
1022
- };
1023
- if (entry.device === null) return {
1024
- blockId,
1025
- status: "starting",
1026
- reason: "the composed device has not been constructed yet"
1027
- };
1028
- const failure = entry.runtime?.state().failure ?? null;
1029
- if (failure !== null) return {
1030
- blockId,
1031
- status: "failed",
1032
- reason: failure
1033
- };
1034
- return {
1035
- blockId,
1036
- status: "running"
1037
- };
2627
+ const runtime = entry?.runtime ?? null;
2628
+ const target = entry?.planned.target;
2629
+ const grafts = target?.kind === "existing" && target.deviceId !== null ? this.grafts.verdict(target.deviceId, target.features) : null;
2630
+ return verdictOf(blockId, entry, runtime !== null && this.unsynced.has(runtime), grafts);
1038
2631
  }
1039
2632
  };
1040
2633
  //#endregion
@@ -1075,6 +2668,262 @@ var NodeDeadlineTimer = class {
1075
2668
  }
1076
2669
  };
1077
2670
  //#endregion
2671
+ //#region src/builtins/composer/graft-host.ts
2672
+ /**
2673
+ * Grafts (D663): a method-serving native provider for a cap a customization
2674
+ * ADDS to a device the composer does not own — a battery on an HA pet feeder
2675
+ * that registers none. Without it the added cap has claimed values on the hub
2676
+ * but nothing answers its methods, so `getBindings` never lists it and a caller
2677
+ * of `battery.wakeForStream` finds no provider.
2678
+ *
2679
+ * - The provider is built ONLY from the cap's `composedMethods` (Task 1): an
2680
+ * `answer` resolves to its value, a `refuse` rejects naming its reason. A cap
2681
+ * with a served method that has no composed answer is refused here as it is
2682
+ * at plan time (`has-commands`, slice 1). `getStatus` reads the MERGED slice
2683
+ * (`readMerged`): the hub overlays it anyway (Task 7), but a direct call to
2684
+ * this runner must never answer `{}`.
2685
+ * - The context is `createContext(stableId, id)` on a FOREIGN device id: the
2686
+ * second use of the forked-runner native path D659 lists as unverified live
2687
+ * (D659 live item 1). Task 16 step 4.1 is its live proof.
2688
+ * - `ungraft` removes only what THIS host registered, through the context's
2689
+ * optional `unregisterNativeCap`. An older kernel without it leaves the graft
2690
+ * routable until the composer respawns — warned once per device, never
2691
+ * silent.
2692
+ */
2693
+ /** The served methods of `def` that have no composed answer — non-empty means the cap cannot be grafted. */
2694
+ function unanswered(def) {
2695
+ return Object.entries(def.methods).filter(([name, m]) => m.systemOnly !== true && def.composedMethods?.[name] === void 0).map(([name]) => name);
2696
+ }
2697
+ function composedMethod(answer) {
2698
+ if (answer.kind === "answer") return async () => answer.value;
2699
+ return async () => {
2700
+ throw new Error(answer.reason);
2701
+ };
2702
+ }
2703
+ var GraftHost = class {
2704
+ ports;
2705
+ lookupCap;
2706
+ readMerged;
2707
+ /** One context per foreign device: `registerNativeCap` is per context, and so is its unregister. */
2708
+ contexts = /* @__PURE__ */ new Map();
2709
+ caps = /* @__PURE__ */ new Map();
2710
+ /** Devices already warned that this kernel cannot unregister a graft. */
2711
+ warnedNoUnregister = /* @__PURE__ */ new Set();
2712
+ constructor(ports, lookupCap, readMerged) {
2713
+ this.ports = ports;
2714
+ this.lookupCap = lookupCap;
2715
+ this.readMerged = readMerged;
2716
+ }
2717
+ graft(deviceId, stableId, capName) {
2718
+ if (this.grafted(deviceId).has(capName)) return { kind: "already" };
2719
+ const def = this.lookupCap(capName);
2720
+ if (def === null) return this.refuse(deviceId, capName, `unknown capability \`${capName}\``);
2721
+ const missing = unanswered(def);
2722
+ if (missing.length > 0) return this.refuse(deviceId, capName, `\`${capName}\` has ${missing.map((m) => `\`${m}\``).join(", ")} with no composed answer — a graft cannot serve it until commands arrive (slice 3)`);
2723
+ const ctx = this.contextFor(deviceId, stableId);
2724
+ try {
2725
+ ctx.registerNativeCap(def, this.providerFor(deviceId, def));
2726
+ } catch (err) {
2727
+ return this.refuse(deviceId, capName, `registerNativeCap threw — ${errMsg(err)}`);
2728
+ }
2729
+ this.caps = new Map([...this.caps, [deviceId, new Set([...this.grafted(deviceId), capName])]]);
2730
+ this.ports.logger.info("graft: an added cap is served on a device the composer does not own", {
2731
+ tags: { deviceId },
2732
+ meta: {
2733
+ cap: capName,
2734
+ stableId
2735
+ }
2736
+ });
2737
+ return { kind: "grafted" };
2738
+ }
2739
+ ungraft(deviceId, capName, reason) {
2740
+ if (!this.grafted(deviceId).has(capName)) return;
2741
+ const ctx = this.contexts.get(deviceId);
2742
+ if (ctx === void 0) return;
2743
+ const outcome = this.unregister(ctx, deviceId, capName, reason);
2744
+ if (outcome === "threw") return;
2745
+ const remaining = new Set([...this.grafted(deviceId)].filter((c) => c !== capName));
2746
+ this.caps = new Map([...this.caps, [deviceId, remaining]]);
2747
+ if (outcome === "unregistered") this.ports.logger.info("graft removed", {
2748
+ tags: { deviceId },
2749
+ meta: {
2750
+ cap: capName,
2751
+ reason
2752
+ }
2753
+ });
2754
+ }
2755
+ /**
2756
+ * I-3: a binding a PREVIOUS composer process left on `deviceId` — this one
2757
+ * never registered it. The kernel retracts it under the composer's addon id;
2758
+ * the hub drops only an entry the composer registered (rule 4). The caller has
2759
+ * read that the binding is the composer's.
2760
+ */
2761
+ retractStale(deviceId, capName, reason) {
2762
+ if (this.grafted(deviceId).has(capName)) {
2763
+ this.ungraft(deviceId, capName, reason);
2764
+ return;
2765
+ }
2766
+ const ctx = this.contextFor(deviceId, `graft-retract:${deviceId}`);
2767
+ if (this.unregister(ctx, deviceId, capName, reason) === "unregistered") this.ports.logger.info("graft left by a previous composer process retracted", {
2768
+ tags: { deviceId },
2769
+ meta: {
2770
+ cap: capName,
2771
+ reason
2772
+ }
2773
+ });
2774
+ }
2775
+ grafted(deviceId) {
2776
+ return this.caps.get(deviceId) ?? /* @__PURE__ */ new Set();
2777
+ }
2778
+ /** A throw keeps the graft known, so a later plan retries (M-2); an older kernel forgets it (warned once). */
2779
+ unregister(ctx, deviceId, capName, reason) {
2780
+ if (ctx.unregisterNativeCap === void 0) {
2781
+ if (!this.warnedNoUnregister.has(deviceId)) {
2782
+ this.warnedNoUnregister = new Set([...this.warnedNoUnregister, deviceId]);
2783
+ this.ports.logger.warn("graft: this kernel cannot unregister a native — the graft stays routable until the composer respawns", {
2784
+ tags: { deviceId },
2785
+ meta: {
2786
+ cap: capName,
2787
+ reason
2788
+ }
2789
+ });
2790
+ }
2791
+ return "unsupported";
2792
+ }
2793
+ try {
2794
+ ctx.unregisterNativeCap(capName);
2795
+ return "unregistered";
2796
+ } catch (err) {
2797
+ this.ports.logger.error("graft: unregistering the added cap threw — it stays routable and is retried by the next plan", {
2798
+ tags: { deviceId },
2799
+ meta: {
2800
+ cap: capName,
2801
+ reason,
2802
+ error: errMsg(err)
2803
+ }
2804
+ });
2805
+ return "threw";
2806
+ }
2807
+ }
2808
+ contextFor(deviceId, stableId) {
2809
+ const existing = this.contexts.get(deviceId);
2810
+ if (existing !== void 0) return existing;
2811
+ const ctx = this.ports.createContext(stableId, deviceId);
2812
+ this.contexts = new Map([...this.contexts, [deviceId, ctx]]);
2813
+ return ctx;
2814
+ }
2815
+ providerFor(deviceId, def) {
2816
+ const answers = Object.entries(def.composedMethods ?? {}).map(([name, answer]) => [name, composedMethod(answer)]);
2817
+ const withStatus = def.status === void 0 && def.runtimeState === void 0 ? [] : [["getStatus", async () => this.readMerged(deviceId, def.name)]];
2818
+ return Object.fromEntries([...answers, ...withStatus]);
2819
+ }
2820
+ refuse(deviceId, capName, reason) {
2821
+ this.ports.logger.error("graft refused — the added cap has no method-serving native", {
2822
+ tags: { deviceId },
2823
+ meta: {
2824
+ cap: capName,
2825
+ reason
2826
+ }
2827
+ });
2828
+ return {
2829
+ kind: "refused",
2830
+ reason
2831
+ };
2832
+ }
2833
+ };
2834
+ //#endregion
2835
+ //#region src/builtins/composer/held-claims.ts
2836
+ function slot(deviceId, cap, owner) {
2837
+ return `${owner}@${deviceId}#${cap}`;
2838
+ }
2839
+ function without(set, key) {
2840
+ return new Set([...set].filter((k) => k !== key));
2841
+ }
2842
+ var HeldClaims = class {
2843
+ held = /* @__PURE__ */ new Set();
2844
+ claiming = /* @__PURE__ */ new Set();
2845
+ /** The `replace` claims the hub holds before this process wrote any (the boot seed). */
2846
+ seed(claims) {
2847
+ const replaced = claims.filter((c) => c.mode === "replace");
2848
+ this.held = new Set([...this.held, ...replaced.map((c) => slot(c.deviceId, c.capName, c.owner))]);
2849
+ }
2850
+ apply(deviceId, cap, owner, event) {
2851
+ const k = slot(deviceId, cap, owner);
2852
+ if (event === "claiming") {
2853
+ this.claiming = new Set([...this.claiming, k]);
2854
+ return;
2855
+ }
2856
+ this.claiming = without(this.claiming, k);
2857
+ if (event === "held") this.held = new Set([...this.held, k]);
2858
+ else if (event === "free") this.held = without(this.held, k);
2859
+ }
2860
+ /** `device.state-changed` of `cap` is NOT the native for `owner`'s self-reads: its claim is held, or being asked for. */
2861
+ shadowsNative(deviceId, cap, owner) {
2862
+ const k = slot(deviceId, cap, owner);
2863
+ return this.held.has(k) || this.claiming.has(k);
2864
+ }
2865
+ };
2866
+ //#endregion
2867
+ //#region src/builtins/composer/source-readings.ts
2868
+ var DEVICE_STATUS_CAP = "device-status";
2869
+ var NATIVE_SUFFIX = "@native";
2870
+ var NO_CAPS = [];
2871
+ function entryKey(entry) {
2872
+ return entry.view === "native" ? `${entry.cap}${NATIVE_SUFFIX}` : entry.cap;
2873
+ }
2874
+ function entryOf(key) {
2875
+ return key.endsWith("@native") ? {
2876
+ cap: key.slice(0, -7),
2877
+ view: "native"
2878
+ } : {
2879
+ cap: key,
2880
+ view: "effective"
2881
+ };
2882
+ }
2883
+ function entriesOf(request) {
2884
+ return [...request.caps.map((cap) => ({
2885
+ cap,
2886
+ view: "effective"
2887
+ })), ...(request.nativeCaps ?? NO_CAPS).map((cap) => ({
2888
+ cap,
2889
+ view: "native"
2890
+ }))];
2891
+ }
2892
+ function valueAtPath(slice, path) {
2893
+ return path.split(".").reduce((node, segment) => isRecord$1(node) ? node[segment] : void 0, slice);
2894
+ }
2895
+ function onlineOf(slice) {
2896
+ const online = slice["online"];
2897
+ return typeof online === "boolean" ? online : null;
2898
+ }
2899
+ function findRow(read, stableId) {
2900
+ if (read.kind === "unreadable") return {
2901
+ kind: "unknown",
2902
+ error: read.error
2903
+ };
2904
+ const row = read.rows.find((r) => r.stableId === stableId);
2905
+ return row === void 0 ? { kind: "absent" } : {
2906
+ kind: "found",
2907
+ deviceId: row.id,
2908
+ type: row.type
2909
+ };
2910
+ }
2911
+ function resolutionOf(source) {
2912
+ if (source.missingReason !== null) return {
2913
+ kind: "missing",
2914
+ reason: source.missingReason
2915
+ };
2916
+ if (source.deviceId !== null && source.type !== null) return {
2917
+ kind: "found",
2918
+ deviceId: source.deviceId,
2919
+ type: source.type
2920
+ };
2921
+ return {
2922
+ kind: "unknown",
2923
+ error: source.indexError ?? "the device index has not been read for it yet"
2924
+ };
2925
+ }
2926
+ //#endregion
1078
2927
  //#region src/builtins/composer/source-tracker.ts
1079
2928
  /**
1080
2929
  * What a composition's sources currently say, per source device and per cap
@@ -1116,29 +2965,35 @@ var NodeDeadlineTimer = class {
1116
2965
  * It is served to nobody else — no cap method, no getter for another addon
1117
2966
  * reads this map; the composed device's slice is the only output. A consumer
1118
2967
  * that wants a source's value asks the addon that owns that source.
2968
+ *
2969
+ * Slice 2 (D663): a cap is read in one of two VIEWS. The `effective` view is
2970
+ * what every consumer sees. The `native` view is what the provider wrote — the
2971
+ * shadow under a `replace` claim — and it is how a composition reads its OWN
2972
+ * target's fields without seeing its own output (rule 6, no self-cycle). The hub
2973
+ * emits the shadow (`device.native-shadow-changed`, owner-only) only for a cap
2974
+ * under a claim, and for an unclaimed cap `device.state-changed` IS the native;
2975
+ * so a native-view cap under the block's OWN claim ignores `device.state-changed`,
2976
+ * and one it does not takes it. What is held is what LANDED (`claimEvent`, the
2977
+ * boot seed), never what a plan wants (C-1); while the block's claim RPC is in
2978
+ * flight, `device.state-changed` is neither (N-1). Every claim or release reply
2979
+ * re-reads the native once — the read that closes the window between the RPC
2980
+ * and its answer (N-4). The target ROW is resolved through the same path as a
2981
+ * source (`resolve`): one list read, two agreeing absent reads to call it
2982
+ * missing, sticky until an operator reset.
2983
+ *
2984
+ * An unavailability is CONFIRMED only when it is an answer (D49, fix round 2):
2985
+ * a GONE row (two reads agreed), a cap the provider unregistered that a
2986
+ * bindings re-read agrees is unbound, a field the source reported without. A
2987
+ * failed read (`unread`, retried by the next `sync` — the converge is the
2988
+ * retry), a first read that finds the cap unbound, an empty read, a source not
2989
+ * tracked yet: unconfirmed. Only a confirmed one lets a `release`-mode field
2990
+ * hand its claim back; an unconfirmed one holds it on its last value.
1119
2991
  */
1120
- var DEVICE_STATUS_CAP = "device-status";
1121
- function valueAtPath(slice, path) {
1122
- return path.split(".").reduce((node, segment) => isRecord(node) ? node[segment] : void 0, slice);
1123
- }
1124
- function onlineOf(slice) {
1125
- const online = slice["online"];
1126
- return typeof online === "boolean" ? online : null;
1127
- }
1128
- function findRow(read, stableId) {
1129
- if (read.kind === "unreadable") return {
1130
- kind: "unknown",
1131
- error: read.error
1132
- };
1133
- const row = read.rows.find((r) => r.stableId === stableId);
1134
- return row === void 0 ? { kind: "absent" } : {
1135
- kind: "found",
1136
- deviceId: row.id
1137
- };
1138
- }
1139
2992
  var SourceTracker = class {
1140
2993
  ports;
1141
2994
  sources = /* @__PURE__ */ new Map();
2995
+ /** The claims the hub holds — what LANDED, never what a plan wants (C-1). */
2996
+ held = new HeldClaims();
1142
2997
  /** The one chain every entry point joins (R3); the pattern is `BlockSupervisor.inFlight`. */
1143
2998
  chain = Promise.resolve();
1144
2999
  constructor(ports) {
@@ -1152,9 +3007,67 @@ var SourceTracker = class {
1152
3007
  sync(requests, reset) {
1153
3008
  return this.serialized(() => this.syncNow(requests, reset));
1154
3009
  }
3010
+ /**
3011
+ * Resolve a ref against the device index through the same path as a source
3012
+ * (D663 rule 1): one list read; two agreeing absent reads make it `missing`,
3013
+ * sticky until `reset` (an operator edit or restart). A source already
3014
+ * resolved is answered from memory; one whose index read FAILED is read
3015
+ * again. The bare source stays tracked, so a later `sync` that names it keeps
3016
+ * its resolution and reads only the caps it asks for.
3017
+ */
3018
+ resolve(ref, reset) {
3019
+ return this.serialized(async () => {
3020
+ const k = compositionSourceKey(ref);
3021
+ const prior = this.sources.get(k);
3022
+ const before = reset ? void 0 : prior;
3023
+ if (before !== void 0 && (before.deviceId !== null || before.missingReason !== null)) return resolutionOf(before);
3024
+ const after = await this.hydrate({
3025
+ ref,
3026
+ caps: []
3027
+ }, before, /* @__PURE__ */ new Map());
3028
+ const kept = prior !== void 0 && after.deviceId !== null && prior.deviceId === after.deviceId ? {
3029
+ ...after,
3030
+ caps: prior.caps,
3031
+ online: prior.online
3032
+ } : after;
3033
+ this.sources = new Map([...this.sources, [k, kept]]);
3034
+ return resolutionOf(kept);
3035
+ });
3036
+ }
3037
+ /** The claims the hub held at boot (the claims index seed). Nothing is read: no native self-read is tracked before it. */
3038
+ seedClaims(claims) {
3039
+ this.held.seed(claims);
3040
+ }
3041
+ /**
3042
+ * A claim RPC of `owner` on `(deviceId, cap)`: dispatched (`claiming`), or
3043
+ * answered — the hub holds it (`held`), holds none of it (`free`), or said
3044
+ * nothing that changes it (`unsettled`). Every ANSWER re-reads the owner's
3045
+ * native-view readings of that cap ONCE: while the RPC was in flight (or a
3046
+ * release was being applied) the provider's writes arrived as a
3047
+ * `device.state-changed` the tracker could not take as the native.
3048
+ */
3049
+ claimEvent(deviceId, cap, owner, event) {
3050
+ return this.serialized(async () => {
3051
+ this.held.apply(deviceId, cap, owner, event);
3052
+ if (event === "claiming") return /* @__PURE__ */ new Set();
3053
+ return this.rereadNative(deviceId, cap, owner);
3054
+ });
3055
+ }
3056
+ /** The last settled resolution of a ref; `unknown` when it was never resolved. Synchronous, from memory. */
3057
+ resolution(ref) {
3058
+ const source = this.sources.get(compositionSourceKey(ref));
3059
+ return source === void 0 ? {
3060
+ kind: "unknown",
3061
+ error: `source \`${compositionSourceKey(ref)}\` is not tracked`
3062
+ } : resolutionOf(source);
3063
+ }
1155
3064
  onStateChanged(deviceId, capName, slice) {
1156
3065
  return this.serialized(async () => this.applyStateChanged(deviceId, capName, slice));
1157
3066
  }
3067
+ /** `device.native-shadow-changed`: the provider's own slice of a cap under a claim (owner-only, D224). */
3068
+ onNativeChanged(deviceId, capName, native) {
3069
+ return this.serialized(async () => this.applyNativeChanged(deviceId, capName, native));
3070
+ }
1158
3071
  onDeviceUnregistered(deviceId) {
1159
3072
  return this.serialized(() => this.confirmUnregistered(deviceId));
1160
3073
  }
@@ -1174,7 +3087,9 @@ var SourceTracker = class {
1174
3087
  const prior = merged.get(k);
1175
3088
  merged.set(k, {
1176
3089
  ref: request.ref,
1177
- caps: [...new Set([...prior?.caps ?? [], ...request.caps])]
3090
+ caps: [...new Set([...prior?.caps ?? [], ...request.caps])],
3091
+ nativeCaps: [...new Set([...prior?.nativeCaps ?? [], ...request.nativeCaps ?? NO_CAPS])],
3092
+ ...(request.nativeOwner ?? prior?.nativeOwner) === void 0 ? {} : { nativeOwner: request.nativeOwner ?? prior?.nativeOwner }
1178
3093
  });
1179
3094
  }
1180
3095
  const lists = /* @__PURE__ */ new Map();
@@ -1184,12 +3099,15 @@ var SourceTracker = class {
1184
3099
  const before = reset.has(k) ? void 0 : this.sources.get(k);
1185
3100
  const after = await this.hydrate(request, before, lists);
1186
3101
  next.set(k, after);
1187
- for (const cap of request.caps) if (before?.caps.get(cap) !== after.caps.get(cap) || before?.missingReason !== after.missingReason) changed.add(compositionSliceKey(request.ref, cap));
3102
+ for (const entry of entriesOf(request)) {
3103
+ const key = entryKey(entry);
3104
+ if (before?.caps.get(key) !== after.caps.get(key) || before?.missingReason !== after.missingReason) changed.add(compositionSliceKey(request.ref, entry.cap));
3105
+ }
1188
3106
  }
1189
3107
  this.sources = next;
1190
3108
  return changed;
1191
3109
  }
1192
- read(read) {
3110
+ read(read, view = "effective") {
1193
3111
  const label = `${compositionSourceKey(read.source)} ${read.cap}.${read.fieldPath}`;
1194
3112
  const tracked = this.sources.get(compositionSourceKey(read.source));
1195
3113
  if (tracked === void 0) return {
@@ -1202,22 +3120,30 @@ var SourceTracker = class {
1202
3120
  reason: tracked.missingReason,
1203
3121
  fatal: true
1204
3122
  };
1205
- const cap = tracked.caps.get(read.cap);
3123
+ const cap = tracked.caps.get(entryKey({
3124
+ cap: read.cap,
3125
+ view
3126
+ }));
1206
3127
  if (cap === void 0) return {
1207
3128
  state: "unavailable",
1208
3129
  reason: `${label}: not tracked yet`,
1209
3130
  fatal: false
1210
3131
  };
1211
- if (cap.kind === "none" || cap.kind === "unbound") return {
1212
- state: "unavailable",
1213
- reason: `${label}: ${cap.reason}`,
1214
- fatal: false
1215
- };
3132
+ if (cap.kind !== "slice") {
3133
+ const confirmed = cap.kind === "none" && cap.confirmed;
3134
+ return {
3135
+ state: "unavailable",
3136
+ reason: `${label}: ${cap.reason}`,
3137
+ fatal: false,
3138
+ confirmed
3139
+ };
3140
+ }
1216
3141
  const value = toExpressionValue(valueAtPath(cap.slice, read.fieldPath));
1217
3142
  if (value === void 0) return {
1218
3143
  state: "unavailable",
1219
3144
  reason: `${label}: the field is absent or not a scalar`,
1220
- fatal: false
3145
+ fatal: false,
3146
+ confirmed: true
1221
3147
  };
1222
3148
  if (cap.staleReason !== null) return {
1223
3149
  state: "stale",
@@ -1240,22 +3166,28 @@ var SourceTracker = class {
1240
3166
  for (const [k, source] of this.sources) {
1241
3167
  if (source.deviceId !== deviceId || source.missingReason !== null) continue;
1242
3168
  let updated = source;
1243
- if (capName === DEVICE_STATUS_CAP) {
3169
+ if (capName === "device-status") {
1244
3170
  const online = onlineOf(slice);
1245
3171
  if (online !== source.online) {
1246
3172
  updated = {
1247
3173
  ...updated,
1248
3174
  online
1249
3175
  };
1250
- for (const cap of source.caps.keys()) changed.add(compositionSliceKey(source.ref, cap));
3176
+ for (const key of source.caps.keys()) changed.add(compositionSliceKey(source.ref, entryOf(key).cap));
1251
3177
  }
1252
3178
  }
1253
- const current = source.caps.get(capName);
1254
- if (current !== void 0) {
3179
+ const views = source.nativeOwner !== null && this.held.shadowsNative(deviceId, capName, source.nativeOwner) ? ["effective"] : ["effective", "native"];
3180
+ for (const view of views) {
3181
+ const key = entryKey({
3182
+ cap: capName,
3183
+ view
3184
+ });
3185
+ const current = source.caps.get(key);
3186
+ if (current === void 0) continue;
1255
3187
  if (current.kind === "unbound") this.logHealed(deviceId, capName, "device.state-changed");
1256
3188
  updated = {
1257
3189
  ...updated,
1258
- caps: new Map([...updated.caps, [capName, {
3190
+ caps: new Map([...updated.caps, [key, {
1259
3191
  kind: "slice",
1260
3192
  slice,
1261
3193
  staleReason: null
@@ -1268,6 +3200,31 @@ var SourceTracker = class {
1268
3200
  this.sources = next;
1269
3201
  return changed;
1270
3202
  }
3203
+ applyNativeChanged(deviceId, capName, native) {
3204
+ const changed = /* @__PURE__ */ new Set();
3205
+ const next = new Map(this.sources);
3206
+ const key = entryKey({
3207
+ cap: capName,
3208
+ view: "native"
3209
+ });
3210
+ for (const [k, source] of this.sources) {
3211
+ if (source.deviceId !== deviceId || source.missingReason !== null) continue;
3212
+ const current = source.caps.get(key);
3213
+ if (current === void 0) continue;
3214
+ if (current.kind === "unbound") this.logHealed(deviceId, capName, "device.native-shadow-changed");
3215
+ next.set(k, {
3216
+ ...source,
3217
+ caps: new Map([...source.caps, [key, {
3218
+ kind: "slice",
3219
+ slice: native,
3220
+ staleReason: null
3221
+ }]])
3222
+ });
3223
+ changed.add(compositionSliceKey(source.ref, capName));
3224
+ }
3225
+ this.sources = next;
3226
+ return changed;
3227
+ }
1271
3228
  async confirmUnregistered(deviceId) {
1272
3229
  const changed = /* @__PURE__ */ new Set();
1273
3230
  for (const [k, source] of this.sources) {
@@ -1287,8 +3244,9 @@ var SourceTracker = class {
1287
3244
  const next = resolution.kind === "missing" ? {
1288
3245
  ...source,
1289
3246
  deviceId: null,
3247
+ type: null,
1290
3248
  missingReason: `source \`${k}\` (device ${deviceId}) was removed — two reads agreed`
1291
- } : await this.rereadUnderNewId(source, resolution.deviceId);
3249
+ } : await this.rereadUnderNewId(source, resolution);
1292
3250
  this.ports.logger.warn(resolution.kind === "missing" ? "composition source removed — its fields are unavailable until the operator acts" : "composition source re-registered under a new id — re-read under it", {
1293
3251
  tags: { deviceId },
1294
3252
  meta: {
@@ -1297,43 +3255,61 @@ var SourceTracker = class {
1297
3255
  }
1298
3256
  });
1299
3257
  this.sources = new Map([...this.sources, [k, next]]);
1300
- for (const cap of source.caps.keys()) changed.add(compositionSliceKey(source.ref, cap));
3258
+ for (const key of source.caps.keys()) changed.add(compositionSliceKey(source.ref, entryOf(key).cap));
1301
3259
  }
1302
3260
  return changed;
1303
3261
  }
1304
3262
  async applyBindingsChanged(deviceId, capName, reason) {
1305
3263
  const changed = /* @__PURE__ */ new Set();
3264
+ let confirm = null;
1306
3265
  for (const [k, source] of this.sources) {
1307
3266
  if (source.deviceId !== deviceId || source.missingReason !== null) continue;
1308
- const current = source.caps.get(capName);
3267
+ const entries = [{
3268
+ cap: capName,
3269
+ view: "effective"
3270
+ }, {
3271
+ cap: capName,
3272
+ view: "native"
3273
+ }];
1309
3274
  let updated = source;
1310
- if (reason === "native-unregistered") {
1311
- if (current?.kind === "slice") {
1312
- const reading = {
3275
+ let healed = false;
3276
+ for (const entry of entries) {
3277
+ const key = entryKey(entry);
3278
+ const current = source.caps.get(key);
3279
+ if (current === void 0) continue;
3280
+ if (reason === "native-unregistered") {
3281
+ confirm ??= (await this.readBindings(deviceId, [capName])).get(capName) ?? "unknown";
3282
+ const reading = confirm === "bound" ? await this.readCap(deviceId, entry, "bound", current) : {
1313
3283
  kind: "none",
1314
- reason: `the provider unregistered \`${capName}\` — no value until it registers again`
3284
+ reason: confirm === "unbound" ? `the provider unregistered \`${capName}\` — a bindings re-read agreed; no value until it registers again` : `the provider unregistered \`${capName}\` — not confirmed (the bindings re-read failed); no value, nothing released`,
3285
+ confirmed: confirm === "unbound"
1315
3286
  };
1316
3287
  updated = {
1317
3288
  ...updated,
1318
- caps: new Map([...updated.caps, [capName, reading]])
3289
+ caps: new Map([...updated.caps, [key, reading]])
1319
3290
  };
3291
+ continue;
1320
3292
  }
1321
- } else {
1322
- const reading = current !== void 0 ? await this.readCap(deviceId, capName, "bound", current) : null;
1323
- if (reading !== null) updated = {
3293
+ const reading = await this.readCap(deviceId, entry, "bound", current);
3294
+ updated = {
1324
3295
  ...updated,
1325
- caps: new Map([...updated.caps, [capName, reading]])
3296
+ caps: new Map([...updated.caps, [key, reading]])
1326
3297
  };
1327
- if (current?.kind === "unbound" && reading !== null && reading.kind !== "unbound") this.logHealed(deviceId, capName, reason);
1328
- if (capName === DEVICE_STATUS_CAP) {
1329
- const online = reading === null ? await this.readOnline(deviceId) : reading.kind === "slice" ? onlineOf(reading.slice) : null;
1330
- if (online !== null && online !== source.online) {
1331
- updated = {
1332
- ...updated,
1333
- online
1334
- };
1335
- for (const cap of source.caps.keys()) changed.add(compositionSliceKey(source.ref, cap));
1336
- }
3298
+ if (current.kind === "unbound" && reading.kind !== "unbound") healed = true;
3299
+ }
3300
+ if (healed) this.logHealed(deviceId, capName, reason);
3301
+ if (reason !== "native-unregistered" && capName === "device-status") {
3302
+ const reading = updated.caps.get(entryKey({
3303
+ cap: capName,
3304
+ view: "effective"
3305
+ }));
3306
+ const online = reading === void 0 ? await this.readOnline(deviceId) : reading.kind === "slice" ? onlineOf(reading.slice) : null;
3307
+ if (online !== null && online !== source.online) {
3308
+ updated = {
3309
+ ...updated,
3310
+ online
3311
+ };
3312
+ for (const key of source.caps.keys()) changed.add(compositionSliceKey(source.ref, entryOf(key).cap));
1337
3313
  }
1338
3314
  }
1339
3315
  if (updated === source) continue;
@@ -1343,26 +3319,33 @@ var SourceTracker = class {
1343
3319
  return changed;
1344
3320
  }
1345
3321
  /** A source found under a NEW id is a re-registration: read it there now (R7c). */
1346
- async rereadUnderNewId(source, deviceId) {
3322
+ async rereadUnderNewId(source, found) {
1347
3323
  const caps = /* @__PURE__ */ new Map();
1348
- for (const [cap, prior] of source.caps) caps.set(cap, await this.readCap(deviceId, cap, "bound", prior));
1349
- const online = await this.readOnline(deviceId) ?? source.online;
3324
+ for (const [key, prior] of source.caps) caps.set(key, await this.readCap(found.deviceId, entryOf(key), "bound", prior));
3325
+ const online = await this.readOnline(found.deviceId) ?? source.online;
1350
3326
  return {
1351
3327
  ...source,
1352
- deviceId,
3328
+ deviceId: found.deviceId,
3329
+ type: found.type,
1353
3330
  online,
1354
3331
  caps
1355
3332
  };
1356
3333
  }
1357
3334
  async hydrate(request, before, lists) {
3335
+ const entries = entriesOf(request);
1358
3336
  if (before !== void 0 && before.missingReason !== null) return before;
1359
3337
  if (before !== void 0 && before.deviceId !== null) {
1360
- const added = request.caps.filter((cap) => !before.caps.has(cap));
1361
- if (added.length === 0 && request.caps.length === before.caps.size) return before;
1362
- const caps = await this.readCaps(before.deviceId, request.caps, before.caps, added);
3338
+ const toRead = entries.filter((entry) => {
3339
+ const held = before.caps.get(entryKey(entry));
3340
+ return held === void 0 || held.kind === "unread";
3341
+ });
3342
+ const nativeOwner = request.nativeOwner ?? null;
3343
+ if (toRead.length === 0 && entries.length === before.caps.size && nativeOwner === before.nativeOwner) return before;
3344
+ const caps = await this.readCaps(before.deviceId, entries, before.caps, toRead);
1363
3345
  return {
1364
3346
  ...before,
1365
- caps
3347
+ caps,
3348
+ nativeOwner
1366
3349
  };
1367
3350
  }
1368
3351
  const k = compositionSourceKey(request.ref);
@@ -1374,9 +3357,12 @@ var SourceTracker = class {
1374
3357
  return {
1375
3358
  ref: request.ref,
1376
3359
  deviceId: null,
3360
+ type: null,
1377
3361
  missingReason: `source \`${k}\` does not exist — two reads agreed`,
3362
+ indexError: null,
1378
3363
  online: null,
1379
- caps: /* @__PURE__ */ new Map()
3364
+ caps: /* @__PURE__ */ new Map(),
3365
+ nativeOwner: request.nativeOwner ?? null
1380
3366
  };
1381
3367
  }
1382
3368
  if (resolution.kind === "unknown") {
@@ -1387,34 +3373,41 @@ var SourceTracker = class {
1387
3373
  return {
1388
3374
  ref: request.ref,
1389
3375
  deviceId: null,
3376
+ type: null,
1390
3377
  missingReason: null,
3378
+ indexError: resolution.error,
1391
3379
  online: null,
1392
- caps: new Map(request.caps.map((cap) => [cap, {
1393
- kind: "none",
3380
+ caps: new Map(entries.map((entry) => [entryKey(entry), {
3381
+ kind: "unread",
1394
3382
  reason: `the source could not be resolved: ${resolution.error}`
1395
- }]))
3383
+ }])),
3384
+ nativeOwner: request.nativeOwner ?? null
1396
3385
  };
1397
3386
  }
1398
- const deviceId = resolution.deviceId;
1399
3387
  const known = before?.caps ?? /* @__PURE__ */ new Map();
1400
- const toRead = request.caps.filter((cap) => known.get(cap)?.kind !== "slice");
1401
- const caps = await this.readCaps(deviceId, request.caps, known, toRead);
1402
- const online = before?.online ?? await this.readOnline(deviceId);
3388
+ const toRead = entries.filter((entry) => known.get(entryKey(entry))?.kind !== "slice");
3389
+ const caps = await this.readCaps(resolution.deviceId, entries, known, toRead);
3390
+ const online = before?.online ?? await this.readOnline(resolution.deviceId);
1403
3391
  return {
1404
3392
  ref: request.ref,
1405
- deviceId,
3393
+ deviceId: resolution.deviceId,
3394
+ type: resolution.type,
1406
3395
  missingReason: null,
3396
+ indexError: null,
1407
3397
  online,
1408
- caps
3398
+ caps,
3399
+ nativeOwner: request.nativeOwner ?? null
1409
3400
  };
1410
3401
  }
1411
- /** Read `toRead` (bindings first, then slices); every other requested cap keeps what `known` holds. */
3402
+ /** Read `toRead` (bindings first, then slices); every other requested entry keeps what `known` holds. */
1412
3403
  async readCaps(deviceId, requested, known, toRead) {
1413
- const bound = toRead.length > 0 ? await this.readBindings(deviceId, toRead) : /* @__PURE__ */ new Map();
3404
+ const bound = toRead.length > 0 ? await this.readBindings(deviceId, [...new Set(toRead.map((e) => e.cap))]) : /* @__PURE__ */ new Map();
3405
+ const reading = new Set(toRead.map(entryKey));
1414
3406
  const caps = /* @__PURE__ */ new Map();
1415
- for (const cap of requested) {
1416
- const prior = known.get(cap);
1417
- caps.set(cap, prior !== void 0 && !toRead.includes(cap) ? prior : await this.readCap(deviceId, cap, bound.get(cap) ?? "unknown", prior));
3407
+ for (const entry of requested) {
3408
+ const key = entryKey(entry);
3409
+ const prior = known.get(key);
3410
+ caps.set(key, prior !== void 0 && !reading.has(key) ? prior : await this.readCap(deviceId, entry, bound.get(entry.cap) ?? "unknown", prior));
1418
3411
  }
1419
3412
  return caps;
1420
3413
  }
@@ -1429,7 +3422,10 @@ var SourceTracker = class {
1429
3422
  });
1430
3423
  return second;
1431
3424
  }
1432
- return second.kind === "absent" ? { kind: "missing" } : second;
3425
+ return second.kind === "absent" ? {
3426
+ kind: "missing",
3427
+ reason: `source \`${compositionSourceKey(ref)}\` does not exist`
3428
+ } : second;
1433
3429
  }
1434
3430
  /**
1435
3431
  * One bindings read. A second one would not confirm anything: back to back
@@ -1443,13 +3439,15 @@ var SourceTracker = class {
1443
3439
  return [c, read.caps.has(c) ? "bound" : "unbound"];
1444
3440
  }));
1445
3441
  }
1446
- async readCap(deviceId, cap, binding, prior) {
3442
+ async readCap(deviceId, entry, binding, prior) {
3443
+ const { cap, view } = entry;
1447
3444
  if (binding === "unbound") {
1448
3445
  const reason = `capability \`${cap}\` is not bound on device ${deviceId} — waiting for \`native-registered\``;
1449
3446
  if (prior?.kind !== "unbound") this.ports.logger.warn("composition source: a requested capability is not bound — the field is unavailable until it registers", {
1450
3447
  tags: { deviceId },
1451
3448
  meta: {
1452
3449
  cap,
3450
+ view,
1453
3451
  reason
1454
3452
  }
1455
3453
  });
@@ -1458,34 +3456,67 @@ var SourceTracker = class {
1458
3456
  reason
1459
3457
  };
1460
3458
  }
1461
- const read = await this.ports.readSlice(deviceId, cap);
3459
+ const read = await this.ports.readSlice(deviceId, cap, view);
1462
3460
  if (read.kind === "slice") return {
1463
3461
  kind: "slice",
1464
3462
  slice: read.slice,
1465
3463
  staleReason: null
1466
3464
  };
1467
- if (read.kind === "none") return prior?.kind === "slice" ? {
1468
- ...prior,
1469
- staleReason: `a re-read found no \`${cap}\` report — the last value is kept`
1470
- } : {
1471
- kind: "none",
1472
- reason: `the source has not reported \`${cap}\` yet`
1473
- };
3465
+ if (read.kind === "none") {
3466
+ if (prior?.kind === "slice") return {
3467
+ ...prior,
3468
+ staleReason: `a re-read found no \`${cap}\` report — the last value is kept`
3469
+ };
3470
+ return {
3471
+ kind: "none",
3472
+ reason: `the source has not reported \`${cap}\` yet`,
3473
+ confirmed: false
3474
+ };
3475
+ }
1474
3476
  this.ports.logger.warn("composition source: a slice read failed — the last value is kept", {
1475
3477
  tags: { deviceId },
1476
3478
  meta: {
1477
3479
  cap,
3480
+ view,
1478
3481
  error: read.error
1479
3482
  }
1480
3483
  });
1481
- return prior?.kind === "slice" ? {
3484
+ if (prior?.kind === "slice") return {
1482
3485
  ...prior,
1483
3486
  staleReason: `re-read failed: ${read.error}`
1484
- } : {
1485
- kind: "none",
3487
+ };
3488
+ if (prior !== void 0 && prior.kind !== "unread") return prior;
3489
+ return {
3490
+ kind: "unread",
1486
3491
  reason: `the slice could not be read: ${read.error}`
1487
3492
  };
1488
3493
  }
3494
+ /** A claim or release of `owner` on `(deviceId, cap)` was answered: read the owner's native-view readings of it once, in place. */
3495
+ async rereadNative(deviceId, cap, owner) {
3496
+ const changed = /* @__PURE__ */ new Set();
3497
+ const key = entryKey({
3498
+ cap,
3499
+ view: "native"
3500
+ });
3501
+ for (const [k, source] of this.sources) {
3502
+ if (source.deviceId !== deviceId || source.missingReason !== null) continue;
3503
+ if (source.nativeOwner !== owner) continue;
3504
+ const current = source.caps.get(key);
3505
+ if (current === void 0) continue;
3506
+ const reading = await this.readCap(deviceId, {
3507
+ cap,
3508
+ view: "native"
3509
+ }, "bound", current);
3510
+ if (reading === current) continue;
3511
+ const latest = this.sources.get(k) ?? source;
3512
+ this.sources = new Map([...this.sources, [k, {
3513
+ ...latest,
3514
+ caps: new Map([...latest.caps, [key, reading]])
3515
+ }]]);
3516
+ changed.add(compositionSliceKey(source.ref, cap));
3517
+ }
3518
+ return changed;
3519
+ }
1489
3520
  logHealed(deviceId, cap, via) {
1490
3521
  this.ports.logger.info("composition source: an unbound capability is served again", {
1491
3522
  tags: { deviceId },
@@ -1496,7 +3527,7 @@ var SourceTracker = class {
1496
3527
  });
1497
3528
  }
1498
3529
  async readOnline(deviceId) {
1499
- const read = await this.ports.readSlice(deviceId, DEVICE_STATUS_CAP);
3530
+ const read = await this.ports.readSlice(deviceId, DEVICE_STATUS_CAP, "effective");
1500
3531
  if (read.kind === "unreadable") this.ports.logger.warn("composition source: `device-status` could not be read — online unknown", {
1501
3532
  tags: { deviceId },
1502
3533
  meta: { error: read.error }
@@ -1514,9 +3545,28 @@ var SourceTracker = class {
1514
3545
  * enforced by `scripts/check-runner-group-isolation.ts`). `CrashSupervisor`
1515
3546
  * bounds it like every forked runner (D6). Hub-only: declarations are cluster
1516
3547
  * state.
3548
+ *
3549
+ * Slice 2 (D663): a composition on an EXISTING device claims its fields on the
3550
+ * hub (`deviceState.claimFields` …) and reads its own replaced fields from the
3551
+ * native shadow (`getNativeCapSlice`, `device.native-shadow-changed`) — the one
3552
+ * subscriber that category has (`scripts/check-owner-only-events.ts`).
1517
3553
  */
1518
3554
  /** Ignored by `DeclaredDevices` whenever `integrationId` is supplied, which is always here. */
1519
3555
  var DECLARED_INTEGRATION_NAME_UNUSED = "Blocks";
3556
+ /** The owner-only shadow payload is not in the typed catalog: narrowed at the boundary, like `device.state-changed`. */
3557
+ function parseNativeShadowChanged(data) {
3558
+ if (!isRecord$1(data)) return null;
3559
+ const deviceId = data["deviceId"];
3560
+ const capName = data["capName"];
3561
+ const native = data["native"];
3562
+ if (typeof deviceId !== "number" || typeof capName !== "string") return null;
3563
+ if (!isRecord$1(native)) return null;
3564
+ return {
3565
+ deviceId,
3566
+ capName,
3567
+ native
3568
+ };
3569
+ }
1520
3570
  var ComposerAddon = class extends BaseAddon {
1521
3571
  composer = null;
1522
3572
  constructor() {
@@ -1525,6 +3575,21 @@ var ComposerAddon = class extends BaseAddon {
1525
3575
  async onInitialize() {
1526
3576
  const api = this.ctx.api;
1527
3577
  const logger = this.ctx.logger;
3578
+ /** ONE `getBindings`: the tracker's binding check and the target description share it. */
3579
+ const readBoundCaps = async (deviceId) => {
3580
+ try {
3581
+ const bindings = await api.deviceManager.getBindings.query({ deviceId });
3582
+ return {
3583
+ kind: "caps",
3584
+ caps: new Map(bindings.entries.map((e) => [e.capName, e.nativeAddonId]))
3585
+ };
3586
+ } catch (err) {
3587
+ return {
3588
+ kind: "unreadable",
3589
+ error: errMsg(err)
3590
+ };
3591
+ }
3592
+ };
1528
3593
  const tracker = new SourceTracker({
1529
3594
  logger: logger.child("sources"),
1530
3595
  listDevicesOf: async (addonId) => {
@@ -1536,7 +3601,8 @@ var ComposerAddon = class extends BaseAddon {
1536
3601
  projection: "slim"
1537
3602
  })).map((r) => ({
1538
3603
  id: r.id,
1539
- stableId: r.stableId
3604
+ stableId: r.stableId,
3605
+ type: r.type
1540
3606
  }))
1541
3607
  };
1542
3608
  } catch (err) {
@@ -1546,9 +3612,12 @@ var ComposerAddon = class extends BaseAddon {
1546
3612
  };
1547
3613
  }
1548
3614
  },
1549
- readSlice: async (deviceId, capName) => {
3615
+ readSlice: async (deviceId, capName, view) => {
1550
3616
  try {
1551
- const slice = await api.deviceState.getCapSlice.query({
3617
+ const slice = view === "native" ? await api.deviceState.getNativeCapSlice.query({
3618
+ deviceId,
3619
+ capName
3620
+ }) : await api.deviceState.getCapSlice.query({
1552
3621
  deviceId,
1553
3622
  capName
1554
3623
  });
@@ -1563,20 +3632,7 @@ var ComposerAddon = class extends BaseAddon {
1563
3632
  };
1564
3633
  }
1565
3634
  },
1566
- readBoundCaps: async (deviceId) => {
1567
- try {
1568
- const bindings = await api.deviceManager.getBindings.query({ deviceId });
1569
- return {
1570
- kind: "caps",
1571
- caps: new Set(bindings.entries.map((e) => e.capName))
1572
- };
1573
- } catch (err) {
1574
- return {
1575
- kind: "unreadable",
1576
- error: errMsg(err)
1577
- };
1578
- }
1579
- }
3635
+ readBoundCaps
1580
3636
  });
1581
3637
  const listOwnDevices = async () => api.deviceManager.listAll.query({ addonId: COMPOSER_ADDON_ID });
1582
3638
  const declared = new DeclaredDevices({
@@ -1596,10 +3652,18 @@ var ComposerAddon = class extends BaseAddon {
1596
3652
  listOwnDevices
1597
3653
  });
1598
3654
  const devices = this.ctx.kernel.devices;
3655
+ const lookupCap = buildCapabilityLookup(ALL_CAPABILITY_DEFINITIONS);
3656
+ const grafts = new GraftHost({
3657
+ createContext: (stableId, id) => devices.createContext(stableId, id),
3658
+ logger: logger.child("graft")
3659
+ }, lookupCap, async (deviceId, capName) => await api.deviceState.getCapSlice.query({
3660
+ deviceId,
3661
+ capName
3662
+ }) ?? null);
1599
3663
  this.composer = new Composer({
1600
3664
  logger: logger.child("composer"),
1601
3665
  tracker,
1602
- lookupCap: buildCapabilityLookup(ALL_CAPABILITY_DEFINITIONS),
3666
+ lookupCap,
1603
3667
  readPersisted: async () => (await listOwnDevices()).map((r) => ({
1604
3668
  id: r.id,
1605
3669
  stableId: r.stableId
@@ -1623,6 +3687,14 @@ var ComposerAddon = class extends BaseAddon {
1623
3687
  decommission: (deviceId) => devices.decommission(deviceId),
1624
3688
  applyDerivedSpec: (deviceId, derived) => devices.applyDerivedSpec(deviceId, derived)
1625
3689
  },
3690
+ claims: {
3691
+ claimFields: (input) => api.deviceState.claimFields.mutate(input),
3692
+ patchOwnedFields: (input) => api.deviceState.patchOwnedFields.mutate(input),
3693
+ releaseClaim: (input) => api.deviceState.releaseClaim.mutate(input),
3694
+ listClaims: (input) => api.deviceState.listClaims.query(input)
3695
+ },
3696
+ describeTarget: readBoundCaps,
3697
+ grafts,
1626
3698
  now: () => Date.now(),
1627
3699
  newTimer: () => new NodeDeadlineTimer(() => Date.now())
1628
3700
  });
@@ -1632,6 +3704,12 @@ var ComposerAddon = class extends BaseAddon {
1632
3704
  this.logEventFailure("device.state-changed", data.deviceId, err);
1633
3705
  });
1634
3706
  });
3707
+ this.subscribe({ category: EventCategory.DeviceNativeShadowChanged }, (event) => {
3708
+ const data = parseNativeShadowChanged(event.data);
3709
+ if (data !== null) this.composer?.onNativeChanged(data).catch((err) => {
3710
+ this.logEventFailure(EventCategory.DeviceNativeShadowChanged, data.deviceId, err);
3711
+ });
3712
+ });
1635
3713
  this.subscribe({ category: EventCategory.DeviceUnregistered }, (event) => {
1636
3714
  this.composer?.onDeviceUnregistered(event.data.deviceId).catch((err) => {
1637
3715
  this.logEventFailure("device.unregistered", event.data.deviceId, err);