indigo-matter-bridge 0.7.0 → 0.9.0

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.
package/README.md CHANGED
@@ -12,7 +12,7 @@ Home and SmartThings are untested and unclaimed.
12
12
  > no discovery, and no idea what an Indigo device is. It is one half of a pair:
13
13
  > the plugin decides *what* to export and the node makes it a Matter accessory.
14
14
  > Install the Indigo plugin; it installs and manages this package for you, via
15
- > its own **Plugins ▸ Matter ▸ Install/update the Matter export bridge** menu
15
+ > its own **Plugins ▸ Matter ▸ Install/update the Matter bridge** menu
16
16
  > item and a launchd LaunchAgent it writes.
17
17
 
18
18
  ## Why it is a separate process
@@ -95,6 +95,38 @@ faults worth catching here (a role factory that builds but writes the wrong
95
95
  attribute; a bridged child publishing the wrong manufacturer) cannot fail against
96
96
  a stub.
97
97
 
98
+ ## Releasing
99
+
100
+ The package is publish-ready by construction: `files` is limited to `dist`,
101
+ `main` is `dist/main.js` (what the plugin's `bridge_agent.DEFAULT_BRIDGE_ENTRY`
102
+ expects), `engines.node` is `>=22.13.0`, and a `prepublishOnly` script runs
103
+ `clean` then `build` so a stale `dist` can never ship. (`npm pack --dry-run`
104
+ also includes `README.md` — npm always ships it regardless of `files`.)
105
+
106
+ ```sh
107
+ npm login # the package owner's npm account
108
+ npm test # publishing an untested build is the one unrecoverable mistake
109
+ npm publish --access public
110
+ ```
111
+
112
+ **Every release bumps two versions in step**: `package.json`'s `version` here,
113
+ and `bridge_agent.DEFAULT_INSTALL_SPEC` in the plugin. `test_bridge_agent.py`
114
+ only asserts the pin is never *ahead* of `package.json` (a trailing pin is
115
+ legal — installs just keep pulling the older release), so the in-step bump is
116
+ manual discipline, not something the suite enforces.
117
+
118
+ **Testing an unreleased node** (dev workaround, *not* the shipped default): the
119
+ on-disk layout the LaunchAgent expects is reproduced by a local install —
120
+
121
+ ```sh
122
+ npm install --prefix ~/indigo-matter /path/to/indigo-matter/bridge-node
123
+ ```
124
+
125
+ which puts the package at `~/indigo-matter/node_modules/indigo-matter-bridge`
126
+ exactly where `LaunchAgent._server_entry()` looks for it (`npm link` works
127
+ too). The plugin's install menu still tries the registry spec — the local
128
+ install covers everything else.
129
+
98
130
  ## Licence
99
131
 
100
132
  MIT. Not affiliated with Perceptive Automation, the Connectivity Standards
@@ -25,6 +25,32 @@
25
25
  * baseline stays, so the drift keeps being reported until a human resolves it
26
26
  * with §3.11.
27
27
  *
28
+ * **One narrow, deliberate exception (issue #140).** An entry the node itself
29
+ * marked {@link EndpointRecord.numberVoid} is not a drifted entry at all —
30
+ * {@link EndpointMapStore.voidNumbers} is only ever called at the two points
31
+ * where matter.js has just erased its OWN number allocation along with every
32
+ * fabric (§3.10's `factory_reset preserveEndpointNumbers: true`, and the
33
+ * last-fabric self-reset). matter.js is always the allocator; this map is only
34
+ * ever its witness (see below), and with no fabric left there is no paired
35
+ * ecosystem that could still be holding the old numbers to disagree with —
36
+ * adoption there is unobservable outside this node. {@link
37
+ * EndpointMapStore.check} adopts a void entry's live number silently instead
38
+ * of reporting it. An entry that was never voided still drifts exactly as
39
+ * documented above; only the reset that erased matter.js's own allocation
40
+ * earns the adoption.
41
+ *
42
+ * The marker's lifetime is bounded by when its `UniqueID` next comes back
43
+ * LIVE, not by the moment of the reset: only entries `check()` actually sees
44
+ * get to adopt, so a device that stays offline through the first post-reset
45
+ * reconcile simply keeps its VOID marker — still unadopted — until it next
46
+ * exports, however much later that is. That is still safe even if fabrics
47
+ * have been re-paired by then: the number it eventually adopts is the one
48
+ * matter.js handed out fresh after THIS reset, not a stale one, and no
49
+ * ecosystem ever saw the old number in between (it was never live to be
50
+ * observed). The safety argument above just has to be read as "no fabric
51
+ * survived the reset that erased the allocation", not "no fabric exists at
52
+ * the moment of adoption".
53
+ *
28
54
  * **It also carries what it takes to REBUILD an endpoint** (issue #141). Numbers
29
55
  * alone were enough while the file was only a witness, but a node that comes
30
56
  * online with an empty aggregator and waits for the plugin tells every paired
@@ -99,6 +125,15 @@ export declare const ENDPOINT_MAP_FILE = "endpoint-map.json";
99
125
  * endpoint set can be rebuilt without the plugin. Version 1 files are still
100
126
  * read — see {@link ENDPOINT_MAP_VERSION_LEGACY} — because a v1 file holds the
101
127
  * one thing that can never be re-derived: the numbers paired ecosystems know.
128
+ *
129
+ * **Still 2 as of issue #140's `numberVoid` marker — not bumped to 3.** A
130
+ * schema bump exists to protect an OLD build from a NEW file it cannot parse;
131
+ * `numberVoid` needs no such protection, because every reader here (old and
132
+ * new) reaches a field by name (`candidate.number`/`.role`/`.label`) rather
133
+ * than by validating the object shape as a whole, so an old build reading a
134
+ * file with an unknown extra key simply never looks at it — no throw, no
135
+ * `readRecord` rejection, the entry loads exactly as it would without the
136
+ * marker. There is nothing here for a version bump to guard.
102
137
  */
103
138
  export declare const ENDPOINT_MAP_VERSION = 2;
104
139
  /** The numbers-only shape shipped by E5. Still read; never written again. */
@@ -117,6 +152,44 @@ export interface EndpointRecord {
117
152
  number: number;
118
153
  role?: string;
119
154
  label?: string;
155
+ /**
156
+ * Set by {@link EndpointMapStore.voidNumbers} (issue #140): `number` is a
157
+ * pre-reset value that {@link EndpointMapStore.check} must silently ADOPT
158
+ * from the next live number it sees for this `UniqueID`, rather than
159
+ * report as drift. Absent (not `false`) on every ordinary entry, so a plain
160
+ * `JSON.stringify` of a non-void record is unchanged from before #140 —
161
+ * `readRecord` only ever sets this to `true` and never anything else. An
162
+ * old build reading a file that has it simply never looks at the key: it
163
+ * destructures `number`/`role`/`label` off the parsed object by name, so
164
+ * an unrecognised extra property is inert, not a crash — see the schema
165
+ * version note below, which is why this stays version 2.
166
+ */
167
+ numberVoid?: true;
168
+ /**
169
+ * Set by {@link EndpointMapStore.forget} (issue #219, this half only —
170
+ * the re-adopt UI itself lands separately): the device was un-exported,
171
+ * so the entry must not be rebuilt by {@link EndpointMapStore.restorable}
172
+ * — but unlike the pre-#219 behaviour, `role`/`label` are KEPT rather
173
+ * than deleted, because they are the only evidence a future re-adopt UI
174
+ * could match a recreated device against. Cleared the moment
175
+ * {@link EndpointMapStore.check} sees the same `UniqueID` live again
176
+ * (`noteRestorable`) — a live device is by
177
+ * definition not orphaned, and re-exporting the same accessory must not
178
+ * leave it permanently excluded from the next boot's pre-seeding. Absent
179
+ * on every ordinary entry, same convention as `numberVoid`.
180
+ */
181
+ orphaned?: true;
182
+ /**
183
+ * Set by {@link recordFor}/{@link noteRestorable} (issue #220): the live
184
+ * endpoint this entry witnesses was built with PowerSource. **Add-only,
185
+ * like {@link numberVoid}/{@link orphaned}** — never written `false` and
186
+ * never cleared once `true`, mirroring the wire rule (BRIDGE_PROTOCOL §4.1:
187
+ * a battery loss is "no evidence right now", not a removal). Absent on
188
+ * every ordinary entry and on every pre-#220 file, so an old build reading
189
+ * a file that has it never looks at the key — same inert-extra-key
190
+ * tolerance as the other two, and the same reason the schema stays 2.
191
+ */
192
+ battery?: true;
120
193
  }
121
194
  /** The on-disk shape (v2). */
122
195
  export interface EndpointMapFile {
@@ -141,6 +214,14 @@ export interface LiveEndpointNumber {
141
214
  */
142
215
  role?: string;
143
216
  label?: string;
217
+ /**
218
+ * Issue #220 — whether the LIVE endpoint carries PowerSource. Optional for
219
+ * the same reason `role`/`label` are: a caller with no live set to report
220
+ * (the seed path) must not be forced to assert `false` and have that
221
+ * silently overwrite a `true` {@link EndpointRecord.battery} already on
222
+ * disk — see {@link noteRestorable}'s add-only handling.
223
+ */
224
+ battery?: boolean;
144
225
  }
145
226
  /** An entry complete enough for `node.ts` to reconstruct before going online. */
146
227
  export interface RestorableEndpoint {
@@ -148,6 +229,8 @@ export interface RestorableEndpoint {
148
229
  endpointNumber: number;
149
230
  role: string;
150
231
  label: string;
232
+ /** Issue #220 — `true` only when the persisted entry has ever seen one. */
233
+ battery?: true;
151
234
  }
152
235
  /** The outcome of reading the file: absent, usable, or present-but-broken. */
153
236
  export interface EndpointMapLoad {
@@ -222,10 +305,35 @@ export declare class EndpointMapStore {
222
305
  * order the numbers were first recorded — irrelevant to matter.js, which
223
306
  * keys each endpoint's number on its `Endpoint.id`, but stable, which makes
224
307
  * the log read the same way twice.
308
+ *
309
+ * **`numberVoid` is deliberately not part of this filter (issue #140).** A
310
+ * voided number is still the best guess for `createEndpoint`'s
311
+ * `Endpoint.id`-keyed restore — matter.js hands back whatever it currently
312
+ * has for that id regardless of what this map believes, and the {@link
313
+ * check} that follows `server.start()` is what reconciles the map to
314
+ * whatever number came back. Excluding void entries here would only widen
315
+ * the online-and-empty window issue #141 already closed, for no benefit.
316
+ *
317
+ * **`orphaned` IS part of this filter (issue #219).** A {@link forget}en
318
+ * entry now keeps its `role`/`label` as re-adopt evidence rather than
319
+ * losing them, so the orphan marker is what still keeps it out of the
320
+ * pre-attach rebuild — exactly the churn {@link forget}'s own doc comment
321
+ * exists to prevent, unaffected by role/label now surviving alongside it.
225
322
  */
226
323
  restorable(): RestorableEndpoint[];
227
324
  /**
228
- * A device was **un-exported**: keep its number, drop what would rebuild it.
325
+ * True when the map is non-empty and EVERY entry in it is
326
+ * {@link EndpointRecord.orphaned} — issue #222's distinction for
327
+ * `node.ts`'s `restoreEndpoints()`: a map in this state is the *correct*
328
+ * "nothing to rebuild" outcome (every device was deliberately un-exported
329
+ * and the next restart will NOT restore them), which is a different fact
330
+ * from a map that simply has no `role`/`label` recorded yet (a v1 file,
331
+ * or one written before the first attach) — and the two must not share
332
+ * one log message.
333
+ */
334
+ allOrphaned(): boolean;
335
+ /**
336
+ * A device was **un-exported**: keep its number AND its role/label, mark it orphaned.
229
337
  *
230
338
  * The other half of {@link restorable}, and without it the restore is a bug
231
339
  * rather than a fix. `check` only ever *adds* and *refreshes*, so once an
@@ -237,13 +345,18 @@ export declare class EndpointMapStore {
237
345
  * devices the user had already told us to stop exporting, and it regresses
238
346
  * XAC7's "un-exported accessories are gone".
239
347
  *
240
- * **The number stays.** §3.3 retains the allocation on purpose, so re-adding
241
- * the same device gets the same endpoint number back and paired ecosystems
242
- * see the accessory they already know rather than a new one. Deleting the
243
- * entry outright would throw that away to save three fields. Clearing only
244
- * the restoration half makes the entry non-restorable — {@link restorable}
245
- * filters on `role` **and** `label` — while leaving the identity intact, and
246
- * one re-export refills it through the ordinary {@link check}.
348
+ * **The number AND the role/label stay (issue #219).** §3.3 already retained
349
+ * the number on purpose, so re-adding the same device gets the same endpoint
350
+ * number back and paired ecosystems see the accessory they already know
351
+ * rather than a new one. Deleting `role`/`label` too — the pre-#219
352
+ * behaviour — threw away the only evidence a future re-adopt UI could match
353
+ * a *recreated* device (a factory-reset accessory that comes back with a new
354
+ * `UniqueID`) against the endpoint it used to occupy. Instead the entry is
355
+ * marked {@link EndpointRecord.orphaned}, which is what keeps it out of
356
+ * {@link restorable}'s pre-attach rebuild — the actual thing #141 needed —
357
+ * without destroying anything. `check`'s `noteRestorable` clears the marker
358
+ * the moment the same `UniqueID` is live again, so a plain re-export is
359
+ * unaffected.
247
360
  *
248
361
  * **Only a caller that watched a specific endpoint go may call this.** An
249
362
  * empty live set is not evidence of anything: a node that has never attached
@@ -254,8 +367,9 @@ export declare class EndpointMapStore {
254
367
  * caller: `erase()` wipes matter.js's endpoints, but the user un-exported
255
368
  * nothing and the plugin's re-attach re-creates the same set.
256
369
  *
257
- * Returns how many entries actually lost something, so a no-op costs no
258
- * disk write.
370
+ * Returns how many entries were newly marked orphaned, so a no-op — no
371
+ * record at all, already orphaned, or nothing worth protecting because the
372
+ * entry never carried a `role`/`label` to begin with — costs no disk write.
259
373
  */
260
374
  forget(uniqueIds: readonly string[]): number;
261
375
  /**
@@ -270,8 +384,51 @@ export declare class EndpointMapStore {
270
384
  * retains the allocation so re-adding the same device restores the same
271
385
  * number, and forgetting it here would throw away the very baseline that
272
386
  * makes a re-add verifiable.
387
+ *
388
+ * **A `numberVoid` entry is adopted, not drift-checked (issue #140).** See
389
+ * the class comment for why that is safe. The live number is taken as the
390
+ * new baseline and the marker is cleared — even when the live number
391
+ * happens to already equal the stale one, because the marker itself is
392
+ * what has to stop being true, not just the mismatch it was guarding
393
+ * against.
273
394
  */
274
395
  check(live: readonly LiveEndpointNumber[]): DriftEntry[];
396
+ /**
397
+ * §3.10's preserving reset and the last-fabric self-reset (issue #140) —
398
+ * mark every entry's number as no longer trustworthy, WITHOUT discarding
399
+ * it, so the next {@link check} adopts whatever number each `UniqueID`
400
+ * comes back with instead of reporting it as drift forever.
401
+ *
402
+ * **Why this is safe — see the class comment for the full argument.** In
403
+ * one line: matter.js is always the allocator and this map only ever
404
+ * witnesses it, and both call sites reach this with an empty fabric set,
405
+ * so nothing paired can still be holding the numbers this call is about
406
+ * to let move.
407
+ *
408
+ * Unlike {@link rebuild}, this keeps every entry (role/label survive
409
+ * untouched — a void number does not make an endpoint any less
410
+ * restorable, see {@link restorable}) and unlike {@link discard}, it
411
+ * throws nothing away: a caller who wants "adopt whatever exists right
412
+ * now" already has {@link rebuild}, and this is deliberately weaker than
413
+ * that — it only stops treating the CURRENT numbers as ground truth.
414
+ *
415
+ * A no-op on an empty map: nothing to mark is not worth a write, and a
416
+ * bridge that has never exported anything must not have this manufacture
417
+ * a baseline out of nothing.
418
+ *
419
+ * Returns whether the voided baseline reached disk — `false` on the
420
+ * empty-map no-op as well as on a failed write, since neither actually
421
+ * persisted anything new. A caller that has to tell those two apart
422
+ * (a no-op is not a failure worth warning about) should check {@link size}
423
+ * before calling, the way both `node.ts` call sites now do.
424
+ *
425
+ * Also drops {@link checked}: a baseline the node itself just declared
426
+ * VOID has not been verified against anything, and leaving the flag set
427
+ * would have §4.3's `driftChecked: true` claim "checked, nothing moved"
428
+ * over numbers that are, by construction, not yet trusted. The first
429
+ * post-reset {@link check} against live entries earns it back.
430
+ */
431
+ voidNumbers(why: string): boolean;
275
432
  /**
276
433
  * Adopt a baseline for a bridge that is already commissioned but has no map
277
434
  * — the E5 upgrade path (PRD §7).
@@ -300,9 +457,10 @@ export declare class EndpointMapStore {
300
457
  *
301
458
  * The recovery path out of `endpoint_map_invalid`, and the only operation
302
459
  * here that discards a mapping. It does not renumber anything in matter.js:
303
- * whatever duplication a lost map implies has already happened by the time a
304
- * user is asked to confirm this, and what the rebuild does is stop refusing
305
- * and start telling the truth about the numbers that now exist.
460
+ * whatever duplication lost Matter storage implies has already happened by
461
+ * the time a user is asked to confirm this, and what the rebuild does is
462
+ * stop refusing and start telling the truth about the numbers that now
463
+ * exist.
306
464
  */
307
465
  rebuild(live: readonly LiveEndpointNumber[]): boolean;
308
466
  /**
@@ -25,6 +25,32 @@
25
25
  * baseline stays, so the drift keeps being reported until a human resolves it
26
26
  * with §3.11.
27
27
  *
28
+ * **One narrow, deliberate exception (issue #140).** An entry the node itself
29
+ * marked {@link EndpointRecord.numberVoid} is not a drifted entry at all —
30
+ * {@link EndpointMapStore.voidNumbers} is only ever called at the two points
31
+ * where matter.js has just erased its OWN number allocation along with every
32
+ * fabric (§3.10's `factory_reset preserveEndpointNumbers: true`, and the
33
+ * last-fabric self-reset). matter.js is always the allocator; this map is only
34
+ * ever its witness (see below), and with no fabric left there is no paired
35
+ * ecosystem that could still be holding the old numbers to disagree with —
36
+ * adoption there is unobservable outside this node. {@link
37
+ * EndpointMapStore.check} adopts a void entry's live number silently instead
38
+ * of reporting it. An entry that was never voided still drifts exactly as
39
+ * documented above; only the reset that erased matter.js's own allocation
40
+ * earns the adoption.
41
+ *
42
+ * The marker's lifetime is bounded by when its `UniqueID` next comes back
43
+ * LIVE, not by the moment of the reset: only entries `check()` actually sees
44
+ * get to adopt, so a device that stays offline through the first post-reset
45
+ * reconcile simply keeps its VOID marker — still unadopted — until it next
46
+ * exports, however much later that is. That is still safe even if fabrics
47
+ * have been re-paired by then: the number it eventually adopts is the one
48
+ * matter.js handed out fresh after THIS reset, not a stale one, and no
49
+ * ecosystem ever saw the old number in between (it was never live to be
50
+ * observed). The safety argument above just has to be read as "no fabric
51
+ * survived the reset that erased the allocation", not "no fabric exists at
52
+ * the moment of adoption".
53
+ *
28
54
  * **It also carries what it takes to REBUILD an endpoint** (issue #141). Numbers
29
55
  * alone were enough while the file was only a witness, but a node that comes
30
56
  * online with an empty aggregator and waits for the plugin tells every paired
@@ -91,6 +117,15 @@ export const ENDPOINT_MAP_FILE = "endpoint-map.json";
91
117
  * endpoint set can be rebuilt without the plugin. Version 1 files are still
92
118
  * read — see {@link ENDPOINT_MAP_VERSION_LEGACY} — because a v1 file holds the
93
119
  * one thing that can never be re-derived: the numbers paired ecosystems know.
120
+ *
121
+ * **Still 2 as of issue #140's `numberVoid` marker — not bumped to 3.** A
122
+ * schema bump exists to protect an OLD build from a NEW file it cannot parse;
123
+ * `numberVoid` needs no such protection, because every reader here (old and
124
+ * new) reaches a field by name (`candidate.number`/`.role`/`.label`) rather
125
+ * than by validating the object shape as a whole, so an old build reading a
126
+ * file with an unknown extra key simply never looks at it — no throw, no
127
+ * `readRecord` rejection, the entry loads exactly as it would without the
128
+ * marker. There is nothing here for a version bump to guard.
94
129
  */
95
130
  export const ENDPOINT_MAP_VERSION = 2;
96
131
  /** The numbers-only shape shipped by E5. Still read; never written again. */
@@ -130,6 +165,20 @@ function readRecord(value) {
130
165
  if (isNonEmptyString(candidate.label)) {
131
166
  record.label = candidate.label;
132
167
  }
168
+ // Tolerant, like role/label: anything other than a literal `true` is
169
+ // simply not a void marker, rather than a reason to reject the entry.
170
+ if (candidate.numberVoid === true) {
171
+ record.numberVoid = true;
172
+ }
173
+ // Same tolerance, same reason: an old-format record simply lacks it.
174
+ if (candidate.orphaned === true) {
175
+ record.orphaned = true;
176
+ }
177
+ // Same tolerance again (issue #220): anything other than a literal `true`
178
+ // is simply not evidence of a battery, never a reason to reject the entry.
179
+ if (candidate.battery === true) {
180
+ record.battery = true;
181
+ }
133
182
  return record;
134
183
  }
135
184
  /**
@@ -215,6 +264,12 @@ function recordFor(entry) {
215
264
  if (entry.label !== undefined) {
216
265
  record.label = entry.label;
217
266
  }
267
+ // Add-only, like every other call site that touches this field (issue
268
+ // #220) — an entry is never MINTED with `battery: false`; it simply omits
269
+ // the key, the same convention `numberVoid`/`orphaned` already use.
270
+ if (entry.battery === true) {
271
+ record.battery = true;
272
+ }
218
273
  return record;
219
274
  }
220
275
  /**
@@ -225,6 +280,13 @@ function recordFor(entry) {
225
280
  * would strip a perfectly good entry of the very fields that make it
226
281
  * restorable. Returns whether anything changed, so a steady state still costs
227
282
  * no disk write.
283
+ *
284
+ * **Also un-orphans (issue #219).** `entry` being here at all means the
285
+ * `UniqueID` is live right now, which a {@link EndpointMapStore.forget}en
286
+ * entry — by definition, no longer live at the moment it was forgotten — is
287
+ * not. A re-export must not stay permanently excluded from the next boot's
288
+ * {@link EndpointMapStore.restorable} pre-seeding just because it was once
289
+ * un-exported.
228
290
  */
229
291
  function noteRestorable(record, entry) {
230
292
  let changed = false;
@@ -236,10 +298,22 @@ function noteRestorable(record, entry) {
236
298
  record.label = entry.label;
237
299
  changed = true;
238
300
  }
301
+ // Add-only (issue #220): a live entry that HAS a battery sets the marker;
302
+ // one that does not is silently no evidence either way, matching the wire
303
+ // rule (BRIDGE_PROTOCOL §4.1) rather than clearing what a previous live
304
+ // pass already recorded.
305
+ if (entry.battery === true && !record.battery) {
306
+ record.battery = true;
307
+ changed = true;
308
+ }
309
+ if (record.orphaned) {
310
+ delete record.orphaned;
311
+ changed = true;
312
+ }
239
313
  return changed;
240
314
  }
241
315
  /** Why {@link EndpointMapStore.check} is writing, for the log line. */
242
- function persistReason(added, refreshed) {
316
+ function persistReason(added, refreshed, adopted) {
243
317
  const parts = [];
244
318
  if (added > 0) {
245
319
  parts.push(`recorded ${added} new endpoint number(s)`);
@@ -247,6 +321,9 @@ function persistReason(added, refreshed) {
247
321
  if (refreshed > 0) {
248
322
  parts.push(`refreshed ${refreshed} endpoint role/label(s)`);
249
323
  }
324
+ if (adopted > 0) {
325
+ parts.push(`adopted ${adopted} renumbered endpoint number(s)`);
326
+ }
250
327
  return parts.length === 0 ? "retried after a failed write" : parts.join(" and ");
251
328
  }
252
329
  /**
@@ -364,11 +441,25 @@ export class EndpointMapStore {
364
441
  * order the numbers were first recorded — irrelevant to matter.js, which
365
442
  * keys each endpoint's number on its `Endpoint.id`, but stable, which makes
366
443
  * the log read the same way twice.
444
+ *
445
+ * **`numberVoid` is deliberately not part of this filter (issue #140).** A
446
+ * voided number is still the best guess for `createEndpoint`'s
447
+ * `Endpoint.id`-keyed restore — matter.js hands back whatever it currently
448
+ * has for that id regardless of what this map believes, and the {@link
449
+ * check} that follows `server.start()` is what reconciles the map to
450
+ * whatever number came back. Excluding void entries here would only widen
451
+ * the online-and-empty window issue #141 already closed, for no benefit.
452
+ *
453
+ * **`orphaned` IS part of this filter (issue #219).** A {@link forget}en
454
+ * entry now keeps its `role`/`label` as re-adopt evidence rather than
455
+ * losing them, so the orphan marker is what still keeps it out of the
456
+ * pre-attach rebuild — exactly the churn {@link forget}'s own doc comment
457
+ * exists to prevent, unaffected by role/label now surviving alongside it.
367
458
  */
368
459
  restorable() {
369
460
  const restorable = [];
370
461
  for (const [uniqueId, record] of this.#endpoints) {
371
- if (record.role === undefined || record.label === undefined) {
462
+ if (record.role === undefined || record.label === undefined || record.orphaned) {
372
463
  continue;
373
464
  }
374
465
  restorable.push({
@@ -376,12 +467,30 @@ export class EndpointMapStore {
376
467
  endpointNumber: record.number,
377
468
  role: record.role,
378
469
  label: record.label,
470
+ // Issue #220: add-only, so `restore-on-start` (`node.ts`)
471
+ // rebuilds the accessory with the same cluster set it had —
472
+ // the one thing that stops every battery accessory losing
473
+ // PowerSource on the very next restart.
474
+ ...(record.battery ? { battery: true } : {}),
379
475
  });
380
476
  }
381
477
  return restorable;
382
478
  }
383
479
  /**
384
- * A device was **un-exported**: keep its number, drop what would rebuild it.
480
+ * True when the map is non-empty and EVERY entry in it is
481
+ * {@link EndpointRecord.orphaned} — issue #222's distinction for
482
+ * `node.ts`'s `restoreEndpoints()`: a map in this state is the *correct*
483
+ * "nothing to rebuild" outcome (every device was deliberately un-exported
484
+ * and the next restart will NOT restore them), which is a different fact
485
+ * from a map that simply has no `role`/`label` recorded yet (a v1 file,
486
+ * or one written before the first attach) — and the two must not share
487
+ * one log message.
488
+ */
489
+ allOrphaned() {
490
+ return this.#endpoints.size > 0 && [...this.#endpoints.values()].every(record => record.orphaned === true);
491
+ }
492
+ /**
493
+ * A device was **un-exported**: keep its number AND its role/label, mark it orphaned.
385
494
  *
386
495
  * The other half of {@link restorable}, and without it the restore is a bug
387
496
  * rather than a fix. `check` only ever *adds* and *refreshes*, so once an
@@ -393,13 +502,18 @@ export class EndpointMapStore {
393
502
  * devices the user had already told us to stop exporting, and it regresses
394
503
  * XAC7's "un-exported accessories are gone".
395
504
  *
396
- * **The number stays.** §3.3 retains the allocation on purpose, so re-adding
397
- * the same device gets the same endpoint number back and paired ecosystems
398
- * see the accessory they already know rather than a new one. Deleting the
399
- * entry outright would throw that away to save three fields. Clearing only
400
- * the restoration half makes the entry non-restorable — {@link restorable}
401
- * filters on `role` **and** `label` — while leaving the identity intact, and
402
- * one re-export refills it through the ordinary {@link check}.
505
+ * **The number AND the role/label stay (issue #219).** §3.3 already retained
506
+ * the number on purpose, so re-adding the same device gets the same endpoint
507
+ * number back and paired ecosystems see the accessory they already know
508
+ * rather than a new one. Deleting `role`/`label` too — the pre-#219
509
+ * behaviour — threw away the only evidence a future re-adopt UI could match
510
+ * a *recreated* device (a factory-reset accessory that comes back with a new
511
+ * `UniqueID`) against the endpoint it used to occupy. Instead the entry is
512
+ * marked {@link EndpointRecord.orphaned}, which is what keeps it out of
513
+ * {@link restorable}'s pre-attach rebuild — the actual thing #141 needed —
514
+ * without destroying anything. `check`'s `noteRestorable` clears the marker
515
+ * the moment the same `UniqueID` is live again, so a plain re-export is
516
+ * unaffected.
403
517
  *
404
518
  * **Only a caller that watched a specific endpoint go may call this.** An
405
519
  * empty live set is not evidence of anything: a node that has never attached
@@ -410,23 +524,25 @@ export class EndpointMapStore {
410
524
  * caller: `erase()` wipes matter.js's endpoints, but the user un-exported
411
525
  * nothing and the plugin's re-attach re-creates the same set.
412
526
  *
413
- * Returns how many entries actually lost something, so a no-op costs no
414
- * disk write.
527
+ * Returns how many entries were newly marked orphaned, so a no-op — no
528
+ * record at all, already orphaned, or nothing worth protecting because the
529
+ * entry never carried a `role`/`label` to begin with — costs no disk write.
415
530
  */
416
531
  forget(uniqueIds) {
417
532
  let forgotten = 0;
418
533
  for (const uniqueId of uniqueIds) {
419
534
  const record = this.#endpoints.get(uniqueId);
420
- if (record === undefined || (record.role === undefined && record.label === undefined)) {
535
+ if (record === undefined ||
536
+ record.orphaned ||
537
+ (record.role === undefined && record.label === undefined)) {
421
538
  continue;
422
539
  }
423
- delete record.role;
424
- delete record.label;
540
+ record.orphaned = true;
425
541
  forgotten += 1;
426
542
  }
427
543
  if (forgotten > 0) {
428
- this.persist(`cleared the role/label of ${forgotten} un-exported endpoint(s), keeping their ` +
429
- "numbers so a re-export returns the same accessory");
544
+ this.persist(`marked ${forgotten} un-exported endpoint(s) orphaned, keeping their role/label ` +
545
+ "as re-adopt evidence and their numbers so a re-export returns the same accessory");
430
546
  }
431
547
  return forgotten;
432
548
  }
@@ -442,11 +558,19 @@ export class EndpointMapStore {
442
558
  * retains the allocation so re-adding the same device restores the same
443
559
  * number, and forgetting it here would throw away the very baseline that
444
560
  * makes a re-add verifiable.
561
+ *
562
+ * **A `numberVoid` entry is adopted, not drift-checked (issue #140).** See
563
+ * the class comment for why that is safe. The live number is taken as the
564
+ * new baseline and the marker is cleared — even when the live number
565
+ * happens to already equal the stale one, because the marker itself is
566
+ * what has to stop being true, not just the mismatch it was guarding
567
+ * against.
445
568
  */
446
569
  check(live) {
447
570
  const drift = [];
448
571
  let added = 0;
449
572
  let refreshed = 0;
573
+ let adopted = 0;
450
574
  for (const entry of live) {
451
575
  const record = this.#endpoints.get(entry.uniqueId);
452
576
  if (record === undefined) {
@@ -461,17 +585,28 @@ export class EndpointMapStore {
461
585
  if (noteRestorable(record, entry)) {
462
586
  refreshed += 1;
463
587
  }
588
+ if (record.numberVoid) {
589
+ record.number = entry.endpointNumber;
590
+ delete record.numberVoid;
591
+ adopted += 1;
592
+ continue;
593
+ }
464
594
  if (record.number !== entry.endpointNumber) {
465
595
  drift.push({ uniqueId: entry.uniqueId, expected: record.number, actual: entry.endpointNumber });
466
596
  }
467
597
  }
598
+ if (adopted > 0) {
599
+ this.log(`Adopted ${adopted} endpoint number(s) renumbered by the factory reset; matter.js's ` +
600
+ "allocation was erased with the fabrics, so no paired ecosystem holds the old " +
601
+ "numbers — this is the reset's own renumbering, not drift.");
602
+ }
468
603
  // `#dirty` is the retry: a write that failed last time leaves the map
469
604
  // owing the disk something even when this pass added nothing, and the
470
605
  // steady state (`added === 0`, clean) still costs no I/O. Without it a
471
606
  // full disk at the moment of the first check would never be revisited,
472
607
  // and `checked` — see the `#dirty` field — would never come true again.
473
- if (added > 0 || refreshed > 0 || this.#dirty) {
474
- this.persist(persistReason(added, refreshed));
608
+ if (added > 0 || refreshed > 0 || adopted > 0 || this.#dirty) {
609
+ this.persist(persistReason(added, refreshed, adopted));
475
610
  }
476
611
  // An empty comparison compared nothing, so it cannot make `driftChecked`
477
612
  // true — the same rule {@link seed} already applies. §4.3 says
@@ -485,6 +620,51 @@ export class EndpointMapStore {
485
620
  }
486
621
  return drift;
487
622
  }
623
+ /**
624
+ * §3.10's preserving reset and the last-fabric self-reset (issue #140) —
625
+ * mark every entry's number as no longer trustworthy, WITHOUT discarding
626
+ * it, so the next {@link check} adopts whatever number each `UniqueID`
627
+ * comes back with instead of reporting it as drift forever.
628
+ *
629
+ * **Why this is safe — see the class comment for the full argument.** In
630
+ * one line: matter.js is always the allocator and this map only ever
631
+ * witnesses it, and both call sites reach this with an empty fabric set,
632
+ * so nothing paired can still be holding the numbers this call is about
633
+ * to let move.
634
+ *
635
+ * Unlike {@link rebuild}, this keeps every entry (role/label survive
636
+ * untouched — a void number does not make an endpoint any less
637
+ * restorable, see {@link restorable}) and unlike {@link discard}, it
638
+ * throws nothing away: a caller who wants "adopt whatever exists right
639
+ * now" already has {@link rebuild}, and this is deliberately weaker than
640
+ * that — it only stops treating the CURRENT numbers as ground truth.
641
+ *
642
+ * A no-op on an empty map: nothing to mark is not worth a write, and a
643
+ * bridge that has never exported anything must not have this manufacture
644
+ * a baseline out of nothing.
645
+ *
646
+ * Returns whether the voided baseline reached disk — `false` on the
647
+ * empty-map no-op as well as on a failed write, since neither actually
648
+ * persisted anything new. A caller that has to tell those two apart
649
+ * (a no-op is not a failure worth warning about) should check {@link size}
650
+ * before calling, the way both `node.ts` call sites now do.
651
+ *
652
+ * Also drops {@link checked}: a baseline the node itself just declared
653
+ * VOID has not been verified against anything, and leaving the flag set
654
+ * would have §4.3's `driftChecked: true` claim "checked, nothing moved"
655
+ * over numbers that are, by construction, not yet trusted. The first
656
+ * post-reset {@link check} against live entries earns it back.
657
+ */
658
+ voidNumbers(why) {
659
+ if (this.#endpoints.size === 0) {
660
+ return false;
661
+ }
662
+ for (const record of this.#endpoints.values()) {
663
+ record.numberVoid = true;
664
+ }
665
+ this.#checked = false;
666
+ return this.persist(`voided every endpoint number — ${why}`);
667
+ }
488
668
  /**
489
669
  * Adopt a baseline for a bridge that is already commissioned but has no map
490
670
  * — the E5 upgrade path (PRD §7).
@@ -524,9 +704,10 @@ export class EndpointMapStore {
524
704
  *
525
705
  * The recovery path out of `endpoint_map_invalid`, and the only operation
526
706
  * here that discards a mapping. It does not renumber anything in matter.js:
527
- * whatever duplication a lost map implies has already happened by the time a
528
- * user is asked to confirm this, and what the rebuild does is stop refusing
529
- * and start telling the truth about the numbers that now exist.
707
+ * whatever duplication lost Matter storage implies has already happened by
708
+ * the time a user is asked to confirm this, and what the rebuild does is
709
+ * stop refusing and start telling the truth about the numbers that now
710
+ * exist.
530
711
  */
531
712
  rebuild(live) {
532
713
  // The unusable file is COPIED aside before it is overwritten. It is the