@asyra/props-manager 0.5.3 → 0.6.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +9 -5
  3. package/dist/components/base.d.ts.map +1 -1
  4. package/dist/components/base.js.map +1 -1
  5. package/dist/factories/create-property.d.ts.map +1 -1
  6. package/dist/factories/create-property.js.map +1 -1
  7. package/dist/index.d.ts +3 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/manager/component-accessor.d.ts +1 -0
  11. package/dist/manager/component-accessor.d.ts.map +1 -1
  12. package/dist/manager/component-accessor.js +3 -0
  13. package/dist/manager/component-accessor.js.map +1 -1
  14. package/dist/manager/property-intents.d.ts +75 -0
  15. package/dist/manager/property-intents.d.ts.map +1 -0
  16. package/dist/manager/property-intents.js +681 -0
  17. package/dist/manager/property-intents.js.map +1 -0
  18. package/dist/manager/props-manager.d.ts +24 -2
  19. package/dist/manager/props-manager.d.ts.map +1 -1
  20. package/dist/manager/props-manager.js +566 -50
  21. package/dist/manager/props-manager.js.map +1 -1
  22. package/dist/manager/subscribes.d.ts.map +1 -1
  23. package/dist/manager/subscribes.js +19 -0
  24. package/dist/manager/subscribes.js.map +1 -1
  25. package/dist/registries/declarative-property-type.d.ts.map +1 -1
  26. package/dist/registries/declarative-property-type.js +119 -23
  27. package/dist/registries/declarative-property-type.js.map +1 -1
  28. package/dist/registries/property-component.d.ts.map +1 -1
  29. package/dist/registries/property-component.js.map +1 -1
  30. package/dist/registries/property-definition-value.d.ts.map +1 -1
  31. package/dist/registries/property-definition-value.js.map +1 -1
  32. package/dist/registries/property-definition.d.ts.map +1 -1
  33. package/dist/registries/property-definition.js +2 -1
  34. package/dist/registries/property-definition.js.map +1 -1
  35. package/dist/registries/property-inheritance.d.ts +9 -0
  36. package/dist/registries/property-inheritance.d.ts.map +1 -0
  37. package/dist/registries/property-inheritance.js +164 -0
  38. package/dist/registries/property-inheritance.js.map +1 -0
  39. package/dist/registries/property-registration.d.ts.map +1 -1
  40. package/dist/registries/property-registration.js.map +1 -1
  41. package/dist/registries/property-schema.d.ts.map +1 -1
  42. package/dist/registries/property-schema.js.map +1 -1
  43. package/dist/registries/property-value-kind.d.ts +2 -1
  44. package/dist/registries/property-value-kind.d.ts.map +1 -1
  45. package/dist/registries/property-value-kind.js +20 -0
  46. package/dist/registries/property-value-kind.js.map +1 -1
  47. package/dist/registries/state.d.ts.map +1 -1
  48. package/dist/registries/state.js.map +1 -1
  49. package/package.json +6 -6
@@ -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';
@@ -105,11 +87,30 @@ class PropsManager {
105
87
  this.activePropertyBatch = null;
106
88
  this.propertyMutationStagedById = null;
107
89
  this.propertyMutationApplyActive = false;
90
+ this.resettingRuntime = false;
108
91
  this.relationshipChildIdsByOwnerId = new Map();
109
92
  this.relationshipOwnerIdsByChildId = new Map();
110
93
  this.propertyStateRevision = 0;
111
94
  this.componentAccessor = {
112
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
+ },
113
114
  addToMap: (component) => this.addToMap(component),
114
115
  createComponent: (data) => this.createPropertyInternal(data, 'relationship-child'),
115
116
  addChange: (change) => this.addChange({
@@ -129,6 +130,23 @@ class PropsManager {
129
130
  const relation = typeof type === 'string'
130
131
  ? getPropertyComponentCanonicalChildRelation(type)
131
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
+ }
132
150
  if (!relation) {
133
151
  return;
134
152
  }
@@ -240,6 +258,8 @@ class PropsManager {
240
258
  type: rawType
241
259
  };
242
260
  });
261
+ validatePropertyInheritanceGraph(sanitized);
262
+ validatePropertyInheritanceCycles(sanitized);
243
263
  return this.createLoadValidationResult(sanitized, diagnostics);
244
264
  }
245
265
  applyValidatedLoad(result) {
@@ -250,7 +270,7 @@ class PropsManager {
250
270
  this.validatedLoadArtifacts.delete(result);
251
271
  this.dispose();
252
272
  Object.keys(validated).forEach((componentId) => {
253
- const newProperty = createProperty(validated[componentId]);
273
+ const newProperty = runWithPropertyComponentAccessor(this.componentAccessor, () => createProperty(validated[componentId]));
254
274
  this.addToMap(newProperty);
255
275
  });
256
276
  }
@@ -817,6 +837,7 @@ class PropsManager {
817
837
  throw new Error(`[PropsManager] Canonical property creation is missing owner root "${componentId}"`);
818
838
  }
819
839
  });
840
+ validatePropertyInheritanceGraph(Object.fromEntries(componentById), (id) => componentById.get(id) ?? this.getPropertyById(id)?.save());
820
841
  const reachableComponentIds = new Set();
821
842
  const visitingComponentIds = new Set();
822
843
  const parentFirstDeclarativeComponentIds = new Set();
@@ -836,6 +857,13 @@ class PropsManager {
836
857
  reachableComponentIds.add(componentId);
837
858
  const registrationContract = registrationContractByType.get(component.type);
838
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
+ }
839
867
  if (!childRelation) {
840
868
  visitingComponentIds.delete(componentId);
841
869
  requiresDeferredRebindById.set(componentId, false);
@@ -919,6 +947,8 @@ class PropsManager {
919
947
  throw new Error('[PropsManager] Expected an owner-issued one-shot prepared property creation batch');
920
948
  }
921
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());
922
952
  const components = this.createAndRegisterPropertyBatch(artifact.components, artifact.registrationContracts, artifact.parentFirstDeclarativeComponentIds, artifact.sourceSemantics);
923
953
  if (artifact.sourceSemantics === 'exact') {
924
954
  measurePropertyBatchPhase('props-manager:creation-exact', () => {
@@ -992,6 +1022,11 @@ class PropsManager {
992
1022
  }
993
1023
  visitedComponentIds.add(componentId);
994
1024
  const childRelation = getPropertyComponentCanonicalChildRelation(component.type);
1025
+ const inheritedDependencies = readPropertyInheritanceDependencies(component, childRelation?.key);
1026
+ if (inheritedDependencies) {
1027
+ inheritedDependencies.forEach(visit);
1028
+ return;
1029
+ }
995
1030
  if (!childRelation) {
996
1031
  return;
997
1032
  }
@@ -1190,17 +1225,26 @@ class PropsManager {
1190
1225
  throw new Error(`[PropsManager] Invalid property restore: malformed owner relation for "${relation.componentId}"`);
1191
1226
  }
1192
1227
  });
1228
+ validatePropertyInheritanceGraph(Object.fromEntries(componentById), (id) => componentById.get(id) ?? this.getPropertyById(id)?.save());
1193
1229
  const reachableSnapshotIds = new Set();
1194
1230
  const visit = (componentId) => {
1195
- if (reachableSnapshotIds.has(componentId))
1231
+ if (reachableSnapshotIds.has(componentId)) {
1196
1232
  return;
1233
+ }
1197
1234
  const component = componentById.get(componentId);
1198
- if (!component)
1235
+ if (!component) {
1199
1236
  return;
1237
+ }
1200
1238
  reachableSnapshotIds.add(componentId);
1201
1239
  const childRelation = getPropertyComponentCanonicalChildRelation(component.type);
1202
- if (!childRelation)
1240
+ const inheritedDependencies = readPropertyInheritanceDependencies(component, childRelation?.key);
1241
+ if (inheritedDependencies) {
1242
+ inheritedDependencies.forEach(visit);
1203
1243
  return;
1244
+ }
1245
+ if (!childRelation) {
1246
+ return;
1247
+ }
1204
1248
  const childIds = component[childRelation.key];
1205
1249
  if (!Array.isArray(childIds) ||
1206
1250
  childIds.some((childId) => typeof childId !== 'string') ||
@@ -1217,8 +1261,9 @@ class PropsManager {
1217
1261
  if (childType !== childRelation.childType) {
1218
1262
  throw new Error(`[PropsManager] Invalid property restore: malformed child relation type for "${childId}"`);
1219
1263
  }
1220
- if (snapshotChild)
1264
+ if (snapshotChild) {
1221
1265
  visit(childId);
1266
+ }
1222
1267
  });
1223
1268
  };
1224
1269
  validatedRelations.forEach(({ componentId }) => visit(componentId));
@@ -1254,6 +1299,7 @@ class PropsManager {
1254
1299
  }
1255
1300
  this.validatedRestoreArtifacts.delete(prepared);
1256
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());
1257
1303
  const materialized = new Map();
1258
1304
  try {
1259
1305
  prepared.entries.forEach(({ componentId, strategy }) => {
@@ -1783,6 +1829,18 @@ class PropsManager {
1783
1829
  }, {});
1784
1830
  }
1785
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
+ }
1786
1844
  propComponentIds.forEach((propComponentId) => {
1787
1845
  const component = this.getPropertyById(propComponentId);
1788
1846
  if (!component) {
@@ -1792,6 +1850,18 @@ class PropsManager {
1792
1850
  this.removeFromMap(propComponentId);
1793
1851
  });
1794
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
+ }
1795
1865
  preparePropertyMutationBatch(sourceRequest) {
1796
1866
  if (!isRecord(sourceRequest) ||
1797
1867
  !Array.isArray(sourceRequest.operations) ||
@@ -1815,6 +1885,14 @@ class PropsManager {
1815
1885
  const persistKeysByType = new Map();
1816
1886
  const defaultsByType = new Map();
1817
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
+ };
1818
1896
  const requestedPropertyIds = new Set();
1819
1897
  const touchedPropertyIds = [];
1820
1898
  const touchedPropertyIdSet = new Set();
@@ -1824,6 +1902,7 @@ class PropsManager {
1824
1902
  const removedCandidateIds = [];
1825
1903
  const removedCandidateIdSet = new Set();
1826
1904
  const exactOrphanCandidateIds = new Set();
1905
+ let exactRetirementIds;
1827
1906
  const retainedRootPropertyIdSet = new Set();
1828
1907
  const retainedRootIdentityReads = [];
1829
1908
  const retainedRootRelationshipReads = new Map();
@@ -1864,7 +1943,8 @@ class PropsManager {
1864
1943
  });
1865
1944
  return;
1866
1945
  }
1867
- if (sourceMutation.kind === 'create-exact-property-graph' &&
1946
+ if ((sourceMutation.kind === 'create-exact-property-graph' ||
1947
+ sourceMutation.kind === 'create-exact-property-records') &&
1868
1948
  Array.isArray(sourceMutation.components)) {
1869
1949
  sourceMutation.components.forEach((component) => {
1870
1950
  if (isRecord(component) &&
@@ -2018,7 +2098,7 @@ class PropsManager {
2018
2098
  return [...value];
2019
2099
  };
2020
2100
  const assertField = (snapshot, contract, propertyId, key, value) => {
2021
- if (key === 'id' || key === 'type') {
2101
+ if (['id', 'type', 'inheritance', 'sharedSource'].includes(key)) {
2022
2102
  throw new Error(`[PropsManager] Property mutation cannot replace canonical field "${propertyId}.${key}"`);
2023
2103
  }
2024
2104
  const field = getFieldByKey(contract).get(key);
@@ -2045,7 +2125,7 @@ class PropsManager {
2045
2125
  }
2046
2126
  });
2047
2127
  };
2048
- const addUpdateEvidence = (propertyId, key, before, after) => {
2128
+ const addUpdateEvidence = (propertyId, key, before, after, layer) => {
2049
2129
  if (isEqual(before, after)) {
2050
2130
  return;
2051
2131
  }
@@ -2054,11 +2134,12 @@ class PropsManager {
2054
2134
  eventName: EventTypes.UPDATE_PROPERTY,
2055
2135
  id: propertyId,
2056
2136
  key,
2137
+ ...(layer ? { layer } : {}),
2057
2138
  before: clonePropsValue(before),
2058
2139
  after: clonePropsValue(after)
2059
2140
  });
2060
2141
  };
2061
- const addReplaceLatestHistoryEvidence = (propertyId, key, before, after) => {
2142
+ const addReplaceLatestHistoryEvidence = (propertyId, key, before, after, layer) => {
2062
2143
  if (mutationOptions?.history?.mode !== 'replace-latest') {
2063
2144
  return;
2064
2145
  }
@@ -2067,6 +2148,7 @@ class PropsManager {
2067
2148
  eventName: EventTypes.UPDATE_PROPERTY,
2068
2149
  id: propertyId,
2069
2150
  key,
2151
+ ...(layer ? { layer } : {}),
2070
2152
  before: clonePropsValue(before),
2071
2153
  after: clonePropsValue(after)
2072
2154
  });
@@ -2371,7 +2453,7 @@ class PropsManager {
2371
2453
  }
2372
2454
  if (!requestedPropertyIds.has(propertyId)) {
2373
2455
  requestedPropertyIds.add(propertyId);
2374
- orderedPropertyIds.push(propertyId);
2456
+ appendOrderedPropertyId(propertyId);
2375
2457
  }
2376
2458
  captureMutationOwner(propertyId, sourceMutation.ownerElementId);
2377
2459
  relations.push({
@@ -2384,12 +2466,16 @@ class PropsManager {
2384
2466
  creationRelationsByMutationIndex.set(mutationIndex, Object.freeze(relations));
2385
2467
  };
2386
2468
  const prepareExactCreation = (sourceMutation, mutationIndex) => {
2387
- if (!Array.isArray(sourceMutation.ownerRelations) ||
2388
- 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)) ||
2389
2473
  !Array.isArray(sourceMutation.components)) {
2390
- 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}`);
2391
2475
  }
2392
- const relations = clonePropertyDefinitionValue(sourceMutation.ownerRelations);
2476
+ const relations = canonicalRecords
2477
+ ? []
2478
+ : clonePropertyDefinitionValue(sourceMutation.ownerRelations);
2393
2479
  const sourceComponents = sourceMutation.components;
2394
2480
  if (sourceComponents.some((component) => !isRecord(component) ||
2395
2481
  typeof component.id !== 'string' ||
@@ -2484,7 +2570,22 @@ class PropsManager {
2484
2570
  throw new Error(`[PropsManager] Exact property creation owner root "${relation.componentId}" has the wrong type`);
2485
2571
  }
2486
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
+ });
2487
2587
  const visiting = new Set();
2588
+ const visitedActive = new Set();
2488
2589
  const visited = new Set();
2489
2590
  const childFirstIds = [];
2490
2591
  const visit = (propertyId) => {
@@ -2496,12 +2597,66 @@ class PropsManager {
2496
2597
  }
2497
2598
  const component = componentById.get(propertyId);
2498
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);
2499
2641
  return;
2500
2642
  }
2501
2643
  visiting.add(propertyId);
2502
2644
  const contract = captureContract(component.type);
2503
2645
  const relation = contract.childRelation;
2504
- 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) {
2505
2660
  const childIds = component[relation.key];
2506
2661
  if (!Array.isArray(childIds) ||
2507
2662
  childIds.some((childId) => typeof childId !== 'string') ||
@@ -2530,7 +2685,12 @@ class PropsManager {
2530
2685
  visited.add(propertyId);
2531
2686
  childFirstIds.push(propertyId);
2532
2687
  };
2533
- relations.forEach(({ componentId }) => visit(componentId));
2688
+ if (canonicalRecords) {
2689
+ components.forEach(({ id }) => visit(id));
2690
+ }
2691
+ else {
2692
+ relations.forEach(({ componentId }) => visit(componentId));
2693
+ }
2534
2694
  if (visited.size !== components.length) {
2535
2695
  throw new Error('[PropsManager] Exact property creation contains an unowned property');
2536
2696
  }
@@ -2546,12 +2706,20 @@ class PropsManager {
2546
2706
  prepareCreationRecord(component, component.type, propertyId, true);
2547
2707
  });
2548
2708
  relations.forEach((relation) => {
2549
- if (!requestedPropertyIds.has(relation.componentId)) {
2709
+ if (!activeById.has(relation.componentId) &&
2710
+ !requestedPropertyIds.has(relation.componentId)) {
2550
2711
  requestedPropertyIds.add(relation.componentId);
2551
- orderedPropertyIds.push(relation.componentId);
2552
2712
  }
2713
+ appendOrderedPropertyId(relation.componentId);
2553
2714
  captureMutationOwner(relation.componentId, relation.ownerElementId);
2554
2715
  });
2716
+ if (canonicalRecords) {
2717
+ components.forEach(({ id }) => {
2718
+ requestedPropertyIds.add(id);
2719
+ appendOrderedPropertyId(id);
2720
+ captureMutationOwner(id);
2721
+ });
2722
+ }
2555
2723
  creationRelationsByMutationIndex.set(mutationIndex, Object.freeze(relations));
2556
2724
  };
2557
2725
  mutations.forEach((sourceMutation, mutationIndex) => {
@@ -2561,7 +2729,8 @@ class PropsManager {
2561
2729
  if (sourceMutation.kind === 'create-owner-properties') {
2562
2730
  prepareOrdinaryCreation(sourceMutation, mutationIndex);
2563
2731
  }
2564
- else if (sourceMutation.kind === 'create-exact-property-graph') {
2732
+ else if (sourceMutation.kind === 'create-exact-property-graph' ||
2733
+ sourceMutation.kind === 'create-exact-property-records') {
2565
2734
  prepareExactCreation(sourceMutation, mutationIndex);
2566
2735
  }
2567
2736
  });
@@ -2574,6 +2743,30 @@ class PropsManager {
2574
2743
  ownerRelations.push(...creationRelations);
2575
2744
  return;
2576
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
+ }
2577
2770
  if (sourceMutation.kind === 'remove-exact-orphan-property-graphs') {
2578
2771
  const orphanRootPropertyIds = sourceMutation.orphanRootPropertyIds;
2579
2772
  const retainedRootPropertyIds = sourceMutation.retainedRootPropertyIds;
@@ -2627,7 +2820,7 @@ class PropsManager {
2627
2820
  throw new Error(`[PropsManager] Exact orphan property graph removal has an invalid active root "${propertyId}"`);
2628
2821
  }
2629
2822
  requestedPropertyIds.add(propertyId);
2630
- orderedPropertyIds.push(propertyId);
2823
+ appendOrderedPropertyId(propertyId);
2631
2824
  const orderedId = captureMutationOwner(propertyId);
2632
2825
  addRemovedCandidate(propertyId, orderedId);
2633
2826
  exactOrphanCandidateIds.add(propertyId);
@@ -2658,7 +2851,134 @@ class PropsManager {
2658
2851
  }
2659
2852
  const orderedId = captureMutationOwner(propertyId);
2660
2853
  requestedPropertyIds.add(propertyId);
2661
- 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
+ }
2662
2982
  if (sourceMutation.kind === 'values') {
2663
2983
  if (!isRecord(sourceMutation.values)) {
2664
2984
  throw new Error(`[PropsManager] Property mutation "${propertyId}" requires value replacements`);
@@ -2882,6 +3202,78 @@ class PropsManager {
2882
3202
  }));
2883
3203
  return new Set(ownerIds);
2884
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));
2885
3277
  const getWorkingChildIds = (ownerId) => workingChildIdsByOwnerId.get(ownerId) ?? readActiveChildIds(ownerId);
2886
3278
  const getWorkingOwnerIds = (childId) => {
2887
3279
  const existing = workingOwnerIdsByChildId.get(childId);
@@ -2930,6 +3322,20 @@ class PropsManager {
2930
3322
  };
2931
3323
  const indexWorkingOwner = (ownerId, snapshot, requireExactActiveIndex = false) => {
2932
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
+ }
2933
3339
  if (!relation) {
2934
3340
  return;
2935
3341
  }
@@ -3011,6 +3417,10 @@ class PropsManager {
3011
3417
  retainedRootPropertyIdSet.has(childId)) {
3012
3418
  return;
3013
3419
  }
3420
+ if (requiresExactRelationshipSet &&
3421
+ snapshot.inheritance?.sourceId === childId) {
3422
+ return;
3423
+ }
3014
3424
  if (requiresExactRelationshipSet) {
3015
3425
  exactOrphanCandidateIds.add(childId);
3016
3426
  }
@@ -3038,6 +3448,28 @@ class PropsManager {
3038
3448
  : undefined;
3039
3449
  const indexedChildIds = this.relationshipChildIdsByOwnerId.get(ownerId);
3040
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
+ }
3041
3473
  const rawChildIds = relation
3042
3474
  ? component.data[relation.key]
3043
3475
  : undefined;
@@ -3106,6 +3538,9 @@ class PropsManager {
3106
3538
  while (removalIndex < pendingRemovalIds.length) {
3107
3539
  const candidateId = pendingRemovalIds[removalIndex++];
3108
3540
  queuedRemovalIds.delete(candidateId);
3541
+ if (exactRetirementIds && !exactRetirementIds.has(candidateId)) {
3542
+ continue;
3543
+ }
3109
3544
  const candidateOwnerIds = canonicalOwnerIdSetByPropertyId.get(candidateId);
3110
3545
  if (!candidateOwnerIds || candidateOwnerIds.size === 0) {
3111
3546
  throw new Error(`[PropsManager] Property mutation cannot resolve canonical owner for removed record "${candidateId}"`);
@@ -3160,12 +3595,18 @@ class PropsManager {
3160
3595
  if (!candidate || !candidateSnapshot) {
3161
3596
  throw new Error(`[PropsManager] Property mutation cannot remove missing record "${candidateId}"`);
3162
3597
  }
3598
+ if (candidateSnapshot.sharedSource &&
3599
+ !requestedPropertyIds.has(candidateId)) {
3600
+ continue;
3601
+ }
3163
3602
  removedIds.add(candidateId);
3164
3603
  orderedRemovedIds.push(candidateId);
3165
3604
  const childIds = getWorkingChildIds(candidateId) ?? [];
3166
3605
  replaceWorkingOwnerEdges(candidateId, []);
3167
3606
  childIds.forEach((childId) => {
3168
- if (retainedRootPropertyIdSet.has(childId)) {
3607
+ if ((candidateSnapshot.inheritance?.sourceId === childId &&
3608
+ !exactRetirementIds?.has(childId)) ||
3609
+ retainedRootPropertyIdSet.has(childId)) {
3169
3610
  return;
3170
3611
  }
3171
3612
  if (exactOrphanCandidateIds.has(candidateId)) {
@@ -3179,6 +3620,11 @@ class PropsManager {
3179
3620
  }
3180
3621
  });
3181
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
+ }
3182
3628
  const orderedCreatedIds = [];
3183
3629
  const orderedCreatedIdSet = new Set();
3184
3630
  const orderCreatedChildFirst = (propertyId) => {
@@ -3208,7 +3654,10 @@ class PropsManager {
3208
3654
  }
3209
3655
  return component;
3210
3656
  });
3211
- const evidence = [];
3657
+ const promotesSource = (change) => change.layer === 'sharedSource' &&
3658
+ isRecord(change.after) &&
3659
+ change.after.present === true;
3660
+ const evidence = updateEvidence.filter(promotesSource);
3212
3661
  if (createdSnapshots.length > 0) {
3213
3662
  evidence.push({
3214
3663
  eventName: EventTypes.ADD_PROPERTY,
@@ -3218,7 +3667,14 @@ class PropsManager {
3218
3667
  undoAction: EventTypes.REMOVE_PROPERTY
3219
3668
  });
3220
3669
  }
3221
- 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)));
3222
3678
  if (removedComponents.length > 0) {
3223
3679
  evidence.push({
3224
3680
  eventName: EventTypes.REMOVE_PROPERTY,
@@ -3287,11 +3743,9 @@ class PropsManager {
3287
3743
  return ownerIds;
3288
3744
  };
3289
3745
  const createLifecycleCanonicalEvidence = (change) => {
3290
- const affectedOwnerIdSet = new Set();
3291
3746
  const recordsByOwnerIds = new Map();
3292
3747
  change.data.forEach((property) => {
3293
3748
  const orderedIds = orderedCanonicalOwnerIds(property.id);
3294
- orderedIds.forEach((orderedId) => affectedOwnerIdSet.add(orderedId));
3295
3749
  const key = JSON.stringify(orderedIds);
3296
3750
  const record = recordsByOwnerIds.get(key);
3297
3751
  if (record) {
@@ -3303,7 +3757,12 @@ class PropsManager {
3303
3757
  data: [property]
3304
3758
  });
3305
3759
  });
3306
- 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
+ ];
3307
3766
  return {
3308
3767
  orderedIds,
3309
3768
  sharedRecords: [...recordsByOwnerIds.values()].map((record) => ({
@@ -3335,7 +3794,12 @@ class PropsManager {
3335
3794
  };
3336
3795
  const replaceLatestHistoryEvidenceByKey = new Map();
3337
3796
  replaceLatestHistoryEvidence.forEach((change) => {
3338
- 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
+ ]);
3339
3803
  const existing = replaceLatestHistoryEvidenceByKey.get(eventKey);
3340
3804
  replaceLatestHistoryEvidenceByKey.set(eventKey, existing ? { ...change, before: existing.before } : change);
3341
3805
  });
@@ -3413,6 +3877,8 @@ class PropsManager {
3413
3877
  this.assertPropertyCreationRegistrationReadiness(artifact.registrationContracts, new Set());
3414
3878
  const sharedRetentionReadByChildId = new Map(artifact.sharedRetentionReads.map((read) => [read.childId, read]));
3415
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')));
3416
3882
  const relationshipIndexesMatch = artifact.relationshipChildrenReads.every(({ ownerId, present, childIds }) => {
3417
3883
  const current = this.relationshipChildIdsByOwnerId.get(ownerId);
3418
3884
  return ((current !== undefined) === present &&
@@ -3421,6 +3887,13 @@ class PropsManager {
3421
3887
  artifact.relationshipOwnersReads.every(({ childId, present, ownerIds }) => {
3422
3888
  const current = this.relationshipOwnerIdsByChildId.get(childId);
3423
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
+ }
3424
3897
  if (sharedRetentionRead) {
3425
3898
  const currentOwnerIds = new Set(current ?? []);
3426
3899
  const preparedRemovedOwnerIds = new Set(sharedRetentionRead.preparedRemovedOwnerIds);
@@ -3826,6 +4299,49 @@ class PropsManager {
3826
4299
  ;
3827
4300
  component.dispose?.();
3828
4301
  });
4302
+ this.clearRuntimeState(hadState);
4303
+ }
4304
+ /** Retire canonical state after external work has quiesced. */
4305
+ resetRuntime() {
4306
+ if (this.resettingRuntime ||
4307
+ this.propertyCreationBatch ||
4308
+ this.activePropertyBatch ||
4309
+ this.propertyMutationStagedById ||
4310
+ this.propertyMutationApplyActive) {
4311
+ throw new Error('[PropsManager] Runtime reset requires idle canonical property batches');
4312
+ }
4313
+ this.resettingRuntime = true;
4314
+ const failures = [];
4315
+ try {
4316
+ const components = new Set([
4317
+ ...this._components.values(),
4318
+ ...this._deletedMap.values()
4319
+ ]);
4320
+ components.forEach((component) => {
4321
+ try {
4322
+ ;
4323
+ component.dispose?.();
4324
+ }
4325
+ catch (error) {
4326
+ failures.push(error);
4327
+ }
4328
+ });
4329
+ this.clearRuntimeState(true);
4330
+ this.validatedLoadArtifacts = new WeakMap();
4331
+ this.validatedRestoreArtifacts = new WeakMap();
4332
+ this.validatedPropertyCreationArtifacts = new WeakMap();
4333
+ this.validatedOrdinaryPropertyCreationArtifacts = new WeakMap();
4334
+ this.validatedActivePropertyArtifacts = new WeakMap();
4335
+ this.validatedPropertyMutationArtifacts = new WeakMap();
4336
+ }
4337
+ finally {
4338
+ this.resettingRuntime = false;
4339
+ }
4340
+ if (failures.length > 0) {
4341
+ throw failures[0];
4342
+ }
4343
+ }
4344
+ clearRuntimeState(advanceRevision) {
3829
4345
  this._components.clear();
3830
4346
  this._deletedMap.clear();
3831
4347
  this.relationshipChildIdsByOwnerId.clear();
@@ -3834,7 +4350,7 @@ class PropsManager {
3834
4350
  this.propertyCreationBatch = null;
3835
4351
  this.activePropertyBatch = null;
3836
4352
  this.propertyMutationStagedById = null;
3837
- if (hadState) {
4353
+ if (advanceRevision) {
3838
4354
  this.advancePropertyStateRevision();
3839
4355
  }
3840
4356
  }