Connect personal mission trees to transactional JARVIS quests, XP, claims and private history

This commit is contained in:
unimatrixgit 2026-11-18 22:53:36 +01:00
commit 907eca40fc
11 changed files with 750 additions and 5 deletions

View file

@ -1,6 +1,9 @@
import {JARVIS_IDENTITY,isJarvisIdentity} from './jarvis-identity.mjs';
import {organisationRuntimeAccess} from './organisation-runtime.mjs';
export const NODES={
'web.progression.xp.correct':'Issue support-approved XP correction instruments',
'web.progression.seasons.manage':'Manage sealed seasonal XP transfers',
'web.projects.review':'Review and fund server projects from the Tax treasury',
'web.forum.admin':'Native Forum administration (Dev service only after migration)',
'web.tickets.support':'Work Customer Support tickets',
'web.tickets.sales':'Work Sales and Account Services tickets',

View file

@ -0,0 +1,49 @@
import {identity} from './auth.mjs';
import {parseOrganisationCode} from '../control-panel/public/codex-code-format.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
export function createProgressionAPI(db,{quests,xp,collect=async()=>{},authenticate=r=>identity(r,db),origin='https://cp.dunerealms.com'}={}){
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});
return async request=>{
const url=new URL(request.url),user=await authenticate(request);if(!user)return reply({message:'Sign in to open your mission journal.'},401);
const actor={...user,revalidate:async()=>authenticate(request)};
if(!quests)return reply({message:'The quest service is not available.'},503);
try{
if(request.method==='GET'){
if(url.pathname==='/api/progression'&&!url.search){const sources=await collect(actor);return reply({...await quests.list(actor),sources});}
if(url.pathname==='/api/progression/history'){
if([...url.searchParams.keys()].some(k=>k!=='page')||url.searchParams.getAll('page').length>1||!/^\d{1,4}$/.test(url.searchParams.get('page')||'1'))return reply({message:'Choose a valid history page.'},400);
const page=Number(url.searchParams.get('page')||1);if(page<1)return reply({message:'Choose a valid history page.'},400);
const rows=await db.query('SELECT key_id,action,details_json,created_at FROM jarvis_progression_history WHERE account_id=? ORDER BY created_at DESC,id DESC LIMIT 26 OFFSET '+((page-1)*25),[user.id]);
return reply({page,hasMore:rows.length>25,records:rows.slice(0,25).map(r=>({keyId:r.key_id,action:r.action,details:JSON.parse(r.details_json),createdAt:Number(r.created_at)}))});
}
return reply({message:'Mission route not found.'},404);
}
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin||url.search)return reply({message:'Origin or account override rejected.'},403);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
const reader=request.body?.getReader();if(!reader)return reply({message:'Request body required.'},400);let raw='',size=0;const decoder=new TextDecoder();
while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>4096){await reader.cancel();return reply({message:'Request too large.'},413);}raw+=decoder.decode(value,{stream:true});}raw+=decoder.decode();
let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid mission request.'},400);}
if(!body||typeof body!=='object'||Array.isArray(body)||body.confirmed!==true)return reply({message:'Confirm the selected action.'},400);
if(url.pathname==='/api/progression/start'){
if(Object.keys(body).some(k=>!['definitionId','confirmed'].includes(k))||typeof body.definitionId!=='string')return reply({message:'Choose a mission.'},400);
await collect(actor);const result=await quests.start(actor,body);return reply({ok:true,keyId:result.id,created:result.created});
}
if(url.pathname==='/api/progression/claim'){
if(Object.keys(body).some(k=>!['definitionId','requestId','revision','confirmed'].includes(k))||typeof body.definitionId!=='string'||!uuid(body.requestId)||!Number.isSafeInteger(body.revision)||body.revision<1)return reply({message:'Review the current mission reward.'},400);
await collect(actor);const result=await quests.claim(actor,body);await quests.processCompletions({accountId:user.id});return reply({ok:true,...result});
}
if(url.pathname==='/api/progression/xp/redeem'){
if(!xp||Object.keys(body).some(k=>!['code','requestId','confirmed'].includes(k))||typeof body.code!=='string'||!uuid(body.requestId))return reply({message:'Provide a complete XP instrument.'},400);
let parsed;try{parsed=parseOrganisationCode(body.code);}catch{return reply({message:'Provide a complete XP instrument.'},400);}
const keyType=parsed.prefix==='XPC'?'xp-correction':parsed.prefix==='XPX'?'xp-transfer':null;if(!keyType)return reply({message:'This instrument is not a player XP key.'},400);
const fresh=await authenticate(request);if(fresh?.id!==user.id)return reply({message:'Your session changed.'},403);
const result=await xp.redeem(actor,{code:body.code,keyType,requestId:body.requestId});await quests.processCompletions({accountId:user.id});return reply({ok:true,...result});
}
return reply({message:'Mission route not found.'},404);
}catch(error){
const safe=/^(Quest|XP |Season|Unknown quest|Current player|A single matching|An approved matching|Trusted observation|Verified deed|No reserved|Source season|Mandatory reward)/.test(error.message||'');
return reply({message:safe?error.message:'The mission service could not confirm this action. Reload before retrying.'},safe?409:503);
}
};
}

View file

@ -0,0 +1,49 @@
import {MISSION_BRANCHES} from '../control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs';
import {defaultQuestXP} from './progression-reward-defaults.mjs';
const spec={
a:[['onboarding',1],['faction',1],['profile',1],['guild-travel',1],['citizen-introduction',1]],
b:[['earned-minor',100000],['bank-deposit',1],['bank-transfer',1],['shop-purchase',1],['earned-minor',2500000],['earned-minor',10000000],['earned-minor',50000000]],
c:[100,1000,5000,25000,100000,250000,500000,1000000].map(n=>['spice-harvest',n]),
d:[['arrakduin-visit',1],['arrakduin-active-minutes',30],['sietch-discovery',1],['oasis-discovery',1],['accessible-planets',1],['arrakduin-active-minutes',600],['advanced-survival',1]],
e:[1,5,20,50,100].map(n=>['jobs-completed',n]).concat([['employment',1],['wage-received',1]]),
f:[['forum-registration',1],...[1,10,25,50,100].map(n=>['forum-contributions',n]),['recognition',1]],
g:[['political-interface',1],['civic-activity',1],['civic-ballot-equivalent',1],['civic-additional',1],['public-event-equivalent',1]],
h:[['faction-kit',1],['starter-kit-repair',1],['equipment-use',1],['mark-upgrade',1],['rarity-enhancement',1],['equipment-mark',7],['equipment-mark',12],['equipment-mark',14]],
i:[['kit-design',1],['kit-publication',1],...[1,5,25,100,500].map(n=>['eligible-kit-sales',n])]
};
// Definitions are server-owned. Browser labels never supply counters, rewards or authority.
export const QUEST_DEFINITIONS=Object.freeze([...MISSION_BRANCHES.filter(b=>b.id!=='discoveries').flatMap(branch=>branch.missions.map((mission,index)=>{
const [metric,target]=spec[branch.id][index]||[];if(!metric)throw Error('Missing quest condition '+mission.id);
const previous=branch.missions[index-1],requires=previous?[previous.id]:[];
return Object.freeze({...mission,branch:branch.id,metric,target,requires,requiresAny:[],season:'S01',xp:defaultQuestXP({branch:branch.id},index),reward:null,revision:1});
})),...['company','clan'].flatMap(kind=>(kind==='company'?[1,3,5]:[1,5,10]).map((target,index)=>Object.freeze({
id:`S1-ACQUIRE-${kind.toUpperCase()}-${target}`,title:`Acquire ${target} ${kind}${target===1?'':'s'}`,
branch:'acquisitions',optional:true,metric:`acquired-${kind}`,target,
requires:index?[`S1-ACQUIRE-${kind.toUpperCase()}-${(kind==='company'?[1,3,5]:[1,5,10])[index-1]}`]:[],
requiresAny:[],season:'S01',xp:defaultQuestXP({branch:'acquisitions',metric:`acquired-${kind}`},index),reward:null,revision:1
})))]);
export const QUEST_METRICS=Object.freeze([...new Set(QUEST_DEFINITIONS.map(d=>d.metric))]);
export const XP_POLICY=Object.freeze({version:1,base:25,seasonCap:70,season:'S01',months:6});
export function xpAtLevel(level,base=XP_POLICY.base){if(!Number.isSafeInteger(level)||level<1||level>1000||!Number.isSafeInteger(base)||base<1||base>100000)throw TypeError('Invalid XP curve');return base*level*(level-1)/2;}
export function levelForXP(xp,{base=XP_POLICY.base,cap=XP_POLICY.seasonCap}={}){if(!Number.isSafeInteger(xp)||xp<0||!Number.isSafeInteger(cap)||cap<1||cap>1000)throw TypeError('Invalid XP state');let level=1;while(level<cap&&xp>=xpAtLevel(level+1,base))level++;return level;}
export function questPrerequisites(definition,claimed){return definition.requires.every(id=>claimed.has(id))&&(!definition.requiresAny.length||definition.requiresAny.some(id=>claimed.has(id)));}
// Only settled acquisitions count. Creating an entity is not acquiring one.
export function acquisitionMetric(kind,origin){
if(kind==='clan'&&['conquest','bend-the-knee'].includes(origin))return 'acquired-clan';
if(kind==='company'&&origin==='purchase')return 'acquired-company';
return null;
}
export function questAwardXP(definition,baseXP){
if(!Number.isSafeInteger(baseXP)||baseXP<0)throw TypeError('Invalid quest XP');
const award=baseXP*(definition.optional?2:1);
if(!Number.isSafeInteger(award))throw TypeError('Invalid quest XP');
return award;
}
// This selects completion records only: it must never fabricate underlying
// gameplay facts or execute unperformed objectives' domain effects.
export function completionByXP(definitions,{earnedXP,thresholdXP,completed=new Set()}){
if(!Number.isSafeInteger(earnedXP)||earnedXP<0||!Number.isSafeInteger(thresholdXP)||thresholdXP<1)throw TypeError('Invalid completion threshold');
if(earnedXP<thresholdXP)return [];
return definitions.filter(d=>!d.optional&&!completed.has(d.id)).map(d=>({definitionId:d.id,reason:'xp-threshold'}));
}

View file

@ -0,0 +1,27 @@
import {randomUUID} from 'node:crypto';
import {QUEST_DEFINITIONS,XP_POLICY} from './progression-definitions.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
export function sixMonthsAfter(timestamp){
const start=new Date(timestamp),day=start.getUTCDate(),target=new Date(timestamp);target.setUTCDate(1);target.setUTCMonth(target.getUTCMonth()+6);
const last=new Date(Date.UTC(target.getUTCFullYear(),target.getUTCMonth()+1,0)).getUTCDate();target.setUTCDate(Math.min(day,last));return target.getTime();
}
// Installation is an ordinary recorded system instrument, not manual data editing.
// Custom configuration is never overwritten by an application restart.
export async function ensureProgressionPolicy(db,keys,{clock=Date.now}={}){
const scopeId='policy:'+XP_POLICY.season+':v'+XP_POLICY.version;
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',scopeId,authorize:async()=>{}});
const key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id);
if(key.status==='used')return {configured:false,replayed:true};
if(!key.code||key.status!=='available')throw Error('Progression policy instrument unavailable');
return keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',code:key.code,targetId:STAFF_OFFICE_ACCOUNT_ID,requestId:grant.id,apply:async(tx,{keyId})=>{
const now=clock(),existing=await tx.first('SELECT * FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[XP_POLICY.season]);
if(!existing){
const active=await tx.query("SELECT season_id FROM jarvis_progression_seasons WHERE state='active' FOR UPDATE");if(active.length)throw Error('A different active season requires an explicit transition');
await tx.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES(?,?,?,?,?,'active')",[XP_POLICY.season,now,sixMonthsAfter(now),XP_POLICY.seasonCap,XP_POLICY.base]);
}
let added=0;for(const d of QUEST_DEFINITIONS){const previous=await tx.first('SELECT definition_id FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[d.id]);if(previous)continue;
await tx.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,?,?,NULL,?,?)',[d.id,1,d.xp,STAFF_OFFICE_ACCOUNT_ID,now]);added++;
}
await tx.query('INSERT INTO jarvis_progression_history(id,account_id,key_id,action,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),STAFF_OFFICE_ACCOUNT_ID,keyId,'policy-configured',JSON.stringify({season:XP_POLICY.season,added,monetaryPayouts:false}),now]);
}});
}

View file

@ -0,0 +1,108 @@
import {createHash,randomUUID} from 'node:crypto';
import {QUEST_DEFINITIONS,questPrerequisites,questAwardXP,xpAtLevel,acquisitionMetric} from './progression-definitions.mjs';
import {creditXP} from './progression-xp-ledger.mjs';
import {lockXPAccount,readActiveXPSeason,saveXPAccount} from './progression-xp-store.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const cap=season=>xpAtLevel(Number(season.level_cap),Number(season.curve_base));
const read=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;};
const deterministicId=text=>{const h=createHash('sha256').update(text).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);};
export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,authorizePlayer,authorizeObservation,verifyAcquisition,resolvePlayer,clock=Date.now}){
if(![authorizePlayer,authorizeObservation,verifyAcquisition,resolvePlayer].every(f=>typeof f==='function'))throw TypeError('Verified quest adapters required');
const types=new Map(definitions.map(d=>[d.id,d])),metrics=new Set(definitions.map(d=>d.metric));
if(types.size!==definitions.length)throw TypeError('Duplicate quest definitions');
const definition=id=>{const d=types.get(id);if(!d)throw Error('Unknown quest definition');return d;};
async function player(actor,store=db){if(!uuid(actor?.id)||!await authorizePlayer(actor,store))throw Error('Current player identity required');}
async function claimed(store,id,season){return new Set((await store.query('SELECT s.definition_id FROM jarvis_quest_states s JOIN jarvis_quest_claims c ON c.key_id=s.key_id WHERE s.account_id=? AND s.season_id=?',[id,season])).map(r=>r.definition_id));}
async function eligibility(store,id,d,season,state){
const completed=await claimed(store,id,season.season_id),fact=await read(store,'SELECT quantity FROM jarvis_progression_facts WHERE account_id=? AND season_id=? AND metric=?',[id,season.season_id,d.metric]);
const bypass=!d.optional&&state.effectiveXP>=cap(season),prerequisites=questPrerequisites(d,completed);
return {progress:Number(fact?.quantity||0),ready:bypass||prerequisites&&Number(fact?.quantity||0)>=d.target,prerequisites:bypass||prerequisites,reason:bypass?'xp-threshold':'verified-objective'};
}
async function updateFact(tx,{accountId,season,metric,value}){
const old=await tx.first('SELECT quantity FROM jarvis_progression_facts WHERE account_id=? AND season_id=? AND metric=? FOR UPDATE',[accountId,season.season_id,metric]);
const quantity=Math.max(Number(old?.quantity||0),value);
await tx.query('INSERT INTO jarvis_progression_facts(account_id,season_id,metric,quantity,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE quantity=VALUES(quantity),updated_at=VALUES(updated_at)',[accountId,season.season_id,metric,quantity,clock()]);
const states=await tx.query("SELECT definition_id,key_id FROM jarvis_quest_states WHERE account_id=? AND season_id=? AND state='active' FOR UPDATE",[accountId,season.season_id]);
for(const row of states){const d=definition(row.definition_id);if(d.metric!==metric)continue;const profile=await lockXPAccount(tx,accountId,clock()),eligible=await eligibility(tx,accountId,d,season,profile);
await tx.query('UPDATE jarvis_quest_states SET progress_value=?,state=?,completed_at=? WHERE key_id=?',[Math.min(quantity,d.target),eligible.ready?'completed':'active',eligible.ready?clock():null,row.key_id]);
}
return quantity;
}
const service={
async list(actor){
await player(actor);const now=clock(),seasons=await db.query("SELECT * FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]);
if(!seasons.length)return {state:'season-not-configured',quests:[]};if(seasons.length!==1)throw Error('Season configuration is ambiguous');
const season=seasons[0],row=await read(db,'SELECT * FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]),profile={totalXP:Number(row?.total_xp||0),effectiveXP:Number(row?.effective_xp||0),reserveXP:Number(row?.total_xp||0)-Number(row?.effective_xp||0),level:Number(row?.level_no||1)};
const states=await db.query('SELECT * FROM jarvis_quest_states WHERE account_id=? AND season_id=?',[actor.id,season.season_id]),configs=await db.query('SELECT * FROM jarvis_quest_config'),done=await claimed(db,actor.id,season.season_id),quests=[];
const facts=new Map((await db.query('SELECT metric,quantity FROM jarvis_progression_facts WHERE account_id=? AND season_id=?',[actor.id,season.season_id])).map(f=>[f.metric,Number(f.quantity)]));
for(const d of definitions.filter(d=>d.season===season.season_id)){const state=states.find(s=>s.definition_id===d.id),config=configs.find(c=>c.definition_id===d.id),progress=facts.get(d.metric)||0,bypass=!d.optional&&profile.effectiveXP>=cap(season),prerequisites=bypass||questPrerequisites(d,done),eligible={progress,prerequisites,ready:bypass||prerequisites&&progress>=d.target},configured=Number.isSafeInteger(config?.xp)&&config.xp>=0;
quests.push({id:d.id,title:d.title,branch:d.branch,metric:d.metric,requires:d.requires,optional:!!d.optional,target:d.target,progress:Math.min(eligible.progress,d.target),state:done.has(d.id)?'claimed':eligible.ready?'completed':state?.state||'not-started',keyId:state?.key_id||null,canStart:eligible.prerequisites&&!done.has(d.id),canClaim:eligible.ready&&configured&&!done.has(d.id),revision:config?Number(config.revision):null,xp:configured?questAwardXP(d,config.xp):null,rewardConfigured:configured});
}
return {state:'active',season:{id:season.season_id,startsAt:Number(season.starts_at),endsAt:Number(season.ends_at),levelCap:Number(season.level_cap)},profile,quests};
},
async start(actor,{definitionId}){
const d=definition(definitionId);await player(actor);
return keys.issue({accountId:actor.id,keyType:'quest',scopeId:d.season+':'+d.id,authorize:async(tx,{keyId})=>{
await player(actor,tx);const state=await lockXPAccount(tx,actor.id,clock()),season=await readActiveXPSeason(tx,clock(),d.season),prior=await tx.first('SELECT key_id FROM jarvis_quest_states WHERE account_id=? AND definition_id=? AND season_id=? FOR UPDATE',[actor.id,d.id,season.season_id]);if(prior)return;
const e=await eligibility(tx,actor.id,d,season,state);if(!e.prerequisites)throw Error('Quest prerequisites are not completed');
await tx.query('INSERT INTO jarvis_quest_states(key_id,account_id,definition_id,season_id,state,progress_value,revision,started_at,completed_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,actor.id,d.id,season.season_id,e.ready?'completed':'active',Math.min(e.progress,d.target),d.revision,clock(),e.ready?clock():null]);
}});
},
async observe(actor,input){
const {accountId,seasonId,metric,value,eventId,source}=input||{};
if(!uuid(accountId)||!metrics.has(metric)||metric.startsWith('acquired-')||!Number.isSafeInteger(value)||value<0||typeof eventId!=='string'||eventId.length<1||eventId.length>160||typeof source!=='string'||source.length<1||source.length>32)throw TypeError('Invalid verified quest observation');
const fingerprint=digest([accountId,seasonId,metric,value,source]);
return db.transaction(async tx=>{
if(!await authorizeObservation(actor,input,tx))throw Error('Trusted observation authority required');
await lockXPAccount(tx,accountId,clock());const season=await readActiveXPSeason(tx,clock(),seasonId),prior=await tx.first('SELECT fingerprint FROM jarvis_progression_observations WHERE event_id=? FOR UPDATE',[eventId]);
if(prior){if(prior.fingerprint!==fingerprint)throw Error('Observation reference conflict');return {replayed:true};}
await tx.query('INSERT INTO jarvis_progression_observations(event_id,account_id,season_id,fingerprint,source,created_at) VALUES(?,?,?,?,?,?)',[eventId,accountId,season.season_id,fingerprint,source,clock()]);
return {replayed:false,progress:await updateFact(tx,{accountId,season,metric,value})};
});
},
async recordAcquisition(actor,{accountId,kind,entityId,origin}){
const metric=acquisitionMetric(kind,origin);if(!uuid(accountId)||!uuid(entityId)||!metric)throw TypeError('Only confirmed acquisitions count');
return db.transaction(async tx=>{
if(!await verifyAcquisition(actor,{accountId,kind,entityId,origin},tx))throw Error('Verified deed settlement required');
await lockXPAccount(tx,accountId,clock());const season=await readActiveXPSeason(tx,clock()),prior=await tx.first('SELECT origin FROM jarvis_progression_acquisitions WHERE account_id=? AND entity_kind=? AND entity_id=? FOR UPDATE',[accountId,kind,entityId]);
if(prior)return {replayed:true};
await tx.query('INSERT INTO jarvis_progression_acquisitions(account_id,entity_kind,entity_id,origin,created_at) VALUES(?,?,?,?,?)',[accountId,kind,entityId,origin,clock()]);
const count=await tx.first('SELECT COUNT(*) total FROM jarvis_progression_acquisitions WHERE account_id=? AND entity_kind=?',[accountId,kind]);return {replayed:false,progress:await updateFact(tx,{accountId,season,metric,value:Number(count.total)})};
});
},
async claim(actor,{definitionId,requestId,revision}){
if(!uuid(requestId)||!Number.isSafeInteger(revision)||revision<1)throw TypeError('Review the current quest reward');
await player(actor);const d=definition(definitionId),grant=await service.start(actor,{definitionId}),prior=await read(db,'SELECT request_id,account_id FROM jarvis_quest_claims WHERE key_id=?',[grant.id]);
if(prior){if(prior.account_id!==actor.id)throw Error('Quest claim unavailable');return {keyId:grant.id,replayed:true};}
const key=(await keys.list(actor.id)).find(k=>k.id===grant.id);if(!key?.code)throw Error('Quest instrument is unavailable');
return keys.consume({accountId:actor.id,keyType:'quest',code:key.code,targetId:actor.id,requestId,apply:async(tx,{keyId,scopeId})=>{
await player(actor,tx);const state=await lockXPAccount(tx,actor.id,clock()),season=await readActiveXPSeason(tx,clock(),d.season),e=await eligibility(tx,actor.id,d,season,state);
if(scopeId!==d.season+':'+d.id||!e.ready)throw Error('Quest objective is not complete');
const config=await tx.first('SELECT * FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[d.id]);
if(!config||!Number.isSafeInteger(config.xp)||config.xp<0||Number(config.revision)!==revision)throw Error('Quest reward changed or is not configured');
const xp=questAwardXP(d,config.xp),reward=config.reward_json?JSON.parse(config.reward_json):{};
await tx.query('INSERT INTO jarvis_quest_claims(key_id,request_id,account_id,xp,reward_json,claimed_at) VALUES(?,?,?,?,?,?)',[keyId,requestId,actor.id,xp,JSON.stringify(reward),clock()]);
await saveXPAccount(tx,actor.id,creditXP(state,xp,{capXP:cap(season)}),season,keyId,'quest-claimed',{definitionId:d.id,xp,reason:e.reason},clock());
await tx.query("UPDATE jarvis_quest_states SET state='claimed',completed_at=COALESCE(completed_at,?) WHERE key_id=?",[clock(),keyId]);
if(Object.keys(reward).length)await tx.query("INSERT INTO jarvis_quest_reward_jobs(key_id,account_id,season_id,payload_json,state,created_at) VALUES(?,?,?,?,'queued',?)",[keyId,actor.id,season.season_id,JSON.stringify(reward),clock()]);
}});
},
async completeMandatory(actor){
await player(actor);const view=await service.list(actor);if(view.state!=='active')throw Error('No active quest season');
const season=await read(db,'SELECT * FROM jarvis_progression_seasons WHERE season_id=?',[view.season.id]);if(view.profile.effectiveXP<cap(season))throw Error('XP completion threshold not reached');
let completed=0;for(const quest of view.quests.filter(q=>!q.optional&&q.state!=='claimed')){
if(!quest.rewardConfigured)throw Error('Mandatory reward configuration is incomplete');
await service.claim(actor,{definitionId:quest.id,revision:quest.revision,requestId:deterministicId('automatic:'+actor.id+':'+season.season_id+':'+quest.id)});completed++;
}
return {completed};
},
async processCompletions({accountId=null}={}){
if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account');
const jobs=await db.query("SELECT * FROM jarvis_progression_outbox WHERE purpose='mandatory-completion' AND state='queued'"+(accountId?' AND account_id=?':'')+' ORDER BY created_at,id LIMIT 20',accountId?[accountId]:[]);let completed=0,failed=0;
for(const job of jobs)try{const actor=await resolvePlayer(job.account_id);if(!actor)throw Error('Player unavailable');const view=await service.list(actor);if(view.season?.id!==job.season_id)throw Error('Season is no longer active');await service.completeMandatory(actor);await db.query("UPDATE jarvis_progression_outbox SET state='completed' WHERE id=? AND state='queued'",[job.id]);completed++;}catch{failed++;}
return {completed,failed};
}
};
return Object.freeze(service);
}

View file

@ -0,0 +1,13 @@
// Configurable Alpha XP defaults. No automatic DM issuance: monetary rewards
// require a separately funded, approved reward configuration and delivery adapter.
const XP={
a:[100,100,150,150,250],b:[200,150,200,200,500,1000,2000],
c:[100,250,500,1000,2000,4000,6000,9000],
d:[200,250,300,300,500,1500,2500],e:[250,500,1000,2000,4000,300,500],
f:[150,100,250,500,1000,2000,2500],g:[150,250,400,500,700],
h:[300,350,500,750,1250,2000,2500,3500],i:[300,500,500,1000,1500,2500,5000]
};
export function defaultQuestXP(definition,index){
if(definition.branch==='acquisitions')return definition.metric==='acquired-company'?[750,1750,3500][index]:[1000,3000,6000][index];
const result=XP[definition.branch]?.[index];if(!Number.isSafeInteger(result))throw Error('Missing Alpha reward default');return result;
}

View file

@ -0,0 +1,52 @@
import {createQuestProgression} from './progression-quests.mjs';
import {createXPInstruments} from './progression-xp-instruments.mjs';
import {firstLoginState} from './first-login.mjs';
import {can} from './permissions.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=async()=>false}={}){
const observer=Object.freeze({internal:'progression-source-reader'});
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]);
}
const quests=createQuestProgression(central,keys,{clock,authorizePlayer,resolvePlayer,
authorizeObservation:async actor=>actor===observer,
// 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 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)=>{
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:'web:'+actor.id+':'+season.season_id+':'+metric+':'+quantity,source:'verified-website'});
};
const source=async(name,metrics,work)=>{try{await work();sources.push({name,metrics,state:'available'});}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<p.pid)",[account.uid,Math.floor(Number(season.starts_at)/1000)]);
await save('forum-contributions',count.total);
});
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 wages=await first(bank,"SELECT COUNT(*) total,COALESCE(SUM(o.amount_minor),0) earned FROM pb_orders o JOIN pb_accounts a ON a.id=o.target_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE e.kind='person' AND e.external_key=? AND o.state='posted' AND o.mode='payroll' AND o.posted_at>=?",[actor.id,Number(season.starts_at)]);await save('wage-received',wages.total);await save('earned-minor',wages.earned);
});
return {state:'verified',sources};
}
return Object.freeze({quests,xp,collect});
}

View file

@ -0,0 +1,16 @@
const table=sql=>sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4';
export const PROGRESSION_SCHEMA=Object.freeze([
table(`CREATE TABLE IF NOT EXISTS jarvis_quest_reward_jobs(key_id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,payload_json TEXT NOT NULL,state VARCHAR(24) NOT NULL,created_at BIGINT NOT NULL)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_progression_acquisitions(account_id CHAR(36) NOT NULL,entity_kind VARCHAR(12) NOT NULL,entity_id CHAR(36) NOT NULL,origin VARCHAR(24) NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(account_id,entity_kind,entity_id))`),
table(`CREATE TABLE IF NOT EXISTS jarvis_xp_instruments(key_id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,kind VARCHAR(24) NOT NULL,amount_xp BIGINT NOT NULL,source_reference VARCHAR(96) NOT NULL,source_season VARCHAR(8) NULL,target_season VARCHAR(8) NULL,issuer_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_progression_accounts(account_id CHAR(36) PRIMARY KEY,total_xp BIGINT NOT NULL DEFAULT 0,effective_xp BIGINT NOT NULL DEFAULT 0,level_no INT NOT NULL DEFAULT 1,version INT NOT NULL DEFAULT 1,updated_at BIGINT NOT NULL)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_progression_seasons(season_id VARCHAR(8) PRIMARY KEY,starts_at BIGINT NOT NULL,ends_at BIGINT NOT NULL,level_cap INT NOT NULL,curve_base INT NOT NULL,state VARCHAR(16) NOT NULL,revision INT NOT NULL DEFAULT 1)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_quest_config(definition_id VARCHAR(64) PRIMARY KEY,revision INT NOT NULL,xp INT NULL,reward_json TEXT NULL,updated_by CHAR(36) NOT NULL,updated_at BIGINT NOT NULL)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_quest_states(key_id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,definition_id VARCHAR(64) NOT NULL,season_id VARCHAR(8) NOT NULL,state VARCHAR(16) NOT NULL,progress_value BIGINT NOT NULL DEFAULT 0,revision INT NOT NULL DEFAULT 1,started_at BIGINT NOT NULL,completed_at BIGINT NULL,UNIQUE KEY quest_identity(account_id,definition_id,season_id))`),
table(`CREATE TABLE IF NOT EXISTS jarvis_progression_facts(account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,metric VARCHAR(64) NOT NULL,quantity BIGINT NOT NULL,updated_at BIGINT NOT NULL,PRIMARY KEY(account_id,season_id,metric))`),
table(`CREATE TABLE IF NOT EXISTS jarvis_progression_observations(event_id VARCHAR(160) PRIMARY KEY,account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,fingerprint CHAR(64) NOT NULL,source VARCHAR(32) NOT NULL,created_at BIGINT NOT NULL)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_quest_claims(key_id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,account_id CHAR(36) NOT NULL,xp INT NOT NULL,reward_json TEXT NULL,claimed_at BIGINT NOT NULL)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_progression_history(id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,key_id CHAR(36) NULL,action VARCHAR(32) NOT NULL,details_json TEXT NOT NULL,created_at BIGINT NOT NULL)`),
table(`CREATE TABLE IF NOT EXISTS jarvis_progression_outbox(id CHAR(36) PRIMARY KEY,account_id CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,purpose VARCHAR(32) NOT NULL,payload_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY milestone_once(account_id,season_id,purpose))`)
]);
export async function initializeProgression(db){for(const sql of PROGRESSION_SCHEMA)await db.query(sql);}

View file

@ -0,0 +1,65 @@
import {lockXPAccount as account,readActiveXPSeason as activeSeason,saveXPAccount as save} from './progression-xp-store.mjs';
import {creditXP,transferReservedXP} from './progression-xp-ledger.mjs';
import {xpAtLevel} from './progression-definitions.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const positive=n=>Number.isSafeInteger(n)&&n>0;
const seasonId=v=>/^S\d{2,4}$/.test(v||'');
// Uses the ordinary J.A.R.V.I.S. issue/consume transaction. resolveCase must read
// the authoritative support decision, not browser-provided ticket metadata.
export function createXPInstruments(db,keys,{authorizeIssue,resolveCase,clock=Date.now}){
if(typeof authorizeIssue!=='function'||typeof resolveCase!=='function')throw TypeError('XP authority and support-case adapters required');
async function approved(tx,reference,accountId){const source=await resolveCase(tx,reference);if(!source||source.approved!==true||source.accountId!==accountId||!positive(source.maxXP))throw Error('An approved matching support case is required');return source;}
async function insert(tx,{keyId,accountId,kind,amount,reference,from=null,to=null,issuer,now}){
await tx.query('INSERT INTO jarvis_xp_instruments(key_id,account_id,kind,amount_xp,source_reference,source_season,target_season,issuer_id,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[keyId,accountId,kind,amount,reference,from,to,issuer,now]);
}
return Object.freeze({
async issueCorrection(actor,{accountId,caseReference,amountXP,requestId}){
if(!uuid(actor?.id)||!uuid(accountId)||!uuid(requestId)||!positive(amountXP)||!/^[-a-zA-Z0-9_]{1,48}$/.test(caseReference||''))throw TypeError('Invalid XP correction');
const scopeId='correction:'+caseReference+':'+requestId;
return keys.issue({accountId,keyType:'xp-correction',scopeId,authorize:async(tx,{keyId})=>{
if(!await authorizeIssue(actor,'xp-correction',tx))throw Error('XP correction permission required');
await account(tx,accountId,clock());const source=await approved(tx,caseReference,accountId);
const prior=await tx.first('SELECT p.* FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE k.account_id=? AND k.key_type=? AND k.scope_id=? FOR UPDATE',[accountId,'xp-correction',scopeId]);
if(prior){if(Number(prior.amount_xp)!==amountXP||prior.issuer_id!==actor.id)throw Error('XP issue reference conflict');return;}
const used=await tx.first("SELECT COALESCE(SUM(p.amount_xp),0) total FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE p.account_id=? AND p.kind='correction' AND p.source_reference=? AND k.revoked_at IS NULL",[accountId,caseReference]);
if(amountXP>source.maxXP-Number(used.total))throw Error('XP correction exceeds the uncompensated case amount');
await insert(tx,{keyId,accountId,kind:'correction',amount:amountXP,reference:caseReference,issuer:actor.id,now:clock()});
}});
},
async issueTransfer(actor,{accountId,fromSeason,toSeason}){
if(!uuid(actor?.id)||!uuid(accountId)||!seasonId(fromSeason)||!seasonId(toSeason)||fromSeason===toSeason)throw TypeError('Invalid XP season transfer');
return keys.issue({accountId,keyType:'xp-transfer',scopeId:'transfer:'+fromSeason+':'+toSeason,authorize:async(tx,{keyId})=>{
if(!await authorizeIssue(actor,'xp-transfer',tx))throw Error('XP transfer permission required');
const now=clock(),state=await account(tx,accountId,now),source=await tx.first('SELECT * FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[fromSeason]);
if(!source||source.state!=='closed'||Number(source.ends_at)>now)throw Error('Source season is not sealed');
const target=await activeSeason(tx,now,toSeason);
const between=await tx.first('SELECT COUNT(*) total FROM jarvis_progression_seasons WHERE starts_at>=? AND ends_at<=?',[Number(source.ends_at),Number(target.starts_at)]);
if(Number(source.ends_at)>Number(target.starts_at)||Number(between.total)!==0)throw Error('XP transfers require consecutive seasons');
const prior=await tx.first('SELECT id FROM organisation_keys WHERE account_id=? AND key_type=? AND scope_id=? FOR UPDATE',[accountId,'xp-transfer','transfer:'+fromSeason+':'+toSeason]);if(prior)return;
if(!positive(state.reserveXP))throw Error('No reserved XP is available');
await insert(tx,{keyId,accountId,kind:'transfer',amount:state.reserveXP,reference:'season:'+fromSeason,from:fromSeason,to:toSeason,issuer:actor.id,now});
}});
},
async redeem(user,{code,keyType,requestId}){
if(!uuid(user?.id)||!['xp-correction','xp-transfer'].includes(keyType))throw TypeError('Invalid XP redemption');
return keys.consume({accountId:user.id,keyType,code,targetId:user.id,requestId,apply:async(tx,{keyId})=>{
if(typeof user.revalidate==='function'&&(await user.revalidate())?.id!==user.id)throw Error('XP redemption session changed');
const now=clock(),state=await account(tx,user.id,now),instrument=await tx.first('SELECT * FROM jarvis_xp_instruments WHERE key_id=? AND account_id=? FOR UPDATE',[keyId,user.id]);
if(!instrument||!positive(Number(instrument.amount_xp)))throw Error('XP instrument unavailable');
const season=await activeSeason(tx,now,keyType==='xp-transfer'?instrument.target_season:null),capXP=xpAtLevel(Number(season.level_cap),Number(season.curve_base));let next;
if(keyType==='xp-correction'){
if(instrument.kind!=='correction')throw Error('XP instrument purpose mismatch');
const source=await approved(tx,instrument.source_reference,user.id),used=await tx.first("SELECT COALESCE(SUM(p.amount_xp),0) total FROM jarvis_xp_instruments p JOIN organisation_keys k ON k.id=p.key_id WHERE p.account_id=? AND p.kind='correction' AND p.source_reference=? AND k.used_at IS NOT NULL",[user.id,instrument.source_reference]);
if(Number(instrument.amount_xp)>source.maxXP-Number(used.total))throw Error('XP correction approval changed');
next=creditXP(state,Number(instrument.amount_xp),{capXP});
}else{
if(instrument.kind!=='transfer')throw Error('XP instrument purpose mismatch');
const source=await tx.first('SELECT state,ends_at FROM jarvis_progression_seasons WHERE season_id=? FOR UPDATE',[instrument.source_season]);
if(source?.state!=='closed'||Number(source.ends_at)>now)throw Error('Source season is not sealed');
next=transferReservedXP(state,{sealedAmount:Number(instrument.amount_xp),capXP});
}
await save(tx,user.id,next,season,keyId,keyType,{sourceReference:instrument.source_reference,amountXP:Number(instrument.amount_xp)},now);
}});
}
});
}

View file

@ -0,0 +1,19 @@
// Account arithmetic shared by quest rewards, approved corrections and transfer
// instruments. Domain callers own authorisation, once-only keys and transactions.
const whole=n=>Number.isSafeInteger(n)&&n>=0;
function check(state){
if(!state||![state.totalXP,state.effectiveXP,state.reserveXP].every(whole)||state.totalXP!==state.effectiveXP+state.reserveXP)throw TypeError('Invalid XP account');
}
export function creditXP(state,amount,{capXP}){
check(state);if(!whole(amount)||!whole(capXP)||state.effectiveXP>capXP)throw TypeError('Invalid XP credit');
const totalXP=state.totalXP+amount;if(!whole(totalXP))throw TypeError('XP account overflow');
const available=Math.min(amount,capXP-state.effectiveXP);
return {...state,totalXP,effectiveXP:state.effectiveXP+available,reserveXP:state.reserveXP+amount-available};
}
export function transferReservedXP(state,{sealedAmount,capXP}){
check(state);
if(!whole(sealedAmount)||sealedAmount>state.reserveXP||!whole(capXP)||capXP<state.effectiveXP)throw TypeError('XP transfer does not match sealed reserve');
const released=Math.min(sealedAmount,capXP-state.effectiveXP);
// A rollover moves existing XP; it never creates lifetime XP a second time.
return {...state,effectiveXP:state.effectiveXP+released,reserveXP:state.reserveXP-released};
}

View file

@ -0,0 +1,20 @@
import {randomUUID} from 'node:crypto';
import {levelForXP} from './progression-definitions.mjs';
export async function lockXPAccount(tx,id,now){
await tx.query('INSERT INTO jarvis_progression_accounts(account_id,total_xp,effective_xp,level_no,version,updated_at) VALUES(?,0,0,1,1,?) ON DUPLICATE KEY UPDATE account_id=VALUES(account_id)',[id,now]);
const row=await tx.first('SELECT * FROM jarvis_progression_accounts WHERE account_id=? FOR UPDATE',[id]);
return {...row,totalXP:Number(row.total_xp),effectiveXP:Number(row.effective_xp),reserveXP:Number(row.total_xp)-Number(row.effective_xp)};
}
export async function readActiveXPSeason(tx,now,expected=null){
const rows=await tx.query("SELECT * FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>? FOR UPDATE",[now,now]);
if(rows.length!==1||expected&&rows[0].season_id!==expected)throw Error('A single matching active season is required');return rows[0];
}
export async function saveXPAccount(tx,id,state,season,keyId,action,details,now){
const level=levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)});
await tx.query('UPDATE jarvis_progression_accounts SET total_xp=?,effective_xp=?,level_no=?,version=version+1,updated_at=? WHERE account_id=?',[state.totalXP,state.effectiveXP,level,now,id]);
await tx.query('INSERT INTO jarvis_progression_history(id,account_id,key_id,action,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,keyId,action,JSON.stringify({...details,seasonId:season.season_id,level,totalXP:state.totalXP,effectiveXP:state.effectiveXP,reserveXP:state.reserveXP}),now]);
const purposes=[];
for(const milestone of [Math.max(1,Math.floor(Number(season.level_cap)/2)),Number(season.level_cap)])if(Number(state.level_no)<milestone&&level>=milestone)purposes.push(['level-'+milestone,{level:milestone,sourceKey:keyId}]);
if(level>=Number(season.level_cap))purposes.push(['mandatory-completion',{sourceKey:keyId}]);
for(const [purpose,payload]of purposes)await tx.query("INSERT INTO jarvis_progression_outbox(id,account_id,season_id,purpose,payload_json,state,created_at) VALUES(?,?,?,?,?,'queued',?) ON DUPLICATE KEY UPDATE purpose=VALUES(purpose)",[randomUUID(),id,season.season_id,purpose,JSON.stringify(payload),now]);
}