-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbelief.mjs
More file actions
2113 lines (1868 loc) · 82.2 KB
/
Copy pathbelief.mjs
File metadata and controls
2113 lines (1868 loc) · 82.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Belief - represents any entity in the game (objects, NPCs, events, observations)
*
* Beliefs are the universal building block. Everything from "hammer" to "Bob saw hammer"
* to "player thinks Bob is lying" is represented as a Belief with traits.
*
* Key concepts:
* - Archetype composition: Beliefs inherit traits from archetypes (e.g., Player = Actor + Mental)
* - Immutability: Create new versions via `base` property instead of mutating
* - Universal structure: Same format for objects, events, NPCs, observations
*
* See docs/SPECIFICATION.md for data model design
* See docs/ALPHA-1.md for how beliefs are used in gameplay
*/
import { assert, log, sysdesig, debug } from './debug.mjs'
import { next_id } from './id_sequence.mjs'
import { Archetype } from './archetype.mjs'
import * as DB from './db.mjs'
import { Subject } from './subject.mjs'
import { Traittype } from './traittype.mjs'
import { State } from './state.mjs'
import { Fuzzy } from './fuzzy.mjs'
/**
* @typedef {import('./mind.mjs').Mind} Mind
*/
/**
* @typedef {import('./state.mjs').StateReference} StateReference
* @typedef {import('./mind.mjs').MindReference} MindReference
*/
/**
* @typedef {number|string|boolean|null|StateReference|MindReference|Array<number|string|boolean|null|StateReference|MindReference>} SerializedTraitValue
* Trait values in JSON can be:
* - number (sid or primitive)
* - string/boolean/null (primitives)
* - StateReference/MindReference (for State/Mind traits)
* - Array of any of the above
*/
/**
* @typedef {object} BeliefJSON
* @property {string} _type - Always "Belief"
* @property {number} _id - Unique version identifier
* @property {number} sid - Subject identifier (stable across versions)
* @property {string|null} label - Optional label for lookup
* @property {number|null} about - Parent belief _id (null if not about another belief)
* @property {string[]} archetypes - Archetype labels for this belief
* @property {(string|number)[]} bases - Base archetype labels or belief _ids
* @property {Object<string, SerializedTraitValue>} traits - Trait values (sids, primitives, or references)
* @property {number|null} origin_state - State _id where this belief was created (null for shared beliefs)
* @property {number[]} [promotions] - Belief _ids registered as promotions of this belief
* @property {number} [certainty] - Probability weight (0 < x < 1)
* @property {boolean} [promotable] - Whether this belief can have promotions registered on it
* @property {number|null} [_promotable_epoch] - Cache invalidation epoch for promotable beliefs
* @property {number} [resolution] - Belief _id that this belief resolves (for uncertainty collapse)
*/
/**
* Represents a belief about an entity with versioning support
* @property {number} _id - Unique version identifier
* @property {Subject} subject - Canonical Subject (identity holder)
* @property {string|null} label - Optional label for lookup
* @property {Mind|undefined} in_mind - Mind this belief belongs to (getter from origin_state)
* @property {Set<Belief|Archetype>} _bases - Base archetypes/beliefs for inheritance
* @property {Map<Traittype, *>} _traits - Trait values (sids, primitives, State/Mind refs)
* @property {Map<string, any>} [_deserialized_traits] - Temporary storage during JSON deserialization
* @property {boolean} locked - Whether belief can be modified
* @property {number|null} certainty - Probability weight (null = not a probability)
* @property {boolean} promotable - Whether this belief can have promotions registered on it
*/
export class Belief {
/**
* @param {State} state - State creating this belief
* @param {Subject|null} [subject] - Subject (provide to create version of existing subject)
* @param {Array<Archetype|Belief>} [bases] - Archetype or Belief objects (no strings)
* @param {Object} [options] - Optional parameters
* @param {boolean} [options.promotable] - Whether this belief can have promotions registered on it
*/
constructor(state, subject = null, bases = [], {promotable = false} = {}) {
for (const base of bases) {
assert(typeof base !== 'string',
'Constructor received string base - use Belief.from_template() instead',
{base})
}
assert(state instanceof State, "belief must be constructed with a state")
/** @type {Mind} */
const mind = state.in_mind // TODO: should not need to check for Eidos
/** @type {Set<Belief|Archetype>} */ this._bases = new Set(bases)
// Eidos and descendants: universals (mater=null), Materia under Logos: particulars (mater=mind)
const mater = mind.in_eidos ? null : mind
this.subject = subject ?? new Subject(null, mater)
// Validate: subject.mater must be null (universal) or this mind
// This prevents beliefs from using subjects from other minds
assert(this.subject.mater === null || this.subject.mater === mind,
`Belief can only use subjects with mater=null (universal) or mater=own_mind`,
{
subject_sid: this.subject.sid,
subject_mater: this.subject.mater?.label || 'null',
belief_in_mind: mind.label
})
this._id = next_id()
this._traits = new Map()
this._locked = false
/** @type {Map<Traittype, any>} */
this._cache = new Map()
/** @type {State} */
this.origin_state = state
/** @type {boolean} - true when all inherited traits are cached */
this._cached_all = false
/** @type {Map<Belief, number>|null} - promotable beliefs this cache depends on */
this._cache_deps = null
/**
* Promoted versions that propagate to children of this belief
* @type {Set<Belief>}
*/
this.promotions = new Set()
/**
* Probability weight for this belief as a promotion (null = not a probability)
* @type {number|null}
*/
this.certainty = null
/**
* Constraints for this belief as a promotion (future: exclusion rules, validity periods)
* @type {Object}
*/
this.constraints = {}
/**
* Reference to belief this resolves (null = not a resolution belief)
* When set, this belief "collapses" uncertainty in the referenced belief.
* Query flow checks Subject.resolutions before normal trait lookup.
* @type {Belief|null}
*/
this.resolution = null
/**
* Whether this belief can have promotions registered on it
* @type {boolean}
*/
this.promotable = promotable
/**
* Cache invalidation epoch for promotable beliefs
* Bumped when a promotion is added, causing dependent caches to invalidate
* @type {number|null}
*/
this._promotable_epoch = promotable ? next_id() : null
DB.register_belief_by_id(this)
this.subject.beliefs.add(this)
DB.register_belief_by_mind(this)
}
/**
* Get locked status of this belief
* @returns {boolean}
*/
get locked() {
return this._locked
}
/**
* Get the mind this belief belongs to
* @returns {Mind|undefined}
*/
get in_mind() {
return this.origin_state?.in_mind
}
/**
* Check if this is a shared belief (prototype/template)
* Shared beliefs live in Eidos mind (realm of forms)
* @returns {boolean}
*/
get is_shared() {
if (!this.in_mind) return false
// Use Mind registry to avoid circular import (belief→eidos→mind→belief)
// @ts-ignore - in_mind.constructor is Mind class with static get_function
const eidos = this.in_mind.constructor.get_function('eidos')
return this.in_mind === eidos()
}
/**
* Extract Subject references from a trait value
* @param {*} value - Trait value (Subject, array, Fuzzy, primitive, etc.)
* @returns {Subject[]} Array of Subjects found in value
*/
extract_subjects(value) {
if (value instanceof Subject) {
return [value]
} else if (Array.isArray(value)) {
return value.filter(item => item instanceof Subject)
} else if (value instanceof Fuzzy) {
return value.alternatives.flatMap(alt => this.extract_subjects(alt.value))
} else {
return []
}
}
/**
* Set trait value and update reverse index
* Computes diff between old and new values to minimize index updates
* @param {Traittype} traittype - Traittype object
* @param {*} new_value - New trait value
* @private
*/
_set_trait(traittype, new_value) {
assert(this.origin_state, 'origin_state required for _set_trait', {belief_id: this._id, traittype: traittype.label})
// Only track reverse graph edges for Subject references
// Primitives, States, Minds don't create searchable graph relationships
if (!traittype.is_subject_reference) {
this._traits.set(traittype, new_value)
return
}
// Get old value from THIS belief's direct traits only (not inherited)
// Inherited values belong to base beliefs and are tracked separately
const old_value = this._traits.get(traittype)
const old_subjects = this.extract_subjects(old_value)
const new_subjects = this.extract_subjects(new_value)
// Compute diff - efficient single-pass algorithm
const old_set = new Set(old_subjects)
const to_add = []
for (const subject of new_subjects) {
if (old_set.has(subject)) {
old_set.delete(subject) // Mark as kept
} else {
to_add.push(subject) // New subject
}
}
for (const subject of old_set) {
this.origin_state.rev_del(subject, traittype, this)
}
for (const subject of to_add) {
this.origin_state.rev_add(subject, traittype, this)
}
this._traits.set(traittype, new_value)
}
/**
* Add trait from template data (resolves via traittype)
* @param {State} state - State context for resolution
* @param {Traittype} traittype - Traittype object
* @param {*} data - Raw data to be resolved by traittype
* @param {object} options - Optional parameters
* @param {State|null} [options.about_state] - State context for belief resolution (for prototype minds)
*/
add_trait_from_template(state, traittype, data, {about_state=null} = {}) {
assert(!this.locked, 'Cannot modify locked belief', {belief_id: this._id, label: this.get_label()})
// Resolve template data to actual value
// For composable traits: own value replaces inherited (composition happens at query time if no own)
// TODO: Support template syntax for replace/remove operations on composable traits
// - {replace: [...]} to ignore base values and use only provided values
// - {remove: [...]} to compose from bases then filter out specified items
const value = traittype.resolve_trait_value_from_template(this, data, {about_state})
this.add_trait(traittype, value)
}
/**
* @param {Traittype} traittype - Traittype object
* @param {any} data
*/
add_trait(traittype, data) {
assert(!this.locked, 'Cannot modify locked belief', {belief_id: this._id, label: this.get_label()})
assert(this.can_have_trait(traittype), `Belief can't have trait ${traittype.label}`, {label: traittype.label, belief: this.get_label(), data, archetypes: [...this.get_archetypes()].map(a => a.label)})
// Validate type before setting
traittype.validate_value(data)
if (debug()) {
const old_value = this.get_trait(this.origin_state, traittype)
if (old_value !== null) {
debug([this.origin_state], 'Replacing trait', traittype.label, 'in', this.get_label() ?? `#${this._id}`, 'old:', old_value, 'new:', data)
}
}
this._set_trait(traittype, data)
}
/**
* Get trait value from this belief only (does not check bases)
* Polymorphic interface - matches Archetype.get_own_trait_value()
* @param {Traittype} traittype - Trait type
* @returns {any} Trait value or undefined if not found
*/
get_own_trait_value(traittype) {
assert(traittype instanceof Traittype, "get_own_trait_value requires Traittype", {belief_id: this._id, traittype})
return this._traits.get(traittype)
}
/**
* Get iterable over trait entries (polymorphic interface)
* Returns iterable of [traittype, value] pairs for trait operations collection
* @returns {Generator<[Traittype, any]>} Iterable iterator of trait entries
*/
*get_trait_entries() {
for (const [traittype, value] of this._traits) {
yield [traittype, value]
}
}
/**
* @param {Traittype} traittype
* @returns {boolean}
*/
can_have_trait(traittype) {
assert(traittype instanceof Traittype, 'can_have_trait requires Traittype', {belief_id: this._id, traittype})
for (const archetype of this.get_archetypes()) {
if (archetype.has_trait(traittype)) return true
}
return false
}
/**
* Get inherited trait value from bases chain
* For composable traits: collects one value per base chain and composes them
* For non-composable traits: walks BFS with promotion checking to find first value
* @param {State} state - State context (used for promotion resolution)
* @param {Traittype} traittype - Traittype to get
* @param {Set<Belief>} [skip_promotions] - Beliefs whose promotions should be skipped (prevents infinite recursion)
* @param {{deps: Map<Belief, number>, last_promotable?: Belief, min_cache_tt: number}} [context] - Mutable context to track cache deps
* @returns {*} trait value (Subject, not Belief), or null if not found
* @private
*/
_get_uncached_trait(state, traittype, skip_promotions = new Set(), context = {deps: new Map(), min_cache_tt: -Infinity}) {
// Composable: BFS walk, merging from all Convergence components if unresolved
if (traittype.composable) {
const values = []
const seen = new Set()
// @ts-ignore - Convergence properties/methods
const conv = state.is_union ? state : state._convergence_ancestor
// @ts-ignore
const sources = conv?.get_resolution(state) === null ? [...conv.get_all_beliefs_by_subject(this.subject)] : [this]
for (const source of sources) {
const queue = [/** @type {Belief|Archetype} */ (source)]
while (queue.length > 0) {
const node = /** @type {Belief|Archetype} */ (queue.shift())
if (seen.has(node)) continue
seen.add(node)
// Track promotable beliefs for cache invalidation (skip this)
if (node !== this && node instanceof Belief) {
if (node.promotions.size > 0 && node._promotable_epoch !== null) {
context.deps.set(node, node._promotable_epoch)
} else if (node.promotable) {
context.last_promotable = node
}
}
const value = node.get_own_trait_value(traittype)
if (value === undefined) {
queue.push(...node._bases)
} else if (value !== null) {
values.push(value)
}
}
}
// Add last_promotable if no promotable edge found yet (epoch is non-null when promotable=true)
if (context.last_promotable && context.deps.size === 0) {
context.deps.set(context.last_promotable, /** @type {number} */ (context.last_promotable._promotable_epoch))
}
if (values.length === 0) return null
if (values.length === 1) return values[0]
return traittype.compose(this, values)
}
// Non-composable traits: full BFS with promotion checking
if (this.promotions.size > 0) {
// Track max tt of temporal promotions - can cache if caching belief's tt >= this
for (const p of this.promotions) {
if (p.certainty === null && p.origin_state.tt != null) {
context.min_cache_tt = Math.max(context.min_cache_tt, p.origin_state.tt)
}
}
}
const own_promo = this._get_trait_from_promotions(state, this, traittype, skip_promotions)
if (own_promo !== undefined) return own_promo
const own = this._traits.get(traittype)
if (own !== undefined) return own
const queue = [...this._bases]
const seen = new Set()
while (queue.length > 0) {
const node = /** @type {Belief|Archetype} */ (queue.shift())
if (seen.has(node)) continue
seen.add(node)
if (node instanceof Belief) {
if (skip_promotions.has(node)) {
for (const b of node._bases) {
if (b instanceof Belief) skip_promotions.add(b)
}
} else if (node.promotions.size > 0 && node._promotable_epoch !== null) {
// First belief with promotions - record as cache dependency
context.deps.set(node, node._promotable_epoch)
// Track max tt of temporal promotions - can cache if caching belief's tt >= this
for (const p of node.promotions) {
if (p.certainty === null && p.origin_state.tt != null) {
context.min_cache_tt = Math.max(context.min_cache_tt, p.origin_state.tt)
}
}
const value = this._get_trait_from_promotions(state, node, traittype, skip_promotions)
if (value !== undefined) return value
} else if (node.promotable) {
// Track last promotable as potential cache dependency
context.last_promotable = node
}
}
const own = node.get_own_trait_value(traittype)
if (own !== undefined) {
// Found value - add last_promotable to deps if not already tracking a promotable edge
if (context.last_promotable && !context.deps.has(context.last_promotable)) {
context.deps.set(context.last_promotable, /** @type {number} */ (context.last_promotable._promotable_epoch))
}
return own
}
queue.push(...node._bases)
}
// No value found - still add last_promotable to deps
if (context.last_promotable && !context.deps.has(context.last_promotable)) {
context.deps.set(context.last_promotable, /** @type {number} */ (context.last_promotable._promotable_epoch))
}
return null
}
/**
* Get trait value from a belief's promotions (lazy propagation)
*
* Resolution algorithm: Only the FIRST promotion encountered is resolved.
* When resolving B→C, we add B AND B.bases to skip_promotions, preventing
* any deeper promotions from being followed.
*
* Rules:
* 1. When processing a node with promotions (not in skip_promotions):
* resolve promotion, add node + its bases to skip_promotions
* 2. When processing a node in skip_promotions:
* skip its promotions, add its bases to skip_promotions (propagate)
* 3. Chained promotions (v1→v2→v3) work because resolved belief is not in skip_promotions
*
* @param {State} state
* @param {Belief} belief - Belief whose promotions to check
* @param {Traittype} traittype
* @param {Set<Belief>} skip_promotions - Beliefs whose promotions to skip
* @returns {*} Trait value if found, undefined if not
* @private
*/
_get_trait_from_promotions(state, belief, traittype, skip_promotions) {
if (belief.promotions.size === 0) return undefined
if (skip_promotions.has(belief)) return undefined
const promos = state.pick_promotion(belief.promotions, {})
if (promos.length === 0) return undefined
// Add belief AND its bases to skip_promotions (first promotion only rule)
const new_skip = new Set(skip_promotions)
new_skip.add(belief)
for (const base of belief._bases) {
if (base instanceof Belief) new_skip.add(base)
}
// Multiple probability promotions - collect values from each
if (promos.length > 1) {
const result = this._collect_fuzzy_from_promotions(state, promos, traittype, new_skip)
if (result instanceof Fuzzy && result.alternatives.length > 0) return result
if (result !== undefined && !(result instanceof Fuzzy)) return result
return undefined
}
// Single promotion - get trait from it
const value = promos[0]._get_trait_skip_promotions(state, traittype, new_skip)
if (value === undefined) return undefined
return this._apply_certainty(value, promos[0].certainty)
}
/**
* Apply certainty to a trait value, wrapping in Fuzzy if needed
* @param {*} value - The trait value
* @param {number|null} certainty - Certainty to apply (null = no wrapping)
* @returns {*} Original value if certainty is null, otherwise Fuzzy
* @private
*/
_apply_certainty(value, certainty) {
if (certainty === null) return value
if (value instanceof Fuzzy) {
return new Fuzzy({
alternatives: value.alternatives.map(alt => ({
value: alt.value,
certainty: alt.certainty * certainty
}))
})
}
return new Fuzzy({
alternatives: [{ value, certainty }]
})
}
/**
* Collect trait values from probability promotions into Fuzzy
* @param {State} state
* @param {Belief[]} promotions - Array of probability promotions
* @param {Traittype} traittype
* @param {Set<Belief>} skip_promotions - Beliefs whose promotions should be skipped (prevents infinite recursion)
* @returns {Fuzzy|*} Fuzzy if values differ, or the common value if all promotions agree
* @private
*/
_collect_fuzzy_from_promotions(state, promotions, traittype, skip_promotions) {
const alternatives = []
for (const promotion of promotions) {
// Only include traits the promotion actually sets (not inherited from before the split)
// If trait comes from archetype/shared ancestor, it shouldn't have promotion's certainty
if (!promotion._traits.has(traittype)) continue
const value = promotion._traits.get(traittype)
const certainty = promotion.certainty ?? 1.0
if (value instanceof Fuzzy) {
// Expand nested Fuzzy, multiply certainties
for (const alt of value.alternatives) {
alternatives.push({ value: alt.value, certainty: certainty * alt.certainty })
}
} else if (value !== undefined && value !== null) {
alternatives.push({ value, certainty })
}
}
// If no promotions set this trait, return undefined so caller falls through
// to find the trait from the common ancestor (without certainty)
if (alternatives.length === 0) {
return undefined
}
return new Fuzzy({ alternatives })
}
/**
* Get trait value, skipping promotion resolution for specified beliefs
* Used to prevent infinite recursion when resolving promotions
* @param {State} state
* @param {Traittype} traittype
* @param {Set<Belief>} skip_promotions - Beliefs whose promotions should be skipped
* @returns {*}
* @private
*/
_get_trait_skip_promotions(state, traittype, skip_promotions) {
// Check own promotions first (enables chained promotions)
const promo = this._get_trait_from_promotions(state, this, traittype, skip_promotions)
if (promo !== undefined) return promo
// Check own traits
const own = this._traits.get(traittype)
if (own !== undefined) return own
// Check cache
const cached = this._get_cached(traittype)
if (cached !== undefined) return cached
// Walk bases with skip_promotions
/** @type {{deps: Map<Belief, number>, last_promotable?: Belief, min_cache_tt: number}} */
const ctx = {deps: new Map(), min_cache_tt: -Infinity}
const value = this._get_uncached_trait(state, traittype, skip_promotions, ctx)
// Cache if locked and all temporal promotions are resolved (tt <= origin_state.tt)
const can_cache = ctx.min_cache_tt <= (this.origin_state.tt ?? Infinity)
if (this.locked && can_cache) {
// Store cache dependencies on promotable beliefs
if (ctx.deps.size > 0) {
this._cache_deps ??= new Map()
for (const [b, e] of ctx.deps) this._cache_deps.set(b, e)
}
this._set_cache(traittype, value)
}
return value
}
/**
* Get trait value (Subject/primitive/State/Mind/array) including inherited
* Returns own trait immediately if present, otherwise looks up inherited value
* Delegates to Traittype for derived values (composable, etc)
* Caches inherited traits when belief is locked (cache is belief-level, not state-level)
* @param {State} state - State context (used by Traittype for derived values)
* @param {Traittype} traittype - Traittype object
* @returns {*} trait value (Subject, not Belief), or null if not found
*/
get_trait(state, traittype) {
assert(state instanceof State, "get_trait requires State - shared beliefs must use origin_state or appropriate context state", {belief_id: this._id, traittype: traittype?.label, state})
assert(traittype instanceof Traittype, "get_trait requires Traittype", {belief_id: this._id, traittype})
// Temporal beliefs must be queried at tt >= origin_state.tt (timeless beliefs skip this check)
if (this.origin_state.tt != null) {
assert(state.tt != null && state.tt >= this.origin_state.tt,
"get_trait query state.tt must be >= belief.origin_state.tt",
{belief_id: this._id, state_tt: state.tt, origin_tt: this.origin_state.tt})
}
// Check for timeline resolution (Phase 4) - Convergence resolves to specific branch
// This must be checked before belief resolution since timeline resolution affects all beliefs
// When branched from Convergence, queries should see Convergence's view (resolved or first-wins)
// Only redirect if this belief predates the Convergence (beliefs created after are authoritative)
// @ts-ignore - _convergence_ancestor exists on states branched from Convergence
const conv_ancestor = state._convergence_ancestor
// @ts-ignore - conv_ancestor.tt is always set for Convergence states
if (conv_ancestor && (this.origin_state.tt === null || this.origin_state.tt < conv_ancestor.tt)) {
// @ts-ignore - get_resolution exists on Convergence
const resolved_branch = conv_ancestor.get_resolution(state)
if (resolved_branch) {
// Resolved: get belief from specific branch
const resolved_belief = resolved_branch.get_belief_by_subject(this.subject)
if (resolved_belief && resolved_belief !== this) {
return resolved_belief.get_trait(resolved_branch, traittype)
}
} else {
// Unresolved: get belief from Convergence (first-wins behavior)
const conv_belief = conv_ancestor.get_belief_by_subject(this.subject)
if (conv_belief && conv_belief !== this) {
// Pass original state (not conv) to preserve context for belief resolution lookup
return conv_belief.get_trait(state, traittype)
}
}
}
// Check for belief resolution (Phase 3) BEFORE cache lookup
// Resolution beliefs short-circuit the entire cache/walk path
const resolution = this.subject.get_resolution(state)
if (resolution && resolution !== this) {
return resolution.get_trait(state, traittype)
}
let value = this._get_cached(traittype)
if (value !== undefined) return value
/** @type {{deps: Map<Belief, number>, last_promotable?: Belief, min_cache_tt: number}} */
const ctx = {deps: new Map(), min_cache_tt: -Infinity}
value = this._get_uncached_trait(state, traittype, undefined, ctx)
// Cache if locked and all temporal promotions are resolved (tt <= origin_state.tt)
const can_cache = ctx.min_cache_tt <= (this.origin_state.tt ?? Infinity)
if (this.locked && can_cache) {
// Store cache dependencies on promotable beliefs
if (ctx.deps.size > 0) {
this._cache_deps ??= new Map()
for (const [b, e] of ctx.deps) this._cache_deps.set(b, e)
}
this._set_cache(traittype, value)
}
return value
}
/**
* Get trait value following a path through Subject references
* Enables dot notation like 'handle.color' for compositional access
* @param {State} state - State context for resolution
* @param {string|string[]} path - Path like 'handle.color' or ['handle', 'color']
* @returns {*|undefined} Trait value at end of path, or undefined if path broken
*/
get_trait_path(state, path) {
const segments = typeof path === 'string' ? path.split('.') : path
let belief = /** @type {Belief} */ (this)
// Walk intermediate segments (all but last)
for (const seg of segments.slice(0, -1)) {
const tt = Traittype.get_by_label(seg)
const subject = tt && belief.get_trait(state, tt)
if (!(subject instanceof Subject)) return undefined
const next = state.get_belief_by_subject(subject)
if (!next) return undefined
belief = next
}
// Get final trait value
const final_tt = Traittype.get_by_label(/** @type {string} */ (segments.at(-1)))
if (!final_tt) return undefined
return belief.get_trait(state, final_tt)
}
/**
* Get beliefs that reference this belief via a trait (reverse lookup)
* Inverse of get_trait(): finds all beliefs where belief.get_trait(state, traittype) includes this.subject
* Uses skip list to efficiently traverse only states with relevant changes
* @param {State} state - State to query
* @param {Traittype} traittype - Traittype to find reverse references for
* @yields {Belief} Beliefs in state that reference this belief's subject via traittype
*/
*rev_trait(state, traittype) {
assert(state instanceof State, 'rev_trait requires State', {belief_id: this._id, traittype: traittype?.label})
assert(traittype instanceof Traittype, 'rev_trait requires Traittype', {belief_id: this._id, traittype})
debug([state], "rev_trait", this, traittype.label)
// TODO: Update the trait indexes here instead of on modify
const seen = new Set()
const yielded = new Set()
// Walk skip list - only visit states with changes for this (subject, traittype)
// Use queue to handle Convergence's multiple component_states
const queue = [state]
while (queue.length > 0) {
const current = /** @type {State} */ (queue.shift())
const del_beliefs = current._rev_del.get(this.subject)?.get(traittype)
if (del_beliefs) {
for (const belief of del_beliefs) {
seen.add(belief._id)
}
}
// Yield additions (not deleted, not already yielded)
const add_beliefs = current._rev_add.get(this.subject)?.get(traittype)
if (add_beliefs) {
for (const belief of add_beliefs) {
if (seen.has(belief._id)) continue
if (yielded.has(belief._id)) continue
yielded.add(belief._id)
yield belief
}
}
// Get next state(s) via polymorphic rev_base (handles Convergence components)
// Pass original query state for resolution checks in Convergence
const next_states = current.rev_base(this.subject, traittype, state)
queue.push(...next_states)
}
}
/**
* Iterate over all reverse trait references (beliefs referencing this subject)
* Corresponds to get_defined_traits() - includes traittypes even when all beliefs are deleted
* @param {State} state - State to query
* @yields {[Traittype, Belief]} [traittype, belief] pairs for all referencing beliefs
*/
*rev_defined_traits(state) {
assert(state instanceof State, 'rev_defined_traits requires State', {belief_id: this._id})
const yielded_traittypes = new Set()
const queue = [state]
const visited_states = new Set()
while (queue.length > 0) {
const current = /** @type {State} */ (queue.shift())
if (visited_states.has(current._id)) continue
visited_states.add(current._id)
// Collect traittypes from both add and del maps for this state
const traittypes_here = new Set()
const add_map = current._rev_add.get(this.subject)
if (add_map) {
for (const traittype of add_map.keys()) {
traittypes_here.add(traittype)
}
}
const del_map = current._rev_del.get(this.subject)
if (del_map) {
for (const traittype of del_map.keys()) {
traittypes_here.add(traittype)
}
}
// Yield beliefs for new traittypes (rev_trait walks full state chain)
for (const traittype of traittypes_here) {
if (yielded_traittypes.has(traittype)) continue
yielded_traittypes.add(traittype)
for (const belief of this.rev_trait(state, traittype)) {
yield [traittype, belief]
}
}
// Walk to base state
if (current.base) queue.push(current.base)
}
}
/**
* Iterate over reverse trait references with non-null values
* Corresponds to get_traits() - excludes traittypes where all beliefs were deleted
* @param {State} state - State to query
* @yields {[Traittype, Belief]} [traittype, belief] pairs for all referencing beliefs
*/
*rev_traits(state) {
for (const pair of this.rev_defined_traits(state)) {
yield pair
}
}
/**
* Collect trait values from all direct bases for composition
* Called by add_trait_from_template() for composable traits at template time
* Collects ONE value per base chain (stops at first found in each chain)
* This implements the "latest version" semantics: each base's chain has one latest value
* @param {Traittype} traittype - Traittype to collect
* @returns {Array<any>} Array of values (one per base chain that has the trait)
*/
collect_latest_value_from_all_bases(traittype) {
const values = []
const queue = [...this._bases]
const seen = new Set()
while (queue.length > 0) {
const base = /** @type {Belief|Archetype} */ (queue.shift())
if (seen.has(base)) continue
seen.add(base)
// Polymorphic call - both Archetype and Belief accept Traittype
const value = base.get_own_trait_value(traittype)
if (value !== undefined) {
if (value !== null) values.push(value)
continue // Stop - found this base's value, don't search its ancestors
}
// Not found - continue searching this base's ancestors
queue.push(...base._bases)
}
return values
}
// ============================================================================
// Trait Caching
// ============================================================================
//
// CURRENT APPROACH (simple, correct):
// - Don't cache values from Eidos hierarchy (in_mind.in_eidos) - promotions may be added
//
// This is conservative but avoids complex invalidation. Since promotions only
// happen in Eidos, world beliefs that inherit from Eidos won't cache those values.
// Certainties are applied from state chain at query time, not stored in cache.
//
// FUTURE OPTIMIZATION IDEAS (see docs/notes/Claude-Cultural knowledge using flyweight model.md):
//
// 1. Epoch-based invalidation:
// - Each belief has _own_epoch (incremented when promotion added)
// - Cache entries store {value, source_belief, source_epoch}
// - On cache read: if source_belief._own_epoch === source_epoch → hit
// - O(1) per read, but requires storing source reference
//
// 2. @resolution pattern (META-PLAN Phase 3):
// - Record collapse in Subject.resolutions index
// - Check resolutions BEFORE walking bases
// - Recorded collapses short-circuit the walk entirely
//
// 3. Flattening with source tracking:
// - When resolving, record which base the value came from
// - Future queries check that one source's epoch directly
// - Amortizes walk cost across multiple queries
//
// 4. resolved_for tracking (from flyweight doc):
// - Base tracks which states have resolved it
// - Clear on promotion add (O(1))
// - Inheritors check if they're in resolved_for set
//
// ============================================================================
/**
* Get cached trait value
* Validates cache dependencies before returning - if any promotable belief
* has a different epoch than when cached, invalidates the entire cache
* @param {Traittype} traittype - Traittype object
* @returns {any|undefined} Cached value or undefined if not cached
* @private
*/
_get_cached(traittype) {
// Validate cache deps - if any promotable belief has changed, invalidate
if (this._cache_deps) {
for (const [belief, epoch] of this._cache_deps) {
if (belief._promotable_epoch !== epoch) {
this._invalidate_cache()
return undefined
}
}
}
return this._cache.get(traittype)
}
/**
* Set cached trait value
* @param {Traittype} traittype - Traittype object
* @param {any} value - Value to cache
* @private
*/
_set_cache(traittype, value) {
this._cache.set(traittype, value)
}
/**
* Invalidate all cached trait values
* Called when a promotable belief's epoch changes
* @private
*/
_invalidate_cache() {
this._cache.clear()
this._cache_deps = null
this._cached_all = false
}
/**
* Iterate over traits that have non-null values (excludes null/undefined traits)
* @heavy O(traits in belief + base chain) - iterates all traits
* @returns {Generator<[Traittype, *]>} Yields [traittype, value] pairs for set traits only
*/
*get_traits() {
for (const pair of this.get_defined_traits()) {
if (pair[1] != null) yield pair
}
}
/**
* Iterate over all defined traits (own and inherited) including those with null values
* Own traits shadow inherited traits with the same name
* Caches inherited traits when belief is locked (belief-level cache)
* Includes all trait definitions from archetypes (even null/unset values)
* Caches inherited traits when belief is locked
* @returns {Generator<[Traittype, any]>}
*/
*get_defined_traits() {
const yielded = new Set()
const composables = new Map() // traittype → values[]
const composable_contributors = new Map() // traittype → Set<nodes that contributed>
// Check if base_node is in derived_node's ancestor chain
const is_base_of = (/** @type {Belief|Archetype} */ base_node, /** @type {Belief|Archetype} */ derived_node) => {
const q = [...derived_node._bases]
const s = new Set()
for (let i = 0; i < q.length; i++) {
const n = q[i]
if (n === base_node) return true
if (s.has(n)) continue
s.add(n)
q.push(...n._bases)
}
return false
}
/** @type {Map<Belief, number>} */
const deps = new Map() // Track promotable beliefs for cache invalidation
/** @type {Belief|null} */
let last_promotable = null
let min_cache_tt = -Infinity // Track max tt of temporal promotions
const origin_tt = this.origin_state.tt ?? Infinity
// Yield cached traits first
for (const [traittype, value] of this._cache) {
yield /** @type {[Traittype, any]} */ ([traittype, value])
yielded.add(traittype)
}
if (this._cached_all) return
// BFS walk starting from this
/** @type {(Belief|Archetype)[]} */
const queue = [this]
const seen = new Set()
while (queue.length > 0) {
const node = /** @type {Belief|Archetype} */ (queue.shift())
if (seen.has(node)) continue
seen.add(node)
// If node has promotions, resolve and process
if (node instanceof Belief && node.promotions.size > 0 && node._promotable_epoch !== null) {
// Record as cache dependency
deps.set(node, node._promotable_epoch)
const promos = this.origin_state.pick_promotion(node.promotions, {})
if (promos.length === 1 && promos[0].certainty === null) {
queue.unshift(promos[0]) // Temporal: add to queue
if (promos[0].origin_state.tt != null) {
min_cache_tt = Math.max(min_cache_tt, promos[0].origin_state.tt)