MC/website/node/rebellion-quests.mjs
2026-11-27 23:43:05 +00:00

160 lines
29 KiB
JavaScript

import {politicalOfficeId} from './political-office-charters.mjs';
import {setEntityParent,entityParent,entityControllers} from './entity-relations.mjs';
import {createHash} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {PUBLIC_OFFICES} from './public-government.mjs';
import {officeDeedFor} from './political-appointments.mjs';
import {currentNaib} from './naib-membership.mjs';
import {rebellionQuest} from './rebellion-quest-policy.mjs';
import {transferOfficeDeed} from './office-deed-transfer.mjs';
import {polProgressionStore} from './progression-pol.mjs';
import {lockXPAccount,readActiveXPSeason,saveXPAccount} from './progression-xp-store.mjs';
import {creditXP} from './progression-xp-ledger.mjs';
const DECLARE='politics.rebellion',CAPTURE='clan.homeblock-victory';
export const REBELLION_COOLDOWN_MS=15*86400000;
export const ORDINARY_REBELLION_CYCLE='00000000-0000-4000-8000-000000000000';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const proofFields=['confirmed','source','mode','outcome','eventId','questKeyId','attackerClanId','defenderClanId','homeBlockId','worldUuid','winnerUuid','sourceTermId','declaredAt','capturedAt'];
const canonicalProof=v=>v&&Object.fromEntries(proofFields.map(k=>[k,v[k]]));
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const first=async(db,sql,args=[])=>db.first?db.first(sql,args):(await db.query(sql,args))[0]||null;
const reject=(message,status=409)=>{throw Object.assign(Error(message),{status});};
export const REBELLION_REWARD_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_rebellion_rewards(clan_id CHAR(36) NOT NULL,office_key VARCHAR(32) NOT NULL,season_id VARCHAR(8) NOT NULL,challenge_key_id CHAR(36) NOT NULL DEFAULT \'00000000-0000-4000-8000-000000000000\',bonus_marker VARCHAR(32) NULL UNIQUE,quest_key_id CHAR(36) NOT NULL UNIQUE,winner_id CHAR(36) NOT NULL,xp INTEGER NOT NULL,amount_minor BIGINT NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(clan_id,office_key,season_id,challenge_key_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4';
export async function initializeRebellionRewards(db){
await db.query(REBELLION_REWARD_SCHEMA);if(db.sqlite)return;
const columns=await db.query('SHOW COLUMNS FROM jarvis_rebellion_rewards'),names=new Set(columns.map(c=>c.Field));
for(const [name,definition]of [['challenge_key_id',"CHAR(36) NOT NULL DEFAULT '00000000-0000-4000-8000-000000000000'"],['bonus_marker','VARCHAR(32) NULL']])if(!names.has(name)){try{await db.query('ALTER TABLE jarvis_rebellion_rewards ADD COLUMN '+name+' '+definition);}catch(error){if(error.code!=='ER_DUP_FIELDNAME')throw error;}}
const indexes=await db.query('SHOW INDEX FROM jarvis_rebellion_rewards');if(indexes.filter(i=>i.Key_name==='PRIMARY').length===3)await db.query('ALTER TABLE jarvis_rebellion_rewards DROP PRIMARY KEY, ADD PRIMARY KEY(clan_id,office_key,season_id,challenge_key_id)');
if(!indexes.some(i=>i.Column_name==='bonus_marker')){try{await db.query('ALTER TABLE jarvis_rebellion_rewards ADD UNIQUE KEY rebellion_first_success(bonus_marker)');}catch(error){if(error.code!=='ER_DUP_KEYNAME')throw error;}}
}
export function createRebellionQuests(central,keys,{clock=Date.now,authorizeProducer=async()=>false,resolveVictory=async()=>null}={}){
async function leader(db,actor,clanId){
if(!uuid(actor?.id)||!uuid(clanId))reject('Choose your clan.',400);
const row=await first(db,"SELECT c.id,c.name,c.owner_id,c.home_world,d.parent_clan_id,d.version AS deed_version,l.minecraft_uuid,i.institution_key FROM site_clans c JOIN site_clan_deeds d ON d.clan_id=c.id JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' JOIN site_accounts a ON a.id=m.user_id JOIN site_game_links l ON l.user_id=m.user_id AND LOWER(l.minecraft_uuid)=LOWER(m.minecraft_uuid) LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.id=? AND c.owner_id=? AND c.active=1 AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','system_account','memorial')",[clanId,actor.id]);
if(!row||row.institution_key||!uuid(row.minecraft_uuid))reject('The current ordinary clan leader and linked identity are required.',403);if(row.parent_clan_id||await entityParent(db,'clan',clanId))reject('Political decisions belong to the mother organisation.',403);return row;
}
async function previousRebellion(db,clanId){return first(db,"SELECT i.key_id,i.created_at FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.action_id=? AND k.key_type='quest' AND JSON_EXTRACT(i.fields_json,'$.clanId')=? ORDER BY i.created_at DESC LIMIT 1",[DECLARE,clanId]);}
async function target(db,actor,clanId,officeKey){
const office=PUBLIC_OFFICES.find(o=>o.key===officeKey);if(!office)reject('Choose an elected office.',400);if(!office.challengeable)reject('This faith office cannot be taken by rebellion.',403);
const attacker=await leader(db,actor,clanId),now=clock(),term=await officeDeedFor(db,officeKey,now);if(term.user_id===actor.id)reject('You already hold this office.');
const defender=await first(db,"SELECT c.id,c.name FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id AND m.clan_role='owner' LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.owner_id=? AND c.active=1 AND i.institution_key IS NULL",[term.user_id]);if(!defender||defender.id===clanId)reject('The incumbent has no eligible main-clan Home Block.');
const choice=await first(db,'SELECT faction FROM site_character_choices WHERE user_id=? AND LOWER(minecraft_uuid)=?',[actor.id,attacker.minecraft_uuid.toLowerCase()]);
if(office.kind==='house'&&choice?.faction!==office.faction||['bene','guild'].includes(office.kind)&&choice?.faction!==office.faction)reject('The clan and political alignment do not match this office.',403);
if(office.kind==='naib_chair'&&!await currentNaib(db,actor.id,{lock:true}))reject('A current sietch deed is required for this office.',403);
const defenderChoice=await first(db,'SELECT faction FROM site_character_choices WHERE user_id=? AND LOWER(minecraft_uuid)=?',[term.user_id,String(term.player_uuid||'').toLowerCase()]);let counterChallengeOf=null,rewardMultiplier=1,chainRoot=null,originalHouseFaction=defenderChoice?.faction||null;
if(officeKey==='emperor'){const source=await load(db,term.id,DECLARE);if(source?.state==='applied'){const sourceManifest=JSON.parse(source.manifest_json),previous=sourceManifest.declaration;if(sourceManifest.receipt?.officeTermId===term.id&&PUBLIC_OFFICES.some(o=>o.kind==='house'&&o.faction===choice?.faction)&&(choice.faction!==previous.houseFaction||clanId===previous.defenderClanId||choice.faction===previous.originalHouseFaction)){counterChallengeOf=source.key_id;rewardMultiplier=2;chainRoot=previous.chainRoot||source.key_id;originalHouseFaction=previous.originalHouseFaction||originalHouseFaction;}}}
const officeId=politicalOfficeId(officeKey),charter=await first(db,"SELECT c.organisation_id FROM political_office_charters c JOIN organisation_keys k ON k.id=c.staff_key_id WHERE c.office_key=? AND c.organisation_id=? AND c.charter_kind='royal' AND k.account_id=? AND k.key_type='staff-office-royal' AND k.scope_id=? AND k.target_id=c.organisation_id AND k.used_at IS NOT NULL AND k.revoked_at IS NULL",[officeKey,officeId,STAFF_OFFICE_ACCOUNT_ID,'office:'+officeKey]);if(!charter)reject('The office charter requires verification.');
const registry=await first(db,"SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind='protected' AND organisation_id=?",[officeId]);let snapshot;try{snapshot=JSON.parse(registry?.snapshot_json);}catch{}
if(!snapshot||snapshot.organisationId!==officeId||snapshot.simulation===true||!uuid(snapshot.homeBlock?.id)||!uuid(snapshot.homeBlock?.worldUuid))reject('The incumbent Home Block is not registered.');
const rebelRegistry=await first(db,"SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id=?",[clanId]);let rebel;try{rebel=JSON.parse(rebelRegistry?.snapshot_json);}catch{}
if(!rebel||rebel.organisationId!==clanId||rebel.simulation===true||!uuid(rebel.homeBlock?.id)||!uuid(rebel.homeBlock?.worldUuid))reject('Your clan Home Block is not registered.');
return {officeKey,houseFaction:choice?.faction||null,counterChallengeOf,rewardMultiplier,chainRoot,originalHouseFaction,sourceTermId:term.id,incumbentId:term.user_id,incumbentUuid:term.player_uuid?.toLowerCase(),rebelDeedVersion:Number(attacker.deed_version),rebelHomeBlockId:rebel.homeBlock.id,rebelWorldUuid:rebel.homeBlock.worldUuid,rebelHomeBlockSource:rebel.source,attackerClanId:clanId,attackerName:attacker.name,winnerId:actor.id,winnerUuid:attacker.minecraft_uuid.toLowerCase(),defenderClanId:defender.id,defenderName:office.scope,defenderClanName:defender.name,defenderOfficeId:officeId,homeBlockKind:'protected',homeBlockId:snapshot.homeBlock.id,worldUuid:snapshot.homeBlock.worldUuid,homeBlockRevision:Number(registry.revision),homeBlockSource:snapshot.source,expiresAt:Number(term.expires_at)};
}
const load=(db,keyId,action)=>first(db,'SELECT i.*,k.key_type,k.account_id AS key_owner,k.scope_id,k.used_at,k.revoked_at FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.key_id=? AND i.action_id=?',[keyId,action]);
const project=row=>{const m=JSON.parse(row.manifest_json);return {keyId:row.key_id,state:row.state,...m.declaration,receipt:m.receipt||null,pendingDefeat:m.pendingDefeat||null,quest:{...rebellionQuest(m.declaration.officeKey,{multiplier:m.declaration.rewardMultiplier||1,counterChallengeOf:m.declaration.counterChallengeOf}),executionRequirements:m.declaration.executionRequirements||rebellionQuest(m.declaration.officeKey).executionRequirements}};};
async function insert(db,{keyId,requestId,accountId,action,fields,manifest,state}){await db.query('INSERT INTO jarvis_generated_instructions(key_id,request_id,account_id,action_id,template_version,fields_json,manifest_json,state,created_at) VALUES(?,?,?,?,1,?,?,?,?)',[keyId,requestId,accountId,action,JSON.stringify(fields),JSON.stringify(manifest),state,clock()]);}
function checkProof(proof,declaration,questKeyId,eventId){if(!PUBLIC_OFFICES.some(o=>o.key===declaration.officeKey&&o.challengeable))reject('This faith office cannot be taken by rebellion.',403);
const defeated=proof?.outcome==='defender-victory';if(proof?.outcome!==undefined&&!['attacker-victory','defender-victory'].includes(proof.outcome))reject('Unknown rebellion outcome.');const home=defeated?declaration.rebelHomeBlockId:declaration.homeBlockId,world=defeated?declaration.rebelWorldUuid:declaration.worldUuid,winner=defeated?declaration.incumbentUuid:declaration.winnerUuid;
if(!proof||proof.confirmed!==true||proof.source!=='minecraft'||proof.mode!=='open-rebellion'||proof.eventId!==eventId||proof.questKeyId!==questKeyId||proof.attackerClanId!==declaration.attackerClanId||proof.defenderClanId!==declaration.defenderClanId||proof.homeBlockId!==home||proof.worldUuid!==world||!winner||proof.winnerUuid?.toLowerCase()!==winner||proof.sourceTermId!==declaration.sourceTermId||proof.declaredAt!==declaration.declaredAt||!Number.isSafeInteger(proof.capturedAt)||proof.capturedAt<declaration.declaredAt||proof.capturedAt>clock()||proof.capturedAt>=declaration.expiresAt)reject('A matching verified open-rebellion Home Block victory is required.');
if((defeated?declaration.rebelHomeBlockSource:declaration.homeBlockSource)!=='minecraft')reject('Development Home Blocks cannot verify an ingame victory.');
}
return Object.freeze({
async nativeWars(){
const rows=await central.query("SELECT i.*,k.revoked_at FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.action_id=? AND k.key_type='quest' ORDER BY i.created_at,i.key_id LIMIT 501",[DECLARE]);
if(rows.length>500)throw Error('Native rebellion inventory exceeds supported batch');
const wars=[];
for(const row of rows){
const d=JSON.parse(row.manifest_json).declaration;if(!d)throw Error('Rebellion key data requires review');
let active=row.revoked_at==null&&row.state==='issued'&&Number(d.expiresAt)>clock();
if(active)try{
const current=await target(central,{id:d.winnerId},d.attackerClanId,d.officeKey);
active=current.sourceTermId===d.sourceTermId&&current.homeBlockId===d.homeBlockId&&current.rebelHomeBlockId===d.rebelHomeBlockId&&current.winnerUuid===d.winnerUuid&&current.incumbentUuid===d.incumbentUuid&&current.defenderClanId===d.defenderClanId&&current.rebelDeedVersion===d.rebelDeedVersion;
}catch(error){if(!error.status)throw error;active=false;}
wars.push({keyId:row.key_id,state:row.state,attackerId:d.attackerClanId,defenderId:d.defenderClanId,declaredAt:d.declaredAt,expiresAt:d.expiresAt,active});
}
return wars;
},
async rewardPolicy(){return {firstSuccessBonusAvailable:!await first(central,'SELECT quest_key_id FROM jarvis_rebellion_rewards LIMIT 1')};},
async declare(actor,input){
if(!input||Object.keys(input).some(k=>!['clanId','officeKey','expectedTermId','expectedHomeBlockId','requestId','confirmed'].includes(k))||!uuid(input.requestId)||!uuid(input.expectedTermId)||!uuid(input.expectedHomeBlockId)||input.confirmed!==true)reject('Confirm the rebellion decision.',400);
const season=await readActiveXPSeason(polProgressionStore(central),clock());
const fields={clanId:input.clanId,officeKey:input.officeKey,expectedTermId:input.expectedTermId,expectedHomeBlockId:input.expectedHomeBlockId},scope=season.season_id+':REBELLION_'+input.requestId;
const grant=await keys.issue({accountId:actor.id,keyType:'quest',scopeId:scope,authorize:async(tx,{keyId})=>{
const prior=await tx.first('SELECT i.account_id,i.fields_json,k.scope_id FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.request_id=? AND i.action_id=?',[input.requestId,DECLARE]);if(prior){if(prior.scope_id!==scope||prior.account_id!==actor.id||prior.fields_json!==JSON.stringify(fields))reject('Rebellion reference conflict.');return;}
await tx.first('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[input.clanId]);const previous=await previousRebellion(tx,input.clanId);if(previous&&Number(previous.created_at)+REBELLION_COOLDOWN_MS>clock())reject('This clan must wait 15 days after its previous rebellion key.');
const declaration={...await target(tx,actor,input.clanId,input.officeKey),seasonId:season.season_id,executionRequirements:rebellionQuest(input.officeKey).executionRequirements,declaredAt:clock()};if(declaration.sourceTermId!==input.expectedTermId||declaration.homeBlockId!==input.expectedHomeBlockId)reject('The incumbent or Home Block changed. Review the current decision.');
const active=await tx.first("SELECT i.key_id FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.action_id=? AND i.account_id=? AND i.state IN ('issued','defeat-recorded') AND k.revoked_at IS NULL AND i.fields_json=?",[DECLARE,actor.id,JSON.stringify(fields)]);if(active)reject('This clan already has an open rebellion quest for that office.');
await insert(tx,{keyId,requestId:input.requestId,accountId:actor.id,action:DECLARE,fields,manifest:{declaration},state:'issued'});
}});const row=await load(central,grant.id,DECLARE);if(!row||row.account_id!==actor.id||row.fields_json!==JSON.stringify(fields))reject('Rebellion reference conflict.');return project(row);
},
async list(actor,clanId){if(!uuid(actor?.id)||!uuid(clanId)||!await first(central,'SELECT c.id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id WHERE c.id=? AND c.active=1 AND m.user_id=?',[clanId,actor.id])&&!(await entityControllers(central,'clan',clanId)).includes(actor.id))reject('Current clan membership or parent deed authority required.',403);const rows=await central.query("SELECT * FROM jarvis_generated_instructions WHERE action_id=? AND JSON_EXTRACT(fields_json,'$.clanId')=? ORDER BY created_at DESC",[DECLARE,clanId]);return rows.map(project);},
async options(actor,clanId){const clan=await leader(central,actor,clanId),choice=await first(central,'SELECT faction FROM site_character_choices WHERE user_id=? AND LOWER(minecraft_uuid)=?',[actor.id,clan.minecraft_uuid.toLowerCase()]),previous=await previousRebellion(central,clanId),cooldownUntil=previous?Number(previous.created_at)+REBELLION_COOLDOWN_MS:null;const result=[];for(const office of PUBLIC_OFFICES){if(!office.challengeable)continue;if(office.kind!=='imperial'&&office.faction!==choice?.faction&&!(office.kind==='naib_chair'&&choice?.faction==='fremen'))continue;try{const snapshot=await target(central,actor,clanId,office.key);result.push({...rebellionQuest(office.key,{multiplier:snapshot.rewardMultiplier,counterChallengeOf:snapshot.counterChallengeOf}),eligible:!cooldownUntil||cooldownUntil<=clock(),cooldownUntil,reason:cooldownUntil>clock()?'This clan must wait 15 days after its previous rebellion key.':null,target:snapshot});}catch(error){if(!error.status)throw error;if(error.message==='You already hold this office.')continue;result.push({...rebellionQuest(office.key),eligible:false,reason:error.message});}}return result;},
async cancel(actor,{questKeyId}){if(!uuid(questKeyId))reject('Choose your rebellion quest.',400);return keys.revoke({accountId:actor.id,keyId:questKeyId,authorize:async(tx,context)=>{const row=await load(tx,questKeyId,DECLARE);if(!row||row.account_id!==actor.id||context.keyType!=='quest'||context.scopeId!==row.scope_id)reject('Rebellion quest unavailable.',403);const d=JSON.parse(row.manifest_json).declaration;if(row.state!=='issued')reject('A verified rebellion result cannot be withdrawn.');await leader(tx,actor,d.attackerClanId);await tx.query("UPDATE jarvis_generated_instructions SET state='cancelled' WHERE key_id=?",[questKeyId]);return true;}});},
async recordCapture(producer,{questKeyId,eventId}){
if(!uuid(questKeyId)||!uuid(eventId)||await authorizeProducer(producer,central)!==true)reject('A registered game key producer is required.',403);
const declaration=await load(central,questKeyId,DECLARE);if(!declaration||declaration.revoked_at!=null)reject('The declared rebellion key is unavailable.');const savedManifest=JSON.parse(declaration.manifest_json),d=savedManifest.declaration;if(declaration.state==='applied'&&savedManifest.receipt?.eventId!==eventId)reject('This rebellion quest is already completed.');
const proof=canonicalProof(await resolveVictory(producer,eventId,central));checkProof(proof,d,questKeyId,eventId);
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'quest-milestone',scopeId:d.seasonId+':HOME_BLOCK_'+eventId,authorize:async(tx,{keyId})=>{
if(await authorizeProducer(producer,tx)!==true)reject('Game producer authority changed.',403);const verified=canonicalProof(await resolveVictory(producer,eventId,tx));checkProof(verified,d,questKeyId,eventId);if(hash(verified)!==hash(proof))reject('Home Block proof changed.');
const prior=await tx.first('SELECT fields_json FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[eventId,CAPTURE]);if(prior){if(prior.fields_json!==JSON.stringify(proof))reject('Home Block event reference conflict.');return;}
await insert(tx,{keyId,requestId:eventId,accountId:STAFF_OFFICE_ACCOUNT_ID,action:CAPTURE,fields:proof,manifest:{questKeyId,proof},state:'recorded'});
if(proof.outcome==='defender-victory'){await tx.first('SELECT id FROM organisation_keys WHERE id=? FOR UPDATE',[questKeyId]);const current=await load(tx,questKeyId,DECLARE);if(!current||current.state!=='issued'||current.revoked_at!=null)reject('This rebellion already has a result.');const m=JSON.parse(current.manifest_json);m.pendingDefeat={evidenceKeyId:keyId,eventId,capturedAt:proof.capturedAt};await tx.query("UPDATE jarvis_generated_instructions SET state='defeat-recorded',manifest_json=? WHERE key_id=?",[JSON.stringify(m),questKeyId]);}
}});const saved=await load(central,grant.id,CAPTURE);if(!saved||saved.fields_json!==JSON.stringify(proof)||JSON.parse(saved.manifest_json).questKeyId!==questKeyId)reject('Home Block event reference conflict.');return {evidenceKeyId:grant.id,eventId,questKeyId};
},
async officeDecisions(actor,{officeKey=null}={}){
if(!uuid(actor?.id))reject('Current office holder required.',403);const owned=[];
for(const office of PUBLIC_OFFICES){if(officeKey&&office.key!==officeKey)continue;try{const term=await officeDeedFor(central,office.key,clock());if(term.user_id===actor.id)owned.push(office.key);}catch(error){if(!error.status)throw error;}}
if(!owned.length)return {decisions:[],hasMore:false};
const rows=await central.query("SELECT * FROM jarvis_generated_instructions WHERE action_id=? AND state='defeat-recorded' AND JSON_EXTRACT(fields_json,'$.officeKey') IN ("+owned.map(()=>'?').join(',')+") ORDER BY created_at,key_id LIMIT 101",[DECLARE,...owned]);
return {decisions:rows.slice(0,100).map(project),hasMore:rows.length>100};
},
async claimDefeatedClan(actor,input){
if(!uuid(actor?.id)||!input||Object.keys(input).some(k=>!['evidenceKeyId','requestId','confirmed'].includes(k))||!uuid(input.evidenceKeyId)||!uuid(input.requestId)||input.confirmed!==true)reject('Confirm the defeated-clan decision.',400);
const evidence=await load(central,input.evidenceKeyId,CAPTURE);if(!evidence||evidence.revoked_at!=null||evidence.key_owner!==STAFF_OFFICE_ACCOUNT_ID||evidence.key_type!=='quest-milestone')reject('Verified defeat evidence required.');
const {questKeyId,proof}=JSON.parse(evidence.manifest_json),row=await load(central,questKeyId,DECLARE);if(!row||proof.outcome!=='defender-victory')reject('Verified defender victory required.');
const manifest=JSON.parse(row.manifest_json),d=manifest.declaration,authority=await officeDeedFor(central,d.officeKey,clock());if(authority.user_id!==actor.id)reject('Only the current office holder may claim the defeated clan.',403);
if(row.state==='defeated')return {...manifest.receipt,replayed:true};
if(row.state!=='defeat-recorded'||manifest.pendingDefeat?.evidenceKeyId!==input.evidenceKeyId)reject('The rebellion defeat decision changed.');
const key=(await keys.list(row.account_id)).find(k=>k.id===questKeyId);if(key?.status!=='available')reject('The rebellion quest key is unavailable.');
await keys.consume({accountId:row.account_id,keyType:'quest',code:key.code,targetId:row.account_id,requestId:input.requestId,apply:async(tx,{keyId,scopeId})=>{
const currentOffice=await officeDeedFor(tx,d.officeKey,clock());if(currentOffice.user_id!==actor.id||scopeId!==row.scope_id)reject('Current office authority changed.',403);
const officeBlock=await tx.first("SELECT snapshot_json FROM site_claim_registry WHERE organisation_kind='protected' AND organisation_id=? FOR UPDATE",[d.defenderOfficeId]);let currentBlock;try{currentBlock=JSON.parse(officeBlock?.snapshot_json).homeBlock;}catch{}if(!currentBlock||currentBlock.id!==d.homeBlockId)reject('The office Home Block is not registered or changed.');
await tx.first('SELECT id FROM organisation_keys WHERE id=? FOR UPDATE',[input.evidenceKeyId]);const currentEvidence=await load(tx,input.evidenceKeyId,CAPTURE);
if(!currentEvidence||currentEvidence.revoked_at!=null||currentEvidence.manifest_json!==evidence.manifest_json||currentEvidence.fields_json!==JSON.stringify(proof))reject('The defeat evidence changed or was revoked.');
const locked=await load(tx,keyId,DECLARE);if(!locked||locked.state!=='defeat-recorded'||locked.manifest_json!==row.manifest_json)reject('The rebellion defeat decision changed.');checkProof(proof,d,keyId,proof.eventId);
await tx.first('SELECT id FROM jarvis_entity_relation_guard WHERE id=1 FOR UPDATE');
const clan=await tx.first('SELECT owner_id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[d.attackerClanId]),deed=await tx.first('SELECT version FROM site_clan_deeds WHERE clan_id=? FOR UPDATE',[d.attackerClanId]);
if(clan?.owner_id!==d.winnerId||Number(deed?.version)!==d.rebelDeedVersion)reject('The defeated clan deed changed. Review is required.');
await leader(tx,{id:d.winnerId},d.attackerClanId);
await setEntityParent(tx,{childKind:'clan',childId:d.attackerClanId,parentKind:'politics',parentId:d.officeKey,origin:'conquest',keyId,requestId:input.requestId,actorId:actor.id,now:clock()});
manifest.receipt={questKeyId:keyId,evidenceKeyId:input.evidenceKeyId,eventId:proof.eventId,outcome:'defender-victory',clanId:d.attackerClanId,officeKey:d.officeKey,controllingOffice:d.officeKey,officeTermId:currentOffice.id,actorId:actor.id,rewardState:'not-applicable',reputationXP:0,amountMinor:0,completedAt:clock()};
await tx.query("UPDATE jarvis_generated_instructions SET state='defeated',manifest_json=? WHERE key_id=?",[JSON.stringify(manifest),keyId]);
}});return JSON.parse((await load(central,questKeyId,DECLARE)).manifest_json).receipt;
},
async applyCapture(producer,{evidenceKeyId}){
if(!uuid(evidenceKeyId)||await authorizeProducer(producer,central)!==true)reject('A registered game key consumer is required.',403);
const evidence=await load(central,evidenceKeyId,CAPTURE);if(!evidence||evidence.key_owner!==STAFF_OFFICE_ACCOUNT_ID||evidence.key_type!=='quest-milestone'||evidence.revoked_at!=null)reject('Verified Home Block evidence key required.');
const {questKeyId,proof}=JSON.parse(evidence.manifest_json);if(proof.outcome==='defender-victory')return {questKeyId,evidenceKeyId,state:'awaiting-office-decision'};const row=await load(central,questKeyId,DECLARE);if(!row)reject('The rebellion declaration is unavailable.');const manifest=JSON.parse(row.manifest_json),d=manifest.declaration;
if(row.state==='applied'){if(manifest.receipt?.evidenceKeyId!==evidenceKeyId)reject('Rebellion completion reference conflict.');return {...manifest.receipt,replayed:true};}
const key=(await keys.list(row.account_id)).find(k=>k.id===questKeyId);if(key?.status!=='available')reject('The rebellion quest key is unavailable.');
await keys.consume({accountId:row.account_id,keyType:'quest',code:key.code,targetId:row.account_id,requestId:proof.eventId,apply:async(tx,{keyId,scopeId})=>{
if(await authorizeProducer(producer,tx)!==true||scopeId!==row.scope_id)reject('Game consumer authority changed.',403);
await tx.first('SELECT id FROM organisation_keys WHERE id=? FOR UPDATE',[evidenceKeyId]);const currentEvidence=await load(tx,evidenceKeyId,CAPTURE);if(!currentEvidence||currentEvidence.revoked_at!=null||currentEvidence.key_type!=='quest-milestone'||currentEvidence.key_owner!==STAFF_OFFICE_ACCOUNT_ID||currentEvidence.fields_json!==JSON.stringify(proof)||currentEvidence.manifest_json!==evidence.manifest_json)reject('Home Block evidence changed or was revoked.');
const locked=await load(tx,keyId,DECLARE);if(!locked||locked.state!=='issued'||locked.manifest_json!==row.manifest_json)reject('Rebellion declaration changed.');checkProof(proof,d,keyId,proof.eventId);
const current=await target(tx,{id:d.winnerId},d.attackerClanId,d.officeKey);for(const field of ['sourceTermId','incumbentId','winnerUuid','defenderClanId','homeBlockId','worldUuid'])if(current[field]!==d[field])reject('The rebellion target or clan authority changed.');
const office=await transferOfficeDeed(tx,{termId:keyId,sourceTermId:d.sourceTermId,officeKey:d.officeKey,winnerId:d.winnerId,playerUuid:d.winnerUuid,sourceId:proof.eventId,method:'rebellion',now:clock()});
const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,clock(),d.seasonId),base=rebellionQuest(d.officeKey).reward,cycle=d.counterChallengeOf||ORDINARY_REBELLION_CYCLE;
await tx.query('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',['rebellion:rewards']);await tx.first('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',['rebellion:rewards']);
const previousAward=await tx.first('SELECT quest_key_id FROM jarvis_rebellion_rewards ORDER BY created_at LIMIT 1'),firstBonus=!previousAward,multiplier=(d.rewardMultiplier||1)+(firstBonus?5:0),reward={reputationXP:base.reputationXP*multiplier,amountMinor:base.amountMinor*multiplier};
const prior=await tx.first('SELECT quest_key_id FROM jarvis_rebellion_rewards WHERE clan_id=? AND office_key=? AND season_id=? AND challenge_key_id=? FOR UPDATE',[d.attackerClanId,d.officeKey,season.season_id,cycle]);let rewardState='already-awarded';
if(!prior){const state=await lockXPAccount(pol,d.winnerId,clock());await saveXPAccount(pol,d.winnerId,creditXP(state,reward.reputationXP,{capXP:Number.MAX_SAFE_INTEGER}),season,keyId,'quest-claimed',{definitionId:'REBELLION-'+d.officeKey.toUpperCase(),xp:reward.reputationXP,clanId:d.attackerClanId,sourceKey:evidenceKeyId},clock());await tx.query('INSERT INTO jarvis_rebellion_rewards(clan_id,office_key,season_id,challenge_key_id,bonus_marker,quest_key_id,winner_id,xp,amount_minor,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[d.attackerClanId,d.officeKey,season.season_id,cycle,firstBonus?'inaugural':null,keyId,d.winnerId,reward.reputationXP,reward.amountMinor,clock()]);await pol.query("INSERT INTO jarvis_quest_reward_jobs(key_id,account_id,season_id,payload_json,state,created_at) VALUES(?,?,?,?,'awaiting_funding',?)",[keyId,d.winnerId,season.season_id,JSON.stringify({kind:'clan-rebellion',clanId:d.attackerClanId,officeKey:d.officeKey,amountMinor:reward.amountMinor,evidenceKeyId}),clock()]);rewardState='awaiting-funding';}
manifest.receipt={questKeyId:keyId,evidenceKeyId,eventId:proof.eventId,clanId:d.attackerClanId,winnerId:d.winnerId,winnerUuid:d.winnerUuid,officeKey:d.officeKey,officeTermId:office.termId,expiresAt:office.expiresAt,rewardState,rewardMultiplier:multiplier,firstSuccessBonus:firstBonus,reputationXP:prior?0:reward.reputationXP,amountMinor:prior?0:reward.amountMinor,completedAt:clock()};
await tx.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=?",[JSON.stringify(manifest),keyId]);
}});return JSON.parse((await load(central,questKeyId,DECLARE)).manifest_json).receipt;
}
});
}