Start eligible quest-chain successors after committed claims
This commit is contained in:
parent
b406b337db
commit
ca5acc79b2
7 changed files with 106 additions and 9 deletions
|
|
@ -39,7 +39,7 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api
|
|||
const claim=row.canClaim,path=claim?'/claim':'/start';
|
||||
const id=requestIds.get(row.id)||crypto.randomUUID();requestIds.set(row.id,id);
|
||||
const payload=claim?{definitionId:row.id,revision:row.revision,requestId:id,confirmed:true}:{definitionId:row.id,confirmed:true};
|
||||
try{await api(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});await load();}
|
||||
try{const result=await api(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});if(claim&&typeof result.nextQuestId==='string')selected=result.nextQuestId;await load();}
|
||||
catch(error){if(active){uncertain=true;message(error.message+' Reload the journal to confirm the recorded result.');}}
|
||||
finally{busy=false;if(active)render();}
|
||||
}
|
||||
|
|
|
|||
11
website/docs/QUEST-CHAIN-AUTO-START-20261129.md
Normal file
11
website/docs/QUEST-CHAIN-AUTO-START-20261129.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# Quest-chain automatic start — execution brief, 29 November 2026
|
||||
|
||||
Owner request: upon completing a quest, start the next one automatically. Apply after the authoritative successful reward claim, since existing prerequisite rules require claimed predecessors. Keep current quest/XP history intact.
|
||||
|
||||
Bounded scope: reuse createQuestProgression for Personal and the existing namespace-mapped Reputation engine. During the original claim transaction, queue a deterministic successor-start job only for definitions with direct same-season/same-branch children. After reward commit, use the ordinary authorized start/key issuance API. Never nest keys.issue inside keys.consume or broaden its transaction-store security boundary. Persist failed starts in the existing namespaced progression outbox and retry through completion processing or idempotent claim retry. Require all real predecessors and cooldowns; one eligible successor starts, competing successors remain choices. Do not automatically claim rewards, create objective facts or select unrelated branches. No new schema or plugin/backend replacement.
|
||||
|
||||
Website refresh selects the authoritative returned nextQuestId. Existing authenticated game journal responses forward the same server-owned successor result; clients cannot supply a nextQuestId. Native optional focus support can consume this field in the separate quest UI work without changing reward authority.
|
||||
|
||||
Validation so far:59 local progression/game/POL tests passed, including four new chain cases (unique next/no extra reward, forks/unrelated branches, all-predecessor gating/retry, failed issuance retaining committed reward) and native response/forged-input coverage. Existing uncapped POL test now checks the absence of mandatory-completion jobs and exactly one real claim, rather than incorrectly treating a successor-start job as an automatic reward. No production quest/XP/account records modified by tests.
|
||||
|
||||
Remaining acceptance: canonical Linux CI/build, focused source review, publication, live serving revision and ordinary user confirmation. This work is separate from the current pack incident; no draft code has been deployed. Existing pending gameplay producers are separate work and are not fabricated by automatic starting.
|
||||
|
|
@ -62,7 +62,7 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null,starter=
|
|||
if(questChannel(quest.executionRequirements)==='website')return json({message:'Complete this website quest in your online mission journal.'},409);
|
||||
const result=input.action==='start'?await runtime.quests.start(actor,{definitionId:quest.id}):await runtime.quests.claim(actor,{definitionId:quest.id,revision:input.revision,requestId:input.requestId});
|
||||
if(input.action==='claim')await runtime.quests.processCompletions?.({accountId:actor.id});
|
||||
return json({ok:true,keyId:result.keyId||result.id,replayed:!!result.replayed,created:!!result.created});
|
||||
return json({ok:true,keyId:result.keyId||result.id,replayed:!!result.replayed,created:!!result.created,...(result.autoNext?{autoNext:result.autoNext,nextQuestId:result.autoNext.nextQuestId}:{})});
|
||||
}catch(error){const safe=/^(Quest |Repeatable quest cooldown|Current player identity|Current POL season|Current Personal season|Verified|A matching)/.test(error.message||'');return json({message:safe?error.message:'The quest action was not confirmed. Refresh the journal before retrying.'},409);}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,34 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
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;};
|
||||
const successors=d=>definitions.filter(next=>next.season===d.season&&next.branch===d.branch&&((next.requires||[]).includes(d.id)||(next.requiresAny||[]).includes(d.id)));
|
||||
const nextPurpose=id=>'quest-next:'+digest([id]).slice(0,21);
|
||||
// This runs after reward commit: issuing another key must never nest a key transaction.
|
||||
async function processNextQuests({accountId=null,parentId=null,actor=null}={}){
|
||||
if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account');
|
||||
const args=[],where=["state='queued'",parentId?'purpose=?':"purpose LIKE 'quest-next:%'"];
|
||||
if(parentId)args.push(nextPurpose(parentId));if(accountId){where.push('account_id=?');args.push(accountId);}
|
||||
const jobs=await db.query('SELECT * FROM jarvis_progression_outbox WHERE '+where.join(' AND ')+' ORDER BY created_at,id LIMIT 20',args);
|
||||
const result={started:0,failed:0,pending:false,nextQuestId:null,choices:[]};
|
||||
for(const job of jobs)try{
|
||||
const current=actor?.id===job.account_id?actor:await resolvePlayer(job.account_id);if(!current)throw Error('Player unavailable');
|
||||
const parent=definition(JSON.parse(job.payload_json).definitionId),view=await service.list(current);
|
||||
if(parent.season!==job.season_id||view.season?.id!==job.season_id){await db.query("UPDATE jarvis_progression_outbox SET state='completed' WHERE id=? AND state='queued'",[job.id]);continue;}
|
||||
const done=new Set(view.quests.filter(q=>q.state==='claimed').map(q=>q.id));if(!done.has(parent.id))throw Error('Quest predecessor is not claimed');
|
||||
const children=successors(parent).filter(d=>!done.has(d.id)),existing=children.map(d=>view.quests.find(q=>q.id===d.id)).filter(q=>q?.keyId);
|
||||
let finish=false;
|
||||
if(existing.length){result.nextQuestId=existing.length===1?existing[0].id:null;result.choices=existing.length>1?existing.map(q=>q.id):[];finish=true;}
|
||||
else{
|
||||
const eligible=children.filter(d=>questPrerequisites(d,done)&&view.quests.find(q=>q.id===d.id)?.canStart);
|
||||
if(eligible.length===1){const next=eligible[0],key=await service.start(current,{definitionId:next.id});result.started+=key.created?1:0;result.nextQuestId=next.id;finish=true;}
|
||||
else if(eligible.length>1){result.choices=eligible.map(d=>d.id);finish=true;}
|
||||
else if(!children.length)finish=true;
|
||||
else result.pending=true;
|
||||
}
|
||||
if(finish)await db.query("UPDATE jarvis_progression_outbox SET state='completed' WHERE id=? AND state='queued'",[job.id]);
|
||||
}catch{result.failed++;result.pending=true;}
|
||||
return result;
|
||||
}
|
||||
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=? AND s.definition_id IN ('+placeholders+')',[id,season,...ids])).map(r=>r.definition_id));}
|
||||
async function questCooldown(store,accountId,d){
|
||||
|
|
@ -87,9 +115,9 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
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};}
|
||||
if(prior){if(prior.account_id!==actor.id)throw Error('Quest claim unavailable');let autoNext;try{autoNext=await processNextQuests({accountId:actor.id,parentId:d.id,actor});}catch{autoNext={started:0,failed:1,pending:true,nextQuestId:null,choices:[]};}return {keyId:grant.id,replayed:true,autoNext,nextQuestId:autoNext.nextQuestId};}
|
||||
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})=>{
|
||||
const result=await 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(!await authorizeClaim(actor,d,tx,{eligibility:e,season,state})||scopeId!==d.season+':'+d.id||!e.ready)throw Error('Quest objective is not complete');
|
||||
if(!(await questCooldown(tx,actor.id,d)).available)throw Error('Repeatable quest cooldown is active');
|
||||
|
|
@ -101,7 +129,10 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
await saveXPAccount(tx,actor.id,creditXP(state,xp,{capXP:cap(season)}),season,keyId,'quest-claimed',{definitionId:d.id,xp,reason:e.reason,...(award.basis?{awardBasis:award.basis}:{})},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()]);
|
||||
if(successors(d).length)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)",[deterministicId('quest-next:'+actor.id+':'+d.season+':'+d.id),actor.id,d.season,nextPurpose(d.id),JSON.stringify({definitionId:d.id}),clock()]);
|
||||
}});
|
||||
let autoNext;try{autoNext=await processNextQuests({accountId:actor.id,parentId:d.id,actor});}catch{autoNext={started:0,failed:1,pending:true,nextQuestId:null,choices:[]};}
|
||||
return {...result,autoNext,nextQuestId:autoNext.nextQuestId};
|
||||
},
|
||||
async completeMandatory(actor){
|
||||
await player(actor);const view=await service.list(actor);if(view.state!=='active')throw Error('No active quest season');
|
||||
|
|
@ -124,6 +155,7 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
|
|||
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++;}
|
||||
const next=await processNextQuests({accountId});failed+=next.failed;
|
||||
return {completed,failed};
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -19,3 +19,13 @@ test('the workshop uses the same authenticated player route and rejects caller-s
|
|||
for(const extra of [{xp:1000},{output:{quality:'legendary'}},{consumed:true},{confirmed:false}])assert.equal((await f.request({...input,...extra})).status,400);
|
||||
assert.equal(calls.length,0);assert.equal((await f.request(input)).status,200);assert.equal(calls.length,1);assert.equal(calls[0].uuid,uuid);f.unlink();assert.equal((await f.request(input)).status,403);
|
||||
});
|
||||
|
||||
|
||||
test('native claims receive the authoritative successor without accepting a client-selected next quest',async()=>{
|
||||
const autoNext={started:1,failed:0,pending:false,nextQuestId:'GAME-2',choices:[]};
|
||||
const runtime={collect:async()=>{},quests:{list:async()=>({state:'active',quests:[{id:'GAME-1',executionRequirements:{website:true,minecraft:true}}]}),claim:async()=>({keyId:requestId,autoNext}),processCompletions:async()=>{}}};
|
||||
const f=fixture({personal:runtime});
|
||||
const response=await f.request({action:'claim',definitionId:'GAME-1',requestId,revision:1,confirmed:true});assert.equal(response.status,200);
|
||||
const body=await response.json();assert.equal(body.nextQuestId,'GAME-2');assert.deepEqual(body.autoNext,autoNext);
|
||||
assert.equal((await f.request({action:'claim',definitionId:'GAME-1',requestId,revision:1,confirmed:true,nextQuestId:'forged'})).status,400);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ test('uncapped POL levels preserve exact integer boundaries and never auto-compl
|
|||
await f.db.query('UPDATE jarvis_pol_progression_accounts SET total_xp=200000,effective_xp=200000,level_no=127 WHERE account_id=?',[f.people.Member.id]);
|
||||
await f.pol.claim(f.people.Member,{definitionId:f.d.id,revision:1,requestId:randomUUID()});
|
||||
const view=await f.pol.list(f.people.Member);assert.equal(view.season.levelCap,null);assert.ok(view.profile.level>70);assert.equal(view.profile.reserveXP,0);
|
||||
assert.equal((await f.db.query('SELECT * FROM jarvis_pol_progression_outbox')).length,0);
|
||||
assert.equal((await f.db.query("SELECT * FROM jarvis_pol_progression_outbox WHERE purpose='mandatory-completion'")).length,0);
|
||||
assert.equal((await f.db.query('SELECT * FROM jarvis_pol_quest_claims')).length,1);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,12 +6,13 @@ const definitions=[
|
|||
{id:'S1-TEST-03',title:'Side objective',branch:'i',season:'S01',metric:'side',target:1,requires:[],requiresAny:[],revision:1,optional:true},
|
||||
{id:'S1-TEST-04',title:'Unfinished side objective',branch:'i',season:'S01',metric:'other',target:100,requires:[],requiresAny:[],revision:1,optional:true}
|
||||
];
|
||||
async function fixture(){const f=await companyFixture();await initializeProgression(f.db);
|
||||
async function fixture({questDefinitions=definitions}={}){const f=await companyFixture();await initializeProgression(f.db);
|
||||
await f.db.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES('S01',0,5000,3,25,'active')");
|
||||
for(const [i,d]of definitions.entries())await f.db.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,1,?,NULL,?,0)',[d.id,i===0?50:25,f.people.Owner.id]);
|
||||
const token={},service=createQuestProgression(f.db,f.keys,{definitions,clock:()=>2000,authorizePlayer:async actor=>actor.id===f.people.Member.id,authorizeObservation:async actor=>actor===token,verifyAcquisition:async actor=>actor===token,resolvePlayer:async id=>id===f.people.Member.id?f.people.Member:null});
|
||||
for(const [i,d]of questDefinitions.entries())await f.db.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,1,?,NULL,?,0)',[d.id,i===0?50:25,f.people.Owner.id]);
|
||||
let failStarts=false;const keys={...f.keys,issue:async input=>{if(failStarts&&input.scopeId.endsWith(':S1-TEST-02'))throw Error('Temporary next-key failure');return f.keys.issue(input);}};
|
||||
const token={},service=createQuestProgression(f.db,keys,{definitions:questDefinitions,clock:()=>2000,authorizePlayer:async actor=>actor.id===f.people.Member.id,authorizeObservation:async actor=>actor===token,verifyAcquisition:async actor=>actor===token,resolvePlayer:async id=>id===f.people.Member.id?f.people.Member:null});
|
||||
const observe=(metric,value,eventId=randomUUID())=>service.observe(token,{accountId:f.people.Member.id,seasonId:'S01',metric,value,eventId,source:'verified-test'});
|
||||
return {...f,service,observe};
|
||||
return {...f,service,observe,failNextStarts:value=>{failStarts=value;}};
|
||||
}
|
||||
test('verified quest counters are idempotent, prerequisite-bound and cannot be supplied by players',async()=>{
|
||||
const f=await fixture();try{
|
||||
|
|
@ -43,3 +44,45 @@ test('changed reward revisions fail before XP or reward delivery is committed',a
|
|||
assert.equal((await f.db.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Member.id])).total_xp,0);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
||||
|
||||
test('claim starts the unique direct successor without rewarding or inventing its objective',async()=>{
|
||||
const f=await fixture();try{
|
||||
await f.observe('first',1);const input={definitionId:'S1-TEST-01',revision:1,requestId:randomUUID()};
|
||||
const result=await f.service.claim(f.people.Member,input);assert.equal(result.autoNext.nextQuestId,'S1-TEST-02');assert.equal(result.autoNext.started,1);
|
||||
const next=(await f.service.list(f.people.Member)).quests.find(q=>q.id==='S1-TEST-02');assert.equal(next.state,'active');assert.ok(next.keyId);assert.equal(next.progress,0);
|
||||
assert.equal((await f.db.query('SELECT * FROM jarvis_quest_claims')).length,1);assert.equal((await f.db.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Member.id])).total_xp,50);
|
||||
await f.service.claim(f.people.Member,input);assert.equal((await f.db.query('SELECT * FROM jarvis_quest_states')).length,2);assert.equal((await f.db.query('SELECT * FROM jarvis_quest_claims')).length,1);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
||||
test('quest forks remain choices and unrelated branches are not auto-started',async()=>{
|
||||
const fork={...definitions[1],id:'S1-TEST-05',metric:'fork'},other={...definitions[1],id:'S1-TEST-06',branch:'other',metric:'other-branch'};
|
||||
const f=await fixture({questDefinitions:[...definitions,fork,other]});try{
|
||||
await f.observe('first',1);const result=await f.service.claim(f.people.Member,{definitionId:'S1-TEST-01',revision:1,requestId:randomUUID()});
|
||||
assert.deepEqual(result.autoNext.choices,['S1-TEST-02','S1-TEST-05']);assert.equal(result.autoNext.started,0);
|
||||
for(const id of ['S1-TEST-02','S1-TEST-05','S1-TEST-06'])assert.equal((await f.service.list(f.people.Member)).quests.find(q=>q.id===id).keyId,null);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
||||
test('all predecessors remain required and queued successors retry without replaying rewards',async()=>{
|
||||
const questDefinitions=definitions.map(d=>d.id==='S1-TEST-02'?{...d,requires:['S1-TEST-01','S1-TEST-03']}:d);
|
||||
const f=await fixture({questDefinitions});try{
|
||||
await f.db.query('UPDATE jarvis_progression_seasons SET level_cap=0');await f.observe('first',1);
|
||||
const result=await f.service.claim(f.people.Member,{definitionId:'S1-TEST-01',revision:1,requestId:randomUUID()});assert.equal(result.autoNext.pending,true);
|
||||
assert.equal((await f.service.list(f.people.Member)).quests.find(q=>q.id==='S1-TEST-02').keyId,null);
|
||||
await f.observe('side',1);await f.service.claim(f.people.Member,{definitionId:'S1-TEST-03',revision:1,requestId:randomUUID()});
|
||||
await f.service.processCompletions({accountId:f.people.Member.id});assert.equal((await f.service.list(f.people.Member)).quests.find(q=>q.id==='S1-TEST-02').state,'active');
|
||||
assert.equal((await f.db.query('SELECT * FROM jarvis_quest_claims')).length,2);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
||||
test('next-key issuance failure preserves a successful reward and retries from durable outbox',async()=>{
|
||||
const f=await fixture();try{
|
||||
f.failNextStarts(true);await f.observe('first',1);const result=await f.service.claim(f.people.Member,{definitionId:'S1-TEST-01',revision:1,requestId:randomUUID()});assert.equal(result.autoNext.pending,true);
|
||||
assert.equal((await f.db.query('SELECT * FROM jarvis_quest_claims')).length,1);assert.equal((await f.db.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Member.id])).total_xp,50);
|
||||
f.failNextStarts(false);assert.deepEqual(await f.service.processCompletions({accountId:f.people.Member.id}),{completed:0,failed:0});
|
||||
assert.equal((await f.service.list(f.people.Member)).quests.find(q=>q.id==='S1-TEST-02').state,'active');await f.service.processCompletions({accountId:f.people.Member.id});
|
||||
assert.equal((await f.db.query('SELECT * FROM jarvis_quest_states')).length,2);assert.equal((await f.db.query('SELECT * FROM jarvis_quest_claims')).length,1);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff