Gate House missionary laws through verified personal referendums
This commit is contained in:
parent
2716317838
commit
f6b23882dd
13 changed files with 337 additions and 15 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import {houseFaithDecision} from '../house-faith-policy.mjs';
|
||||
import {clanFaithDecision} from '../clan-faith-policy.mjs';
|
||||
import {tradeDecision} from '../world-trade-policy.mjs';
|
||||
import {politicalDecision} from '../political-decision-policy.mjs';
|
||||
|
|
@ -9,5 +10,5 @@ const related={
|
|||
'FRE-01':{adapter:'createNaibCouncil',gap:'The independent Council vote already enforces current sietch deed, one vote per sietch, 24 hours, quorum and tie rejection. The v2.2 1,000 DM fee and quest XP award are not enabled.'}
|
||||
};
|
||||
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'};
|
||||
export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status: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: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: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)?'Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically; existing publication/profile consumers display the result.':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:!!clanFaithDecision(d.id)||!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)})));
|
||||
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)?'Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically; existing publication/profile consumers display the result.':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;
|
||||
|
|
|
|||
24
website/control-panel/public/cp-v2/cp-v2-house-faith.mjs
Normal file
24
website/control-panel/public/cp-v2/cp-v2-house-faith.mjs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
const names={veiled_concord:'Old Faith · Veiled Concord',muad_dib:'New Faith · Church of Muad’Dib'};
|
||||
export function mountHouseFaith(host,decisionId,{fetcher=fetch}={}){
|
||||
const api=createUserAPI(fetcher),endpoint='/api/politics/house-faith',status=el('p','Reading House referendums…'),form=el('section'),ballots=el('section'),review=el('p'),confirm=el('button','Confirm'),cancel=el('button','Cancel');status.setAttribute('role','status');confirm.hidden=cancel.hidden=true;for(const b of [confirm,cancel])b.type='button';host.append(status,form,ballots,review,confirm,cancel);let pending=null,busy=false;
|
||||
function controls(){for(const b of [...form.querySelectorAll('button,select'),...ballots.querySelectorAll('button')])b.disabled=busy||!!pending;confirm.disabled=cancel.disabled=busy;}
|
||||
function prepare(payload,message){pending={...payload,confirmed:true,requestId:crypto.randomUUID()};review.textContent=message;confirm.hidden=cancel.hidden=false;controls();}
|
||||
async function load(){busy=true;controls();try{
|
||||
const data=await api.request(endpoint+'?decisionId='+encodeURIComponent(decisionId));if(!host.isConnected)return;
|
||||
status.textContent='One personal vote per verified House citizen. Voting lasts 48 hours; a majority of the recorded electorate must participate and more than half of votes must agree. Existing clan faith and earned rewards stay unchanged.';
|
||||
form.replaceChildren();if(data.canManage){form.append(el('p','Reputation '+data.levelNow+'/5. '+(data.cooldownUntil>Date.now()?'Next proposal: '+new Date(data.cooldownUntil).toLocaleString()+'.':'This House can propose once every seven days.')));
|
||||
const faith=el('select'),policy=el('select');faith.setAttribute('aria-label','Faith');policy.setAttribute('aria-label','Missionary law');for(const [key,name]of Object.entries(names)){const o=el('option',name);o.value=key;faith.append(o);}for(const [value,name]of [['prohibit','Prohibit new conversions'],['allow','Allow new conversions']]){const o=el('option',name);o.value=value;policy.append(o);}
|
||||
const b=el('button','Review referendum');b.type='button';b.disabled=!data.canPropose;b.dataset.unavailable=String(!data.canPropose);b.onclick=()=>prepare({action:'propose',decisionId,faith:faith.value,prohibited:policy.value==='prohibit'},'Open a 48-hour vote: '+policy.selectedOptions[0].textContent+' to '+names[faith.value]+'. A passed law lasts at most seven days and ends when the source mandate ends. No funds or XP are issued.');form.append(faith,policy,b);
|
||||
}
|
||||
ballots.replaceChildren(el('h4','House referendums'));for(const ballot of data.ballots){const card=el('article',undefined,'organisation-settings-card');card.append(el('h4',(ballot.prohibited?'Prohibit':'Allow')+' new conversions · '+names[ballot.faith]),el('p',ballot.state==='open'?'Closes '+new Date(ballot.closesAt).toLocaleString(): 'Result: '+ballot.result.replaceAll('_',' ')),el('p',ballot.electorate+' verified citizens in the recorded electorate'));
|
||||
if(ballot.state==='open'&&Date.now()>=ballot.closesAt)card.append(el('p','Voting has closed. The next scheduled reconciliation records the result.'));
|
||||
if(ballot.ownVote)card.append(el('p','Your vote: '+ballot.ownVote));if(ballot.tally)card.append(el('p',ballot.tally.yes+' yes · '+ballot.tally.no+' no · quorum '+ballot.tally.quorum));if(ballot.expiresAt)card.append(el('p','Law expires '+new Date(ballot.expiresAt).toLocaleString()+'. A revoked or ended mandate makes it inactive sooner.'));
|
||||
if(ballot.canVote)for(const choice of ['yes','no']){const b=el('button',choice==='yes'?'Review support':'Review opposition');b.type='button';b.onclick=()=>prepare({action:'vote',ballotId:ballot.id,choice},'Record your definitive '+choice+' vote. It does not spend candidate-election votes or change your personal voting rights.');card.append(b);}ballots.append(card);
|
||||
}if(!data.ballots.length)ballots.append(el('p','No House referendums have been recorded.'));
|
||||
}catch(e){status.textContent=e.message;}finally{busy=false;controls();for(const b of form.querySelectorAll('button[data-unavailable="true"]'))b.disabled=true;}}
|
||||
cancel.onclick=()=>{pending=null;confirm.hidden=cancel.hidden=true;review.textContent='';void load();};
|
||||
confirm.onclick=async()=>{if(!pending||busy)return;busy=true;controls();try{await api.request(endpoint,pending);pending=null;confirm.hidden=cancel.hidden=true;review.textContent='Confirmed and recorded.';}catch(e){review.textContent=e.message+(e.uncertain?' Retry this same confirmation to check its result.':'');if(!e.uncertain){pending=null;confirm.hidden=cancel.hidden=true;}}finally{busy=false;await load();}};
|
||||
void load();
|
||||
}
|
||||
|
|
@ -1,10 +1,12 @@
|
|||
import {POLITICAL_DECISION_CATALOGUE} from '../political-decision-policy.mjs';
|
||||
import {CLAN_FAITH_DECISIONS} from '../clan-faith-policy.mjs';
|
||||
import {HOUSE_FAITH_DECISIONS} from '../house-faith-policy.mjs';
|
||||
import {TRADE_DECISIONS} from '../world-trade-policy.mjs';
|
||||
import {decisionCooldownMs} from '../action-cooldown-policy.mjs';
|
||||
import {IMPERIAL_PASSAGE_DECISION} from '../imperial-passage-policy.mjs';
|
||||
import {FAITH_BLESSING_CATALOGUE} from '../faith-blessing-policy.mjs';
|
||||
// Design-only catalogue from accepted handovers; does not issue state or authority.
|
||||
// Accepted proposals with connected fixed policies. Only domain adapters can
|
||||
// execute them; catalogue fields never establish state or authority.
|
||||
export const MISSION_BRANCHES=[
|
||||
{
|
||||
"id": "a",
|
||||
|
|
@ -948,4 +950,4 @@ export const DECISION_CATALOGUE=[
|
|||
"cost": "2,500 / 72h",
|
||||
"office": "CLD"
|
||||
}
|
||||
,...POLITICAL_DECISION_CATALOGUE.filter(d=>d.id.endsWith('-PROCLAIM')),...TRADE_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE',spacing_guild:'SG'})[d.office],xp:0,cost:'0 / 7d',xpType:'pol',executionStatus:'world-trade-controller'}))].flatMap(decision=>decision.office==='BG'&&decision.id!=='BG-01'?[decision,{...decision,id:decision.id.replace('BG-','NF-'),office:'NF',copiedFrom:decision.id,title:decision.title.replaceAll('Sisterhood','Church'),effect:decision.effect.replaceAll('Sisterhood','Church')}]:[decision]).concat(CLAN_FAITH_DECISIONS.map(d=>({...d,office:d.office==='muad_dib'?'NF':'BG',cost:'0 / 24h',xpType:'pol',executionStatus:'clan-faith-controller'}))).map(decision=>Object.freeze({...decision,...POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id),...FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id),cooldownMs:FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??decisionCooldownMs(decision)}));
|
||||
,...POLITICAL_DECISION_CATALOGUE.filter(d=>d.id.endsWith('-PROCLAIM')),...TRADE_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE',spacing_guild:'SG'})[d.office],xp:0,cost:'0 / 7d',xpType:'pol',executionStatus:'world-trade-controller'}))].flatMap(decision=>decision.office==='BG'&&decision.id!=='BG-01'?[decision,{...decision,id:decision.id.replace('BG-','NF-'),office:'NF',copiedFrom:decision.id,title:decision.title.replaceAll('Sisterhood','Church'),effect:decision.effect.replaceAll('Sisterhood','Church')}]:[decision]).concat(CLAN_FAITH_DECISIONS.map(d=>({...d,office:d.office==='muad_dib'?'NF':'BG',cost:'0 / 24h',xpType:'pol',executionStatus:'clan-faith-controller'}))).concat(HOUSE_FAITH_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE'})[d.office],xpType:'pol'}))).map(decision=>Object.freeze({...decision,...POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id),...FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id),cooldownMs:FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??decisionCooldownMs(decision)}));
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import {faithBlessing} from '../faith-blessing-policy.mjs';
|
||||
import {mountFaithInvitation} from './cp-v2-clan-faith.mjs';
|
||||
import {mountHouseFaith} from './cp-v2-house-faith.mjs';
|
||||
import {mountWorldTrade} from './cp-v2-world-trade.mjs';
|
||||
import {appendOfficeMissionPreview,appendOfficeMissionBanner,appendOfficeDecisionBanner,planningImage} from './cp-v2-war-planning.mjs';
|
||||
import {POL_PLANNING_ART,officeDecisionPreviews} from './cp-v2-war-planning-content.mjs';
|
||||
|
|
@ -43,6 +44,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
|
|||
if(isDecision&&faithBlessing(row.id)){mountFaithBlessing(pane,row.id);return pane;}
|
||||
if(isDecision&&politicalDecision(row.id)){mountPoliticalDecision(pane,row.id);return pane;}
|
||||
if(isDecision&&row.executionStatus==='clan-faith-controller'){mountFaithInvitation(pane,row.office==='NF'?'muad_dib':'veiled_concord');return pane;}
|
||||
if(isDecision&&row.executionStatus==='house-faith-controller'){mountHouseFaith(pane,row.id);return pane;}
|
||||
if(isDecision&&row.executionStatus==='world-trade-controller'){mountWorldTrade(pane,row.id);return pane;}
|
||||
if(isDecision&&row.id==='IMP-10'){mountImperialPassage(pane);return pane;}
|
||||
if(isDecision&&row.executionStatus==='war-exchange-controller'){const link=el('a','Open War Exchange →');link.href='#household/war-exchange';pane.append(el('p','Current organisation authority is checked on every action. Both organisations approve alliances; all sides must choose the same hour. Changes clear previous calendar consent. No DM or XP is awarded for a proposal.'),link);return pane;}
|
||||
|
|
@ -61,7 +63,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
|
|||
connectorObserver=new ResizeObserver(connect);connectorObserver.observe(tree);requestAnimationFrame(connect);
|
||||
}
|
||||
function renderDecisions(){if(activeContext==='politics')appendOfficeDecisionBanner(content,officeCode);if(activeContext==='politics'&&!manage){const live=el('div');content.append(live);disposePersonal=mountOfficeRebellionDecisions(live,{officeKey:organisation?.id||({IMP:'emperor',ATR:'atreides',HAR:'harkonnen',COR:'corrino',ORD:'ordos',FRE:'fremen',BG:'veiled_concord',NF:'muad_dib',SG:'spacing_guild',CLD:'clan_delegate'})[officeCode]});}const toolbar=el('div',undefined,'progression-toolbar'),search=el('input');search.type='search';search.placeholder='Search decisions';search.setAttribute('aria-label','Search decisions');search.value=query;search.oninput=()=>{query=search.value;renderDecisionsList();};toolbar.append(search);if(activeContext==='personal'&&xpKind==='pol'){const chooser=field('Questgiver',POL_QUEST_BRANCHES.map(b=>b.title));chooser.querySelector('select').selectedIndex=POL_QUEST_BRANCHES.findIndex(b=>b.id===polDecisionBranch);chooser.onchange=e=>{polDecisionBranch=POL_QUEST_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(chooser);}if((dashboard&&activeContext==='politics')||manage){const chooser=field('Office catalogue',OFFICES.map(([,name])=>name));chooser.querySelector('select').selectedIndex=OFFICES.findIndex(([id])=>id===officeCode);chooser.onchange=e=>{officeCode=OFFICES[e.target.selectedIndex][0];selected=null;render();};toolbar.append(chooser);}content.append(toolbar);const listHost=el('div');content.append(listHost);
|
||||
function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',row.executionStatus==='clan-faith-controller'?'Invite a clan':row.executionStatus==='world-trade-controller'?'Review trade decision':politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':faithBlessing(row.id)?'Prepare clan blessing':row.executionStatus==='war-exchange-controller'?'Manage war agreement':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList();
|
||||
function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',row.executionStatus==='clan-faith-controller'?'Invite a clan':row.executionStatus==='house-faith-controller'?'Review House referendum':row.executionStatus==='world-trade-controller'?'Review trade decision':politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':faithBlessing(row.id)?'Prepare clan blessing':row.executionStatus==='war-exchange-controller'?'Manage war agreement':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList();
|
||||
}
|
||||
function render(){dossier.close();connectorObserver?.disconnect();disposePersonal?.();disposePersonal=null;notice.textContent=activeContext==='personal'&&!manage?(xpKind==='pol'?'Reputation missions use verified J.A.R.V.I.S. records and their system questgivers. Decision execution awaits configuration.':'Personal missions use verified J.A.R.V.I.S. records. Decision and organisation integrations remain in preview.'):'Connected decisions open a review and confirmation. Other proposals remain unavailable until their consumers are connected.';root.dataset.context=activeContext;notice.hidden=activeContext==='personal'&&!manage;nav.hidden=report.available&&activeContext==='personal'&&!manage;report.setNavigation(xpKind,tab);report.showBranches(activeContext==='personal');xpNav.replaceChildren();xpNav.hidden=activeContext!=='personal'||manage||report.available;if(!xpNav.hidden)for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const b=button(label,()=>{xpKind=kind;selected=null;render();});b.setAttribute('aria-pressed',String(kind===xpKind));xpNav.append(b);}contextNav.replaceChildren();for(const[id,[label]]of Object.entries(CONTEXTS)){const b=button(label,()=>{activeContext=id;selected=null;query='';render();});b.setAttribute('aria-pressed',String(id===activeContext));contextNav.append(b);}renderGallery();nav.replaceChildren();for(const[id,label]of [['missions',manage?'Mission Definitions':'Missions'],['decisions',manage?'Decision Definitions':'Decisions'],...(manage?[['rewards','Progression & Rewards']]:[]),['history','History']]){const b=button(label,()=>{tab=id;selected=null;render();});b.setAttribute('aria-pressed',String(tab===id));nav.append(b);}content.replaceChildren();if(activeContext==='clan'&&!manage){notice.hidden=true;disposePersonal=mountClanRebellions(content,{clanId:organisation?.id||null,embedded:true,view:tab,onDecisions:()=>{tab='decisions';render();}});return;}if(activeContext==='personal'&&!manage&&['missions','history'].includes(tab))disposePersonal=mountPersonalProgression(content,{view:tab,apiBase:xpKind==='pol'?'/api/progression/pol':'/api/progression',externalBranches:report.available,initialBranch:branch,onData:data=>report.setJournal(xpKind,data),onBranches:(rows,id)=>{branch=id;report.setBranches(rows,id);}});else if(tab==='missions')renderMissions();else if(tab==='decisions')renderDecisions();else if(tab==='rewards'){content.append(el('h3','Progression & Rewards'),field('Season cap',['70 · proposed']),field('Milestone announcements',['Halfway and completion only']),el('p','Rewards, XP curves, repair recipes and signing editions await backend review. No configuration writes enabled.'));}else content.append(el('h3','J.A.R.V.I.S. History'),el('p','Verified completion, claims, decisions and any staff overrides will appear here after integration. No sample audit records are shown.'));}
|
||||
render();return()=>{dossier.dispose();connectorObserver?.disconnect();disposePersonal?.();report.dispose();root.remove();};
|
||||
|
|
|
|||
7
website/control-panel/public/decision-ballot-policy.mjs
Normal file
7
website/control-panel/public/decision-ballot-policy.mjs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
// Shared quorum and strict-majority rule. Callers supply their actual seat or
|
||||
// player identity; this does not allocate or consume candidate-election votes.
|
||||
export function decisionBallotOutcome(choices,seats,votes){
|
||||
if(!Number.isInteger(seats)||seats<1||votes.length>seats||new Set(votes.map(v=>v.identity)).size!==votes.length||votes.some(v=>!v.identity||!choices.includes(v.choice)))throw Error('Ballot records require review.');
|
||||
const quorum=Math.floor(seats/2)+1,counts=Object.fromEntries(choices.map(choice=>[choice,votes.filter(v=>v.choice===choice).length])),winner=choices.find(choice=>counts[choice]>votes.length/2)||null;
|
||||
return{quorum,participation:votes.length,counts,result:votes.length<quorum?'no_quorum':winner||'not_adopted'};
|
||||
}
|
||||
9
website/control-panel/public/house-faith-policy.mjs
Normal file
9
website/control-panel/public/house-faith-policy.mjs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import {TRADE_WORLDS} from './world-trade-policy.mjs';
|
||||
export const FAITH_BALLOT_MS=48*3600000;
|
||||
export const FAITH_LAW_MS=7*86400000;
|
||||
export const HOUSE_FAITH_DECISIONS=Object.freeze(TRADE_WORLDS.map(w=>Object.freeze({
|
||||
id:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE'})[w.house]+'-FAITH',office:w.house,world:w.id,
|
||||
title:'Missionary law referendum',level:5,xp:0,cost:'0 / 7d',cooldownMs:FAITH_LAW_MS,executionStatus:'house-faith-controller',
|
||||
effect:'Ask verified House citizens to allow or prohibit new Old Faith or New Faith conversions on '+w.name+'. Voting lasts 48 hours; a majority of the recorded electorate must vote and more than half of votes must agree. A passed law lasts at most seven days and ends with its source mandate. Existing clan faith and earned rewards remain unchanged.'
|
||||
})));
|
||||
export const houseFaithDecision=id=>HOUSE_FAITH_DECISIONS.find(d=>d.id===id)||null;
|
||||
|
|
@ -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('faith.house-referendum','House missionary-law referendum','entity-state',[field('decisionId','House decision','select',{options:['ATR-FAITH','HAR-FAITH','COR-FAITH','ORD-FAITH','FRE-FAITH']}),field('faith','Faith','select',{options:['veiled_concord','muad_dib']}),field('prohibited','Prohibit new conversions','boolean'),field('requestId','Referendum UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createHouseFaithLaws.propose / reconcile / missionaryFaithOutlawed',executionStatus:'current-house-authority-personal-ballot-consumer',effect:'Current Royal elected House holder and Reputation 5. Frozen verified House electorate; 48-hour vote, majority quorum and strict majority. Seven-day office cooldown survives succession. An adopted law lasts at most seven days and ends with its source mandate; the latest signed law gates only new faith offers and acceptance on the registered clan homeworld. Existing allegiance and earned rewards remain unchanged. No fee, XP, election-clock change or personal vote transfer. Private scheduled settlement is idempotent; key revocation never restores an older law.'}),
|
||||
action('faith.house-ballot-vote','Personal missionary-law vote','entity-state',[field('ballotId','House referendum UUID'),field('choice','Vote','select',{options:['yes','no']}),field('requestId','Vote UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createHouseFaithLaws.vote',executionStatus:'current-recorded-house-citizen-only',effect:'One immutable personal vote per linked Minecraft UUID in the recorded electorate. Revalidate the current House, account and link under transaction locks; no staff bypass or candidate-election vote consumption. Open choices and totals remain private; the closed tally is sealed at settlement. Exact retries reuse their receipt and cannot cast or pay twice.'}),
|
||||
action('faith.invitation','Invite a clan to a faith','entity-state',[field('decisionId','Faith decision','select',{options:['BG-CONVERT','NF-CONVERT']}),field('clanId','Active clan UUID'),field('requestId','Invitation UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createClanFaith.offer',executionStatus:'current-faith-officer-service',effect:'Current Royal faith leader or canonical appointed officer, Reputation 5, one invitation per office per 24 hours. Signed offer expires after 72 hours. It changes no clan faith, membership, owner, vote or account. Target-clan owner must separately consent; any configured missionary-law consumer is checked again on acceptance.'}),
|
||||
action('faith.blessing','Consenting clan faith bonus','entity-state',[field('decisionId','Registered faith bonus','select',{options:['holy-day','sacred-bounty','prior-blessing','sisterhood-discipline','sisterhood-patronage','reverend-blessing']}),field('clanId','Consenting clan UUID'),field('requestId','Bonus UUID')],{version:2,webIssue:false,recordOnly:true,domainAdapter:'createFaithBlessings/faithMultipliers/validFaithReward',executionStatus:'current-faith-authority-and-owner-consent-service',effect:'Old Faith and New Faith share the existing clan XP/funded-DM bonus consumer. Revalidate the Royal office, current leader or assigned clan officer, owner-approved allegiance, source term and cooldown. Bonuses cap at twice the normal reward and expire with the source appointment. New reward proofs bind the accepted faith at claim time; a later lawful conversion cannot redirect or cancel an already earned queued payment. Existing pre-consent blessings retain only their original expiry and become inactive upon an opposing clan choice.'}),
|
||||
action('progression.faith-service-policy','Consenting faith community quest policy','progression-policy',[],{version:6,webIssue:false,recordOnly:true,domainAdapter:'ensureFaithQuestPolicy/faithQuestEvidence',executionStatus:'verified-consent-evidence-consumer',effect:'Install six Old Faith and New Faith Reputation quests through policy:POL:S01:v6. Count one, three and five distinct currently consenting active clans invited by the current authorised faith specialist. Re-read the signed invitation and legal-owner consent, current faith and current authority at claim. Small separate Personal XP rewards; fixed DM queued from P&O to the faith office payment account. New research payments use the same transaction and Basic organisations route to the current legal owner; legacy payment receipts remain unchanged.'}),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import {createOrganisationFundedRewards} from '../node/organisation-quest-rewards.mjs';
|
||||
import {ensureFaithQuestPolicy} from '../node/progression-pol.mjs';
|
||||
import {initializeClanFaith,createClanFaithAPI} from '../node/clan-faith.mjs';
|
||||
import {initializeClanFaith,createClanFaithAPI,createClanFaith} from '../node/clan-faith.mjs';
|
||||
import {initializeHouseFaith,createHouseFaithAPI,createHouseFaithLaws,missionaryFaithOutlawed} from '../node/house-faith-laws.mjs';
|
||||
import {initializeWorldTrade,createWorldTradeAPI} from '../node/world-trade-governance.mjs';
|
||||
import {publicWelcomeContext} from '../node/welcome-context.mjs';
|
||||
import {createEconomyRuntime} from '../node/economy-runtime.mjs';
|
||||
|
|
@ -282,7 +283,8 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const gameGuild=createGameGuildAPI(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings);
|
||||
const politicalDecisions=createPoliticalDecisions(db,dependencies.bankDatabase||null,dependencies.organisationKeys);
|
||||
const politicalDecisionAPI=createPoliticalDecisionAPI(db,politicalDecisions,{origin});
|
||||
const clanFaith=createClanFaithAPI(db,dependencies.organisationKeys,{origin});
|
||||
const clanFaith=createClanFaithAPI(db,dependencies.organisationKeys,{origin,service:createClanFaith(db,dependencies.organisationKeys,{isOutlawed:missionaryFaithOutlawed})});
|
||||
const houseFaith=createHouseFaithAPI(db,dependencies.organisationKeys,{origin});
|
||||
const worldTrade=createWorldTradeAPI(db,dependencies.organisationKeys,{origin,bank:dependencies.bankDatabase||null});
|
||||
const imperialPassage=createImperialPassageAPI(db,dependencies.organisationKeys,{origin});
|
||||
const faithBlessings=createFaithBlessingAPI(db,dependencies.organisationKeys,{origin});
|
||||
|
|
@ -391,6 +393,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path==='/api/network/layout')return networkLayouts(request);
|
||||
if(path==='/api/politics/decisions')return politicalDecisionAPI(request);
|
||||
if(path==='/api/politics/faith')return clanFaith(request);
|
||||
if(path==='/api/politics/house-faith')return houseFaith(request);
|
||||
if(path==='/api/politics/world-trade')return worldTrade(request);
|
||||
if(path==='/api/politics/arrakis-passage')return imperialPassage(request);
|
||||
if(path==='/api/politics/faith-blessings')return faithBlessings(request);
|
||||
|
|
@ -559,7 +562,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||||
}
|
||||
const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1);
|
||||
if(!['kitset-model.mjs','item-design-model.mjs','item-metadata-policy.mjs','mining-tool-policy.mjs','tool-template-policy.mjs','equipment-template-policy.mjs','organisation-refit-policy.mjs','organisation-research-policy.mjs','action-cooldown-policy.mjs','political-decision-policy.mjs','world-trade-policy.mjs','clan-faith-policy.mjs','imperial-passage-policy.mjs','faith-blessing-policy.mjs','faith-pol-policy.mjs','item-lore-model.mjs','item-lore-view.mjs','item-lore.css','organisation-editor.mjs','organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','starter-kit-policy.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404});
|
||||
if(!['kitset-model.mjs','item-design-model.mjs','item-metadata-policy.mjs','mining-tool-policy.mjs','tool-template-policy.mjs','equipment-template-policy.mjs','organisation-refit-policy.mjs','organisation-research-policy.mjs','action-cooldown-policy.mjs','political-decision-policy.mjs','world-trade-policy.mjs','clan-faith-policy.mjs','house-faith-policy.mjs','decision-ballot-policy.mjs','imperial-passage-policy.mjs','faith-blessing-policy.mjs','faith-pol-policy.mjs','item-lore-model.mjs','item-lore-view.mjs','item-lore.css','organisation-editor.mjs','organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','starter-kit-policy.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404});
|
||||
return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}});
|
||||
};
|
||||
}
|
||||
|
|
@ -571,9 +574,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);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);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:'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:'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);}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "19e19b7887345eeca81b2d7dc1bb7c817f7f0b02432cf1d0ed7d5aa7a5ea744f",
|
||||
"sourceHash": "c0c49bb831ad6b71f2c30a8ba8e68fe0dbe7b8ef83336b0a8f0331491512d64a",
|
||||
"actions": [
|
||||
{
|
||||
"id": "war.coalition-consent",
|
||||
|
|
@ -431,6 +431,101 @@
|
|||
"webIssue": false,
|
||||
"recordOnly": false
|
||||
},
|
||||
{
|
||||
"id": "faith.house-referendum",
|
||||
"label": "POL & orders · House missionary-law referendum",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "decisionId",
|
||||
"label": "House decision",
|
||||
"type": "select",
|
||||
"required": true,
|
||||
"options": [
|
||||
"ATR-FAITH",
|
||||
"HAR-FAITH",
|
||||
"COR-FAITH",
|
||||
"ORD-FAITH",
|
||||
"FRE-FAITH"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "faith",
|
||||
"label": "Faith",
|
||||
"type": "select",
|
||||
"required": true,
|
||||
"options": [
|
||||
"veiled_concord",
|
||||
"muad_dib"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "prohibited",
|
||||
"label": "Prohibit new conversions",
|
||||
"type": "boolean",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "requestId",
|
||||
"label": "Referendum UUID",
|
||||
"type": "text",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Current Royal elected House holder and Reputation 5. Frozen verified House electorate; 48-hour vote, majority quorum and strict majority. Seven-day office cooldown survives succession. An adopted law lasts at most seven days and ends with its source mandate; the latest signed law gates only new faith offers and acceptance on the registered clan homeworld. Existing allegiance and earned rewards remain unchanged. No fee, XP, election-clock change or personal vote transfer. Private scheduled settlement is idempotent; key revocation never restores an older law.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "faith.house-ballot-vote",
|
||||
"label": "POL & orders · Personal missionary-law vote",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
{
|
||||
"name": "ticketId",
|
||||
"label": "Ban / support ticket ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"maxLength": 80
|
||||
},
|
||||
{
|
||||
"name": "ballotId",
|
||||
"label": "House referendum UUID",
|
||||
"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": "One immutable personal vote per linked Minecraft UUID in the recorded electorate. Revalidate the current House, account and link under transaction locks; no staff bypass or candidate-election vote consumption. Open choices and totals remain private; the closed tally is sealed at settlement. Exact retries reuse their receipt and cannot cast or pay twice.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
},
|
||||
{
|
||||
"id": "faith.invitation",
|
||||
"label": "POL & orders · Invite a clan to a faith",
|
||||
|
|
|
|||
107
website/node/house-faith-laws.mjs
Normal file
107
website/node/house-faith-laws.mjs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {boardReadStore} from './board-deed-source.mjs';
|
||||
import {officeAuthority} from './political-decisions.mjs';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {validUuid} from './game-link.mjs';
|
||||
import {polProgressionStore} from './progression-pol.mjs';
|
||||
import {readActiveXPSeason} from './progression-xp-store.mjs';
|
||||
import {levelForXP} from './progression-definitions.mjs';
|
||||
import {identity} from './auth.mjs';
|
||||
import {accessFor} from './permissions.mjs';
|
||||
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
|
||||
import {decisionBallotOutcome} from '../control-panel/public/decision-ballot-policy.mjs';
|
||||
import {FAITH_BALLOT_MS,FAITH_LAW_MS,HOUSE_FAITH_DECISIONS,houseFaithDecision} from '../control-panel/public/house-faith-policy.mjs';
|
||||
export const HOUSE_FAITH_SCHEMA=[
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_locks(office_key VARCHAR(32) PRIMARY KEY,last_proposed_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_ballots(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,decision_id VARCHAR(24) NOT NULL,office_key VARCHAR(32) NOT NULL,world VARCHAR(32) NOT NULL,faith_key VARCHAR(32) NOT NULL,prohibited INT NOT NULL,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,input_hash CHAR(64) NOT NULL,electorate TEXT NOT NULL,opens_at BIGINT NOT NULL,closes_at BIGINT NOT NULL,mandate_expires_at BIGINT NOT NULL,state VARCHAR(24) NOT NULL,result VARCHAR(24),expires_at BIGINT,tally_json TEXT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_votes(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,ballot_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) 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 faith_ballot_player(ballot_id,minecraft_uuid)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_house_faith_rules(world VARCHAR(32) NOT NULL,faith_key VARCHAR(32) NOT NULL,request_id CHAR(36) NOT NULL,PRIMARY KEY(world,faith_key)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
];
|
||||
const fail=(m,status=409)=>{throw Object.assign(Error(m),{status});};
|
||||
const digest=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||||
const exact=(v,names)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join(',')===names;
|
||||
const faiths=['veiled_concord','muad_dib'];
|
||||
export async function initializeHouseFaith(db){for(const sql of HOUSE_FAITH_SCHEMA)await db.query(sql);for(const d of HOUSE_FAITH_DECISIONS)await db.query('INSERT INTO jarvis_house_faith_locks(office_key) VALUES(?) ON DUPLICATE KEY UPDATE office_key=VALUES(office_key)',[d.office]);db.houseFaithEnabled=true;}
|
||||
async function electors(db,office,{lock=false}={}){
|
||||
const rows=await db.query("SELECT a.id userId,l.minecraft_uuid playerUuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.minecraft_uuid=l.minecraft_uuid WHERE c.faction=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=a.id) AND (SELECT COUNT(*) FROM site_game_links x WHERE LOWER(x.minecraft_uuid)=LOWER(l.minecraft_uuid))=1 ORDER BY a.id LIMIT 5001"+(lock?' FOR SHARE':''),[office]);
|
||||
if(rows.length>5000)fail('The House electorate requires review.',503);
|
||||
if(rows.some(r=>!validUuid(r.userId)||!validUuid(r.playerUuid))||new Set(rows.map(r=>r.playerUuid.toLowerCase())).size!==rows.length||new Set(rows.map(r=>r.userId)).size!==rows.length)fail('The House electorate requires review.',409);
|
||||
return rows.map(r=>({userId:r.userId,playerUuid:r.playerUuid.toLowerCase()}));
|
||||
}
|
||||
// A referendum is distinct from a candidate election: one verified personal
|
||||
// identity, no vote allocations consumed and no change to the election clock.
|
||||
export function faithBallotOutcome(seats,votes){
|
||||
let tally;try{tally=decisionBallotOutcome(['yes','no'],seats,votes.map(v=>({identity:v.minecraft_uuid,choice:v.choice})));}catch{fail('Faith ballot records require review.');}
|
||||
return{participation:tally.participation,quorum:tally.quorum,yes:tally.counts.yes,no:tally.counts.no,result:tally.result==='yes'?'adopted':tally.result==='no'?'not_adopted':tally.result};
|
||||
}
|
||||
const proofSQL="SELECT b.*,k.id verified_key FROM jarvis_house_faith_ballots b LEFT JOIN organisation_keys k ON k.id=b.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:house-faith-ballot:',b.request_id) AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>?)";
|
||||
function validBallot(row){
|
||||
const d=houseFaithDecision(row?.decision_id);return !!row?.verified_key&&!!d&&d.world===row.world&&d.office===row.office_key&&faiths.includes(row.faith_key)&&[0,1].includes(Number(row.prohibited))&&Number.isSafeInteger(Number(row.opens_at))&&Number(row.closes_at)===Number(row.opens_at)+FAITH_BALLOT_MS&&Number(row.mandate_expires_at)>Number(row.closes_at)&&row.input_hash===digest([row.actor_id,d.id,row.faith_key,!!Number(row.prohibited)]);
|
||||
}
|
||||
export async function missionaryFaithOutlawed(tx,clanId,faith,now){
|
||||
if(!faiths.includes(faith))fail('Unknown faith.',400);
|
||||
const clan=(await tx.query('SELECT home_world FROM site_clans WHERE id=? AND active=1 FOR SHARE',[clanId]))[0],world=tradeWorld(clan?.home_world);if(!world)return false;
|
||||
const row=(await tx.query(proofSQL+' JOIN jarvis_house_faith_rules r ON r.request_id=b.request_id WHERE r.world=? AND r.faith_key=? FOR SHARE',[STAFF_OFFICE_ACCOUNT_ID,now,world,faith]))[0];
|
||||
if(!validBallot(row)||row.state!=='closed'||row.result!=='adopted'||Number(row.prohibited)!==1||!Number.isSafeInteger(Number(row.expires_at))||Number(row.expires_at)<=now||Number(row.expires_at)>Math.min(Number(row.closes_at)+FAITH_LAW_MS,Number(row.mandate_expires_at))||row.world!==world||row.faith_key!==faith)return false;
|
||||
const d=houseFaithDecision(row.decision_id);if(!d||d.world!==world||d.office!==row.office_key)return false;
|
||||
const holder=await officeAuthority(tx,d,{id:row.actor_id},now);return holder?.termId===row.term_id;
|
||||
}
|
||||
export function createHouseFaithLaws(base,keys,{clock=Date.now}={}){
|
||||
if(typeof base?.query!=='function')return{read:async()=>fail('House faith records unavailable.',503),propose:async()=>fail('House faith records unavailable.',503),vote:async()=>fail('House faith records unavailable.',503),reconcile:async()=>fail('House faith records unavailable.',503)};
|
||||
const db=boardReadStore(base,base);
|
||||
async function authority(tx,d,actor,now,lock=false){const holder=await officeAuthority(tx,d,actor,now,lock);if(!holder)return null;const term=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[holder.termId]);return term?{...holder,expiresAt:Number(term.expires_at)}:null;}
|
||||
async function level(tx,actor,now){const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),xp=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]);return levelForXP(Number(xp?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null});}
|
||||
async function read(actor,id){
|
||||
const d=houseFaithDecision(id);if(!d)fail('Unknown House decision.',400);const now=clock(),holder=await authority(db,d,actor,now),row=await db.first('SELECT last_proposed_at FROM jarvis_house_faith_locks WHERE office_key=?',[d.office]),cooldownUntil=row?.last_proposed_at==null?null:Number(row.last_proposed_at)+FAITH_LAW_MS,current=await electors(db,d.office),me=current.find(p=>p.userId===actor.id),levelNow=holder?await level(db,actor,now):0;
|
||||
const ballots=await db.query(proofSQL+' WHERE b.office_key=? ORDER BY b.opens_at DESC,b.request_id DESC LIMIT 30',[STAFF_OFFICE_ACCOUNT_ID,now,d.office]),views=[];
|
||||
for(const b of ballots){const electorate=JSON.parse(b.electorate),votes=await db.query('SELECT v.minecraft_uuid,v.choice FROM jarvis_house_faith_votes v 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:house-faith-vote:\',v.request_id) AND k.revoked_at IS NULL WHERE v.ballot_id=?',[STAFF_OFFICE_ACCOUNT_ID,b.request_id]),ownVote=me?votes.find(v=>v.minecraft_uuid===me.playerUuid)?.choice||null:null;
|
||||
views.push({id:b.request_id,faith:b.faith_key,prohibited:!!b.prohibited,opensAt:Number(b.opens_at),closesAt:Number(b.closes_at),expiresAt:b.expires_at==null?null:Number(b.expires_at),state:b.state,result:b.result,electorate:electorate.length,ownVote,canVote:!!b.verified_key&&!!me&&!ownVote&&b.state==='open'&&now<Number(b.closes_at)&&electorate.some(e=>e.userId===me.userId&&e.playerUuid===me.playerUuid),tally:b.state==='closed'&&b.tally_json?JSON.parse(b.tally_json):null});
|
||||
}
|
||||
return{...d,canManage:!!holder,levelNow,cooldownUntil,canPropose:!!keys&&!!holder&&levelNow>=d.level&&holder.expiresAt>now+FAITH_BALLOT_MS&&(!cooldownUntil||now>=cooldownUntil)&¤t.length>0,ballots:views};
|
||||
}
|
||||
async function propose(actor,input){
|
||||
const d=houseFaithDecision(input?.decisionId);if(!d||!exact(input,'confirmed,decisionId,faith,prohibited,requestId')||!validUuid(input.requestId)||!faiths.includes(input.faith)||typeof input.prohibited!=='boolean'||input.confirmed!==true)fail('Review and confirm a House faith referendum.',400);if(!keys)fail('Key service unavailable.',503);
|
||||
input={...input,requestId:input.requestId.toLowerCase()};
|
||||
const hash=digest([actor.id,d.id,input.faith,input.prohibited]);let receipt;
|
||||
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:house-faith-ballot:'+input.requestId,authorize:async(raw,{keyId})=>{
|
||||
const tx=boardReadStore(raw,db),now=clock(),holder=await authority(tx,d,actor,now,true);if(!holder)fail('The current elected House holder is required.',403);
|
||||
const lock=await tx.first('SELECT * FROM jarvis_house_faith_locks WHERE office_key=? FOR UPDATE',[d.office]);if(!lock)fail('House faith policy unavailable.',503);
|
||||
const prior=await tx.first('SELECT * FROM jarvis_house_faith_ballots WHERE request_id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.input_hash!==hash)fail('Referendum reference already used.');receipt={id:prior.request_id,replayed:true};return;}
|
||||
if(lock.last_proposed_at!=null&&now<Number(lock.last_proposed_at)+FAITH_LAW_MS)fail('This House decision is on its seven-day cooldown.');
|
||||
if(holder.expiresAt<=now+FAITH_BALLOT_MS)fail('This mandate ends before voting would close.');if(await level(tx,actor,now)<d.level)fail('Reputation level '+d.level+' required.',403);
|
||||
const electorate=await electors(tx,d.office,{lock:true});if(!electorate.length)fail('No verified House citizens are available.');
|
||||
await tx.query("INSERT INTO jarvis_house_faith_ballots(request_id,key_id,decision_id,office_key,world,faith_key,prohibited,actor_id,term_id,input_hash,electorate,opens_at,closes_at,mandate_expires_at,state) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,'open')",[input.requestId,keyId,d.id,d.office,d.world,input.faith,input.prohibited?1:0,actor.id,holder.termId,hash,JSON.stringify(electorate),now,now+FAITH_BALLOT_MS,holder.expiresAt]);
|
||||
await tx.query('UPDATE jarvis_house_faith_locks SET last_proposed_at=? WHERE office_key=?',[now,d.office]);receipt={id:input.requestId,replayed:false};
|
||||
}});return receipt;
|
||||
}
|
||||
async function vote(actor,input){
|
||||
if(!exact(input,'ballotId,choice,confirmed,requestId')||!validUuid(input.requestId)||!validUuid(input.ballotId)||!['yes','no'].includes(input.choice)||input.confirmed!==true)fail('Confirm one referendum vote.',400);if(!keys)fail('Key service unavailable.',503);
|
||||
input={...input,requestId:input.requestId.toLowerCase(),ballotId:input.ballotId.toLowerCase()};
|
||||
const hash=digest([actor.id,input.ballotId,input.choice]);let receipt;
|
||||
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:house-faith-vote:'+input.requestId,authorize:async(raw,{keyId})=>{
|
||||
const tx=boardReadStore(raw,db),now=clock(),b=await tx.first(proofSQL+' WHERE b.request_id=? FOR UPDATE',[STAFF_OFFICE_ACCOUNT_ID,now,input.ballotId]);if(!validBallot(b))fail('Verified referendum not found.',404);
|
||||
const me=(await electors(tx,b.office_key,{lock:true})).find(p=>p.userId===actor.id);if(!me||!JSON.parse(b.electorate).some(p=>p.userId===me.userId&&p.playerUuid===me.playerUuid))fail('A current recorded House citizen is required.',403);
|
||||
const prior=await tx.first('SELECT * FROM jarvis_house_faith_votes WHERE request_id=?',[input.requestId]);if(prior){if(prior.input_hash!==hash||prior.actor_id!==actor.id)fail('Vote reference already used.');receipt={ok:true,replayed:true};return;}
|
||||
if(b.state!=='open'||now>=Number(b.closes_at))fail('Referendum voting has closed.');
|
||||
if(await tx.first('SELECT request_id FROM jarvis_house_faith_votes WHERE ballot_id=? AND minecraft_uuid=?',[b.request_id,me.playerUuid]))fail('This personal identity has already voted.');
|
||||
await tx.query('INSERT INTO jarvis_house_faith_votes(request_id,key_id,ballot_id,minecraft_uuid,actor_id,choice,input_hash,created_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,keyId,b.request_id,me.playerUuid,actor.id,input.choice,hash,now]);receipt={ok:true,replayed:false};
|
||||
}});return receipt;
|
||||
}
|
||||
async function reconcile(){
|
||||
const due=await db.query("SELECT request_id FROM jarvis_house_faith_ballots WHERE state='open' AND closes_at<=? ORDER BY closes_at,request_id LIMIT 100",[clock()]);
|
||||
for(const row of due)await base.transaction(async raw=>{const tx=boardReadStore(raw,db),now=clock(),b=await tx.first(proofSQL+' WHERE b.request_id=? FOR UPDATE',[STAFF_OFFICE_ACCOUNT_ID,now,row.request_id]);if(!b||b.state!=='open')return;
|
||||
const d=houseFaithDecision(b.decision_id),holder=d&&await authority(tx,d,{id:b.actor_id},now,true),votes=await tx.query("SELECT v.minecraft_uuid,v.choice FROM jarvis_house_faith_votes v 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:house-faith-vote:',v.request_id) AND k.revoked_at IS NULL WHERE v.ballot_id=?",[STAFF_OFFICE_ACCOUNT_ID,b.request_id]);
|
||||
const outcome=faithBallotOutcome(JSON.parse(b.electorate).length,votes),result=!validBallot(b)||holder?.termId!==b.term_id?'mandate_ended':outcome.result,expiresAt=result==='adopted'?Math.min(Number(b.closes_at)+FAITH_LAW_MS,Number(b.mandate_expires_at),holder.expiresAt):null;
|
||||
await tx.query("UPDATE jarvis_house_faith_ballots SET state='closed',result=?,expires_at=?,tally_json=? WHERE request_id=?",[result,expiresAt,JSON.stringify(outcome),b.request_id]);
|
||||
if(result==='adopted')await tx.query('INSERT INTO jarvis_house_faith_rules(world,faith_key,request_id) VALUES(?,?,?) ON DUPLICATE KEY UPDATE request_id=VALUES(request_id)',[b.world,b.faith_key,b.request_id]);
|
||||
});return{closed:due.length};
|
||||
}
|
||||
return{read,propose,vote,reconcile};
|
||||
}
|
||||
export function createHouseFaithAPI(db,keys,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=a=>accessFor(db,a),service=createHouseFaithLaws(db,keys)}={}){
|
||||
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
return async request=>{try{const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);if(!(await access(actor)).nodes.includes('web.menu.game'))return reply({message:'Player access required.'},403);const u=new URL(request.url);
|
||||
if(request.method==='GET'){if(u.searchParams.size!==1||u.searchParams.getAll('decisionId').length!==1)return reply({message:'Choose one House decision.'},400);return reply(await service.read(actor,u.searchParams.get('decisionId')));}
|
||||
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(u.search||request.headers.get('origin')!==origin)return reply({message:'Origin or query rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);const raw=await request.text();if(raw.length>2048)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid referendum request.'},400);}const {action,...input}=body||{};if(!['propose','vote'].includes(action))return reply({message:'Unknown referendum action.'},400);return reply(await service[action](actor,input));
|
||||
}catch(e){return reply({message:e.status?e.message:'Referendum was not confirmed. Refresh before retrying.'},e.status||503);}};
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {JarvisError} from './jarvis-listings.mjs';
|
||||
import {naibSeats,currentNaib} from './naib-membership.mjs';
|
||||
import {decisionBallotOutcome} from '../control-panel/public/decision-ballot-policy.mjs';
|
||||
export const COUNCIL_PROPOSAL_COOLDOWN_MS=86400000;
|
||||
export const NAIB_COUNCIL_SCHEMA=[
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_council_proposal_locks(scope_key VARCHAR(80) PRIMARY KEY,last_proposed_at BIGINT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
|
|
@ -20,10 +21,7 @@ async function previousProposal(db,kind,userId){
|
|||
}
|
||||
export const councilChoices=kind=>kind==='imperial-peace'?['accept','reject','negotiate']:['yes','no'];
|
||||
export function councilOutcome(kind,seats,votes){
|
||||
if(!Number.isInteger(seats)||seats<1||votes.length>seats||new Set(votes.map(v=>v.clan_id)).size!==votes.length||votes.some(v=>!councilChoices(kind).includes(v.choice)))throw new JarvisError('Council vote records require review.',409);
|
||||
const quorum=Math.floor(seats/2)+1,counts=Object.fromEntries(councilChoices(kind).map(choice=>[choice,votes.filter(v=>v.choice===choice).length]));
|
||||
const winner=Object.keys(counts).find(choice=>counts[choice]>votes.length/2);
|
||||
return {quorum,participation:votes.length,counts,result:votes.length<quorum?'no_quorum':winner||'not_adopted'};
|
||||
try{return decisionBallotOutcome(councilChoices(kind),seats,votes.map(v=>({identity:v.clan_id,choice:v.choice})));}catch{throw new JarvisError('Council vote records require review.',409);}
|
||||
}
|
||||
export async function reconcileNaibChairs(db,{clock=Date.now}={}){
|
||||
const now=clock(),terms=await db.query("SELECT id FROM political_office_terms WHERE kind='naib_chair' AND faction='arrakis' AND outcome='winner' AND starts_at<=? AND expires_at>? ORDER BY starts_at,id LIMIT 100",[now,now]);let ended=0;
|
||||
|
|
|
|||
72
website/tests/house-faith-laws.test.mjs
Normal file
72
website/tests/house-faith-laws.test.mjs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {clanFaithFixture} from './clan-faith-fixture.mjs';
|
||||
import {initializeHouseFaith,createHouseFaithLaws,missionaryFaithOutlawed,faithBallotOutcome,createHouseFaithAPI} from '../node/house-faith-laws.mjs';
|
||||
import {createClanFaith,currentClanFaith} from '../node/clan-faith.mjs';
|
||||
import {PUBLIC_OFFICES} from '../node/public-government.mjs';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs';
|
||||
import {FAITH_BALLOT_MS,FAITH_LAW_MS} from '../control-panel/public/house-faith-policy.mjs';
|
||||
async function fixture(){
|
||||
const f=await clanFaithFixture();await initializeHouseFaith(f.db);f.db.sqlite.exec('CREATE TABLE site_character_choices(minecraft_uuid TEXT PRIMARY KEY,faction TEXT)');
|
||||
const players={};for(const [name,p]of Object.entries(f.people)){const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[p.id]);players[name]=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[players[name],p.id]);await f.db.query('UPDATE site_clan_members SET minecraft_uuid=? WHERE user_id=?',[players[name],p.id]);await f.db.query("INSERT INTO site_character_choices VALUES(?,'atreides')",[players[name]]);}
|
||||
const key=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:atreides',authorize:async()=>true});
|
||||
await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:key.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query("INSERT INTO political_office_charters VALUES('atreides','royal',?)",[keyId])});
|
||||
const o=PUBLIC_OFFICES.find(o=>o.key==='atreides'),term=randomUUID();await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[term,f.people.Ceo.id,o.kind,o.faction,o.office]);
|
||||
return{...f,players,term,laws:createHouseFaithLaws(f.db,f.keys,{clock:f.clock}),faith:createClanFaith(f.db,f.keys,{clock:f.clock,isOutlawed:missionaryFaithOutlawed}),proposal:()=>({decisionId:'ATR-FAITH',requestId:randomUUID(),faith:'muad_dib',prohibited:true,confirmed:true}),vote:(ballotId,choice='yes')=>({ballotId,requestId:randomUUID(),choice,confirmed:true})};
|
||||
}
|
||||
async function adopt(f,p=f.proposal()){
|
||||
await f.laws.propose(f.people.Ceo,p);for(const name of ['Owner','Member','Other'])await f.laws.vote(f.people[name],f.vote(p.requestId));f.setTime(f.clock()+FAITH_BALLOT_MS);await f.laws.reconcile();return p;
|
||||
}
|
||||
test('a real personal House ballot gates only future conversions; existing owner consent and election votes are preserved',async()=>{
|
||||
const f=await fixture();try{
|
||||
const offer=f.offer();await f.faith.offer(f.people.Owner,offer);await f.faith.reply(f.people.Other,f.reply(offer.requestId));
|
||||
const p=f.proposal();await f.laws.propose(f.people.Ceo,p);assert.equal((await f.laws.propose(f.people.Ceo,p)).replayed,true);
|
||||
assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),false);
|
||||
for(const name of ['Owner','Member','Other'])await f.laws.vote(f.people[name],f.vote(p.requestId));
|
||||
const open=await f.laws.read(f.people.Owner,'ATR-FAITH');assert.equal(open.ballots[0].tally,null);assert.equal(open.ballots[0].ownVote,'yes');
|
||||
f.setTime(1000+FAITH_BALLOT_MS);assert.equal((await f.laws.reconcile()).closed,1);assert.equal((await f.laws.reconcile()).closed,0);
|
||||
assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),true);
|
||||
assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'veiled_concord',f.clock()),false);
|
||||
assert.equal((await currentClanFaith(f.db,f.clan)).faith,'muad_dib');
|
||||
await f.db.query("UPDATE site_clans SET home_world='kaiterhof' WHERE id=?",[f.clan]);assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),false);
|
||||
const closed=await f.laws.read(f.people.Owner,'ATR-FAITH');assert.equal(closed.ballots[0].tally.yes,3);assert.equal(closed.ballots[0].tally.quorum,3);
|
||||
assert.equal((await f.db.first("SELECT COUNT(*) n FROM sqlite_master WHERE type='table' AND name='political_ballots'")).n,0,'referendum does not create candidate votes');
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('outlawed invitations and acceptance issue no conversion, while law expiry and changed mandate restore freedom',async()=>{
|
||||
const f=await fixture();try{
|
||||
const offer=f.offer();await f.faith.offer(f.people.Owner,offer);await adopt(f);
|
||||
const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;
|
||||
await assert.rejects(f.faith.reply(f.people.Other,f.reply(offer.requestId)),/outlawed/);
|
||||
await assert.rejects(f.faith.offer(f.people.Owner,f.offer()),/outlawed/);
|
||||
assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);
|
||||
await f.db.query("UPDATE political_office_terms SET outcome='resigned' WHERE id=?",[f.term]);assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),false);
|
||||
await f.db.query("UPDATE political_office_terms SET outcome='winner' WHERE id=?",[f.term]);f.setTime(1000+FAITH_BALLOT_MS+FAITH_LAW_MS);assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),false);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('eligibility, one linked identity, frozen electorate, strict input and safe vote retries are enforced',async()=>{
|
||||
const f=await fixture();try{
|
||||
const p=f.proposal();await assert.rejects(f.laws.propose({...f.people.Other,role:'owner'},p),/House holder/);await assert.rejects(f.laws.propose(f.people.Ceo,{...p,world:'arrakis'}),/Review/);
|
||||
await f.laws.propose(f.people.Ceo,p);const v=f.vote(p.requestId);await f.laws.vote(f.people.Owner,v);assert.equal((await f.laws.vote(f.people.Owner,v)).replayed,true);
|
||||
await assert.rejects(f.laws.vote(f.people.Owner,f.vote(p.requestId)),/already voted/);await assert.rejects(f.laws.vote(f.people.Owner,{...v,choice:'no'}),/reference/);
|
||||
await f.db.query("UPDATE site_character_choices SET faction='corrino' WHERE minecraft_uuid=?",[f.players.Member]);await assert.rejects(f.laws.vote(f.people.Member,f.vote(p.requestId)),/current recorded/);
|
||||
await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[f.players.Other,f.people.Member.id]);await assert.rejects(f.laws.vote(f.people.Other,f.vote(p.requestId)),/current recorded/);
|
||||
f.setTime(1000+FAITH_BALLOT_MS);await f.laws.reconcile();assert.equal((await f.laws.read(f.people.Owner,'ATR-FAITH')).ballots[0].result,'no_quorum');assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),false);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('office cooldown survives succession, new law revocation never revives an old prohibition and writes roll back atomically',async()=>{
|
||||
const f=await fixture();try{
|
||||
await adopt(f);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Owner.id,f.term]);await assert.rejects(f.laws.propose(f.people.Owner,f.proposal()),/cooldown/);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Ceo.id,f.term]);
|
||||
f.setTime(1000+FAITH_LAW_MS);const p={...f.proposal(),prohibited:false};await adopt(f,p);
|
||||
const latest=await f.db.first('SELECT key_id FROM jarvis_house_faith_ballots WHERE request_id=?',[p.requestId]);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[latest.key_id]);assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),false);
|
||||
f.setTime(1000+2*FAITH_LAW_MS);const count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER reject_faith_ballot BEFORE INSERT ON jarvis_house_faith_ballots BEGIN SELECT RAISE(ABORT,'ballot journal failed');END");await assert.rejects(f.laws.propose(f.people.Ceo,f.proposal()),/journal failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('a departed mandate cannot enact a law and the existing strict-majority rule rejects ties',async()=>{
|
||||
assert.equal(faithBallotOutcome(4,[{minecraft_uuid:'a',choice:'yes'},{minecraft_uuid:'b',choice:'no'},{minecraft_uuid:'c',choice:'no'}]).result,'not_adopted');assert.equal(faithBallotOutcome(3,[{minecraft_uuid:'a',choice:'yes'},{minecraft_uuid:'b',choice:'no'}]).result,'not_adopted');
|
||||
const f=await fixture();try{const p=f.proposal();await f.laws.propose(f.people.Ceo,p);for(const name of ['Owner','Member','Other'])await f.laws.vote(f.people[name],f.vote(p.requestId));await f.db.query("UPDATE political_office_terms SET outcome='resigned' WHERE id=?",[f.term]);f.setTime(1000+FAITH_BALLOT_MS);await f.laws.reconcile();assert.equal((await f.laws.read(f.people.Owner,'ATR-FAITH')).ballots[0].result,'mandate_ended');assert.equal(await missionaryFaithOutlawed(f.db,f.clan,'muad_dib',f.clock()),false);}finally{f.db.close();}
|
||||
});
|
||||
test('private API rejects identity and cross-origin overrides without performing a decision',async()=>{
|
||||
const f=await fixture();try{const api=createHouseFaithAPI(f.db,f.keys,{service:f.laws,authenticate:async()=>f.people.Ceo,access:async()=>({nodes:['web.menu.game']})}),req=(body,origin='https://cp.dunerealms.com')=>new Request('https://cp.dunerealms.com/api/politics/house-faith',{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(body)});
|
||||
assert.equal((await api(req({action:'propose',...f.proposal()},'https://evil.invalid'))).status,403);assert.equal((await api(req({action:'propose',...f.proposal(),actorId:f.people.Owner.id}))).status,400);assert.equal((await api(req({action:'propose',...f.proposal(),confirmed:false}))).status,400);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {MISSION_BRANCHES,DECISION_CATALOGUE} from '../control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs';
|
||||
test('accepted design includes all nine personal branches, repair quest and private discovery placeholder',()=>{assert.equal(MISSION_BRANCHES.filter(b=>/^[a-i]$/.test(b.id)).length,9);const equipment=MISSION_BRANCHES.find(b=>b.id==='h').missions;assert.match(equipment[0].title,/faction kit/i);assert.equal(equipment[1].title,'Repair Your Starter Kit');assert.equal(MISSION_BRANCHES.find(b=>b.id==='c').missions.length,8);assert(MISSION_BRANCHES.find(b=>b.id==='discoveries').missions.every(m=>m.hidden&&m.optional));assert(MISSION_BRANCHES.find(b=>b.id==='i').missions.filter(m=>/Sell/.test(m.title)).every(m=>m.optional));const ids=MISSION_BRANCHES.flatMap(b=>b.missions.map(m=>m.id));assert.equal(new Set(ids).size,ids.length);});
|
||||
test('decision catalogue keeps five to ten distinct proposals per office, including consenting faith invitations',()=>{assert.equal(DECISION_CATALOGUE.length,86);assert.equal(new Set(DECISION_CATALOGUE.map(d=>d.id)).size,86);assert.deepEqual(Object.fromEntries(['IMP','ATR','HAR','COR','ORD','FRE','BG','NF','SG','CLD'].map(id=>[id,DECISION_CATALOGUE.filter(d=>d.office===id).length])),{IMP:10,ATR:9,HAR:9,COR:9,ORD:9,FRE:8,BG:8,NF:10,SG:9,CLD:5});assert(DECISION_CATALOGUE.some(d=>d.id==='NF-CONVERT'));assert(!DECISION_CATALOGUE.some(d=>d.id==='NF-01'));assert.equal(DECISION_CATALOGUE.find(d=>d.id==='IMP-01').level,50);assert(DECISION_CATALOGUE.every(d=>Number.isInteger(d.level)&&d.level>=0&&Number.isInteger(d.xp)&&d.xp>=0&&d.cost));});
|
||||
test('decision catalogue keeps five to ten distinct proposals per office, including consent and House faith referendums',()=>{assert.equal(DECISION_CATALOGUE.length,91);assert.equal(new Set(DECISION_CATALOGUE.map(d=>d.id)).size,91);assert.deepEqual(Object.fromEntries(['IMP','ATR','HAR','COR','ORD','FRE','BG','NF','SG','CLD'].map(id=>[id,DECISION_CATALOGUE.filter(d=>d.office===id).length])),{IMP:10,ATR:10,HAR:10,COR:10,ORD:10,FRE:9,BG:8,NF:10,SG:9,CLD:5});assert(DECISION_CATALOGUE.some(d=>d.id==='NF-CONVERT'));assert(!DECISION_CATALOGUE.some(d=>d.id==='NF-01'));assert.equal(DECISION_CATALOGUE.find(d=>d.id==='IMP-01').level,50);assert(DECISION_CATALOGUE.every(d=>Number.isInteger(d.level)&&d.level>=0&&Number.isInteger(d.xp)&&d.xp>=0&&d.cost));});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff