import {mentorAward,currentMentorPolicy,mentorXP} from './pol-mentor-rewards.mjs'; import {grantSmugglerAffiliations,readSmugglerAffiliations} from './clandestine-institutions.mjs'; import {createPOLProgression} from './progression-pol.mjs'; import {createSystemCharacters} from './system-characters.mjs'; import {POL_QUEST_BRANCHES,POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs'; import {verifiedPOLActivities} from './pol-activity-events.mjs'; import {verifiedPOLDeathTotals} from './pol-death-evidence.mjs'; import {repeatableDefinitions} from './pol-repeatable-quests.mjs'; import {createHash} from 'node:crypto'; export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyObservation=null}={}){ const observer=Object.freeze({internal:'pol-key-source-reader'}); const resolvePlayer=async id=>(await central.query("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null; const authorizePlayer=async(actor,store)=>{ if(typeof actor.revalidate==='function'&&(await actor.revalidate())?.id!==actor.id)return false; return !!(await store.query("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[actor.id]))[0]; }; const authorizeIssuer=async(tx,definition)=>{ const bound=await tx.first('SELECT key_id FROM jarvis_system_identities WHERE character_key=?',[definition.issuer]);if(!bound)throw Error('POL quest issuer is unavailable'); await tx.first('SELECT id FROM organisation_keys WHERE id=? FOR UPDATE',[bound.key_id]); const identity=await createSystemCharacters(tx,keys,{authorizeOperator:async()=>false}).inspect(definition.issuer); if(!identity?.capabilities.includes('quest.issue'))throw Error('POL quest issuer is unavailable');return identity; }; async function evidence(actor,store=central,{lock=false}={}){ if(!central.polActivityEventsEnabled)return null; const now=clock(),seasons=await store.query("SELECT season_id,starts_at,ends_at FROM jarvis_pol_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?"+(lock?' FOR UPDATE':''),[now,now]);if(seasons.length!==1)throw Error('Current POL season required'); const links=await store.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?'+(lock?' FOR UPDATE':''),[actor.id]);if(links.length!==1)throw Error('Current activity identity required'); const season=seasons[0],input={accountId:actor.id,minecraftUuid:links[0].minecraft_uuid.toLowerCase(),seasonId:season.season_id,startsAt:Number(season.starts_at),endsAt:Number(season.ends_at),now,lock},activity=await verifiedPOLActivities(store,keys,input); if(central.polRepeatablesEnabled){const deaths=await verifiedPOLDeathTotals(store,keys,input);for(const [metric,value]of deaths.totals)activity.totals.set(metric,value);activity.proofIds.push(...deaths.proofIds);} return {...activity,season}; } const adapters={clock,authorizePlayer,authorizeIssuer,resolvePlayer, resolveAward:async(actor,definition,tx,award)=>mentorAward(tx,keys,{actor,definition,issuer:await authorizeIssuer(tx,definition),award,enabled:central.polMentorBonusEnabled}), authorizeObservation:async(actor,input,store)=>actor===observer||typeof verifyObservation==='function'&&await verifyObservation(actor,input,store),verifyAcquisition:async()=>false, authorizeClaim:async(actor,definition,polStore)=>{ // An explicitly supplied authoritative adapter retains its existing contract. if(typeof verifyObservation==='function')return true; // polStore already rewrites the fixed table namespace. The evidence tables // and original account/key stores are deliberately outside that rewrite. const proof=await evidence(actor,polStore,{lock:true});if(!proof||(proof.totals.get(definition.metric)||0)q.state==='claimed'&&q.keyId).map(q=>q.keyId),claimedAwards=new Map((claimedIds.length?await central.query('SELECT key_id,xp FROM jarvis_pol_quest_claims WHERE account_id=? AND key_id IN ('+claimedIds.map(()=>'?').join(',')+')',[actor.id,...claimedIds]):[]).map(r=>[r.key_id,Number(r.xp)])); const bonusPolicy=central.polMentorBonusEnabled?await currentMentorPolicy(central):null,bonusIssuers=new Map(); if(bonusPolicy){const characters=createSystemCharacters(central,keys,{authorizeOperator:async()=>false});for(const issuer of new Set(current.definitions.map(d=>d.issuer))){const identity=await characters.inspect(issuer);bonusIssuers.set(issuer,!!identity?.capabilities.includes('quest.reward-bonus'));}} return {...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!d.repeatable&&q.revision===null,baseXP=derived?d.xp:q.xp,xp=claimedAwards.has(q.keyId)?claimedAwards.get(q.keyId):Number.isSafeInteger(baseXP)&&bonusPolicy&&bonusIssuers.get(d.issuer)?mentorXP(baseXP,bonusPolicy.xpBonusBps):baseXP;return {...q,baseXP,xp,mentorBonusXP:q.state==='claimed'?null:Number.isSafeInteger(xp)?xp-baseXP:0,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified,...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}),xpType:'pol',branches:[...POL_QUEST_BRANCHES.map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]}; } }); async function collect(actor){ if(!await authorizePlayer(actor,central))throw Error('Current player identity required');const proof=await evidence(actor);if(!proof)return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:false,reason:'pending-verified-producer'}]}; const digest=createHash('sha256').update(JSON.stringify(proof.proofIds)).digest('hex'); const current=await engineFor(actor);for(const [metric,value]of proof.totals)await current.engine.observe(observer,{accountId:actor.id,seasonId:proof.season.season_id,metric,value,eventId:'pol-activity:'+actor.id+':'+metric+':'+digest.slice(0,32),source:'verified-activity-key'}); return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:true,verifiedEvents:proof.proofIds.length}]}; } return Object.freeze({quests,collect}); }