Merge pull request 'Connect Landsraad and Caladan consultations to independent institutional votes' (#591) from dev/MC:feature/political-consultations-20261125 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m28s

This commit is contained in:
unimatrix 2026-11-25 03:20:14 +00:00
commit 8136fbcfad
12 changed files with 212 additions and 16 deletions

View file

@ -12,7 +12,7 @@ const related={
const authority={IMP:'Current Emperor deed',ATR:'Current Aerdrecht House office deed',HAR:'Current Harkveen House office deed',COR:'Current Korenholt House office deed',ORD:'Current Oordwijk House office deed',FRE:'Current recognised sietch deed; independent Council',BG:'Current Veiled Concord office deed',NF:'Current Church of Muad’Dib office deed',SG:'Current Spacing Guild office deed',CLD:'Current clan delegate deed'};
function paidDecisionGap(id){
const kind=politicalDecision(id)?.kind,base='Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically. ';
return base+(kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder. Acceptance or refusal requires that same current Royal mandate, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.');
return base+(kind==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder. Acceptance or refusal requires that same current Royal mandate, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.');
}
export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status:houseFaithDecision(d.id)||clanFaithDecision(d.id)||tradeDecision(d.id)||politicalDecision(d.id)||d.id==='IMP-10'||faithBlessing(d.id)?'active':'design',currency:'DM',amountConversion:1,authority:authority[d.office],conditions:'Current unexpired and unrevoked deed, eligible target and all stated effect conditions must be checked by the domain consumer. Level and XP do not grant office authority.',costCooldown:d.cost,effect:d.effect,level:d.level,proposedXP:d.xp,adapter:houseFaithDecision(d.id)?'createHouseFaithLaws / missionaryFaithOutlawed':clanFaithDecision(d.id)?'createClanFaith.offer / reply':tradeDecision(d.id)?'createWorldTradeGovernance / createGameExchangeService / createGuildService':politicalDecision(d.id)?'createPoliticalDecisions':faithBlessing(d.id)?'createFaithBlessings / faithAward':d.id==='IMP-10'?'createImperialPassage / createGuildService':related[d.id]?.adapter||null,gap:houseFaithDecision(d.id)?'Royal House authority and Reputation checked before a sealed 48-hour personal referendum. Seven-day office cooldown survives succession; quorum and strict majority required. Only future invitations and clan-owner acceptance are gated by the latest live law; existing allegiance and earned rewards remain unchanged.':clanFaithDecision(d.id)?'Current faith officer can invite; only the receiving clan’s legal owner can consent. Daily invitation and seven-day clan-change cooldowns are enforced; no membership or rights move.':tradeDecision(d.id)?'Current Royal office and Reputation, immutable creation-world metadata, seven-day cooldown, retained stock and atomic seller-funded bank levy; no default activation.':politicalDecision(d.id)?paidDecisionGap(d.id):faithBlessing(d.id)?'Current faith leader/officer deed, owner-approved clan allegiance, appointment expiry and cooldown are checked centrally. Old Faith and New Faith use the same capped bonus consumer; historical queued rewards retain their claim-time consent proof.':d.id==='IMP-10'?'Native House selection replaces the prior grant; seven-day office cooldown and current Emperor deed are checked centrally.':related[d.id]?.gap||'No complete registered domain consumer implements this exact target, price, cooldown, duration and effect. Execution remains unavailable.',repeatability:'Only after the stated cooldown; no implied stacking or automatic renewal.',executionEnabled:!!houseFaithDecision(d.id)||!!clanFaithDecision(d.id)||!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)})));
export const decisionAudit=id=>DECISION_AUDIT.find(row=>row.id===id)||null;

View file

@ -0,0 +1,14 @@
import {element as el} from './cp-v2-page-template.mjs';
import {createUserAPI} from './cp-v2-user-api.mjs';
export function mountPoliticalConsultations(host,{fetcher=fetch}={}){
const root=el('section',undefined,'cp-political-agreement-inbox'),heading=el('h3','Council resolutions'),status=el('p','Reading institutional consultations…'),list=el('div'),refresh=el('button','Refresh consultations'),api=createUserAPI(fetcher);refresh.type='button';status.setAttribute('role','status');root.append(heading,status,list,refresh);host.append(root);let busy=false;
async function load(){if(busy)return;busy=true;refresh.disabled=true;try{const data=await api.request('/api/politics/consultations');if(!root.isConnected)return;list.replaceChildren();status.textContent=data.ballots.length?'Institutional votes are separate from your personal election votes.':'No institutional consultations are registered.';
for(const b of data.ballots){const card=el('article');card.append(el('h4',b.title),el('p',b.terms),el('p',b.state+' · '+b.participation+' / '+b.seats+' seats participated · quorum '+(Math.floor(b.seats/2)+1)),el('p','Closes: '+new Date(b.closesAt).toLocaleString()));if(b.tally)card.append(el('p','Result: '+({yes:'Supported',no:'Opposed',no_quorum:'No quorum',not_adopted:'No majority',cancelled:'Cancelled'})[b.tally.result]));for(const s of b.ownSeats.filter(s=>s.vote))card.append(el('p',s.name+': '+s.vote));
if(b.canVote){const label=el('label','Your institutional seat'),select=el('select'),review=el('p'),yes=el('button','Review support'),no=el('button','Review opposition'),confirm=el('button','Confirm institutional vote'),cancel=el('button','Cancel');label.append(select);for(const s of b.ownSeats.filter(s=>!s.vote)){const option=el('option',s.name);option.value=s.id;select.append(option);}for(const button of [yes,no,confirm,cancel])button.type='button';confirm.hidden=cancel.hidden=true;let pending=null;
const prepare=choice=>{if(!select.value)return;pending={ballotId:b.id,seatKey:select.value,choice,requestId:crypto.randomUUID(),confirmed:true};review.textContent=(choice==='yes'?'Support':'Oppose')+' “'+b.title+'” for '+select.selectedOptions[0].textContent+'? One recorded vote per institutional seat.';confirm.hidden=cancel.hidden=false;yes.disabled=no.disabled=select.disabled=true;};yes.onclick=()=>prepare('yes');no.onclick=()=>prepare('no');cancel.onclick=()=>{pending=null;review.textContent='';confirm.hidden=cancel.hidden=true;yes.disabled=no.disabled=select.disabled=false;};
confirm.onclick=async()=>{if(!pending||busy)return;busy=true;confirm.disabled=cancel.disabled=refresh.disabled=true;try{await api.request('/api/politics/consultations',pending);pending=null;busy=false;await load();}catch(error){status.textContent=error.message+(error.uncertain?' Retry this same vote to check its recorded result.':'');if(!error.uncertain)cancel.onclick();}finally{busy=false;confirm.disabled=cancel.disabled=refresh.disabled=false;}};card.append(label,yes,no,review,confirm,cancel);
}card.append(el('small','J.A.R.V.I.S. reference: '+b.reference));list.append(card);
}
}catch(error){status.textContent=error.message;}finally{busy=false;refresh.disabled=false;}}
refresh.onclick=load;load();
}

View file

@ -8,7 +8,8 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
status.setAttribute('role','status');form.className='cp-political-decision-form';const fields=[];
function field(title,tag){const label=el('label',title),input=el(tag);label.append(input);form.append(label);fields.push(input);return input;}
const account=field('Office funding account','select');let title,body,recipient,citation,search,find,startsAt,endsAt,percent,houseSelect,clanSelect,grantAmount,grantReason,officeSelect;
if(d.kind==='agreement'){officeSelect=field('Receiving political office','select');title=field('Proposal title','input');title.maxLength=100;body=field('Confidential diplomatic terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p','The receiving current Royal office holder must consent within 72 hours. Accepted terms last at most '+d.durationMs/86400000+' days and end with either mandate. No votes, ownership, war, bank or travel rights are transferred.'));}
if(d.kind==='ballot'){title=field('Resolution title','input');title.maxLength=100;body=field('Resolution and consultation terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p',d.electorate==='houses'?'One institutional vote per current Royal Great House. A resolution does not automatically change laws or personal voting rights.':'One institutional vote per native Caladan clan, exercised by its current legal owner. The result is nonbinding and does not consume personal election votes.'));}
else if(d.kind==='agreement'){officeSelect=field('Receiving political office','select');title=field('Proposal title','input');title.maxLength=100;body=field('Confidential diplomatic terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p','The receiving current Royal office holder must consent within 72 hours. Accepted terms last at most '+d.durationMs/86400000+' days and end with either mandate. No votes, ownership, war, bank or travel rights are transferred.'));}
else if(d.kind==='proclamation'){title=field('Title','input');title.maxLength=120;title.minLength=3;body=field('Official message','textarea');body.maxLength=6000;body.minLength=10;body.rows=6;}
else if(d.kind==='event'){title=field('Session title','input');title.maxLength=100;body=field('Purpose and invitation','textarea');body.maxLength=2000;body.rows=4;startsAt=field('Start time (UTC)','input');endsAt=field('End time (UTC)','input');startsAt.type=endsAt.type='datetime-local';form.append(el('p','Schedule at least one minute ahead and no more than 30 days ahead. The session must finish before your mandate ends and last at most '+(d.maxEventMs||86400000)/3600000+' hours. It appears in the existing political calendar.'));if(d.id==='SG-06')form.append(el('p','This convenes voluntary mediation. Participants must separately approve any treaty, coalition or peace through its existing consent flow.'));}
else if(d.kind==='tariff'){percent=field('Guild surcharge','select');for(let n=0;n<=5;n++){const o=el('option',n===0?'0% · repeal':n+'%');o.value=String(n);percent.append(o);}form.append(el('p','Applies to new Guild bookings for seven days, while this mandate remains current. Confirmed fares remain unchanged. It does not open blocked routes or change smuggler fares.'));}
@ -30,7 +31,8 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
if(d.kind==='clan-grant')status.textContent=(data.canManage?'Current office verified. ':'Current office required. ')+(d.grantMinMinor/100).toFixed(2)+'–'+(d.grantMaxMinor/100).toFixed(2)+' DM development allocation'+(d.feeMinor?' + '+(d.feeMinor/100).toFixed(2)+' DM administrative fee':'')+'; up to '+d.xp+' Reputation points, proportional to the funded amount. Reputation '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.');
}catch(e){status.textContent=e.message;}finally{busy=false;controls();}}
prepare.onclick=()=>{
const payload=d.kind==='agreement'?{targetOffice:officeSelect.value,title:title.value,terms:body.value}:d.kind==='proclamation'?{title:title.value,body:body.value}:d.kind==='event'?{title:title.value,description:body.value,startsAt:Date.parse(startsAt.value+'Z'),endsAt:Date.parse(endsAt.value+'Z')}:d.kind==='clan-grant'?{clanId:clanSelect.value,amountMinor:Math.round(Number(grantAmount.value)*100),reason:grantReason.value}:d.kind==='guild-discount'?{house:houseSelect.value}:d.kind==='tariff'?{percent:Number(percent.value)}:d.kind==='report'?{}:{recipientId:recipient.value,citation:citation.value};
const payload=d.kind==='ballot'?{title:title.value,terms:body.value}:d.kind==='agreement'?{targetOffice:officeSelect.value,title:title.value,terms:body.value}:d.kind==='proclamation'?{title:title.value,body:body.value}:d.kind==='event'?{title:title.value,description:body.value,startsAt:Date.parse(startsAt.value+'Z'),endsAt:Date.parse(endsAt.value+'Z')}:d.kind==='clan-grant'?{clanId:clanSelect.value,amountMinor:Math.round(Number(grantAmount.value)*100),reason:grantReason.value}:d.kind==='guild-discount'?{house:houseSelect.value}:d.kind==='tariff'?{percent:Number(percent.value)}:d.kind==='report'?{}:{recipientId:recipient.value,citation:citation.value};
if(d.kind==='ballot'&&(title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Complete the resolution title and terms.';return;}
if(d.kind==='agreement'&&(!officeSelect.value||title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Choose a receiving office and complete the proposal title and terms.';return;}
if(d.kind==='clan-grant'&&(!clanSelect.value||!grantAmount.reportValidity()||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinor<d.grantMinMinor||payload.amountMinor>d.grantMaxMinor||grantReason.value.trim().length<10)){status.textContent='Choose a receiving clan, published grant amount and development purpose.';return;}
if(!account.value||['proclamation','event'].includes(d.kind)&&(title.value.trim().length<3||body.value.trim().length<10)||d.kind==='event'&&(!Number.isSafeInteger(payload.startsAt)||!Number.isSafeInteger(payload.endsAt)||payload.startsAt<Date.now()+60000||payload.endsAt<=payload.startsAt)||d.kind==='honour'&&(!recipient.value||citation.value.trim().length<3)){status.textContent='Choose funding and complete the decision details and dates.';return;}

View file

@ -1,3 +1,4 @@
import {mountPoliticalConsultations} from './cp-v2-political-consultations.mjs';
import {mountPoliticalAgreements} from './cp-v2-political-agreements.mjs';
import {faithBlessing} from '../faith-blessing-policy.mjs';
import {mountFaithInvitation} from './cp-v2-clan-faith.mjs';
@ -35,7 +36,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
let connectorObserver=null,disposePersonal=null;const dossier=createProgressionDialog(root);
const hero=el('header',undefined,'progression-hero'),head=el('div');head.append(el('small',manage?'IMPERIAL BUREAU · J.A.R.V.I.S.':'REALM PROGRESSION'),el('h2',manage?'Progression definitions':dashboard?'Quest Dashboard':'Missions & Decisions'),el('p','Your objectives, authority and recorded achievements.'));hero.append(image('exchange-quests-v1.png'),head);if(manage||(context!=='personal'&&context!=='clan')||!applyShellHeading(host,{title:context==='clan'?'Clan Missions & Decisions':dashboard?'Quest Dashboard':'Missions & Decisions',description:'Your objectives, authority and recorded achievements.',artwork:'exchange-quests-v1.png'}))root.append(hero);root.append(notice);
const xpNav=el('nav',undefined,'progression-tabs progression-xp-types');xpNav.setAttribute('aria-label','XP type');const contextNav=el('nav',undefined,'progression-contexts'),gallery=el('section',undefined,'progression-gallery'),nav=el('nav',undefined,'progression-tabs'),content=el('section',undefined,'progression-content');nav.setAttribute('aria-label','Progression views');contextNav.setAttribute('aria-label','Progression contexts');
root.append(gallery,xpNav,nav,content);host.replaceChildren(root);if(context==='politics')mountPoliticalAgreements(root);const report=!manage&&(context==='personal'||dashboard)?createProgressionSidebar(host,{onBranch:id=>{branch=id;if(tab==='missions')disposePersonal?.selectBranch?.(id);else{tab='missions';selected=null;render();}},onNavigate:(kind,view)=>{xpKind=kind;tab=view;selected=null;render();}}):{available:false,setJournal(){},setBranches(){},showBranches(){},setNavigation(){},dispose(){}};
root.append(gallery,xpNav,nav,content);host.replaceChildren(root);if(['politics','clan'].includes(context))mountPoliticalConsultations(root);if(context==='politics')mountPoliticalAgreements(root);const report=!manage&&(context==='personal'||dashboard)?createProgressionSidebar(host,{onBranch:id=>{branch=id;if(tab==='missions')disposePersonal?.selectBranch?.(id);else{tab='missions';selected=null;render();}},onNavigate:(kind,view)=>{xpKind=kind;tab=view;selected=null;render();}}):{available:false,setJournal(){},setBranches(){},showBranches(){},setNavigation(){},dispose(){}};
function renderGallery(){gallery.replaceChildren();gallery.hidden=activeContext==='personal'||activeContext==='clan'||manage;gallery.className='progression-gallery'+(activeContext==='politics'&&officeCode==='IMP'?' progression-imperial':'');if(gallery.hidden)return;
const title=activeContext==='politics'?OFFICES.find(([id])=>id===officeCode)?.[1]:organisation?.name||CONTEXTS[activeContext][0];gallery.append(el('h3',title||'Your organisation'));
if(activeContext==='politics'&&officeCode==='IMP'){const throne=el('div',undefined,'progression-throne');throne.append(image('seals/emperor-v1.png'),el('strong','Padishah Emperor'),el('span','Officeholder avatar · preview'));gallery.append(throne);const seals=el('div',undefined,'progression-electors');for(const[name,file]of SEALS){const card=el('figure');card.append(image('seals/'+file),el('figcaption',name),el('span','Leader avatar · preview'));seals.append(card);}gallery.append(seals);return;}

View file

@ -14,6 +14,8 @@ export const MASTER_KEY_TEMPLATES=[
action('company.subsidiary','Subsidiary founding','company-subsidiary',[field('parentCompanyId','Mother company'),field('recipient','Recipient')]),
action('company.royal','Royal company charter','staff-company-royal',[field('companyId','Company'),reference])]},
{id:'politics',label:'POL & orders',actions:[
action('politics.institutional-consultation','Convene an institutional resolution vote','entity-state',[field('decisionId','Registered Council decision','select',{options:['IMP-05','ATR-02']}),field('sourceAccount','Authorised office funding account'),field('title','Resolution title'),field('terms','Consultation terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalConsultations',executionStatus:'current-office-and-institutional-seat-consumer',effect:'Landsraad: Emperor, Reputation25,5000DM,400 Reputation,72h consultation/cooldown; snapshot occupied Royal Great House offices. Caladan: Atreides holder,Reputation15,2000DM,250 Reputation,48h consultation/cooldown; snapshot native active clans. The issuing mandate must cover the entire ballot. Current independent legal clan owners or the original House mandates cast one signed institutional vote per seat. More-than-half participation and strict majority; ties fail. Immutable final tally; no personal election votes, ownership, law or war participation change. Fee, electorate, scoped key and Reputation commit together.'}),
action('politics.institutional-vote','Cast an institutional resolution vote','entity-state',[field('ballotId','Consultation UUID'),field('seatKey','Current institutional seat'),field('choice','Vote','select',{options:['yes','no']}),field('requestId','Vote UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalConsultations.vote / reconcile',executionStatus:'current-independent-institutional-deed-only',effect:'Revalidate the signed live ballot, original issuing mandate and current independent institutional seat under the same transaction. One signed vote per seat; exact retries retain the receipt. No fee or Reputation for voting. Mother control does not confer client clan votes; revoked recorded votes cannot be replaced. Final tally uses the existing quorum/strict-majority rule and remains fixed after closure.'}),
action('politics.diplomatic-proposal','Confidential diplomatic proposal','entity-state',[field('decisionId','Diplomatic decision','select',{options:['ATR-05','COR-06','ORD-05','BG-05','NF-05']}),field('sourceAccount','Authorised office funding account'),field('targetOffice','Receiving Royal office'),field('title','Proposal title'),field('terms','Confidential diplomatic terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-officeholder-bilateral-consent-consumer',effect:'Five fixed diplomatic policies charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.'}),
action('politics.diplomatic-response','Accept or refuse a diplomatic proposal','entity-state',[field('proposalId','Proposal UUID'),field('choice','Response','select',{options:['accept','decline']}),field('requestId','Response UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalAgreements.reply',executionStatus:'original-receiving-officeholder-consent-consumer',effect:'Only the original receiving current Royal mandate can accept or refuse a live72h proposal. Recheck both original mandates and the unrevoked signed proposal under the same transaction; record one signed response. Exact retries return the original receipt; conflicting responses, changed holders, expired or revoked proposals cannot manufacture acceptance. No further payment or Reputation is issued for replying.'}),
action('politics.clan-development-grant','Office clan development allocation','entity-state',[field('decisionId','Registered development grant','select',{options:['ATR-01','ATR-04','HAR-02','COR-02','COR-04','NF-03']}),field('sourceAccount','Authorised House funding account'),field('clanId','Receiving clan UUID'),field('amountMinor','Development allocation in DM minor units','number',{min:10000}),field('reason','Development purpose','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalClanGrants / organisationRewardRoute',executionStatus:'current-house-office-and-current-clan-deed-consumer',effect:'House development policies re-read the native clan homeworld, current legal deed, active receiving bank account and authorised House source. Atreides Patronage is exactly10,000 DM; other published grants range from100 DM to their15,000/25,000 DM cap. Basic clans route to their current legal owner, keyed clans to their own account; mother control never substitutes for that owner. Actual funded amount scales Reputation up to the catalogue cap. Existing balanced bank transfer, immutable purpose, ordinary key and Reputation commit together; safe retries retain the original payment recipient. Church sponsorship additionally requires current signed New Faith consent, caps funding at10,000 DM and pays a separate2,500 DM Tax admin fee; grant, fee and proportional Reputation commit or roll back together, with a7d cooldown. No P&O issuance, account activation, construction completion, inventory progress or ownership change is fabricated.'}),

View file

@ -7,6 +7,8 @@ export const POLITICAL_DECISIONS=Object.freeze([
['BG-05','veiled_concord','Whispered Alliance',35,600,500000,168,7],
['NF-05','muad_dib','Whispered Alliance',35,600,500000,168,7]
].map(([id,office,title,level,xp,feeMinor,hours,days])=>({id,office,title,level,xp,feeMinor,cooldownMs:hours*3600000,kind:'agreement',responseMs:72*3600000,durationMs:days*86400000})),
{id:'IMP-05',office:'emperor',title:'Convene Landsraad',kind:'ballot',electorate:'houses',level:25,xp:400,feeMinor:500000,cooldownMs:72*3600000,ballotMs:72*3600000},
{id:'ATR-02',office:'atreides',title:'Council of Caladan',kind:'ballot',electorate:'clans',ballotWorld:'caladan',level:15,xp:250,feeMinor:200000,cooldownMs:48*3600000,ballotMs:48*3600000},
{id:'NF-03',office:'muad_dib',title:'Church Patronage',kind:'clan-grant',grantFaith:'muad_dib',level:25,xp:400,feeMinor:250000,grantMinMinor:10000,grantMaxMinor:1000000,cooldownMs:7*86400000},
{id:'ATR-01',office:'atreides',title:'Atreides Patronage',kind:'clan-grant',grantWorld:'caladan',level:10,xp:200,feeMinor:0,grantMinMinor:1000000,grantMaxMinor:1000000,cooldownMs:72*3600000},
{id:'ATR-04',office:'atreides',title:'Waterworld Development',kind:'clan-grant',grantWorld:'caladan',level:25,xp:400,feeMinor:0,grantMinMinor:10000,grantMaxMinor:2500000,cooldownMs:7*86400000},
@ -38,4 +40,4 @@ export const POLITICAL_DECISIONS=Object.freeze([
].map(d=>Object.freeze({...d,durationMs:d.durationMs??(d.kind==='honour'?30*86400000:null)})));
export const politicalDecision=id=>POLITICAL_DECISIONS.find(d=>d.id===id)||null;
export function proclamationDecisionId(kind,faction){return kind==='imperial'?'IMP-04':kind==='guild'?'SG-PROCLAIM':kind==='house'?({atreides:'ATR-PROCLAIM',harkonnen:'HAR-PROCLAIM',corrino:'COR-PROCLAIM',ordos:'ORD-PROCLAIM',veiled_concord:'BG-04',muad_dib:'NF-04'})[faction]||null:null;}
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount')+(d.feeMinor?' + '+(d.feeMinor/100).toLocaleString('en-GB')+' admin':''):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='agreement'?'Send a confidential diplomatic proposal to another current Royal office holder, who must consent within 72 hours. Accepted terms last '+d.durationMs/86400000+' days at most and end with either mandate. This records diplomatic terms without moving votes, ownership, military allegiance or bank rights.':d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+(d.grantFaith?' from the Church to a clan with current signed New Faith consent. A separate 2,500 DM administrative fee goes to Tax.':' from this House to a current clan on its native world.')+' Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount')+(d.feeMinor?' + '+(d.feeMinor/100).toLocaleString('en-GB')+' admin':''):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='ballot'?'Open a '+d.ballotMs/3600000+'-hour nonbinding resolution vote. '+(d.electorate==='houses'?'One seat for each currently occupied Royal Great House office. Its original mandate must still be current to vote.':'One seat for each current native Caladan clan, exercised by its legal owner; mother control does not confer a seat.')+' Frozen electorate; more-than-half participation and strict majority required. Ties fail. Personal election votes are untouched.':d.kind==='agreement'?'Send a confidential diplomatic proposal to another current Royal office holder, who must consent within 72 hours. Accepted terms last '+d.durationMs/86400000+' days at most and end with either mandate. This records diplomatic terms without moving votes, ownership, military allegiance or bank rights.':d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+(d.grantFaith?' from the Church to a clan with current signed New Faith consent. A separate 2,500 DM administrative fee goes to Tax.':' from this House to a current clan on its native world.')+' Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));

View file

@ -3,6 +3,7 @@ import {ensureFaithQuestPolicy} from '../node/progression-pol.mjs';
import {initializeClanFaith,createClanFaithAPI,createClanFaith} from '../node/clan-faith.mjs';
import {initializeHouseFaith,createHouseFaithAPI,createHouseFaithLaws,missionaryFaithOutlawed} from '../node/house-faith-laws.mjs';
import {createPoliticalMarketReports} from '../node/political-market-reports.mjs';
import {POLITICAL_CONSULTATION_SCHEMA,createPoliticalConsultations,createPoliticalConsultationAPI} from '../node/political-consultations.mjs';
import {POLITICAL_AGREEMENT_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs';
import {createPoliticalClanGrants} from '../node/political-clan-grants.mjs';
import {initializeWorldTrade,createWorldTradeAPI} from '../node/world-trade-governance.mjs';
@ -284,9 +285,11 @@ export function createPanel(db,settings={},dependencies={}){
const gameNativeState=createGameNativeStateAPI(db,settings,{read:currentNativeState});
const gameOrganisations=createGameOrganisationsAPI(db,dependencies.organisationKeys,settings,{bank:dependencies.bankDatabase||null,readState:currentNativeState,extraWars:campaignWars});
const gameGuild=createGameGuildAPI(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings);
const politicalConsultations=createPoliticalConsultations(db,dependencies.organisationKeys);
const politicalConsultationAPI=createPoliticalConsultationAPI(db,politicalConsultations,{origin});
const politicalAgreements=createPoliticalAgreements(db,dependencies.organisationKeys);
const politicalAgreementAPI=createPoliticalAgreementAPI(db,politicalAgreements,{origin});
const politicalDecisions=createPoliticalDecisions(db,dependencies.bankDatabase||null,dependencies.organisationKeys,{marketReports:createPoliticalMarketReports(db,dependencies.bankDatabase||null,settings),clanGrants:createPoliticalClanGrants(db),agreements:politicalAgreements});
const politicalDecisions=createPoliticalDecisions(db,dependencies.bankDatabase||null,dependencies.organisationKeys,{marketReports:createPoliticalMarketReports(db,dependencies.bankDatabase||null,settings),clanGrants:createPoliticalClanGrants(db),agreements:politicalAgreements,consultations:politicalConsultations});
const politicalDecisionAPI=createPoliticalDecisionAPI(db,politicalDecisions,{origin});
const clanFaith=createClanFaithAPI(db,dependencies.organisationKeys,{origin,service:createClanFaith(db,dependencies.organisationKeys,{isOutlawed:missionaryFaithOutlawed})});
const houseFaith=createHouseFaithAPI(db,dependencies.organisationKeys,{origin});
@ -396,6 +399,7 @@ export function createPanel(db,settings={},dependencies={}){
if(/^\/api\/public\/(companies|political-houses)(?:\/|$)/.test(path))return publicOrganisations(request);
if(path==='/api/rihla')return rihla(request);
if(path==='/api/network/layout')return networkLayouts(request);
if(path==='/api/politics/consultations')return politicalConsultationAPI(request);
if(path==='/api/politics/agreements')return politicalAgreementAPI(request);
if(path==='/api/politics/decisions')return politicalDecisionAPI(request);
if(path==='/api/politics/faith')return clanFaith(request);
@ -580,9 +584,9 @@ export async function startPanel(settings=process.env){
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
}
const bankDatabase=await openPostbankDatabase(settings);
const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db);
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'house_faith_ballots',slot:now=>Math.floor(now/60000)*60000,run:()=>createHouseFaithLaws(db,organisationKeys).reconcile()},{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'organisation_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createOrganisationFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]});
const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'political_consultations',slot:now=>Math.floor(now/60000)*60000,run:()=>createPoliticalConsultations(db,organisationKeys).reconcile()},{key:'house_faith_ballots',slot:now=>Math.floor(now/60000)*60000,run:()=>createHouseFaithLaws(db,organisationKeys).reconcile()},{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'organisation_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createOrganisationFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]});
const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP};
const server=createServer(async(req,res)=>{try{
req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);}

View file

@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"sourceHash": "44c98855fa02fc5a36c6dae8457232fd9177b869eca449fad50074c6f36ca4b8",
"sourceHash": "6d2a3b4d5fb8cd165486c7848285106db837346c24a237cab670b1c86d18fdaa",
"actions": [
{
"id": "war.coalition-consent",
@ -431,6 +431,106 @@
"webIssue": false,
"recordOnly": false
},
{
"id": "politics.institutional-consultation",
"label": "POL & orders · Convene an institutional resolution vote",
"version": 1,
"keyType": "entity-state",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "decisionId",
"label": "Registered Council decision",
"type": "select",
"required": true,
"options": [
"IMP-05",
"ATR-02"
]
},
{
"name": "sourceAccount",
"label": "Authorised office funding account",
"type": "text",
"required": true
},
{
"name": "title",
"label": "Resolution title",
"type": "text",
"required": true
},
{
"name": "terms",
"label": "Consultation terms",
"type": "textarea",
"required": true
},
{
"name": "requestId",
"label": "Request UUID",
"type": "text",
"required": true
}
],
"effect": "Landsraad: Emperor, Reputation25,5000DM,400 Reputation,72h consultation/cooldown; snapshot occupied Royal Great House offices. Caladan: Atreides holder,Reputation15,2000DM,250 Reputation,48h consultation/cooldown; snapshot native active clans. The issuing mandate must cover the entire ballot. Current independent legal clan owners or the original House mandates cast one signed institutional vote per seat. More-than-half participation and strict majority; ties fail. Immutable final tally; no personal election votes, ownership, law or war participation change. Fee, electorate, scoped key and Reputation commit together.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "politics.institutional-vote",
"label": "POL & orders · Cast an institutional resolution vote",
"version": 1,
"keyType": "entity-state",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "ballotId",
"label": "Consultation UUID",
"type": "text",
"required": true
},
{
"name": "seatKey",
"label": "Current institutional seat",
"type": "text",
"required": true
},
{
"name": "choice",
"label": "Vote",
"type": "select",
"required": true,
"options": [
"yes",
"no"
]
},
{
"name": "requestId",
"label": "Vote UUID",
"type": "text",
"required": true
}
],
"effect": "Revalidate the signed live ballot, original issuing mandate and current independent institutional seat under the same transaction. One signed vote per seat; exact retries retain the receipt. No fee or Reputation for voting. Mother control does not confer client clan votes; revoked recorded votes cannot be replaced. Final tally uses the existing quorum/strict-majority rule and remains fixed after closure.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "politics.diplomatic-proposal",
"label": "POL & orders · Confidential diplomatic proposal",

View file

@ -41,7 +41,7 @@ export function createOrganisationKeys(db,{secret,editions=null}={}){
return Object.freeze({
async inspect(code,{accountId=null,expectedType=null}={}){let parsed,keyType,hash;try{parsed=parseOrganisationCode(code);keyType=Object.keys(ORGANISATION_KEY_TYPES).find(k=>ORGANISATION_KEY_TYPES[k].prefix===parsed.prefix);if(!keyType)return{valid:false,state:'unsupported'};hash=hashOrganisationKey(code,keyType);}catch{return{valid:false,state:'invalid'};}const row=await readFirst(db,'SELECT id,account_id,key_type,expires_at,revoked_at,used_at FROM organisation_keys WHERE code_hash=?',[hash]);if(!row||accountId&&row.account_id!==accountId||expectedType&&row.key_type!==expectedType)return{valid:false,state:'invalid'};if(parsed.edition){if(!editions)return{valid:false,state:'unavailable'};const edition=await editions.read(row.id);if(['stage','version','season'].some(k=>edition[k]!==parsed.edition[k]))return{valid:false,state:'invalid'};}return{valid:true,type:row.key_type,purpose:type(row.key_type).purpose,state:row.revoked_at!=null?'revoked':row.used_at!=null?'used':row.expires_at!=null&&Number(row.expires_at)<=Date.now()?'expired':'available'};},
async issue({accountId,keyType,scopeId,expiresAt=null,authorize=null,transactionStore=null}){
if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-agreement-reply|world-trade):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required');
if(transactionStore&&(!(keyType==='organisation-action'||keyType==='entity-state'&&accountId===STAFF_OFFICE_ACCOUNT_ID&&/^state:(?:political-decision|political-agreement-reply|political-ballot-vote|world-trade):[a-f0-9-]{36}$/i.test(scopeId))||typeof transactionStore.query!=='function'||typeof transactionStore.first!=='function'))throw TypeError('A scoped action transaction is required');
type(keyType);
if(keyType==='economy-operation'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^economy\.(reset-balances|repay-loans|federal-cycle):[a-f0-9-]{36}$/i.test(scopeId)))throw TypeError('Economic keys require a scoped system authority adapter');
if(keyType==='kit-definition'&&(accountId!==STAFF_OFFICE_ACCOUNT_ID||expiresAt!==null||typeof authorize!=='function'||!/^kitset:[a-f0-9-]{36}:v[1-9]\d{0,5}$/i.test(scopeId)))throw TypeError('Kit definitions require a saved set and authority adapter');

View file

@ -0,0 +1,59 @@
import {createHash} from 'node:crypto';
import {boardReadStore} from './board-deed-source.mjs';
import {officeAuthority} from './political-decisions.mjs';
import {PUBLIC_OFFICES} from './public-government.mjs';
import {currentOfficeController} from './entity-relations.mjs';
import {readClanDeed} from './clan-deeds.mjs';
import {politicalDecision} from '../control-panel/public/political-decision-policy.mjs';
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
import {decisionBallotOutcome} from '../control-panel/public/decision-ballot-policy.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {validUuid} from './game-link.mjs';
import {identity} from './auth.mjs';
export const POLITICAL_CONSULTATION_SCHEMA=[
`CREATE TABLE IF NOT EXISTS jarvis_political_consultations(request_id CHAR(36) PRIMARY KEY,closes_at BIGINT NOT NULL,closed_at BIGINT,tally_json TEXT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS jarvis_political_consultation_votes(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,ballot_id CHAR(36) NOT NULL,seat_key VARCHAR(64) NOT NULL,actor_id CHAR(36) NOT NULL,choice VARCHAR(8) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY political_ballot_seat(ballot_id,seat_key)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});},hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
export function createPoliticalConsultations(raw,keys,{clock=Date.now}={}){
if(typeof raw?.query!=='function')return{read:async()=>fail('Consultations unavailable.',503),create:async()=>fail('Consultations unavailable.',503),vote:async()=>fail('Consultations unavailable.',503),reconcile:async()=>({closed:0})};
const db=boardReadStore(raw,raw);
async function seat(tx,d,s,actor,now,lock=false){
if(d.electorate==='houses'){
if(s.kind!=='office'||!PUBLIC_OFFICES.some(o=>o.key===s.id&&o.kind==='house'))return false;const holder=await officeAuthority(tx,{office:s.id},actor,now,lock);return holder?.termId===s.termId;
}
if(s.kind!=='clan'||!validUuid(s.id))return false;if(lock)await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[s.id]);
try{const deed=await readClanDeed(tx,s.id);return deed.owner?.id===actor.id&&tradeWorld(deed.clan.home_world)===d.ballotWorld;}catch{return false;}
}
async function electorate(tx,d,now){
const seats=[];
if(d.electorate==='houses'){for(const office of PUBLIC_OFFICES.filter(o=>o.kind==='house')){const h=await currentOfficeController(tx,office.key,now);if(h&&await officeAuthority(tx,{office:office.key},{id:h.userId},now,true))seats.push({kind:'office',id:office.key,name:office.scope,termId:h.termId});}}
else{const clans=await tx.query('SELECT id,name,home_world FROM site_clans WHERE active=1 ORDER BY id LIMIT 1001 FOR SHARE');if(clans.length>1000)fail('Narrow the consultation registry.',503);for(const c of clans)if(tradeWorld(c.home_world)===d.ballotWorld){try{const deed=await readClanDeed(tx,c.id);if(deed.owner)seats.push({kind:'clan',id:c.id,name:c.name});}catch(cause){throw Object.assign(Error('A native clan deed requires review.',{cause}),{status:409});}}}
if(!seats.length)fail('No eligible institutional seats are currently registered.');return seats;
}
async function create(tx,{d,holder,now,requestId}){
tx=boardReadStore(tx,db);
const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[holder.termId]);if(Number(term?.expires_at||0)<=now+d.ballotMs)fail('This mandate must cover the complete consultation.');
const seats=await electorate(tx,d,now);if(Buffer.byteLength(JSON.stringify(seats),'utf8')>48000)fail('The institutional electorate exceeds the safe consultation size.',413);await tx.query('INSERT INTO jarvis_political_consultations(request_id,closes_at) VALUES(?,?)',[requestId,now+d.ballotMs]);return{closesAt:now+d.ballotMs,seats};
}
async function verified(tx,row,now,lock=false){
const d=politicalDecision(row?.decision_id);if(d?.kind!=='ballot')return null;
const key=await tx.first("SELECT id FROM organisation_keys WHERE id=? AND account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL"+(lock?' FOR SHARE':''),[row.key_id,STAFF_OFFICE_ACCOUNT_ID,'state:political-decision:'+row.request_id]);if(!key)return null;
const receipt=JSON.parse(row.receipt_json),payload=JSON.parse(row.payload_json),ballot=receipt.ballot;if(!ballot||ballot.closesAt!==Number(row.created_at)+d.ballotMs||!Array.isArray(ballot.seats)||!ballot.seats.length||ballot.seats.length>1000||new Set(ballot.seats.map(s=>s.kind+':'+s.id)).size!==ballot.seats.length)return null;
const holder=await officeAuthority(tx,d,{id:row.actor_id},now,lock);return{d,payload,ballot,mandate:holder?.termId===row.term_id};
}
async function votes(tx,id){return tx.query("SELECT v.*,k.id verified_key FROM jarvis_political_consultation_votes v LEFT JOIN organisation_keys k ON k.id=v.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:political-ballot-vote:',v.request_id) AND k.revoked_at IS NULL WHERE v.ballot_id=? ORDER BY v.seat_key",[STAFF_OFFICE_ACCOUNT_ID,id]);}
function outcome(v,rows,id){const known=new Set(v.ballot.seats.map(s=>s.kind+':'+s.id));if(rows.some(r=>!known.has(r.seat_key)||Number(r.created_at)>=v.ballot.closesAt||r.input_hash!==hash([r.actor_id,id,r.seat_key,r.choice])))fail('Consultation vote records require review.');return decisionBallotOutcome(['yes','no'],known.size,rows.map(r=>({identity:r.seat_key,choice:r.choice})));}
async function read(actor){const rows=await db.query("SELECT p.*,c.closed_at,c.tally_json FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id ORDER BY p.created_at DESC,p.request_id DESC LIMIT 100"),ballots=[],now=clock(),owned=new Set((await db.query('SELECT id FROM site_clans WHERE active=1 AND owner_id=?',[actor.id])).map(c=>c.id)),officeSeats=new Set(),seatCache=new Map();for(const o of PUBLIC_OFFICES.filter(o=>o.kind==='house'))if((await currentOfficeController(db,o.key,now))?.userId===actor.id)officeSeats.add(o.key);for(const row of rows){const v=await verified(db,row,now);if(!v)continue;const recorded=await votes(db,row.request_id),cast=recorded.filter(r=>r.verified_key),own=[];for(const s of v.ballot.seats){if(s.kind==='clan'?!owned.has(s.id):!officeSeats.has(s.id))continue;const cacheKey=[s.kind,s.id,s.termId||'',v.d.ballotWorld||''].join(':');if(!seatCache.has(cacheKey))seatCache.set(cacheKey,await seat(db,v.d,s,actor,now));if(seatCache.get(cacheKey))own.push({id:s.kind+':'+s.id,name:s.name,vote:(recorded.find(r=>r.seat_key===s.kind+':'+s.id)?(cast.find(r=>r.seat_key===s.kind+':'+s.id)?.choice||'recorded-invalid'):null)});}const state=row.closed_at!=null?'closed':!v.mandate?'mandate-ended':now>=v.ballot.closesAt?'awaiting-result':'open';ballots.push({id:row.request_id,decisionId:v.d.id,title:v.payload.title,terms:v.payload.terms,closesAt:v.ballot.closesAt,state,seats:v.ballot.seats.length,participation:cast.length,ownSeats:own,canVote:state==='open'&&own.some(s=>!s.vote),tally:row.closed_at!=null?JSON.parse(row.tally_json):null,reference:row.key_id});}return{ballots};}
async function vote(actor,input){
if(!input||Object.keys(input).sort().join(',')!=='ballotId,choice,confirmed,requestId,seatKey'||input.confirmed!==true||!validUuid(input.ballotId)||!validUuid(input.requestId)||typeof input.seatKey!=='string'||input.seatKey.length>64||!['yes','no'].includes(input.choice))fail('Review and confirm your institutional vote.',400);if(!keys||!raw.transaction)fail('Consultations unavailable.',503);
return raw.transaction(async original=>{const tx=boardReadStore(original,db),row=await tx.first('SELECT p.*,c.closed_at FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id WHERE c.request_id=? FOR UPDATE',[input.ballotId]);if(!row)fail('Consultation not found.',404);
const digest=hash([actor.id,input.ballotId,input.seatKey,input.choice]),prior=await tx.first('SELECT * FROM jarvis_political_consultation_votes WHERE request_id=? OR (ballot_id=? AND seat_key=?) FOR UPDATE',[input.requestId,input.ballotId,input.seatKey]);if(prior){if(prior.request_id!==input.requestId||prior.input_hash!==digest||prior.actor_id!==actor.id)fail('This institutional seat already voted.');return{ok:true,replayed:true,reference:prior.key_id};}
const now=clock(),v=await verified(tx,row,now,true),s=v?.ballot.seats.find(s=>s.kind+':'+s.id===input.seatKey);if(!v||!v.mandate||row.closed_at!=null||now>=v.ballot.closesAt)fail('This consultation is no longer open.');if(!s||!await seat(tx,v.d,s,actor,now,true))fail('The current independent institutional deed is required.',403);
let reference;await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-ballot-vote:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{reference=keyId;await tx.query('INSERT INTO jarvis_political_consultation_votes VALUES(?,?,?,?,?,?,?,?)',[input.requestId,keyId,input.ballotId,input.seatKey,actor.id,input.choice,digest,now]);}});return{ok:true,replayed:false,reference};
});
}
async function reconcile(){const rows=await db.query('SELECT c.request_id FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id WHERE c.closed_at IS NULL AND c.closes_at<=? ORDER BY c.closes_at,p.request_id LIMIT 100',[clock()]);let closed=0;for(const candidate of rows)await raw.transaction(async original=>{const tx=boardReadStore(original,db),row=await tx.first('SELECT p.*,c.closed_at FROM jarvis_political_consultations c JOIN jarvis_political_decisions p ON p.request_id=c.request_id WHERE c.request_id=? FOR UPDATE',[candidate.request_id]),now=clock();if(!row||row.closed_at!=null)return;const policy=politicalDecision(row.decision_id),atDeadline=policy?.kind==='ballot'?Math.min(now,Number(row.created_at)+policy.ballotMs-1):now,v=await verified(tx,row,atDeadline,true);if(v?.mandate&&now<v.ballot.closesAt)return;const tally=v?.mandate?outcome(v,(await votes(tx,row.request_id)).filter(r=>r.verified_key),row.request_id):{result:'cancelled',reason:'issuing-mandate-ended-or-revoked'};await tx.query('UPDATE jarvis_political_consultations SET closed_at=?,tally_json=? WHERE request_id=?',[now,JSON.stringify(tally),row.request_id]);closed++;});return{closed};}
return{create,read,vote,reconcile};
}
export function createPoliticalConsultationAPI(db,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db)}={}){return async request=>{const respond=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store'}});try{if(!['GET','POST'].includes(request.method))return respond({message:'Method not allowed.'},405);const actor=await authenticate(request);if(!actor)return respond({message:'Sign in first.'},401);if(new URL(request.url).search)return respond({message:'Unexpected consultation fields.'},400);if(request.method==='GET')return respond(await service.read(actor));if(request.headers.get('origin')!==origin)return respond({message:'Origin rejected.'},403);const body=await request.text();if(body.length>4096)return respond({message:'Vote too large.'},413);let input;try{input=JSON.parse(body);}catch{return respond({message:'Invalid vote.'},400);}return respond(await service.vote(actor,input));}catch(error){return respond({message:error.status?error.message:'Consultations are temporarily unavailable.'},error.status||503);}};}

View file

@ -25,10 +25,10 @@ const fingerprint=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex'
const funding=d=>entityId('office',d.office==='emperor'?'emperor':'leader:'+d.office);
export function politicalDecisionReader(tx,base){const reader=boardReadStore(tx,base);if(tx!==base)reader.readSnapshot=async work=>work(reader);return reader;}
export function decisionInput(input){
const d=politicalDecision(input?.decisionId),fields=d?.kind==='agreement'?'confirmed,decisionId,requestId,sourceAccount,targetOffice,terms,title':d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?'confirmed,decisionId,requestId,sourceAccount':'citation,confirmed,decisionId,recipientId,requestId,sourceAccount';
const d=politicalDecision(input?.decisionId),fields=d?.kind==='ballot'?'confirmed,decisionId,requestId,sourceAccount,terms,title':d?.kind==='agreement'?'confirmed,decisionId,requestId,sourceAccount,targetOffice,terms,title':d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?'confirmed,decisionId,requestId,sourceAccount':'citation,confirmed,decisionId,recipientId,requestId,sourceAccount';
if(!d||!input||Object.keys(input).sort().join(',')!==fields||!validUuid(input.requestId)||input.confirmed!==true||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount))fail('Review and confirm a registered decision and its funding account.',400);
const clean=(value,min,max)=>{if(typeof value!=='string'||value.trim().length<min||value.trim().length>max||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))fail('Invalid announcement or citation.',400);return value.replaceAll('\r\n','\n').trim();};
const payload=d.kind==='agreement'?{targetOffice:input.targetOffice,title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?{}:{recipientId:input.recipientId,citation:clean(input.citation,3,2000)};
const payload=d.kind==='ballot'?{title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='agreement'?{targetOffice:input.targetOffice,title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?{}:{recipientId:input.recipientId,citation:clean(input.citation,3,2000)};
if(d.kind==='agreement'&&(!PUBLIC_OFFICES.some(o=>o.key===payload.targetOffice)||payload.targetOffice===d.office))fail('Choose another registered political office.',400);
if(d.kind==='clan-grant'&&(!validUuid(payload.clanId)||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinor<d.grantMinMinor||payload.amountMinor>d.grantMaxMinor))fail('Choose an eligible clan and a grant within the published budget.',400);
if(d.kind==='guild-discount'&&!TRADE_WORLDS.some(w=>w.house===payload.house))fail('Choose a native House for the preferred fare.',400);
@ -51,7 +51,7 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
// The production central pool exposes prepared reads rather than first().
// Keep every transaction callback on its original connection.
db={...boardReadStore(db,db),transaction:db.transaction.bind(db)};
const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','jarvis_political_agreement_replies','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','jarvis_clan_faith','jarvis_faith_consents','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']});
const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','jarvis_political_agreement_replies','jarvis_political_consultations','jarvis_political_consultation_votes','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','jarvis_clan_faith','jarvis_faith_consents','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']});
async function accounts(tx,actor,d){const b=banking.view(tx),r=politicalDecisionReader(tx,db),authority=deps.authority||createPostbankAuthority(r,{bank:b,clock});const rights=await authority(actor,{bank:b});return(await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[funding(d)])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));}
const eventBanking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,bankTables:['jarvis_events','jarvis_event_history']});
async function recipients(tx,actor,d,search=''){
@ -66,7 +66,7 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
const choices=holder?await accounts(db,actor,d):[];let reportAvailable=true;if(d.kind==='report'){try{if(!deps.marketReports)throw Error('No reporting source');await deps.marketReports.ready();}catch{reportAvailable=false;}}
const clans=holder&&d.kind==='clan-grant'&&deps.clanGrants?await deps.clanGrants.targets(db,d):[],grantAvailable=d.kind!=='clan-grant'||!!deps.clanGrants&&clans.length>0,minimum=d.kind==='clan-grant'?d.grantMinMinor+d.feeMinor:d.feeMinor;
const diplomacyTargets=holder&&d.kind==='agreement'&&deps.agreements?await deps.agreements.targets(db,d,actor,now):[];
return{...d,diplomacyTargets,clans,grantAvailable,canManage:!!holder,canExecute:(d.kind!=='agreement'||diplomacyTargets.length>0)&&grantAvailable&&reportAvailable&&!!holder&&!!keys&&!!season&&level>=d.level&&(!cooldownUntil||now>=cooldownUntil)&&choices.some(a=>BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(minimum)),reportAvailable,report:holder&&d.kind==='report'&&prior?JSON.parse(prior.receipt_json).report||null:null,levelNow:level,cooldownUntil,accounts:choices.map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))})),recipients:holder?await recipients(db,actor,d,search):[]};
return{...d,diplomacyTargets,clans,grantAvailable,canManage:!!holder,canExecute:(d.kind!=='ballot'||!!deps.consultations)&&(d.kind!=='agreement'||diplomacyTargets.length>0)&&grantAvailable&&reportAvailable&&!!holder&&!!keys&&!!season&&level>=d.level&&(!cooldownUntil||now>=cooldownUntil)&&choices.some(a=>BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(minimum)),reportAvailable,report:holder&&d.kind==='report'&&prior?JSON.parse(prior.receipt_json).report||null:null,levelNow:level,cooldownUntil,accounts:choices.map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))})),recipients:holder?await recipients(db,actor,d,search):[]};
}
async function execute(actor,input){
const {d,requestId,sourceAccount,payload}=decisionInput(input);if(!keys)fail('Key service unavailable.',503);await banking.ready();if(d.kind==='event')await eventBanking.ready();const digest=fingerprint([actor.id,d.id,sourceAccount,payload]);
@ -94,11 +94,12 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),state=await lockXPAccount(pol,actor.id,now),level=levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)||null});if(level<d.level)fail('Reputation level '+d.level+' is required.',403);
let report=null;if(d.kind==='report'){if(!deps.marketReports)fail('Verified Exchange reporting unavailable. No decision was charged.',503);report=await deps.marketReports.report(tx,d,now);}
let agreement=null;if(d.kind==='agreement'){if(!deps.agreements)fail('Political agreements unavailable.',503);agreement=await deps.agreements.create(tx,{d,actor,payload,holder,now});}
let ballot=null;if(d.kind==='ballot'){if(!deps.consultations)fail('Consultations unavailable.',503);ballot=await deps.consultations.create(tx,{d,holder,now,requestId});}
const rewardXP=grant?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.grantMaxMinor)):d.xp;
let receipt;
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-decision:'+requestId,transactionStore:tx,authorize:async(_,{keyId})=>{
const effectId=randomUUID(),expiresAt=d.durationMs?now+d.durationMs:null;
receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(amount+adminAmount),adminFeeMinor:String(adminAmount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(report?{report}:{}),...(agreement?{agreement}:{}),...(grant?{grant:{clanId:grant.clanId,clanName:grant.clanName,amountMinor:String(amount),basicFallback:grant.basic,recipientKind:grant.recipientKind}}:{})};
receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(amount+adminAmount),adminFeeMinor:String(adminAmount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(report?{report}:{}),...(agreement?{agreement}:{}),...(ballot?{ballot}:{}),...(grant?{grant:{clanId:grant.clanId,clanName:grant.clanName,amountMinor:String(amount),basicFallback:grant.basic,recipientKind:grant.recipientKind}}:{})};
await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[requestId,actor.id,source.id,tax.id,digest,String(amount),d.title,now]);
await new PostbankPayments(bank,null,{clock}).post(b,{id:requestId,actor_id:actor.id,amount_minor:String(amount)},source,tax,false);
if(adminAmount){const adminId=randomUUID(),remaining=await b.first(accountsSQL+' WHERE a.id=?',[source.id]);await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[adminId,actor.id,source.id,admin.id,fingerprint([requestId,d.id,'administration']),String(adminAmount),d.title+' administration',now]);await new PostbankPayments(bank,null,{clock}).post(b,{id:adminId,actor_id:actor.id,amount_minor:String(adminAmount)},remaining,admin,false);}

View file

@ -17,10 +17,11 @@ import {initializeClans} from '../control-panel/clans.mjs';
import {POLITICAL_AGREEMENT_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs';
import {initializeClanFaith,createClanFaith} from '../node/clan-faith.mjs';
import {POLITICAL_APPOINTMENT_SCHEMA} from '../node/political-appointments.mjs';
import {POLITICAL_CONSULTATION_SCHEMA,createPoliticalConsultations,createPoliticalConsultationAPI} from '../node/political-consultations.mjs';
async function fixture(office='emperor',extra={}){
const f=await companyFixture(),old=f.db.query.bind(f.db);f.db.query=(sql,args=[])=>old(sql.replace(/,\s*KEY \w+\([^)]*\)/g,''),args);f.db.sqlite.function('CONCAT',{varargs:true},(...args)=>args.join(''));
f.db.sqlite.exec('ALTER TABLE political_office_terms ADD COLUMN id TEXT;ALTER TABLE political_office_terms ADD COLUMN kind TEXT;CREATE TABLE political_office_charters(office_key TEXT PRIMARY KEY,charter_kind TEXT,staff_key_id TEXT);CREATE TABLE site_character_choices(minecraft_uuid TEXT PRIMARY KEY,faction TEXT);');
await f.db.query(POLITICAL_DECISION_SCHEMA);await f.db.query(POLITICAL_AGREEMENT_SCHEMA);f.db.politicalDecisionsEnabled=true;
await f.db.query(POLITICAL_DECISION_SCHEMA);await f.db.query(POLITICAL_AGREEMENT_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await f.db.query(sql);f.db.politicalDecisionsEnabled=true;
f.db.sqlite.exec('CREATE TABLE political_proclamations(id TEXT PRIMARY KEY,request_id TEXT,scope TEXT,title TEXT,body TEXT,author_id TEXT,created_at INT,version INT);');
await initializePOLProgression(f.db);let now=1000;const pol=polProgressionStore(f.db);await pol.query("INSERT INTO jarvis_progression_seasons VALUES('S01',0,9999999999,0,25,'active',1)");await pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,10000,10000,28,1,0)',[f.people.Owner.id]);
const grant=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+office,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:grant.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[office,'royal',keyId])});
@ -257,3 +258,13 @@ async function sponsorshipFixture(){const f=await grantFixture('muad_dib');for(c
test('Church sponsorship pays the signed consenting clan and a separate Tax admin fee atomically without minting money',async()=>{const f=await sponsorshipFixture();try{const input=f.grant('NF-03',1000000),before=(await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,view=await f.service.read(f.people.Owner,'NF-03');assert.equal(view.clans[0].id,f.clanId);const r=await f.service.execute(f.people.Owner,input);assert.equal(r.feeMinor,'1250000');assert.equal(r.adminFeeMinor,'250000');assert.equal(r.grant.amountMinor,'1000000');assert.equal(r.xp,400);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,r.keyId);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,750000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,1000000);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_tax_treasury'")).balance_minor,250000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,before+2);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);}finally{f.db.close();}});
test('sponsorship rechecks current faith consent and total funding before either transfer',async()=>{for(const failure of ['consent','funds']){const f=await sponsorshipFixture();try{if(failure==='consent')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=(SELECT key_id FROM jarvis_faith_consents WHERE request_id=?)',[f.consent]);else await f.db.query('UPDATE pb_accounts SET balance_minor=1000000 WHERE id=?',[f.source.id]);await assert.rejects(f.service.execute(f.people.Owner,f.grant('NF-03',1000000)),failure==='consent'?/eligible clan/:/Insufficient funds/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}});
test('failed sponsorship administration rolls back the grant, fee, key and Reputation as one decision',async()=>{const f=await sponsorshipFixture();try{const tax=await f.db.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'"),count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec('CREATE TRIGGER fail_sponsorship_fee BEFORE INSERT ON pb_entries WHEN NEW.account_id='+Number(tax.id)+" AND NEW.amount_minor>0 BEGIN SELECT RAISE(ABORT,'administration failed');END");await assert.rejects(f.service.execute(f.people.Owner,f.grant('NF-03',1000000)),/administration failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10000);}finally{f.db.close();}});
async function consultationFixture(){const f=await grantFixture(),clans=[{id:f.clanId,actor:f.people.Other}];for(const person of [f.people.Member,f.people.Owner]){const id=randomUUID(),link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[person.id]);await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,?,?,?,?,'kaladam',?,1,1)",[id,person.username+' clan',person.username.toLowerCase()+' clan',person.username.toUpperCase(),'Native clan',person.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[person.id,link.minecraft_uuid,id]);clans.push({id,actor:person});}const consultations=createPoliticalConsultations(f.db,f.keys,{clock:f.clock}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,consultations});f.db.sqlite.exec('CREATE TABLE personal_vote_sentinel(amount INT);INSERT INTO personal_vote_sentinel VALUES(17)');return{...f,clans,consultations,service,ballot:()=>({decisionId:'ATR-02',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Council water consultation',terms:'Consult native clans about the next water distribution priorities.',confirmed:true}),vote:(ballotId,clan,choice='yes')=>({ballotId,seatKey:'clan:'+clan.id,choice,requestId:randomUUID(),confirmed:true})};}
test('Caladan consultation charges once and gives each native clan one independent institutional vote',async()=>{const f=await consultationFixture();try{const input=f.ballot(),r=await f.service.execute(f.people.Owner,input);assert.equal(r.ballot.seats.length,3);assert.equal(r.ballot.closesAt,1000+48*3600000);assert.equal(r.feeMinor,'200000');assert.equal(r.xp,250);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,r.keyId);const vote=f.vote(input.requestId,f.clans[0]);await assert.rejects(f.consultations.vote(f.people.Member,vote),/independent institutional/);const receipt=await f.consultations.vote(f.people.Other,vote);assert.equal((await f.consultations.vote(f.people.Other,vote)).reference,receipt.reference);await assert.rejects(f.consultations.vote(f.people.Other,f.vote(input.requestId,f.clans[0],'no')),/already voted/);assert.equal((await f.consultations.read(f.people.Ceo)).ballots[0].canVote,false);assert.equal((await f.db.first('SELECT amount FROM personal_vote_sentinel')).amount,17);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}});
test('consultation closes with frozen quorum, strict majority and immutable result; ties and low participation fail',async()=>{for(const [choices,expected]of [[['yes'],'no_quorum'],[['yes','no'],'not_adopted'],[['yes','yes','no'],'yes']]){const f=await consultationFixture();try{const input=f.ballot(),r=await f.service.execute(f.people.Owner,input);for(let i=0;i<choices.length;i++)await f.consultations.vote(f.clans[i].actor,f.vote(input.requestId,f.clans[i],choices[i]));f.setTime(r.ballot.closesAt);await assert.rejects(f.consultations.vote(f.people.Owner,f.vote(input.requestId,f.clans[2])),/no longer open|already voted/);assert.equal((await f.consultations.reconcile()).closed,1);const before=(await f.consultations.read(f.people.Owner)).ballots[0];assert.equal(before.tally.result,expected);assert.equal(before.tally.quorum,2);await f.db.query("UPDATE site_clans SET active=0 WHERE id=?",[f.clans[0].id]);assert.deepEqual((await f.consultations.read(f.people.Owner)).ballots[0].tally,before.tally);assert.equal((await f.consultations.reconcile()).closed,0);}finally{f.db.close();}}});
test('mother control cannot vote for a client clan and revoked votes cannot be replaced or counted',async()=>{const f=await consultationFixture();try{const input=f.ballot();await f.service.execute(f.people.Owner,input);await f.db.query('INSERT INTO site_clan_deeds(clan_id,parent_clan_id,updated_at) VALUES(?,?,1)',[f.clanId,f.clans[2].id]);await assert.rejects(f.consultations.vote(f.people.Owner,f.vote(input.requestId,f.clans[0])),/independent institutional/);const receipt=await f.consultations.vote(f.people.Other,f.vote(input.requestId,f.clans[0]));await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.reference]);const own=(await f.consultations.read(f.people.Other)).ballots[0];assert.equal(own.ownSeats[0].vote,'recorded-invalid');assert.equal(own.canVote,false);assert.equal(own.participation,0);}finally{f.db.close();}});
test('consultation and vote journal failures roll back payments, Reputation and scoped keys',async()=>{const f=await consultationFixture();try{const input=f.ballot(),count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_consultation BEFORE INSERT ON jarvis_political_consultations BEGIN SELECT RAISE(ABORT,'consultation failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/consultation failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);f.db.sqlite.exec('DROP TRIGGER fail_consultation');await f.service.execute(f.people.Owner,input);const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_institutional_vote BEFORE INSERT ON jarvis_political_consultation_votes BEGIN SELECT RAISE(ABORT,'vote journal failed');END");await assert.rejects(f.consultations.vote(f.people.Other,f.vote(input.requestId,f.clans[0])),/vote journal failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_political_consultation_votes')).n,0);}finally{f.db.close();}});
test('Landsraad snapshots occupied Royal Great Houses and current mandates alone can cast each House vote',async()=>{const f=await diplomacyFixture('emperor');try{const consultations=createPoliticalConsultations(f.db,f.keys,{clock:f.clock}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,consultations}),input={decisionId:'IMP-05',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Landsraad deliberation',terms:'Deliberate the priorities of the Great Houses without changing election rights.',confirmed:true};const r=await service.execute(f.people.Owner,input);assert.deepEqual(r.ballot.seats.map(s=>s.id),['corrino']);assert.equal(r.ballot.closesAt,1000+72*3600000);const vote={ballotId:input.requestId,seatKey:'office:corrino',choice:'yes',requestId:randomUUID(),confirmed:true};await assert.rejects(consultations.vote(f.people.Owner,vote),/independent institutional/);await consultations.vote(f.people.Other,vote);f.setTime(r.ballot.closesAt);await consultations.reconcile();assert.equal((await consultations.read(f.people.Owner)).ballots[0].tally.result,'yes');}finally{f.db.close();}});
test('consultation API rejects foreign writes, identity overrides and invalid input without votes',async()=>{const f=await consultationFixture();try{const api=createPoliticalConsultationAPI(f.db,f.consultations,{authenticate:async()=>f.people.Other}),input=f.vote(randomUUID(),f.clans[0]),post=(body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/consultations',{method:'POST',headers:{origin},body:JSON.stringify(body)}));assert.equal((await post(input,'https://example.invalid')).status,403);assert.equal((await post({...input,actorId:f.people.Owner.id})).status,400);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_political_consultation_votes')).n,0);}finally{f.db.close();}});
test('late consultation workers retain a valid deadline result after natural mandate expiry',async()=>{const f=await consultationFixture();try{const input=f.ballot(),deadline=1000+48*3600000;await f.db.query('UPDATE political_office_terms SET expires_at=? WHERE id=?',[deadline+1,f.term]);await f.service.execute(f.people.Owner,input);for(const clan of f.clans.slice(0,2))await f.consultations.vote(clan.actor,f.vote(input.requestId,clan));f.setTime(deadline+120000);await f.consultations.reconcile();assert.equal((await f.consultations.read(f.people.Owner)).ballots[0].tally.result,'yes');}finally{f.db.close();}});