head-state.ts (5456B)
1 import { 2 projectFoodParts, 3 type FoodProjection 4 } from '../contracts/food-availability-v1/read.ts'; 5 import { 6 verifiedEnvelopeSnapshot, 7 type VerifiedEnvelope 8 } from '../nostr/verified-envelope.ts'; 9 import { 10 createPublicHeadCandidate, 11 publicHeadEnvelope, 12 publicHeadSnapshot, 13 selectPublicHead, 14 type PublicHead, 15 type PublicHeadDecision, 16 type PublicHeadSnapshot 17 } from './heads.ts'; 18 import { 19 assessFutureTimestamp, 20 wallClockAvailable, 21 type WallClock 22 } from './clock-policy.ts'; 23 24 declare const stateBrand: unique symbol; 25 export type FoodHeadState = Readonly<{ readonly [stateBrand]: true }>; 26 export type ClockDirection = 27 'initial' | 'forward' | 'backward' | 'unchanged' | 'unavailable'; 28 export type FoodHeadDisplay = 29 'focused_known' | 'unsupported' | 'future_quarantined' | 'clock_unavailable'; 30 export type FoodHeadStateSnapshot = Readonly<{ 31 head: PublicHeadSnapshot; 32 classification: 'focused' | 'unsupported'; 33 display: FoodHeadDisplay; 34 assessedAtSeconds: number | null; 35 clockDirection: ClockDirection; 36 unsupportedReason: string | undefined; 37 food: FoodProjection | undefined; 38 }>; 39 interface Owner { 40 readonly head: PublicHead; 41 readonly nowSeconds: () => number; 42 readonly lastValidClock: number | undefined; 43 readonly view: FoodHeadStateSnapshot; 44 } 45 const owners = new WeakMap<FoodHeadState, Owner>(); 46 function ownerOf(state: FoodHeadState): Owner { 47 const owner = owners.get(state); 48 if (!owner) throw new Error('food_head_state_invalid'); 49 return owner; 50 } 51 function assess( 52 selectedHead: PublicHead, 53 nowSeconds: () => number, 54 lastValidClock: number | undefined 55 ): Owner { 56 const head = publicHeadSnapshot(selectedHead); 57 const event = verifiedEnvelopeSnapshot(publicHeadEnvelope(selectedHead)); 58 if (!event) throw new Error('food_head_proof_invalid'); 59 const projected = projectFoodParts(event); 60 const focused = projected.outcome === 'focused'; 61 let now: number | undefined; 62 try { 63 const sample = nowSeconds(); 64 if (wallClockAvailable(sample)) now = sample; 65 } catch { 66 /* Unavailable clock denies display, never discards new evidence. */ 67 } 68 const clockDirection: ClockDirection = 69 now === undefined 70 ? 'unavailable' 71 : lastValidClock === undefined 72 ? 'initial' 73 : now > lastValidClock 74 ? 'forward' 75 : now < lastValidClock 76 ? 'backward' 77 : 'unchanged'; 78 const timing = 79 now === undefined 80 ? 'clock_unavailable' 81 : assessFutureTimestamp(head.created_at, now); 82 const display: FoodHeadDisplay = 83 timing !== 'within_policy' 84 ? timing 85 : focused 86 ? 'focused_known' 87 : 'unsupported'; 88 const view: FoodHeadStateSnapshot = { 89 head, 90 classification: focused ? 'focused' : 'unsupported', 91 display, 92 assessedAtSeconds: now ?? null, 93 clockDirection, 94 unsupportedReason: 95 projected.outcome === 'rejected' 96 ? projected.error.code 97 : projected.outcome === 'excluded' 98 ? projected.partition 99 : undefined, 100 food: 101 display === 'focused_known' && projected.outcome === 'focused' 102 ? projected.projection 103 : undefined 104 }; 105 return { 106 head: selectedHead, 107 nowSeconds, 108 lastValidClock: now ?? lastValidClock, 109 view 110 }; 111 } 112 export function createFoodHeadState( 113 head: PublicHead, 114 clock: WallClock 115 ): FoodHeadState { 116 if (publicHeadSnapshot(head).kind !== 30402) 117 throw new Error('food_head_kind_invalid'); 118 const readClock = clock.nowSeconds; 119 if (typeof readClock !== 'function') 120 throw new Error('food_head_clock_invalid'); 121 const token = Object.freeze({}) as FoodHeadState; 122 owners.set( 123 token, 124 assess(head, () => readClock(), undefined) 125 ); 126 return token; 127 } 128 // No profile admission can run before HCP033 selects the generic winner. 129 export function advanceFoodHeadState( 130 state: FoodHeadState, 131 proof: VerifiedEnvelope 132 ): PublicHeadDecision | 'ignored' { 133 const owner = ownerOf(state), 134 candidate = createPublicHeadCandidate(proof); 135 if (!candidate) return 'ignored'; 136 const selected = selectPublicHead(owner.head, candidate); 137 if (selected.decision === 'applied') { 138 // Reserve the protocol winner before invoking caller-controlled clock code. 139 // Until assessment settles, expose its evidence with no display authority. 140 const pending: Owner = { 141 ...assess(selected.head, () => NaN, owner.lastValidClock), 142 nowSeconds: owner.nowSeconds 143 }; 144 owners.set(state, pending); 145 publishAssessment(state, pending); 146 } 147 return selected.decision; 148 } 149 // Called by a bounded explicit refresh, never an automatic wall-clock timer. 150 export function refreshFoodHeadState(state: FoodHeadState): void { 151 publishAssessment(state, ownerOf(state)); 152 } 153 function publishAssessment(state: FoodHeadState, owner: Owner): void { 154 const measured = assess(owner.head, owner.nowSeconds, owner.lastValidClock); 155 // A nested advance or refresh owns its replacement; never publish stale data. 156 if (owners.get(state) === owner) owners.set(state, measured); 157 } 158 export function foodHeadStateHead(state: FoodHeadState): PublicHead { 159 return ownerOf(state).head; 160 } 161 export function foodHeadStateSnapshot( 162 state: FoodHeadState 163 ): FoodHeadStateSnapshot { 164 const view = ownerOf(state).view; 165 return { 166 ...view, 167 head: { ...view.head }, 168 food: 169 view.food === undefined 170 ? undefined 171 : (JSON.parse(JSON.stringify(view.food)) as FoodProjection) 172 }; 173 }