import {PERSONAL_ACTIVITY_METRICS,verifiedPersonalActivities} from './personal-activity-events.mjs'; import {createHash} from 'node:crypto'; import {xpAtLevel} from './progression-definitions.mjs'; import {verifiedStarterKitEvidence} from './starter-kit-events.mjs'; import {verifyDeedAcquisition} from './deed-acquisition-proof.mjs'; import {createProgressionMilestoneNews} from './progression-milestone-news.mjs'; import {createQuestProgression} from './progression-quests.mjs'; import {createXPInstruments} from './progression-xp-instruments.mjs'; import {firstLoginState} from './first-login.mjs'; import {can} from './permissions.mjs'; import {createBankQuestActivities,bankQuestIncome} from './bank-quest-activities.mjs'; import {faithMultipliers,faithAward} from './faith-blessings.mjs'; const first=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;}; export function createProgressionRuntime(central,bank,keys,{clock=Date.now,resolveCase=async()=>null,verifyAcquisition=(input,store=central)=>verifyDeedAcquisition(store,bank,input)}={}){ const observer=Object.freeze({internal:'progression-source-reader'}); const collectBankActivities=bank&&keys?createBankQuestActivities(central,bank,keys,{clock}):null; const resolvePlayer=id=>first(central,"SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]); async function authorizePlayer(actor,store){ if(typeof actor.revalidate==='function'&&(await actor.revalidate())?.id!==actor.id)return false; return !!await first(store,"SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[actor.id]); } async function activityEvidence(actor,store=central,{lock=false}={}){ if(!central.personalActivityEventsEnabled)return null; const now=clock(),seasons=await store.query("SELECT season_id,starts_at,ends_at FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?"+(lock?' FOR UPDATE':''),[now,now]);if(seasons.length!==1)throw Error('Current Personal 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];return {...await verifiedPersonalActivities(store,keys,{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}),season}; } const engine=createQuestProgression(central,keys,{clock,authorizePlayer,resolvePlayer, resolveAward:async(actor,_d,tx,award)=>faithAward(award,await faithMultipliers(central,tx,actor.id,{clock})), authorizeObservation:async actor=>actor===observer, authorizeClaim:async(actor,d,tx,{eligibility})=>{ if(!PERSONAL_ACTIVITY_METRICS.includes(d.metric)||eligibility.reason==='xp-threshold')return true; const proof=await activityEvidence(actor,tx,{lock:true});return !!proof&&(proof.totals.get(d.metric)||0)>=d.target; }, // A relation label alone cannot prove a settled transfer or its beneficiary. // The existing deed settlement flow must supply its verified adapter. verifyAcquisition:async(actor,input,tx)=>actor===observer&&await verifyAcquisition(input,tx) }); const quests=Object.freeze({...engine,async list(actor){ const original=await engine.list(actor),boost=original.state==='active'?await faithMultipliers(central,central,actor.id,{clock}):{xp:1};const view=boost.xp===1?original:{...original,quests:original.quests.map(q=>q.state==='claimed'||!Number.isSafeInteger(q.xp)?q:{...q,faithBonusXP:q.xp,xp:q.xp*2})};if(!central.personalActivityEventsEnabled||view.state!=='active')return view; let proof=null;try{proof=await activityEvidence(actor);}catch{/* Missing current identity/evidence never supplies objective progress. */} const bypass=view.season.levelCap!==null&&view.profile.effectiveXP>=xpAtLevel(view.season.levelCap,view.season.curveBase); return {...view,quests:view.quests.map(q=>{if(!PERSONAL_ACTIVITY_METRICS.includes(q.metric)||q.state==='claimed'||bypass&&!q.optional)return q;const verified=(proof?.totals.get(q.metric)||0)>=q.target;return {...q,canClaim:q.canClaim&&verified,...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};})}; }}); const xp=createXPInstruments(central,keys,{clock,resolveCase,authorizeIssue:async(actor,type)=>{ const fresh=await resolvePlayer(actor.id);if(!fresh)return false; return can(central,fresh,type==='xp-correction'?'web.progression.xp.correct':'web.progression.seasons.manage'); }}); async function collect(actor){ if(!await authorizePlayer(actor,central))throw Error('Current player identity required'); const now=clock(),seasons=await central.query("SELECT season_id,starts_at FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]); if(seasons.length!==1)return {state:'season-not-configured',sources:[]};const season=seasons[0],sources=[]; const save=async(metric,value,sourceKind='verified-website')=>{ const quantity=Number(value);if(!Number.isSafeInteger(quantity)||quantity<0)throw Error('Source counter is not safe'); await quests.observe(observer,{accountId:actor.id,seasonId:season.season_id,metric,value:quantity,eventId:(sourceKind==='verified-equipment-key'?'equipment:':'web:')+actor.id+':'+season.season_id+':'+metric+':'+quantity,source:sourceKind}); }; const source=async(name,metrics,work)=>{try{const details=await work();sources.push({name,metrics,state:'available',...(details?.pendingMetrics?{pendingMetrics:details.pendingMetrics.filter(m=>metrics.includes(m))}:{})});}catch{sources.push({name,metrics,state:'unavailable'});}}; await source('profile',['onboarding','profile','faction'],async()=>{ const profile=await first(central,'SELECT a.display_name,p.bio,l.minecraft_uuid FROM site_accounts a LEFT JOIN site_profiles p ON p.user_id=a.id LEFT JOIN site_game_links l ON l.user_id=a.id WHERE a.id=?',[actor.id]); if(profile?.minecraft_uuid&&!await firstLoginState(central,actor))await save('onboarding',1); if(profile?.display_name?.trim()&&String(profile.bio||'').trim().length>=10)await save('profile',1); const choice=await first(central,'SELECT c.faction FROM site_character_choices c JOIN site_game_links l ON l.user_id=c.user_id AND l.minecraft_uuid=c.minecraft_uuid WHERE c.user_id=?',[actor.id]);if(choice?.faction)await save('faction',1); }); await source('forum',['forum-registration','forum-contributions'],async()=>{ const account=await first(central,'SELECT uid FROM drforum_dune_accounts WHERE website_id=?',[actor.id]);if(!account)return;await save('forum-registration',1); // Count unique meaningful, moderated-visible messages, with at most the first // eligible contribution per thread/day; copied text never adds extra progress. const count=await first(central,"SELECT COUNT(DISTINCT SHA2(LOWER(TRIM(p.message)),256)) total FROM drforum_posts p JOIN drforum_threads t ON t.tid=p.tid WHERE p.uid=? AND p.visible=1 AND t.visible=1 AND p.dateline>=? AND LENGTH(TRIM(p.message))>=40 AND NOT EXISTS(SELECT 1 FROM drforum_posts earlier WHERE earlier.uid=p.uid AND earlier.tid=p.tid AND earlier.visible=1 AND LENGTH(TRIM(earlier.message))>=40 AND FLOOR(earlier.dateline/86400)=FLOOR(p.dateline/86400) AND earlier.pid{ const design=await first(central,"SELECT COUNT(*) total FROM site_kit_blueprints WHERE owner_user_id=? AND active=1 AND commerce_kind='personal_sale' AND LENGTH(TRIM(name))>=3",[actor.id]); const listing=await first(central,"SELECT COUNT(*) total FROM site_kit_listings l JOIN site_kit_blueprints b ON b.id=l.blueprint_id WHERE b.owner_user_id=? AND b.active=1 AND b.commerce_kind='personal_sale' AND l.active=1 AND l.published=1 AND l.price_cents>0 AND l.blueprint_version=b.version",[actor.id]); let designs=Number(design.total),publications=Number(listing.total); if(central.kitsetsEnabled){ const draft=await first(central,'SELECT COUNT(*) total FROM jarvis_kitsets WHERE author_id=? AND LENGTH(TRIM(design_json))>0',[actor.id]); const published=await first(central,"SELECT COUNT(*) total FROM jarvis_kitset_listings l JOIN jarvis_kitset_versions v ON v.key_id=l.key_id AND v.kitset_id=l.kitset_id JOIN organisation_keys k ON k.id=v.key_id WHERE l.published_by=? AND k.key_type='kit-definition' AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>?)",[actor.id,clock()]); designs+=Number(draft.total);publications+=Number(published.total); } await save('kit-design',designs>0?1:0);await save('kit-publication',publications>0?1:0); }); if(central.starterKitEventsEnabled)await source('starter-equipment',['faction-kit','starter-kit-repair'],async()=>{ const link=await first(central,'SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[actor.id]);if(!link)return {pendingMetrics:['faction-kit','starter-kit-repair']}; const evidence=await verifiedStarterKitEvidence(central,actor.id,season.season_id,{minecraftUuid:link.minecraft_uuid});if(!evidence)return {pendingMetrics:['faction-kit','starter-kit-repair']}; await save('faction-kit',1,'verified-equipment-key');if(evidence.repair)await save('starter-kit-repair',1,'verified-equipment-key');return {pendingMetrics:evidence.repair?[]:['starter-kit-repair']}; }); await source('elections',['civic-activity','civic-ballot-equivalent','civic-additional'],async()=>{ const ballots=await first(central,'SELECT COUNT(DISTINCT b.id) total FROM political_ballots b JOIN political_voters v ON v.round_id=b.round_id AND v.player_uuid=b.player_uuid JOIN political_ballot_allocations a ON a.ballot_id=b.id AND a.votes>0 WHERE v.user_id=? AND b.created_at>=?',[actor.id,Number(season.starts_at)]); const total=Number(ballots.total);await save('civic-activity',total);await save('civic-ballot-equivalent',total);await save('civic-additional',Math.max(0,total-1)); }); if(bank)await source('bank',['bank-transfer','wage-received','earned-minor'],async()=>{ const transfers=await first(bank,"SELECT COUNT(*) total FROM pb_orders o JOIN pb_accounts a ON a.id=o.source_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_accounts target ON target.id=o.target_id WHERE e.kind='person' AND e.external_key=? AND o.state='posted' AND o.mode IN ('standard','instant') AND o.posted_at>=? AND o.source_id<>o.target_id AND (target.client_number IS NULL OR target.client_number<>a.client_number)",[actor.id,Number(season.starts_at)]);await save('bank-transfer',transfers.total); const income=await bankQuestIncome(bank,actor.id,Number(season.starts_at),now);await save('wage-received',income.wages);await save('earned-minor',income.earned); }); if(bank)await source('deed-acquisitions',['acquired-clan','acquired-company'],async()=>{ const rows=await bank.query("SELECT quote_json FROM jarvis_deed_purchases WHERE actor_id=? AND state='posted' ORDER BY created_at,id",[actor.id]); for(const row of rows){const q=JSON.parse(row.quote_json);if(!['clan','company'].includes(q.kind))continue;await quests.recordAcquisition(observer,{accountId:actor.id,kind:q.kind,entityId:q.entityId,origin:q.kind==='clan'?'bend-the-knee':'purchase'});} }); await source('clan-conquests',['acquired-clan'],async()=>{ const rows=await central.query("SELECT key_id,manifest_json FROM jarvis_generated_instructions WHERE action_id='politics.rebellion' AND state='defeated' AND JSON_EXTRACT(manifest_json,'$.receipt.actorId')=? ORDER BY created_at,key_id LIMIT 501",[actor.id]); if(rows.length>500)throw Error('The conquest registry requires a larger reviewed window'); for(const row of rows){const receipt=JSON.parse(row.manifest_json).receipt;await quests.recordAcquisition(observer,{accountId:actor.id,kind:'clan',entityId:receipt.clanId,origin:'conquest',sourceKeyId:row.key_id});} }); if(central.personalActivityEventsEnabled&&collectBankActivities)await source('exchange-purchases',['shop-purchase'],()=>collectBankActivities(actor,season)); if(central.personalActivityEventsEnabled)await source('personal-activity-keys',PERSONAL_ACTIVITY_METRICS,async()=>{ const proof=await activityEvidence(actor);if(!proof)return {pendingMetrics:PERSONAL_ACTIVITY_METRICS}; const digest=createHash('sha256').update(JSON.stringify(proof.proofIds)).digest('hex'); for(const [metric,value]of proof.totals)await quests.observe(observer,{accountId:actor.id,seasonId:proof.season.season_id,metric,value,eventId:'personal-activity:'+actor.id+':'+metric+':'+digest.slice(0,32),source:'verified-activity-key'}); return {pendingMetrics:PERSONAL_ACTIVITY_METRICS.filter(metric=>!proof.totals.has(metric))}; }); return {state:'verified',sources}; } async function recordPoliticalVisit(actor){ if(!await authorizePlayer(actor,central))throw Error('Current player identity required');const now=clock(); const seasons=await central.query("SELECT season_id FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]); if(seasons.length!==1)return; return quests.observe(observer,{accountId:actor.id,seasonId:seasons[0].season_id,metric:'political-interface',value:1,eventId:'political-interface:'+actor.id+':'+seasons[0].season_id,source:'verified-website-visit'}); } return Object.freeze({quests,xp,collect,recordPoliticalVisit,announcements:createProgressionMilestoneNews(central,keys,{clock})}); }