@asyra/props-manager 0.5.4 → 0.6.1

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 (47) hide show
  1. package/dist/components/base.d.ts.map +1 -1
  2. package/dist/components/base.js.map +1 -1
  3. package/dist/factories/create-property.d.ts.map +1 -1
  4. package/dist/factories/create-property.js.map +1 -1
  5. package/dist/index.d.ts +3 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/manager/component-accessor.d.ts +1 -0
  9. package/dist/manager/component-accessor.d.ts.map +1 -1
  10. package/dist/manager/component-accessor.js +3 -0
  11. package/dist/manager/component-accessor.js.map +1 -1
  12. package/dist/manager/property-intents.d.ts +75 -0
  13. package/dist/manager/property-intents.d.ts.map +1 -0
  14. package/dist/manager/property-intents.js +681 -0
  15. package/dist/manager/property-intents.js.map +1 -0
  16. package/dist/manager/props-manager.d.ts +20 -2
  17. package/dist/manager/props-manager.d.ts.map +1 -1
  18. package/dist/manager/props-manager.js +523 -50
  19. package/dist/manager/props-manager.js.map +1 -1
  20. package/dist/manager/subscribes.d.ts.map +1 -1
  21. package/dist/manager/subscribes.js +19 -0
  22. package/dist/manager/subscribes.js.map +1 -1
  23. package/dist/registries/declarative-property-type.d.ts.map +1 -1
  24. package/dist/registries/declarative-property-type.js +119 -23
  25. package/dist/registries/declarative-property-type.js.map +1 -1
  26. package/dist/registries/property-component.d.ts.map +1 -1
  27. package/dist/registries/property-component.js.map +1 -1
  28. package/dist/registries/property-definition-value.d.ts.map +1 -1
  29. package/dist/registries/property-definition-value.js.map +1 -1
  30. package/dist/registries/property-definition.d.ts.map +1 -1
  31. package/dist/registries/property-definition.js +2 -1
  32. package/dist/registries/property-definition.js.map +1 -1
  33. package/dist/registries/property-inheritance.d.ts +9 -0
  34. package/dist/registries/property-inheritance.d.ts.map +1 -0
  35. package/dist/registries/property-inheritance.js +164 -0
  36. package/dist/registries/property-inheritance.js.map +1 -0
  37. package/dist/registries/property-registration.d.ts.map +1 -1
  38. package/dist/registries/property-registration.js.map +1 -1
  39. package/dist/registries/property-schema.d.ts.map +1 -1
  40. package/dist/registries/property-schema.js.map +1 -1
  41. package/dist/registries/property-value-kind.d.ts +2 -1
  42. package/dist/registries/property-value-kind.d.ts.map +1 -1
  43. package/dist/registries/property-value-kind.js +20 -0
  44. package/dist/registries/property-value-kind.js.map +1 -1
  45. package/dist/registries/state.d.ts.map +1 -1
  46. package/dist/registries/state.js.map +1 -1
  47. package/package.json +5 -5
@@ -1,3 +1,5 @@
1
+ import { readPropertyTargets, prepareOwnerPropertyMutations, prepareSharedPropertySourceBatch, preparePropertyIntentBatch } from './property-intents.js';
2
+ import { readPropertyInheritance, readPropertyInheritanceDependencies, validatePropertyInheritanceGraph, validatePropertyInheritanceCycles } from '../registries/property-inheritance.js';
1
3
  import { IDTypes, PROPS_ACTIONS, SharedDataChannelNames, beginBrowserDragPhase, measureBrowserDragPhase, id, isRecord } from '@asyra/utils';
2
4
  import { acknowledgeTransactionReplayApplied, EventTypes, getTransactionReplayMode, TransactionEventTypes, updateTransaction, updateTransactionBatch } from '@asyra/reactive-events';
3
5
  import * as lodashModule from 'lodash';
@@ -5,7 +7,7 @@ import { createProperty, createPropertyWithConstructor } from '../factories/crea
5
7
  import { arePropertyChildRelationsEqual, getPropertyComponent, getPropertyComponentBatchRebindableRelation, getPropertyComponentCanonicalChildRelation, getPropertyComponentConfigDefinition, getPropertyComponentRegistrationRevision, isPropertyComponentBatchRebindable, resolvePropertyComponentConfigRoles } from '../registries/property-component.js';
6
8
  import { clonePropertyDefinitionValue } from '../registries/property-definition-value.js';
7
9
  import elementPropertyRegistry from '../registries/property-definition.js';
8
- import { matchesPropertyValueKind } from '../registries/property-value-kind.js';
10
+ import { isRuntimePropertyFieldValueValid } from '../registries/property-value-kind.js';
9
11
  import { getPropertySchemaRegistrationRevision, getRegisteredPropertySchema, runWithPropertySchemaResolver } from '../registries/property-schema.js';
10
12
  import { runWithPropertyComponentAccessor, setComponentAccessor } from './component-accessor.js';
11
13
  const lodash = lodashModule.default ?? lodashModule;
@@ -49,26 +51,6 @@ const snapshotPropertySchema = (schema) => schema
49
51
  })
50
52
  : undefined;
51
53
  const snapshotPropertyChildRelation = (relation) => relation ? Object.freeze({ ...relation }) : undefined;
52
- const isRuntimePropertyFieldValueValid = (field, value) => {
53
- if (!matchesPropertyValueKind(field.kind, value)) {
54
- return false;
55
- }
56
- if (field.allowedUnits &&
57
- field.allowedUnits.length > 0 &&
58
- typeof value === 'string' &&
59
- !field.allowedUnits.some((unit) => unit === value)) {
60
- return false;
61
- }
62
- if (!field.validate) {
63
- return true;
64
- }
65
- try {
66
- return field.validate(value);
67
- }
68
- catch {
69
- return false;
70
- }
71
- };
72
54
  const describeInvalidRuntimePropertyFieldValue = (value) => {
73
55
  if (typeof value === 'number' && !Number.isFinite(value)) {
74
56
  return 'non-finite number';
@@ -111,6 +93,24 @@ class PropsManager {
111
93
  this.propertyStateRevision = 0;
112
94
  this.componentAccessor = {
113
95
  getPropertyById: (propertyId) => this.resolvePropertyForComponent(propertyId),
96
+ validateSharedWrite: (propertyId, key, value) => {
97
+ const active = this._components.get(propertyId);
98
+ if (!active) {
99
+ throw new Error(`[PropsManager] Shared property "${propertyId}" is not active`);
100
+ }
101
+ const records = {};
102
+ for (const dependent of this.resolvePropertyAncestorIds([propertyId])) {
103
+ const component = this._components.get(dependent);
104
+ if (component) {
105
+ records[dependent] = component.save();
106
+ }
107
+ }
108
+ records[propertyId] = {
109
+ ...active.save(),
110
+ [key]: clonePropsValue(value)
111
+ };
112
+ validatePropertyInheritanceGraph(records, (id) => records[id] ?? this._components.get(id)?.save());
113
+ },
114
114
  addToMap: (component) => this.addToMap(component),
115
115
  createComponent: (data) => this.createPropertyInternal(data, 'relationship-child'),
116
116
  addChange: (change) => this.addChange({
@@ -130,6 +130,23 @@ class PropsManager {
130
130
  const relation = typeof type === 'string'
131
131
  ? getPropertyComponentCanonicalChildRelation(type)
132
132
  : undefined;
133
+ const raw = sourceSnapshot ??
134
+ component.data;
135
+ const inheritance = readPropertyInheritance(raw);
136
+ if (inheritance) {
137
+ const explicitChildren = relation
138
+ ? inheritance.overrides[relation.key]
139
+ : undefined;
140
+ return Object.freeze([
141
+ ...new Set([
142
+ inheritance.sourceId,
143
+ ...Object.values(inheritance.childBindings),
144
+ ...(Array.isArray(explicitChildren)
145
+ ? explicitChildren
146
+ : [])
147
+ ])
148
+ ]);
149
+ }
133
150
  if (!relation) {
134
151
  return;
135
152
  }
@@ -241,6 +258,8 @@ class PropsManager {
241
258
  type: rawType
242
259
  };
243
260
  });
261
+ validatePropertyInheritanceGraph(sanitized);
262
+ validatePropertyInheritanceCycles(sanitized);
244
263
  return this.createLoadValidationResult(sanitized, diagnostics);
245
264
  }
246
265
  applyValidatedLoad(result) {
@@ -251,7 +270,7 @@ class PropsManager {
251
270
  this.validatedLoadArtifacts.delete(result);
252
271
  this.dispose();
253
272
  Object.keys(validated).forEach((componentId) => {
254
- const newProperty = createProperty(validated[componentId]);
273
+ const newProperty = runWithPropertyComponentAccessor(this.componentAccessor, () => createProperty(validated[componentId]));
255
274
  this.addToMap(newProperty);
256
275
  });
257
276
  }
@@ -818,6 +837,7 @@ class PropsManager {
818
837
  throw new Error(`[PropsManager] Canonical property creation is missing owner root "${componentId}"`);
819
838
  }
820
839
  });
840
+ validatePropertyInheritanceGraph(Object.fromEntries(componentById), (id) => componentById.get(id) ?? this.getPropertyById(id)?.save());
821
841
  const reachableComponentIds = new Set();
822
842
  const visitingComponentIds = new Set();
823
843
  const parentFirstDeclarativeComponentIds = new Set();
@@ -837,6 +857,13 @@ class PropsManager {
837
857
  reachableComponentIds.add(componentId);
838
858
  const registrationContract = registrationContractByType.get(component.type);
839
859
  const childRelation = registrationContract?.childRelation;
860
+ const inheritedDependencies = readPropertyInheritanceDependencies(component, childRelation?.key);
861
+ if (inheritedDependencies) {
862
+ inheritedDependencies.forEach((dependency) => visit(dependency));
863
+ visitingComponentIds.delete(componentId);
864
+ requiresDeferredRebindById.set(componentId, false);
865
+ return false;
866
+ }
840
867
  if (!childRelation) {
841
868
  visitingComponentIds.delete(componentId);
842
869
  requiresDeferredRebindById.set(componentId, false);
@@ -920,6 +947,8 @@ class PropsManager {
920
947
  throw new Error('[PropsManager] Expected an owner-issued one-shot prepared property creation batch');
921
948
  }
922
949
  this.validatedPropertyCreationArtifacts.delete(prepared);
950
+ const inheritedRecords = Object.fromEntries(artifact.components.map((record) => [record.id, record]));
951
+ validatePropertyInheritanceGraph(inheritedRecords, (id) => inheritedRecords[id] ?? this.getPropertyById(id)?.save());
923
952
  const components = this.createAndRegisterPropertyBatch(artifact.components, artifact.registrationContracts, artifact.parentFirstDeclarativeComponentIds, artifact.sourceSemantics);
924
953
  if (artifact.sourceSemantics === 'exact') {
925
954
  measurePropertyBatchPhase('props-manager:creation-exact', () => {
@@ -993,6 +1022,11 @@ class PropsManager {
993
1022
  }
994
1023
  visitedComponentIds.add(componentId);
995
1024
  const childRelation = getPropertyComponentCanonicalChildRelation(component.type);
1025
+ const inheritedDependencies = readPropertyInheritanceDependencies(component, childRelation?.key);
1026
+ if (inheritedDependencies) {
1027
+ inheritedDependencies.forEach(visit);
1028
+ return;
1029
+ }
996
1030
  if (!childRelation) {
997
1031
  return;
998
1032
  }
@@ -1191,17 +1225,26 @@ class PropsManager {
1191
1225
  throw new Error(`[PropsManager] Invalid property restore: malformed owner relation for "${relation.componentId}"`);
1192
1226
  }
1193
1227
  });
1228
+ validatePropertyInheritanceGraph(Object.fromEntries(componentById), (id) => componentById.get(id) ?? this.getPropertyById(id)?.save());
1194
1229
  const reachableSnapshotIds = new Set();
1195
1230
  const visit = (componentId) => {
1196
- if (reachableSnapshotIds.has(componentId))
1231
+ if (reachableSnapshotIds.has(componentId)) {
1197
1232
  return;
1233
+ }
1198
1234
  const component = componentById.get(componentId);
1199
- if (!component)
1235
+ if (!component) {
1200
1236
  return;
1237
+ }
1201
1238
  reachableSnapshotIds.add(componentId);
1202
1239
  const childRelation = getPropertyComponentCanonicalChildRelation(component.type);
1203
- if (!childRelation)
1240
+ const inheritedDependencies = readPropertyInheritanceDependencies(component, childRelation?.key);
1241
+ if (inheritedDependencies) {
1242
+ inheritedDependencies.forEach(visit);
1204
1243
  return;
1244
+ }
1245
+ if (!childRelation) {
1246
+ return;
1247
+ }
1205
1248
  const childIds = component[childRelation.key];
1206
1249
  if (!Array.isArray(childIds) ||
1207
1250
  childIds.some((childId) => typeof childId !== 'string') ||
@@ -1218,8 +1261,9 @@ class PropsManager {
1218
1261
  if (childType !== childRelation.childType) {
1219
1262
  throw new Error(`[PropsManager] Invalid property restore: malformed child relation type for "${childId}"`);
1220
1263
  }
1221
- if (snapshotChild)
1264
+ if (snapshotChild) {
1222
1265
  visit(childId);
1266
+ }
1223
1267
  });
1224
1268
  };
1225
1269
  validatedRelations.forEach(({ componentId }) => visit(componentId));
@@ -1255,6 +1299,7 @@ class PropsManager {
1255
1299
  }
1256
1300
  this.validatedRestoreArtifacts.delete(prepared);
1257
1301
  const snapshotById = new Map(artifact.snapshot.components.map((component) => [component.id, component]));
1302
+ validatePropertyInheritanceGraph(Object.fromEntries(snapshotById), (id) => snapshotById.get(id) ?? this.getPropertyById(id)?.save());
1258
1303
  const materialized = new Map();
1259
1304
  try {
1260
1305
  prepared.entries.forEach(({ componentId, strategy }) => {
@@ -1784,6 +1829,18 @@ class PropsManager {
1784
1829
  }, {});
1785
1830
  }
1786
1831
  removeProperty(propComponentIds, _options) {
1832
+ const removed = new Set(propComponentIds);
1833
+ for (const propertyId of removed) {
1834
+ for (const ownerId of this.relationshipOwnerIdsByChildId.get(propertyId) ?? []) {
1835
+ if (removed.has(ownerId)) {
1836
+ continue;
1837
+ }
1838
+ const owner = this._components.get(ownerId)?.save();
1839
+ if (owner?.inheritance) {
1840
+ throw new Error(`[PropsManager] Cannot remove inherited source or local binding "${propertyId}" still used by "${ownerId}"`);
1841
+ }
1842
+ }
1843
+ }
1787
1844
  propComponentIds.forEach((propComponentId) => {
1788
1845
  const component = this.getPropertyById(propComponentId);
1789
1846
  if (!component) {
@@ -1793,6 +1850,18 @@ class PropsManager {
1793
1850
  this.removeFromMap(propComponentId);
1794
1851
  });
1795
1852
  }
1853
+ readPropertyTargets(targets) {
1854
+ return readPropertyTargets(this, targets);
1855
+ }
1856
+ preparePropertyIntentBatch(intents, options) {
1857
+ return preparePropertyIntentBatch(this, intents, options, (propertyId, parentId) => [...(this.relationshipOwnerIdsByChildId.get(propertyId) ?? [])].some((ownerId) => ownerId !== parentId));
1858
+ }
1859
+ prepareOwnerPropertyMutations(updates, options) {
1860
+ return prepareOwnerPropertyMutations(this, updates, options, (propertyId, parentId) => [...(this.relationshipOwnerIdsByChildId.get(propertyId) ?? [])].some((ownerId) => ownerId !== parentId));
1861
+ }
1862
+ prepareSharedPropertySourceBatch(updates, options) {
1863
+ return prepareSharedPropertySourceBatch(this, updates, options);
1864
+ }
1796
1865
  preparePropertyMutationBatch(sourceRequest) {
1797
1866
  if (!isRecord(sourceRequest) ||
1798
1867
  !Array.isArray(sourceRequest.operations) ||
@@ -1816,6 +1885,14 @@ class PropsManager {
1816
1885
  const persistKeysByType = new Map();
1817
1886
  const defaultsByType = new Map();
1818
1887
  const orderedPropertyIds = [];
1888
+ const orderedPropertyIdSet = new Set();
1889
+ const appendOrderedPropertyId = (propertyId) => {
1890
+ if (orderedPropertyIdSet.has(propertyId)) {
1891
+ return;
1892
+ }
1893
+ orderedPropertyIdSet.add(propertyId);
1894
+ orderedPropertyIds.push(propertyId);
1895
+ };
1819
1896
  const requestedPropertyIds = new Set();
1820
1897
  const touchedPropertyIds = [];
1821
1898
  const touchedPropertyIdSet = new Set();
@@ -1825,6 +1902,7 @@ class PropsManager {
1825
1902
  const removedCandidateIds = [];
1826
1903
  const removedCandidateIdSet = new Set();
1827
1904
  const exactOrphanCandidateIds = new Set();
1905
+ let exactRetirementIds;
1828
1906
  const retainedRootPropertyIdSet = new Set();
1829
1907
  const retainedRootIdentityReads = [];
1830
1908
  const retainedRootRelationshipReads = new Map();
@@ -1865,7 +1943,8 @@ class PropsManager {
1865
1943
  });
1866
1944
  return;
1867
1945
  }
1868
- if (sourceMutation.kind === 'create-exact-property-graph' &&
1946
+ if ((sourceMutation.kind === 'create-exact-property-graph' ||
1947
+ sourceMutation.kind === 'create-exact-property-records') &&
1869
1948
  Array.isArray(sourceMutation.components)) {
1870
1949
  sourceMutation.components.forEach((component) => {
1871
1950
  if (isRecord(component) &&
@@ -2019,7 +2098,7 @@ class PropsManager {
2019
2098
  return [...value];
2020
2099
  };
2021
2100
  const assertField = (snapshot, contract, propertyId, key, value) => {
2022
- if (key === 'id' || key === 'type') {
2101
+ if (['id', 'type', 'inheritance', 'sharedSource'].includes(key)) {
2023
2102
  throw new Error(`[PropsManager] Property mutation cannot replace canonical field "${propertyId}.${key}"`);
2024
2103
  }
2025
2104
  const field = getFieldByKey(contract).get(key);
@@ -2046,7 +2125,7 @@ class PropsManager {
2046
2125
  }
2047
2126
  });
2048
2127
  };
2049
- const addUpdateEvidence = (propertyId, key, before, after) => {
2128
+ const addUpdateEvidence = (propertyId, key, before, after, layer) => {
2050
2129
  if (isEqual(before, after)) {
2051
2130
  return;
2052
2131
  }
@@ -2055,11 +2134,12 @@ class PropsManager {
2055
2134
  eventName: EventTypes.UPDATE_PROPERTY,
2056
2135
  id: propertyId,
2057
2136
  key,
2137
+ ...(layer ? { layer } : {}),
2058
2138
  before: clonePropsValue(before),
2059
2139
  after: clonePropsValue(after)
2060
2140
  });
2061
2141
  };
2062
- const addReplaceLatestHistoryEvidence = (propertyId, key, before, after) => {
2142
+ const addReplaceLatestHistoryEvidence = (propertyId, key, before, after, layer) => {
2063
2143
  if (mutationOptions?.history?.mode !== 'replace-latest') {
2064
2144
  return;
2065
2145
  }
@@ -2068,6 +2148,7 @@ class PropsManager {
2068
2148
  eventName: EventTypes.UPDATE_PROPERTY,
2069
2149
  id: propertyId,
2070
2150
  key,
2151
+ ...(layer ? { layer } : {}),
2071
2152
  before: clonePropsValue(before),
2072
2153
  after: clonePropsValue(after)
2073
2154
  });
@@ -2372,7 +2453,7 @@ class PropsManager {
2372
2453
  }
2373
2454
  if (!requestedPropertyIds.has(propertyId)) {
2374
2455
  requestedPropertyIds.add(propertyId);
2375
- orderedPropertyIds.push(propertyId);
2456
+ appendOrderedPropertyId(propertyId);
2376
2457
  }
2377
2458
  captureMutationOwner(propertyId, sourceMutation.ownerElementId);
2378
2459
  relations.push({
@@ -2385,12 +2466,16 @@ class PropsManager {
2385
2466
  creationRelationsByMutationIndex.set(mutationIndex, Object.freeze(relations));
2386
2467
  };
2387
2468
  const prepareExactCreation = (sourceMutation, mutationIndex) => {
2388
- if (!Array.isArray(sourceMutation.ownerRelations) ||
2389
- sourceMutation.ownerRelations.length === 0 ||
2469
+ const canonicalRecords = sourceMutation.kind === 'create-exact-property-records';
2470
+ if ((!canonicalRecords &&
2471
+ (!Array.isArray(sourceMutation.ownerRelations) ||
2472
+ sourceMutation.ownerRelations.length === 0)) ||
2390
2473
  !Array.isArray(sourceMutation.components)) {
2391
- throw new Error(`[PropsManager] Exact property creation requires owner relations and a components array at item ${mutationIndex}`);
2474
+ throw new Error(`[PropsManager] Exact property creation requires canonical records or owner relations at item ${mutationIndex}`);
2392
2475
  }
2393
- const relations = clonePropertyDefinitionValue(sourceMutation.ownerRelations);
2476
+ const relations = canonicalRecords
2477
+ ? []
2478
+ : clonePropertyDefinitionValue(sourceMutation.ownerRelations);
2394
2479
  const sourceComponents = sourceMutation.components;
2395
2480
  if (sourceComponents.some((component) => !isRecord(component) ||
2396
2481
  typeof component.id !== 'string' ||
@@ -2485,7 +2570,22 @@ class PropsManager {
2485
2570
  throw new Error(`[PropsManager] Exact property creation owner root "${relation.componentId}" has the wrong type`);
2486
2571
  }
2487
2572
  });
2573
+ // Reachability uses the final registered relationships of existing owners
2574
+ // in this same preparation. Validation below still checks every delta.
2575
+ const pendingLayerMutations = new Map();
2576
+ mutations.forEach((mutation) => {
2577
+ if (!isRecord(mutation) ||
2578
+ mutation.kind !== 'layers' ||
2579
+ typeof mutation.propertyId !== 'string' ||
2580
+ !Array.isArray(mutation.changes)) {
2581
+ return;
2582
+ }
2583
+ const changes = pendingLayerMutations.get(mutation.propertyId) ?? [];
2584
+ changes.push(...mutation.changes.filter(isRecord));
2585
+ pendingLayerMutations.set(mutation.propertyId, changes);
2586
+ });
2488
2587
  const visiting = new Set();
2588
+ const visitedActive = new Set();
2489
2589
  const visited = new Set();
2490
2590
  const childFirstIds = [];
2491
2591
  const visit = (propertyId) => {
@@ -2497,12 +2597,66 @@ class PropsManager {
2497
2597
  }
2498
2598
  const component = componentById.get(propertyId);
2499
2599
  if (!component) {
2600
+ if (visitedActive.has(propertyId)) {
2601
+ return;
2602
+ }
2603
+ const active = captureActiveSnapshot(propertyId);
2604
+ if (!active) {
2605
+ return;
2606
+ }
2607
+ visiting.add(propertyId);
2608
+ const prospective = clonePropsValue(active);
2609
+ for (const change of pendingLayerMutations.get(propertyId) ?? []) {
2610
+ if ((change.layer !== 'overrides' &&
2611
+ change.layer !== 'childBindings') ||
2612
+ typeof change.key !== 'string' ||
2613
+ !isRecord(change.state) ||
2614
+ !prospective.inheritance) {
2615
+ continue;
2616
+ }
2617
+ const fields = prospective.inheritance[change.layer];
2618
+ if (change.state.present === true) {
2619
+ Object.defineProperty(fields, change.key, {
2620
+ value: change.state.value,
2621
+ enumerable: true,
2622
+ writable: true,
2623
+ configurable: true
2624
+ });
2625
+ }
2626
+ else if (change.state.present === false) {
2627
+ Reflect.deleteProperty(fields, change.key);
2628
+ }
2629
+ }
2630
+ const relation = captureContract(prospective.type).childRelation;
2631
+ const dependencies = readPropertyInheritanceDependencies(prospective, relation?.key) ??
2632
+ (relation &&
2633
+ Array.isArray(prospective[relation.key])
2634
+ ? prospective[relation.key]
2635
+ : []);
2636
+ for (const child of dependencies) {
2637
+ visit(child);
2638
+ }
2639
+ visiting.delete(propertyId);
2640
+ visitedActive.add(propertyId);
2500
2641
  return;
2501
2642
  }
2502
2643
  visiting.add(propertyId);
2503
2644
  const contract = captureContract(component.type);
2504
2645
  const relation = contract.childRelation;
2505
- if (relation) {
2646
+ const inheritance = readPropertyInheritance(component);
2647
+ if (inheritance) {
2648
+ const dependencies = [
2649
+ inheritance.sourceId,
2650
+ ...Object.values(inheritance.childBindings),
2651
+ ...(relation && Array.isArray(inheritance.overrides[relation.key])
2652
+ ? inheritance.overrides[relation.key]
2653
+ : [])
2654
+ ];
2655
+ for (const dependency of dependencies) {
2656
+ visit(dependency);
2657
+ }
2658
+ }
2659
+ else if (relation) {
2506
2660
  const childIds = component[relation.key];
2507
2661
  if (!Array.isArray(childIds) ||
2508
2662
  childIds.some((childId) => typeof childId !== 'string') ||
@@ -2531,7 +2685,12 @@ class PropsManager {
2531
2685
  visited.add(propertyId);
2532
2686
  childFirstIds.push(propertyId);
2533
2687
  };
2534
- relations.forEach(({ componentId }) => visit(componentId));
2688
+ if (canonicalRecords) {
2689
+ components.forEach(({ id }) => visit(id));
2690
+ }
2691
+ else {
2692
+ relations.forEach(({ componentId }) => visit(componentId));
2693
+ }
2535
2694
  if (visited.size !== components.length) {
2536
2695
  throw new Error('[PropsManager] Exact property creation contains an unowned property');
2537
2696
  }
@@ -2547,12 +2706,20 @@ class PropsManager {
2547
2706
  prepareCreationRecord(component, component.type, propertyId, true);
2548
2707
  });
2549
2708
  relations.forEach((relation) => {
2550
- if (!requestedPropertyIds.has(relation.componentId)) {
2709
+ if (!activeById.has(relation.componentId) &&
2710
+ !requestedPropertyIds.has(relation.componentId)) {
2551
2711
  requestedPropertyIds.add(relation.componentId);
2552
- orderedPropertyIds.push(relation.componentId);
2553
2712
  }
2713
+ appendOrderedPropertyId(relation.componentId);
2554
2714
  captureMutationOwner(relation.componentId, relation.ownerElementId);
2555
2715
  });
2716
+ if (canonicalRecords) {
2717
+ components.forEach(({ id }) => {
2718
+ requestedPropertyIds.add(id);
2719
+ appendOrderedPropertyId(id);
2720
+ captureMutationOwner(id);
2721
+ });
2722
+ }
2556
2723
  creationRelationsByMutationIndex.set(mutationIndex, Object.freeze(relations));
2557
2724
  };
2558
2725
  mutations.forEach((sourceMutation, mutationIndex) => {
@@ -2562,7 +2729,8 @@ class PropsManager {
2562
2729
  if (sourceMutation.kind === 'create-owner-properties') {
2563
2730
  prepareOrdinaryCreation(sourceMutation, mutationIndex);
2564
2731
  }
2565
- else if (sourceMutation.kind === 'create-exact-property-graph') {
2732
+ else if (sourceMutation.kind === 'create-exact-property-graph' ||
2733
+ sourceMutation.kind === 'create-exact-property-records') {
2566
2734
  prepareExactCreation(sourceMutation, mutationIndex);
2567
2735
  }
2568
2736
  });
@@ -2575,6 +2743,30 @@ class PropsManager {
2575
2743
  ownerRelations.push(...creationRelations);
2576
2744
  return;
2577
2745
  }
2746
+ if (sourceMutation.kind === 'remove-exact-property-records') {
2747
+ if (exactRetirementIds || !Array.isArray(sourceMutation.components)) {
2748
+ throw new Error('[PropsManager] Exact record retirement requires one canonical record list');
2749
+ }
2750
+ exactRetirementIds = new Set();
2751
+ for (const record of sourceMutation.components) {
2752
+ if (!isRecord(record) ||
2753
+ typeof record.id !== 'string' ||
2754
+ !record.id ||
2755
+ exactRetirementIds.has(record.id)) {
2756
+ throw new Error('[PropsManager] Exact record retirement has duplicate or invalid identities');
2757
+ }
2758
+ const current = captureActiveSnapshot(record.id);
2759
+ if (!current || !isEqual(current, record)) {
2760
+ throw new Error(`[PropsManager] Exact record retirement has missing or stale data for "${record.id}"`);
2761
+ }
2762
+ exactRetirementIds.add(record.id);
2763
+ requestedPropertyIds.add(record.id);
2764
+ appendOrderedPropertyId(record.id);
2765
+ addRemovedCandidate(record.id, captureMutationOwner(record.id));
2766
+ relationshipMutationRootIds.add(record.id);
2767
+ }
2768
+ return;
2769
+ }
2578
2770
  if (sourceMutation.kind === 'remove-exact-orphan-property-graphs') {
2579
2771
  const orphanRootPropertyIds = sourceMutation.orphanRootPropertyIds;
2580
2772
  const retainedRootPropertyIds = sourceMutation.retainedRootPropertyIds;
@@ -2628,7 +2820,7 @@ class PropsManager {
2628
2820
  throw new Error(`[PropsManager] Exact orphan property graph removal has an invalid active root "${propertyId}"`);
2629
2821
  }
2630
2822
  requestedPropertyIds.add(propertyId);
2631
- orderedPropertyIds.push(propertyId);
2823
+ appendOrderedPropertyId(propertyId);
2632
2824
  const orderedId = captureMutationOwner(propertyId);
2633
2825
  addRemovedCandidate(propertyId, orderedId);
2634
2826
  exactOrphanCandidateIds.add(propertyId);
@@ -2659,7 +2851,134 @@ class PropsManager {
2659
2851
  }
2660
2852
  const orderedId = captureMutationOwner(propertyId);
2661
2853
  requestedPropertyIds.add(propertyId);
2662
- orderedPropertyIds.push(propertyId);
2854
+ appendOrderedPropertyId(propertyId);
2855
+ if (sourceMutation.kind === 'layers') {
2856
+ if (!Array.isArray(sourceMutation.changes) ||
2857
+ !sourceMutation.changes.length) {
2858
+ throw new Error(`[PropsManager] Property layer mutation "${propertyId}" requires changes`);
2859
+ }
2860
+ const nextSnapshot = clonePropsValue(snapshot);
2861
+ const seen = new Set();
2862
+ for (const change of sourceMutation.changes) {
2863
+ if (!isRecord(change) ||
2864
+ typeof change.key !== 'string' ||
2865
+ !change.key ||
2866
+ !['overrides', 'childBindings', 'sharedSource'].includes(String(change.layer)) ||
2867
+ !isRecord(change.state) ||
2868
+ typeof change.state.present !== 'boolean' ||
2869
+ (change.state.present
2870
+ ? !Object.prototype.hasOwnProperty.call(change.state, 'value')
2871
+ : Object.prototype.hasOwnProperty.call(change.state, 'value')) ||
2872
+ Object.keys(change.state).some((key) => !['present', 'value'].includes(key))) {
2873
+ throw new Error(`[PropsManager] Invalid property layer change "${propertyId}"`);
2874
+ }
2875
+ const identity = JSON.stringify([change.layer, change.key]);
2876
+ if (seen.has(identity)) {
2877
+ throw new Error(`[PropsManager] Duplicate property layer change "${propertyId}"`);
2878
+ }
2879
+ seen.add(identity);
2880
+ let target;
2881
+ if (change.layer === 'sharedSource') {
2882
+ if (change.key !== 'sharedSource' ||
2883
+ nextSnapshot.inheritance ||
2884
+ (change.state.present && change.state.value !== true)) {
2885
+ throw new Error(`[PropsManager] Invalid shared source transition "${propertyId}"`);
2886
+ }
2887
+ target = nextSnapshot;
2888
+ }
2889
+ else {
2890
+ const inheritance = nextSnapshot.inheritance;
2891
+ if (!inheritance) {
2892
+ throw new Error(`[PropsManager] Property "${propertyId}" has no inheritance layer`);
2893
+ }
2894
+ if (change.layer === 'overrides' &&
2895
+ (!getPersistKeys(snapshot.type).has(change.key) ||
2896
+ !getFieldByKey(contract).has(change.key))) {
2897
+ throw new Error(`[PropsManager] Unknown override field "${propertyId}.${change.key}"`);
2898
+ }
2899
+ if (change.layer === 'childBindings') {
2900
+ const relation = contract.childRelation;
2901
+ const source = captureActiveSnapshot(inheritance.sourceId) ??
2902
+ createdComponents.get(inheritance.sourceId);
2903
+ let membership;
2904
+ if (relation) {
2905
+ membership = Object.prototype.hasOwnProperty.call(inheritance.overrides, relation.key)
2906
+ ? inheritance.overrides[relation.key]
2907
+ : source?.[relation.key];
2908
+ }
2909
+ if (!Array.isArray(membership) ||
2910
+ (!membership.includes(change.key) &&
2911
+ (change.state.present ||
2912
+ !Object.prototype.hasOwnProperty.call(inheritance.childBindings, change.key)))) {
2913
+ throw new Error(`[PropsManager] Unknown inherited child "${propertyId}.${change.key}"`);
2914
+ }
2915
+ }
2916
+ target =
2917
+ change.layer === 'overrides'
2918
+ ? inheritance.overrides
2919
+ : inheritance.childBindings;
2920
+ }
2921
+ const before = Object.prototype.hasOwnProperty.call(target, change.key)
2922
+ ? { present: true, value: target[change.key] }
2923
+ : { present: false };
2924
+ if (change.layer === 'overrides' &&
2925
+ change.key === contract.childRelation?.key) {
2926
+ const inheritance = nextSnapshot.inheritance;
2927
+ if (!inheritance) {
2928
+ throw new Error('[PropsManager] Missing inheritance for membership edit');
2929
+ }
2930
+ const source = createdComponents.get(inheritance.sourceId) ??
2931
+ captureActiveSnapshot(inheritance.sourceId);
2932
+ const inherited = source?.[change.key];
2933
+ const previous = before.present ? before.value : inherited;
2934
+ const next = change.state.present ? change.state.value : inherited;
2935
+ if (!Array.isArray(previous) ||
2936
+ !Array.isArray(next) ||
2937
+ next.some((id) => typeof id !== 'string') ||
2938
+ new Set(next).size !== next.length) {
2939
+ throw new Error('[PropsManager] Invalid local membership replacement');
2940
+ }
2941
+ for (const childId of previous) {
2942
+ if (!next.includes(childId)) {
2943
+ addRemovedCandidate(inheritance.childBindings[childId] ?? childId, orderedId);
2944
+ }
2945
+ }
2946
+ }
2947
+ if (change.layer === 'childBindings' &&
2948
+ before.present &&
2949
+ typeof before.value === 'string' &&
2950
+ (!change.state.present || change.state.value !== before.value)) {
2951
+ addRemovedCandidate(before.value, orderedId);
2952
+ }
2953
+ if (change.state.present) {
2954
+ Object.defineProperty(target, change.key, {
2955
+ value: clonePropsValue(change.state.value),
2956
+ writable: true,
2957
+ enumerable: true,
2958
+ configurable: true
2959
+ });
2960
+ }
2961
+ else {
2962
+ Reflect.deleteProperty(target, change.key);
2963
+ }
2964
+ addUpdateEvidence(propertyId, change.key, before, change.state, change.layer);
2965
+ addReplaceLatestHistoryEvidence(propertyId, change.key, before, change.state, change.layer);
2966
+ }
2967
+ workingSnapshots.set(propertyId, nextSnapshot);
2968
+ if (!isEqual(snapshot, nextSnapshot)) {
2969
+ touchExisting(propertyId);
2970
+ if (sourceMutation.changes.some((change) => isRecord(change) &&
2971
+ (change.layer === 'childBindings' ||
2972
+ (change.layer === 'overrides' &&
2973
+ change.key === contract.childRelation?.key)))) {
2974
+ relationshipMutationRootIds.add(propertyId);
2975
+ }
2976
+ }
2977
+ return;
2978
+ }
2979
+ if (snapshot.inheritance) {
2980
+ throw new Error(`[PropsManager] Inherited property "${propertyId}" requires an explicit layer mutation`);
2981
+ }
2663
2982
  if (sourceMutation.kind === 'values') {
2664
2983
  if (!isRecord(sourceMutation.values)) {
2665
2984
  throw new Error(`[PropsManager] Property mutation "${propertyId}" requires value replacements`);
@@ -2883,6 +3202,78 @@ class PropsManager {
2883
3202
  }));
2884
3203
  return new Set(ownerIds);
2885
3204
  };
3205
+ const inheritanceCandidates = new Map();
3206
+ const visitInheritanceDependents = (propertyId) => {
3207
+ if (inheritanceCandidates.has(propertyId)) {
3208
+ return;
3209
+ }
3210
+ const record = createdComponents.get(propertyId) ?? captureActiveSnapshot(propertyId);
3211
+ if (!record) {
3212
+ return;
3213
+ }
3214
+ inheritanceCandidates.set(propertyId, record);
3215
+ for (const ownerId of readActiveOwnerIds(propertyId)) {
3216
+ visitInheritanceDependents(ownerId);
3217
+ }
3218
+ };
3219
+ for (const propertyId of new Set([
3220
+ ...touchedPropertyIds,
3221
+ ...createdComponents.keys()
3222
+ ])) {
3223
+ const after = createdComponents.get(propertyId) ?? workingSnapshots.get(propertyId);
3224
+ const before = originalSnapshots.get(propertyId);
3225
+ if (after?.inheritance ||
3226
+ after?.sharedSource ||
3227
+ before?.inheritance ||
3228
+ before?.sharedSource) {
3229
+ visitInheritanceDependents(propertyId);
3230
+ }
3231
+ }
3232
+ // Membership belongs to the source collection. An explicitly detached local
3233
+ // child cannot pin a removed source slot, but its exact record remains undoable.
3234
+ for (const [propertyId, record] of inheritanceCandidates) {
3235
+ const inheritance = record.inheritance;
3236
+ const relation = getComponentConfig(record.type)?.children;
3237
+ if (!inheritance || !relation || !activeById.has(propertyId)) {
3238
+ continue;
3239
+ }
3240
+ const source = createdComponents.get(inheritance.sourceId) ??
3241
+ captureActiveSnapshot(inheritance.sourceId);
3242
+ const membership = Object.prototype.hasOwnProperty.call(inheritance.overrides, relation.key)
3243
+ ? inheritance.overrides[relation.key]
3244
+ : source?.[relation.key];
3245
+ if (!Array.isArray(membership)) {
3246
+ continue;
3247
+ }
3248
+ for (const [sourceChildId, localId] of Object.entries(inheritance.childBindings)) {
3249
+ if (membership.includes(sourceChildId)) {
3250
+ continue;
3251
+ }
3252
+ const local = createdComponents.get(localId) ?? captureActiveSnapshot(localId);
3253
+ if (!local || local.inheritance) {
3254
+ continue;
3255
+ }
3256
+ Reflect.deleteProperty(inheritance.childBindings, sourceChildId);
3257
+ const ownerId = captureMutationOwner(propertyId);
3258
+ if (!requestedPropertyIds.has(propertyId)) {
3259
+ requestedPropertyIds.add(propertyId);
3260
+ appendOrderedPropertyId(propertyId);
3261
+ }
3262
+ touchExisting(propertyId);
3263
+ relationshipMutationRootIds.add(propertyId);
3264
+ updateEvidence.unshift({
3265
+ action: PROPS_ACTIONS.UPDATE_PROPERTY,
3266
+ eventName: EventTypes.UPDATE_PROPERTY,
3267
+ id: propertyId,
3268
+ layer: 'childBindings',
3269
+ key: sourceChildId,
3270
+ before: { present: true, value: localId },
3271
+ after: { present: false }
3272
+ });
3273
+ addRemovedCandidate(localId, ownerId);
3274
+ }
3275
+ }
3276
+ validatePropertyInheritanceGraph(Object.fromEntries(inheritanceCandidates), (propertyId) => createdComponents.get(propertyId) ?? captureActiveSnapshot(propertyId));
2886
3277
  const getWorkingChildIds = (ownerId) => workingChildIdsByOwnerId.get(ownerId) ?? readActiveChildIds(ownerId);
2887
3278
  const getWorkingOwnerIds = (childId) => {
2888
3279
  const existing = workingOwnerIdsByChildId.get(childId);
@@ -2931,6 +3322,20 @@ class PropsManager {
2931
3322
  };
2932
3323
  const indexWorkingOwner = (ownerId, snapshot, requireExactActiveIndex = false) => {
2933
3324
  const relation = captureContract(snapshot.type).childRelation;
3325
+ const inheritance = readPropertyInheritance(snapshot);
3326
+ if (inheritance) {
3327
+ const inheritedChildren = relation && Array.isArray(inheritance.overrides[relation.key])
3328
+ ? inheritance.overrides[relation.key]
3329
+ : [];
3330
+ replaceWorkingOwnerEdges(ownerId, [
3331
+ ...new Set([
3332
+ inheritance.sourceId,
3333
+ ...Object.values(inheritance.childBindings),
3334
+ ...inheritedChildren
3335
+ ])
3336
+ ], activeById.has(ownerId));
3337
+ return;
3338
+ }
2934
3339
  if (!relation) {
2935
3340
  return;
2936
3341
  }
@@ -3012,6 +3417,10 @@ class PropsManager {
3012
3417
  retainedRootPropertyIdSet.has(childId)) {
3013
3418
  return;
3014
3419
  }
3420
+ if (requiresExactRelationshipSet &&
3421
+ snapshot.inheritance?.sourceId === childId) {
3422
+ return;
3423
+ }
3015
3424
  if (requiresExactRelationshipSet) {
3016
3425
  exactOrphanCandidateIds.add(childId);
3017
3426
  }
@@ -3039,6 +3448,28 @@ class PropsManager {
3039
3448
  : undefined;
3040
3449
  const indexedChildIds = this.relationshipChildIdsByOwnerId.get(ownerId);
3041
3450
  const indexedAffected = indexedChildIds?.some((childId) => exactOrphanCandidateIds.has(childId)) ?? false;
3451
+ const inheritance = component.data.inheritance;
3452
+ if (inheritance) {
3453
+ if (!indexedAffected) {
3454
+ return;
3455
+ }
3456
+ const snapshot = captureActiveSnapshot(ownerId);
3457
+ if (!snapshot) {
3458
+ throw new Error(`[PropsManager] Missing inherited owner "${ownerId}"`);
3459
+ }
3460
+ const expectedEdges = this.prepareRelationshipIndexEntry(component, snapshot);
3461
+ if (!isEqual(indexedChildIds, expectedEdges)) {
3462
+ throw new Error(`[PropsManager] Inconsistent inherited source index "${ownerId}"`);
3463
+ }
3464
+ readActiveChildIds(ownerId);
3465
+ for (const dependency of expectedEdges ?? []) {
3466
+ if (!readActiveOwnerIds(dependency).has(ownerId)) {
3467
+ throw new Error(`[PropsManager] Inconsistent inherited reverse source index "${ownerId}"`);
3468
+ }
3469
+ }
3470
+ indexWorkingOwner(ownerId, snapshot, true);
3471
+ return;
3472
+ }
3042
3473
  const rawChildIds = relation
3043
3474
  ? component.data[relation.key]
3044
3475
  : undefined;
@@ -3107,6 +3538,9 @@ class PropsManager {
3107
3538
  while (removalIndex < pendingRemovalIds.length) {
3108
3539
  const candidateId = pendingRemovalIds[removalIndex++];
3109
3540
  queuedRemovalIds.delete(candidateId);
3541
+ if (exactRetirementIds && !exactRetirementIds.has(candidateId)) {
3542
+ continue;
3543
+ }
3110
3544
  const candidateOwnerIds = canonicalOwnerIdSetByPropertyId.get(candidateId);
3111
3545
  if (!candidateOwnerIds || candidateOwnerIds.size === 0) {
3112
3546
  throw new Error(`[PropsManager] Property mutation cannot resolve canonical owner for removed record "${candidateId}"`);
@@ -3161,12 +3595,18 @@ class PropsManager {
3161
3595
  if (!candidate || !candidateSnapshot) {
3162
3596
  throw new Error(`[PropsManager] Property mutation cannot remove missing record "${candidateId}"`);
3163
3597
  }
3598
+ if (candidateSnapshot.sharedSource &&
3599
+ !requestedPropertyIds.has(candidateId)) {
3600
+ continue;
3601
+ }
3164
3602
  removedIds.add(candidateId);
3165
3603
  orderedRemovedIds.push(candidateId);
3166
3604
  const childIds = getWorkingChildIds(candidateId) ?? [];
3167
3605
  replaceWorkingOwnerEdges(candidateId, []);
3168
3606
  childIds.forEach((childId) => {
3169
- if (retainedRootPropertyIdSet.has(childId)) {
3607
+ if ((candidateSnapshot.inheritance?.sourceId === childId &&
3608
+ !exactRetirementIds?.has(childId)) ||
3609
+ retainedRootPropertyIdSet.has(childId)) {
3170
3610
  return;
3171
3611
  }
3172
3612
  if (exactOrphanCandidateIds.has(candidateId)) {
@@ -3180,6 +3620,11 @@ class PropsManager {
3180
3620
  }
3181
3621
  });
3182
3622
  }
3623
+ if (exactRetirementIds &&
3624
+ (removedIds.size !== exactRetirementIds.size ||
3625
+ [...exactRetirementIds].some((id) => !removedIds.has(id)))) {
3626
+ throw new Error('[PropsManager] Exact record retirement cannot remove records retained by live owners');
3627
+ }
3183
3628
  const orderedCreatedIds = [];
3184
3629
  const orderedCreatedIdSet = new Set();
3185
3630
  const orderCreatedChildFirst = (propertyId) => {
@@ -3209,7 +3654,10 @@ class PropsManager {
3209
3654
  }
3210
3655
  return component;
3211
3656
  });
3212
- const evidence = [];
3657
+ const promotesSource = (change) => change.layer === 'sharedSource' &&
3658
+ isRecord(change.after) &&
3659
+ change.after.present === true;
3660
+ const evidence = updateEvidence.filter(promotesSource);
3213
3661
  if (createdSnapshots.length > 0) {
3214
3662
  evidence.push({
3215
3663
  eventName: EventTypes.ADD_PROPERTY,
@@ -3219,7 +3667,14 @@ class PropsManager {
3219
3667
  undoAction: EventTypes.REMOVE_PROPERTY
3220
3668
  });
3221
3669
  }
3222
- evidence.push(...updateEvidence);
3670
+ const remainingUpdates = updateEvidence.filter((change) => !promotesSource(change));
3671
+ const removesChildBinding = (change) => change.layer === 'childBindings' &&
3672
+ isRecord(change.after) &&
3673
+ change.after.present === false;
3674
+ // Replay validates each canonical link. Remove links before removing their
3675
+ // membership; inverse replay restores membership before restoring links.
3676
+ evidence.push(...remainingUpdates.filter(removesChildBinding));
3677
+ evidence.push(...remainingUpdates.filter((change) => !removesChildBinding(change)));
3223
3678
  if (removedComponents.length > 0) {
3224
3679
  evidence.push({
3225
3680
  eventName: EventTypes.REMOVE_PROPERTY,
@@ -3288,11 +3743,9 @@ class PropsManager {
3288
3743
  return ownerIds;
3289
3744
  };
3290
3745
  const createLifecycleCanonicalEvidence = (change) => {
3291
- const affectedOwnerIdSet = new Set();
3292
3746
  const recordsByOwnerIds = new Map();
3293
3747
  change.data.forEach((property) => {
3294
3748
  const orderedIds = orderedCanonicalOwnerIds(property.id);
3295
- orderedIds.forEach((orderedId) => affectedOwnerIdSet.add(orderedId));
3296
3749
  const key = JSON.stringify(orderedIds);
3297
3750
  const record = recordsByOwnerIds.get(key);
3298
3751
  if (record) {
@@ -3304,7 +3757,12 @@ class PropsManager {
3304
3757
  data: [property]
3305
3758
  });
3306
3759
  });
3307
- const orderedIds = orderedOwnerIds.filter((orderedId) => affectedOwnerIdSet.has(orderedId));
3760
+ // Lifecycle payloads follow their dependency-safe record order. Their
3761
+ // ordering metadata must describe those actual deliveries, not the
3762
+ // separately retained caller/result order.
3763
+ const orderedIds = [
3764
+ ...new Set([...recordsByOwnerIds.values()].flatMap((record) => record.orderedIds))
3765
+ ];
3308
3766
  return {
3309
3767
  orderedIds,
3310
3768
  sharedRecords: [...recordsByOwnerIds.values()].map((record) => ({
@@ -3336,7 +3794,12 @@ class PropsManager {
3336
3794
  };
3337
3795
  const replaceLatestHistoryEvidenceByKey = new Map();
3338
3796
  replaceLatestHistoryEvidence.forEach((change) => {
3339
- const eventKey = JSON.stringify([change.eventName, change.id, change.key]);
3797
+ const eventKey = JSON.stringify([
3798
+ change.eventName,
3799
+ change.id,
3800
+ change.layer ?? null,
3801
+ change.key
3802
+ ]);
3340
3803
  const existing = replaceLatestHistoryEvidenceByKey.get(eventKey);
3341
3804
  replaceLatestHistoryEvidenceByKey.set(eventKey, existing ? { ...change, before: existing.before } : change);
3342
3805
  });
@@ -3414,6 +3877,8 @@ class PropsManager {
3414
3877
  this.assertPropertyCreationRegistrationReadiness(artifact.registrationContracts, new Set());
3415
3878
  const sharedRetentionReadByChildId = new Map(artifact.sharedRetentionReads.map((read) => [read.childId, read]));
3416
3879
  const reactivatedComponentById = new Map(artifact.reactivatedComponents.map((read) => [read.before.id, read]));
3880
+ const retainedRootIds = new Set(artifact.retainedRootIdentityReads.map(({ propertyId }) => propertyId));
3881
+ const removedOwnerIds = new Set(artifact.removedComponents.map((component) => component.get('id')));
3417
3882
  const relationshipIndexesMatch = artifact.relationshipChildrenReads.every(({ ownerId, present, childIds }) => {
3418
3883
  const current = this.relationshipChildIdsByOwnerId.get(ownerId);
3419
3884
  return ((current !== undefined) === present &&
@@ -3422,6 +3887,13 @@ class PropsManager {
3422
3887
  artifact.relationshipOwnersReads.every(({ childId, present, ownerIds }) => {
3423
3888
  const current = this.relationshipOwnerIdsByChildId.get(childId);
3424
3889
  const sharedRetentionRead = sharedRetentionReadByChildId.get(childId);
3890
+ if (retainedRootIds.has(childId)) {
3891
+ // Explicit retention makes unrelated incoming edges irrelevant. The
3892
+ // exact edges that this preparation will remove must still exist.
3893
+ return ownerIds
3894
+ .filter((ownerId) => removedOwnerIds.has(ownerId))
3895
+ .every((ownerId) => current?.has(ownerId));
3896
+ }
3425
3897
  if (sharedRetentionRead) {
3426
3898
  const currentOwnerIds = new Set(current ?? []);
3427
3899
  const preparedRemovedOwnerIds = new Set(sharedRetentionRead.preparedRemovedOwnerIds);
@@ -3865,8 +4337,9 @@ class PropsManager {
3865
4337
  finally {
3866
4338
  this.resettingRuntime = false;
3867
4339
  }
3868
- if (failures.length > 0)
4340
+ if (failures.length > 0) {
3869
4341
  throw failures[0];
4342
+ }
3870
4343
  }
3871
4344
  clearRuntimeState(advanceRevision) {
3872
4345
  this._components.clear();