MC/website/node/war-military-affiliations.mjs
2026-11-27 23:43:05 +00:00

86 lines
8.2 KiB
JavaScript

import {createHash} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {attachWarSupermother,endWarSupermother} from './war-affiliations.mjs';
import {readGameNativeState} from './game-native-state.mjs';
import {boardReadStore} from './board-deed-source.mjs';
const ACTION='war.military-affiliation';
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const stableId=value=>{const h=hash(value);return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);};
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const fail=message=>{throw Object.assign(Error(message),{status:409});};
export function planMilitaryAffiliations(state){
const memberships=new Map(),reviewOffices=[],reviewOwners=[],plans=[];
for(const office of state.offices){
if(office.militaryReview){reviewOffices.push(office.officeKey);continue;}
if(office.lifecycle!=='active'||!uuid(office.source?.termId)||!uuid(office.source?.keyId))continue;
for(const member of office.members||[]){if(!uuid(member.uuid)||typeof member.binding!=='string')continue;const entries=memberships.get(member.uuid)||[];entries.push({office,member});memberships.set(member.uuid,entries);}
}
for(const [owner,entries]of memberships){
const emperor=entries.find(e=>e.office.officeKey==='emperor'&&e.office.leader?.uuid===owner);
if(emperor)memberships.set(owner,[emperor]);
else if(new Set(entries.map(e=>e.office.officeKey)).size>1)reviewOwners.push(owner);
}
for(const [kind,records]of [['clan',state.clans],['company',state.companies]])for(const child of records){
if(child.lifecycle!=='active'||child.protected||child.hidden||!uuid(child.ownerUuid)||reviewOwners.includes(child.ownerUuid))continue;
// Appointments bind an owner's existing mother, never take a client's mother
// from another owner or replace a permanent purchase/conquest relationship.
if(child.parent&&(child.parent.kind!=='politics'||child.parent.origin!=='war'))continue;
const matches=memberships.get(child.ownerUuid);if(!matches?.length)continue;
const {office,member}=matches[0],source={officeKey:office.officeKey,officeId:office.id,charterKeyId:office.source.keyId,termId:office.source.termId,binding:member.binding,childKind:kind,childId:child.id,ownerUuid:child.ownerUuid};
const operationId=stableId(['military-affiliation',source]);plans.push({operationId,...source});
}
return {plans,reviewOffices,reviewOwners,reviewChildren:(state.review||[]).map(r=>r.kind+':'+r.id)};
}
// No browser mutation route. The existing scheduler invokes one verified,
// scoped parent-link key for an appointment or its expiry. No ownership or bank
// account is replaced and no timer is added to a Minecraft server.
export function createMilitaryAffiliations(db,keys,{clock=Date.now,readAssignments=null,lockAuthority=null}={}){
if(!keys)throw TypeError('Organisation key service required');
const read=readAssignments||(async tx=>{const reader=boardReadStore(tx||db,db);reader.readSnapshot=undefined;return planMilitaryAffiliations(await readGameNativeState(reader,{clock}));});
const first=(store,sql,args=[])=>store.first?store.first(sql,args):store.prepare(sql).bind(...args).first();
const load=(store,requestId)=>first(store,'SELECT * FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[requestId,ACTION]);
const lock=lockAuthority||(async(tx,source,action)=>{
const term=await tx.first('SELECT id,outcome,starts_at,expires_at FROM political_office_terms WHERE id=? FOR UPDATE',[source.termId]);
if(!term||action==='attach'&&(term.outcome!=='winner'||Number(term.starts_at)>clock()||Number(term.expires_at)<=clock()))fail('The political source term changed.');
const key=await tx.first('SELECT id,used_at,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[source.charterKeyId]);
if(!key||action==='attach'&&(key.used_at===null||key.revoked_at!==null))fail('The political Royal charter changed.');
});
const uncertain=(state,row)=>state.reviewOffices.includes(row.parent_id)||state.reviewChildren.includes(row.child_kind+':'+row.child_id);
async function execute(action,source){
const operationId=source.operationId,requestId=stableId([ACTION,action,operationId]),scopeId='military-'+action+':'+operationId,fields={action,...source},encoded=JSON.stringify(fields);
const existing=await load(db,requestId);if(existing?.fields_json!==undefined&&existing.fields_json!==encoded)fail('Military instruction reference conflict.');if(existing?.state==='applied')return {state:'applied',replayed:true};
async function verify(tx){
await lock(tx,source,action);
const current=await read(tx);
if(action==='attach'){if(!current.plans.some(p=>JSON.stringify(p)===JSON.stringify(source)))fail('Political appointment or mother deed changed.');}
else{
const row=await tx.first('SELECT * FROM jarvis_war_affiliations WHERE operation_id=? AND child_kind=? AND child_id=? FOR UPDATE',[operationId,source.childKind,source.childId]);
if(!row||row.parent_kind!=='politics'||row.parent_id!==source.officeKey||uncertain(current,row)||current.reviewOwners.includes(source.ownerUuid)||current.plans.some(p=>p.operationId===operationId))fail('Military expiry requires a current resolved deed.');
}
}
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',scopeId,authorize:async(tx,{keyId})=>{
const prior=await load(tx,requestId);if(prior){if(prior.fields_json!==encoded)fail('Military instruction changed.');if(prior.state!=='applied')await verify(tx);return;}
await verify(tx);await tx.query("INSERT INTO jarvis_generated_instructions VALUES(?,?,?,?,1,?,?,'issued',?)",[keyId,requestId,STAFF_OFFICE_ACCOUNT_ID,ACTION,encoded,JSON.stringify({schema:1,source:fields}),clock()]);
}});
const instruction=await load(db,requestId);if(instruction?.key_id!==grant.id||instruction.fields_json!==encoded)fail('Military system instrument requires review.');if(instruction.state==='applied')return {state:'applied',replayed:true};
const available=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id&&k.status==='available');if(!available?.code)fail('Military system key unavailable.');
await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',code:available.code,targetId:source.childId,requestId,apply:async(tx,{keyId,scopeId:scope})=>{
const row=await load(tx,requestId);if(scope!==scopeId||row?.key_id!==keyId||row.state!=='issued'||row.fields_json!==encoded)fail('Military system instruction changed.');await verify(tx);
const input={operationId,childKind:source.childKind,childId:source.childId,actorId:STAFF_OFFICE_ACCOUNT_ID,now:clock()};
const result=action==='attach'?await attachWarSupermother(tx,{...input,parentKind:'politics',parentId:source.officeKey,keyId,requestId}):await endWarSupermother(tx,input);
await tx.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=?",[JSON.stringify({schema:1,source:fields,receipt:result}),keyId]);
}});
return {state:'applied',replayed:false};
}
return {async drain(){
const desired=await read(),active=await db.query("SELECT * FROM jarvis_war_affiliations WHERE state='active' AND parent_kind='politics' ORDER BY created_at,operation_id LIMIT 1001");if(active.length>1000)fail('Military affiliation register requires review.');
let attempted=0,applied=0,failed=0;
for(const row of active){if(attempted>=25)break;if(uncertain(desired,row)||desired.plans.some(p=>p.operationId===row.operation_id))continue;
const issued=await first(db,'SELECT fields_json FROM jarvis_generated_instructions WHERE key_id=? AND action_id=?',[row.key_id,ACTION]);if(!issued)continue;const {action,...source}=JSON.parse(issued.fields_json);if(action!=='attach'||desired.reviewOwners.includes(source.ownerUuid))continue;
attempted++;try{await execute('end',source);applied++;}catch{failed++;}
}
for(const plan of desired.plans){if(attempted>=25)break;if(active.some(r=>r.operation_id===plan.operationId))continue;attempted++;try{const result=await execute('attach',plan);if(!result.replayed)applied++;}catch{failed++;}}
return {attempted,applied,failed,review:desired.reviewOffices.length+desired.reviewOwners.length};
}};
}