From 79d46b5656d8df5cb83e6140d2d9921e045554e9 Mon Sep 17 00:00:00 2001 From: Dev Date: Wed, 25 Nov 2026 05:06:40 +0100 Subject: [PATCH] Connect voluntary Fremen Council accords to funded consent and withdrawal --- .../public/cp-v2/cp-v2-decision-audit.mjs | 2 +- .../public/cp-v2/cp-v2-naib-council.css | 2 + .../public/cp-v2/cp-v2-naib-council.mjs | 17 +++---- .../public/cp-v2/cp-v2-progression.mjs | 2 +- .../public/jarvis-master-keys.mjs | 3 +- .../public/naib-council-policy.mjs | 11 ++++- website/control-panel/server.mjs | 2 +- .../osticket/dev-jarvis-catalogue.json | 47 ++++++++++++++++++- website/node/naib-council-accords.mjs | 28 +++++++++++ website/node/naib-council-api.mjs | 4 +- website/node/naib-council-funding.mjs | 13 ++--- website/node/naib-council.mjs | 34 ++++++++------ website/tests/political-decisions.test.mjs | 9 ++++ 13 files changed, 135 insertions(+), 39 deletions(-) create mode 100644 website/node/naib-council-accords.mjs diff --git a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs index 61bee6a4..ea2d3975 100644 --- a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs @@ -15,5 +15,5 @@ function paidDecisionGap(id){ const kind=politicalDecision(id)?.kind,base='Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically. '; return base+(kind==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder or legal company owner. Acceptance or refusal requires that same current mandate or company ownership, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.'); } -export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status:naibDecision(d.id)||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:naibDecision(d.id)?'createNaibCouncil / createNaibCouncilFunding':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:naibDecision(d.id)?'Current independent sietch deed, Reputation10,1000DM from its active account or the legal Basic owner,200 Reputation and24h seat cooldown. Fee, signed key, proposal electorate and reward commit together. No free production fallback; one Council vote per current sietch. Personal election votes are unchanged.':houseFaithDecision(d.id)?'Royal House authority and Reputation checked before a sealed 48-hour personal referendum. Seven-day office cooldown survives succession; quorum and strict majority required. Only future invitations and clan-owner acceptance are gated by the latest live law; existing allegiance and earned rewards remain unchanged.':clanFaithDecision(d.id)?'Current faith officer can invite; only the receiving clan’s legal owner can consent. Daily invitation and seven-day clan-change cooldowns are enforced; no membership or rights move.':tradeDecision(d.id)?'Current Royal office and Reputation, immutable creation-world metadata, seven-day cooldown, retained stock and atomic seller-funded bank levy; no default activation.':politicalDecision(d.id)?paidDecisionGap(d.id):faithBlessing(d.id)?'Current faith leader/officer deed, owner-approved clan allegiance, appointment expiry and cooldown are checked centrally. Old Faith and New Faith use the same capped bonus consumer; historical queued rewards retain their claim-time consent proof.':d.id==='IMP-10'?'Native House selection replaces the prior grant; seven-day office cooldown and current Emperor deed are checked centrally.':related[d.id]?.gap||'No complete registered domain consumer implements this exact target, price, cooldown, duration and effect. Execution remains unavailable.',repeatability:'Only after the stated cooldown; no implied stacking or automatic renewal.',executionEnabled:!!naibDecision(d.id)||!!houseFaithDecision(d.id)||!!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:naibDecision(d.id)||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:naibDecision(d.id)?'createNaibCouncil / createNaibCouncilFunding':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:naibDecision(d.id)?'Current independent sietch deed, Reputation'+naibDecision(d.id).level+','+naibDecision(d.id).feeMinor/100+'DM from its active account or the legal Basic owner,'+naibDecision(d.id).xp+' Reputation and'+naibDecision(d.id).cooldownMs/3600000+'h seat cooldown. Fee, signed key, proposal electorate and reward commit together. No free production fallback; one Council vote per current sietch. Personal election votes are unchanged.':houseFaithDecision(d.id)?'Royal House authority and Reputation checked before a sealed 48-hour personal referendum. Seven-day office cooldown survives succession; quorum and strict majority required. Only future invitations and clan-owner acceptance are gated by the latest live law; existing allegiance and earned rewards remain unchanged.':clanFaithDecision(d.id)?'Current faith officer can invite; only the receiving clan’s legal owner can consent. Daily invitation and seven-day clan-change cooldowns are enforced; no membership or rights move.':tradeDecision(d.id)?'Current Royal office and Reputation, immutable creation-world metadata, seven-day cooldown, retained stock and atomic seller-funded bank levy; no default activation.':politicalDecision(d.id)?paidDecisionGap(d.id):faithBlessing(d.id)?'Current faith leader/officer deed, owner-approved clan allegiance, appointment expiry and cooldown are checked centrally. Old Faith and New Faith use the same capped bonus consumer; historical queued rewards retain their claim-time consent proof.':d.id==='IMP-10'?'Native House selection replaces the prior grant; seven-day office cooldown and current Emperor deed are checked centrally.':related[d.id]?.gap||'No complete registered domain consumer implements this exact target, price, cooldown, duration and effect. Execution remains unavailable.',repeatability:'Only after the stated cooldown; no implied stacking or automatic renewal.',executionEnabled:!!naibDecision(d.id)||!!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; diff --git a/website/control-panel/public/cp-v2/cp-v2-naib-council.css b/website/control-panel/public/cp-v2/cp-v2-naib-council.css index 9fc86485..2467768d 100644 --- a/website/control-panel/public/cp-v2/cp-v2-naib-council.css +++ b/website/control-panel/public/cp-v2/cp-v2-naib-council.css @@ -8,3 +8,5 @@ @media(max-width:650px){.naib-council .organisation-settings-card,.naib-council .politics-card{padding:14px}.naib-council .cp-v2-template-tabs button{flex:1 1 120px}.naib-council th,.naib-council td{padding:8px}} .naib-council input,.naib-council textarea,.naib-council select,.naib-council button{font:inherit}.naib-council [hidden]{display:none!important} + +.naib-council{font-family:"DM Sans",Arial,sans-serif}.naib-council h3,.naib-council h4{font-family:"Cinzel",Georgia,serif} diff --git a/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs b/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs index 8fe9c74d..b4ed8bac 100644 --- a/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-naib-council.mjs @@ -5,26 +5,27 @@ import {renderVoting} from '../election-voting-view.mjs'; import {mountElectionResults} from './cp-v2-election-results.mjs'; export function mountNaibCouncil(host){ if(!document.querySelector('link[data-naib-council]')){const style=el('link');style.rel='stylesheet';style.href=new URL('./cp-v2-naib-council.css',import.meta.url).href;style.dataset.naibCouncil='';document.head.append(style);} - const controller=new AbortController(),api=createUserAPI(fetch,controller.signal);let active=true,busy=false,selectedTab='sietches',selectedAccount='',disposeResults=()=>{}; + const controller=new AbortController(),api=createUserAPI(fetch,controller.signal);let active=true,busy=false,selectedTab='sietches',selectedAccount='',selectedKind='decision',disposeResults=()=>{}; const status=el('p','Loading the Council of Naibs…');status.setAttribute('role','status');host.replaceChildren(status); async function load(){try{const [data,session]=await Promise.all([api.request('/api/politics/naibs'),api.request('/api/auth/session')]);if(!active)return;draw(data,session.user);}catch(error){if(active)status.textContent=error.message;}} function draw(data,user){ disposeResults();const seats=el('section',undefined,'organisation-settings-card'),decisions=el('section',undefined,'organisation-settings-card'),diplomacy=el('section',undefined,'organisation-settings-card'),powers=el('section',undefined,'organisation-settings-card'),elections=el('section'),results=el('section'); seats.append(el('h3','Recognised sietches'),el('p','One Council seat belongs to each active Arrakduin sietch. Its current clan owner is its Naib. Imperial appointments cannot grant or remove these seats.')); const table=el('table'),head=el('tr');for(const text of ['Sietch','Naib'])head.append(el('th',text));const thead=el('thead');thead.append(head);const tbody=el('tbody');for(const seat of data.seats){const row=el('tr'),name=el('td'),person=el('td'),link=el('a',seat.name);link.href='https://www.dunerealms.com/clans/'+encodeURIComponent(seat.tag);link.target='_top';name.append(link);const profile=el('a',seat.displayName);profile.href='https://www.dunerealms.com/people/'+encodeURIComponent(seat.username);profile.target='_top';person.append(profile);row.append(name,person);tbody.append(row);}table.append(thead,tbody);seats.append(table);if(!data.seats.length)seats.append(el('p','No recognised sietches are currently eligible.')); - decisions.append(el('h3','Council decisions'),el('p','Voting lasts 24 hours. More than half of the recorded sietches must participate; a choice needs more than half of the votes cast. A tie does not adopt a proposal. The electorate is recorded when a proposal opens; a new owner inherits the existing sietch seat.')); + decisions.append(el('h3','Council decisions'),el('p','Voting lasts 24 hours. More than half of the recorded sietches must participate; a choice needs more than half of the votes cast. A tie does not adopt a proposal. The electorate is recorded when a proposal opens; a new owner inherits the existing sietch seat. Accord consent does not pass to a new owner.')); diplomacy.append(el('h3','Imperial diplomacy'),el('p','Imperial Peace offers can be accepted, rejected or returned for negotiation. These are diplomatic records; automatic war, claim and PvP changes remain unavailable.')); const form=el('form'),kind=el('select'),title=el('input'),message=el('textarea'),confirm=el('input'),send=el('button','Submit proposal');title.maxLength=100;title.required=true;message.rows=5;message.minLength=20;message.maxLength=4000;message.required=true;confirm.type='checkbox';confirm.required=true; - const available=data.proposalKinds||[]; - for(const entry of available){const option=el('option',entry.kind==='decision'?'Council proposal':'Imperial Peace offer');option.value=entry.kind;kind.append(option);} - const fundingLabel=el('label','Sietch funding account'),account=el('select');fundingLabel.append(account);for(const a of data.funding?.accounts||[]){const option=el('option',a.name+' · '+a.number+' · '+(Number(a.availableMinor)/100).toFixed(2)+' DM available');option.value=a.id;account.append(option);}if(data.funding?.accounts?.some(a=>a.id===selectedAccount))account.value=selectedAccount;const cooldownNotice=el('p');form.append(cooldownNotice,fundingLabel); - const refreshProposal=()=>{const policy=available.find(p=>p.kind===kind.value),paid=kind.value==='decision'&&data.funding?.required,selected=data.funding?.accounts?.find(a=>a.id===account.value),canFund=!paid||!!selected&&BigInt(selected.availableMinor)>=BigInt(data.funding.feeMinor);fundingLabel.hidden=!paid;account.disabled=busy||!paid;send.textContent=paid?'Pay '+(data.funding.feeMinor/100).toLocaleString('en-GB')+' DM and submit':'Submit proposal';send.disabled=busy||!policy?.canPropose||!canFund;cooldownNotice.textContent=paid&&!data.funding.available?'Council banking is unavailable; no proposal payment can be made.':paid&&data.funding.levelNow{selectedAccount=account.value;refreshProposal();};refreshProposal(); + const available=data.proposalKinds||[],fundingPolicy=()=>({...data.funding,...(data.funding?.policies?.find(p=>p.kind===kind.value)||{})}); + for(const entry of available){const option=el('option',entry.title||(entry.kind==='decision'?'Council proposal':'Imperial Peace offer'));option.value=entry.kind;kind.append(option);}if(available.some(p=>p.kind===selectedKind))kind.value=selectedKind; + const fundingLabel=el('label','Sietch funding account'),account=el('select');fundingLabel.append(account);for(const a of data.funding?.accounts||[]){const option=el('option',a.name+' · '+a.number+' · '+(Number(a.availableMinor)/100).toFixed(2)+' DM available');option.value=a.id;account.append(option);}if(data.funding?.accounts?.some(a=>a.id===selectedAccount))account.value=selectedAccount;const cooldownNotice=el('p'),accordNotice=el('p');form.append(cooldownNotice,accordNotice,fundingLabel); + const refreshProposal=()=>{const funding=fundingPolicy(),policy=available.find(p=>p.kind===kind.value),paid=kind.value!=='imperial-peace'&&funding.required,selected=data.funding?.accounts?.find(a=>a.id===account.value),canFund=!paid||!!selected&&BigInt(selected.availableMinor)>=BigInt(funding.feeMinor);fundingLabel.hidden=!paid;accordNotice.hidden=!funding.durationMs;accordNotice.textContent=funding.durationMs?'A24-hour consent ballot. If supported, the accord lasts '+funding.durationMs/86400000+' days. Only sietches voting yes join; each may leave. War participation and water deliveries remain separate actions.':'';account.disabled=busy||!paid;send.textContent=paid?'Pay '+(funding.feeMinor/100).toLocaleString('en-GB')+' DM and submit':'Submit proposal';send.disabled=busy||!policy?.canPropose||!canFund;cooldownNotice.textContent=paid&&!funding.available?'Council banking is unavailable; no proposal payment can be made.':paid&&funding.levelNow{selectedKind=kind.value;refreshProposal();};account.onchange=()=>{selectedAccount=account.value;refreshProposal();};refreshProposal(); for(const [text,field]of [['Proposal type',kind],['Title',title],['Terms and message',message],['I confirm this proposal',confirm]]){const label=el('label',text);label.append(field);form.append(label);}send.type='submit';form.append(send);diplomacy.append(form);let requestId=crypto.randomUUID();form.oninput=()=>{if(!busy)requestId=crypto.randomUUID();}; const lock=value=>{busy=value;for(const field of [title,message,confirm])field.disabled=value;kind.disabled=value||available.length<2;refreshProposal();};lock(false); - form.onsubmit=async event=>{event.preventDefault();if(busy||!available.find(p=>p.kind===kind.value)?.canPropose||!form.reportValidity())return;const input={requestId,kind:kind.value,title:title.value,message:message.value,confirmed:confirm.checked,...(kind.value==='decision'&&data.funding?.required?{sourceAccount:account.value}:{})};lock(true);status.textContent='Recording the proposal…';try{await api.request('/api/politics/naibs/propose',input);await load();status.textContent='Council proposal recorded.';}catch(error){if(active){status.textContent=error.message;lock(false);}}}; + form.onsubmit=async event=>{event.preventDefault();if(busy||!available.find(p=>p.kind===kind.value)?.canPropose||!form.reportValidity())return;const input={requestId,kind:kind.value,title:title.value,message:message.value,confirmed:confirm.checked,...(kind.value!=='imperial-peace'&&data.funding?.required?{sourceAccount:account.value}:{})};lock(true);status.textContent='Recording the proposal…';try{await api.request('/api/politics/naibs/propose',input);await load();status.textContent='Council proposal recorded.';}catch(error){if(active){status.textContent=error.message;lock(false);}}}; for(const dossier of data.dossiers){const card=el('article',undefined,'organisation-settings-card');card.append(el('small',dossier.reference),el('h3',dossier.title),el('p',dossier.message),el('p',dossier.state==='closed'?'Decision: '+dossier.result:'Voting closes '+new Date(dossier.closesAt).toLocaleString('en-GB',{timeZone:'UTC'})+' UTC'),el('p',dossier.electorate+' sietches in the recorded electorate'));if(dossier.tally)card.append(el('p',dossier.tally.participation+' votes · quorum '+dossier.tally.quorum+' · '+Object.entries(dossier.tally.counts).map(([choice,total])=>choice+': '+total).join(' · ')));if(dossier.ownVote)card.append(el('p','Your sietch voted: '+dossier.ownVote));else if(dossier.canVote){const choice=el('select');for(const value of dossier.choices){const option=el('option',value);option.value=value;choice.append(option);}const consent=el('label'),check=el('input');check.type='checkbox';consent.append(check,el('span','I confirm this definitive vote for my sietch.'));const button=el('button','Cast Council vote');button.type='button';button.onclick=async()=>{if(busy||!check.checked){status.textContent='Confirm your vote first.';return;}busy=true;button.disabled=true;try{await api.request('/api/politics/naibs/vote',{dossierId:dossier.id,choice:choice.value,confirmed:true});await load();status.textContent='Council vote recorded.';}catch(error){if(active){status.textContent=error.message;button.disabled=false;}}finally{busy=false;}};card.append(choice,consent,button);} (dossier.kind==='imperial-peace'?diplomacy:decisions).append(card);} elections.append(el('p','Naibs elect the chair from their own members. The existing general Fremen leadership election remains separate.'),renderApplications({user,context:{linked:true,naib:data.naib,clanId:data.seatId},kind:'naib_chair'}),renderVoting('naib_chair')); + if(data.accords?.length){decisions.append(el('h3','Council accords'));for(const accord of data.accords){const card=el('article',undefined,'politics-card');card.append(el('h4',accord.title),el('p',accord.terms),el('p',({active:'Active',expired:'Expired','insufficient-current-consent':'Not enough current participants'})[accord.state]+' · ends '+new Date(accord.endsAt).toLocaleString()),el('p','Current participants: '+(accord.participants.map(p=>p.name).join(', ')||'none')));if(accord.canWithdraw){const label=el('label','I confirm my sietch is leaving this accord'),sure=el('input'),leave=el('button','Leave accord');sure.type='checkbox';label.append(sure);leave.type='button';leave.disabled=true;const withdrawal={dossierId:accord.id,requestId:crypto.randomUUID(),confirmed:true};sure.onchange=()=>leave.disabled=!sure.checked;leave.onclick=async()=>{if(busy||!sure.checked)return;lock(true);leave.disabled=true;try{await api.request('/api/politics/naibs/withdraw',withdrawal);await load();status.textContent='Sietch consent withdrawn.';}catch(error){status.textContent=error.message;lock(false);leave.disabled=!sure.checked;}};card.append(label,leave);}decisions.append(card);}} powers.append(el('h3','Council powers'),el('p','Political powers are awaiting a separate design. No gameplay action is available from this page.')); const restoreTab=selectedTab,page=createCPV2Page({shellHost:host,title:'Council of Naibs',description:'House of Arrakis · independent sietches of Arrakduin',artwork:'seals/office-house_leader.png',tabs:[{id:'sietches',label:'Sietches',content:seats},{id:'decisions',label:'Decisions',content:decisions},{id:'diplomacy',label:'Diplomacy',content:diplomacy},{id:'elections',label:'Chair election',content:elections},{id:'results',label:'Results',content:results},{id:'powers',label:'Powers',content:powers}],onActivate:id=>{selectedTab=id;if(id==='results'){disposeResults();disposeResults=mountElectionResults(results,{kind:'naib_chair'});}}});host.replaceChildren(status,page.root);page.root.classList.add('naib-council');page.activate(restoreTab);busy=false; } diff --git a/website/control-panel/public/cp-v2/cp-v2-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-progression.mjs index 142d83d3..3abe730b 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-progression.mjs @@ -43,7 +43,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false, const roster=el('div',undefined,'progression-roster');for(const member of members.slice(0,12)){const person=el('figure');const avatar=member.avatar||member.avatarUrl||(member.username?'https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username):null);if(avatar&&/^https:\/\//.test(avatar)){const img=el('img');img.src=avatar;img.alt='';person.append(img);}else person.append(image(CONTEXTS[activeContext][1]));person.append(el('figcaption',member.displayName||member.display_name||member.name||member.username||'Member'));roster.append(person);}if(!members.length)roster.append(image(CONTEXTS[activeContext][1]),el('p','Your verified roster and avatars will appear here. No sample memberships are assigned.'));gallery.append(roster); } function details(row,isDecision=false){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected '+(isDecision?'decision':'mission'));pane.append(image(isDecision?(POL_PLANNING_ART[officeCode]?.banner||'exchange-political-positions-v1.png'):artFor(branch)),el('small',row.id),el('h3',lore(row.title)),el('p',isDecision?lore(row.effect):row.title==='Repair Your Starter Kit'?'Collect four repair components and surrender the damaged Q0 kit to receive one intact kit.':'Complete the verified objective. Conditions and progress will be supplied by J.A.R.V.I.S.')); - if(isDecision&&row.executionStatus==='naib-council-controller'){const council=el('a','Open Council of Naibs →');council.href='https://www.dunerealms.com/government.html#household/naibs';pane.append(el('p','Independent sietch assembly: Reputation10,1,000 DM and200 Reputation points. One proposal per sietch every24h; existing Council voting and chair election remain separate.'),council);return pane;} + if(isDecision&&row.executionStatus==='naib-council-controller'){const council=el('a','Open Council of Naibs →');council.href='https://www.dunerealms.com/government.html#household/naibs';pane.append(el('p','Independent sietch Council: Reputation'+row.level+','+(row.feeMinor/100).toLocaleString('en-GB')+' DM and'+row.xp+' Reputation points. This decision has a'+row.cooldownMs/3600000+'-hour sietch cooldown. Council votes and chair elections remain separate.'),council);return pane;} 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;} diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 77bd9a7c..41054cfe 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -16,7 +16,8 @@ export const MASTER_KEY_TEMPLATES=[ {id:'politics',label:'POL & orders',actions:[ action('politics.institutional-consultation','Convene an institutional resolution vote','entity-state',[field('decisionId','Registered Council decision','select',{options:['IMP-05','ATR-02']}),field('sourceAccount','Authorised office funding account'),field('title','Resolution title'),field('terms','Consultation terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalConsultations',executionStatus:'current-office-and-institutional-seat-consumer',effect:'Landsraad: Emperor, Reputation25,5000DM,400 Reputation,72h consultation/cooldown; snapshot occupied Royal Great House offices. Caladan: Atreides holder,Reputation15,2000DM,250 Reputation,48h consultation/cooldown; snapshot native active clans. The issuing mandate must cover the entire ballot. Current independent legal clan owners or the original House mandates cast one signed institutional vote per seat. More-than-half participation and strict majority; ties fail. Immutable final tally; no personal election votes, ownership, law or war participation change. Fee, electorate, scoped key and Reputation commit together.'}), action('politics.institutional-vote','Cast an institutional resolution vote','entity-state',[field('ballotId','Consultation UUID'),field('seatKey','Current institutional seat'),field('choice','Vote','select',{options:['yes','no']}),field('requestId','Vote UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalConsultations.vote / reconcile',executionStatus:'current-independent-institutional-deed-only',effect:'Revalidate the signed live ballot, original issuing mandate and current independent institutional seat under the same transaction. One signed vote per seat; exact retries retain the receipt. No fee or Reputation for voting. Mother control does not confer client clan votes; revoked recorded votes cannot be replaced. Final tally uses the existing quorum/strict-majority rule and remains fixed after closure.'}), - action('politics.naib-council-assembly','Fund an independent sietch Council proposal','entity-state',[field('requestId','Council request UUID'),field('sourceAccount','Authorised sietch funding account'),field('title','Council proposal title'),field('message','Consultation terms','textarea')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createNaibCouncil.propose / createNaibCouncilFunding',executionStatus:'current-independent-sietch-owner-funded-council',effect:'FRE01 uses the existing24h Council, current independent Naib ownership and one institutional vote per recognised sietch. Reputation10,1000DM to Tax and200 Reputation points;24h seat cooldown survives ownership transfer. Keyed sietches fund their own active payment account; Basic sietches use the current legal owner’s active personal account. Source authority, balances, Reputation, ordinary scoped ESK key and complete dossier commit atomically. No free production fallback or extra charge/reward for voting. Personal election rights and Imperial appointment authority remain unchanged.'}), + action('politics.naib-accord-withdraw','Withdraw a sietch accord consent','organisation-action',[field('dossierId','Closed Council dossier UUID'),field('requestId','Withdrawal UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createNaibCouncil.withdraw / withdrawCouncilAccord',executionStatus:'current-original-consenting-sietch-owner-only',effect:'Use the existing Council audit transaction to withdraw the current sietch from a funded, accepted and unexpired accord. Recheck current independent ownership and the original yes vote; mother control and successor ownership do not inherit consent. Record a single idempotent withdrawal event without deleting the historical vote, charging money or awarding Reputation. No arbitrary JARVIS key is issued by this ordinary Council event flow.'}), + action('politics.naib-council-assembly','Fund an independent sietch Council proposal','entity-state',[field('kind','Registered Council decision','select',{options:['decision','defense-coalition','water-sharing','desert-alliance']}),field('requestId','Council request UUID'),field('sourceAccount','Authorised sietch funding account'),field('title','Council proposal title'),field('message','Consultation terms','textarea')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createNaibCouncil.propose / createNaibCouncilFunding',executionStatus:'current-independent-sietch-owner-funded-council',effect:'FRE01 uses the existing24h Council, current independent Naib ownership and one institutional vote per recognised sietch. Reputation10,1000DM to Tax and200 Reputation points;24h seat cooldown survives ownership transfer. Keyed sietches fund their own active payment account; Basic sietches use the current legal owner’s active personal account. Source authority, balances, Reputation, ordinary scoped ESK key and complete dossier commit atomically. FRE02:15000DM,400 Reputation,level25,7d cooldown and7d defensive accord. FRE03:2500DM,300 Reputation,level20,72h cooldown and7d water-sharing accord. FRE06:5000DM,500 Reputation,level30,7d cooldown and14d alliance. All use24h Council consent, frozen institutional electorate and the existing quorum rule. Only current sietches whose original Naib voted yes join; they may withdraw through the normal Council audit flow. No automatic war consent or delivery is fabricated. No free production fallback or extra charge/reward for voting. Personal election rights and Imperial appointment authority remain unchanged.'}), action('politics.company-consortium','Ordos confidential company consortium','entity-state',[field('decisionId','Company agreement','select',{options:['ORD-02']}),field('sourceAccount','Authorised Ordos funding account'),field('targetCompanyId','Receiving active company UUID'),field('title','Proposal title'),field('terms','Confidential commercial terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements / readCompanyDeed',executionStatus:'current-ordos-office-and-original-company-owner-consent',effect:'Current Royal Ordos holder,Reputation35,5000DM,600 Reputation and7d cooldown. Reuse the confidential bilateral proposal flow, with72h response by a different current legal owner of an active company. CEO or mother-company control never substitutes for ownership. Accepted terms last at most14d, clipped to the source mandate, and end on ownership change. Separate typed company reply proofs preserve existing office replies without altering their table. No ownership, corporate control, bank, vote or war rights change.'}), action('politics.diplomatic-proposal','Confidential diplomatic proposal','entity-state',[field('decisionId','Diplomatic decision','select',{options:['ATR-05','COR-06','ORD-05','BG-05','NF-05']}),field('sourceAccount','Authorised office funding account'),field('targetOffice','Receiving Royal office'),field('title','Proposal title'),field('terms','Confidential diplomatic terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-officeholder-bilateral-consent-consumer',effect:'Five fixed diplomatic policies charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.'}), action('politics.diplomatic-response','Accept or refuse a diplomatic proposal','entity-state',[field('proposalId','Proposal UUID'),field('choice','Response','select',{options:['accept','decline']}),field('requestId','Response UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalAgreements.reply',executionStatus:'original-receiving-officeholder-consent-consumer',effect:'Only the original receiving current Royal mandate can accept or refuse a live72h proposal. Recheck both original mandates and the unrevoked signed proposal under the same transaction; record one signed response. Exact retries return the original receipt; conflicting responses, changed holders, expired or revoked proposals cannot manufacture acceptance. No further payment or Reputation is issued for replying.'}), diff --git a/website/control-panel/public/naib-council-policy.mjs b/website/control-panel/public/naib-council-policy.mjs index fd866f10..1cd0398b 100644 --- a/website/control-panel/public/naib-council-policy.mjs +++ b/website/control-panel/public/naib-council-policy.mjs @@ -1,2 +1,9 @@ -export const NAIB_COUNCIL_DECISION=Object.freeze({id:'FRE-01',level:10,xp:200,feeMinor:100000,cooldownMs:86400000}); -export const naibDecision=id=>id===NAIB_COUNCIL_DECISION.id?NAIB_COUNCIL_DECISION:null; +export const NAIB_COUNCIL_DECISIONS=Object.freeze([ + {id:'FRE-01',kind:'decision',title:'Council Assembly',level:10,xp:200,feeMinor:100000,cooldownMs:86400000,durationMs:null}, + {id:'FRE-02',kind:'defense-coalition',title:'Defend Sietches',level:25,xp:400,feeMinor:1500000,cooldownMs:7*86400000,durationMs:7*86400000}, + {id:'FRE-03',kind:'water-sharing',title:'Water Discipline',level:20,xp:300,feeMinor:250000,cooldownMs:72*3600000,durationMs:7*86400000}, + {id:'FRE-06',kind:'desert-alliance',title:'Desert Alliance',level:30,xp:500,feeMinor:500000,cooldownMs:7*86400000,durationMs:14*86400000} +].map(Object.freeze)); +export const NAIB_COUNCIL_DECISION=NAIB_COUNCIL_DECISIONS[0]; +export const naibDecision=id=>NAIB_COUNCIL_DECISIONS.find(d=>d.id===id)||null; +export const naibProposal=kind=>NAIB_COUNCIL_DECISIONS.find(d=>d.kind===kind)||null; diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 464e3d8d..42e1a67a 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -412,7 +412,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/jarvis/auctions'||path==='/api/jarvis/auction'||path==='/api/jarvis/auctions/bid')return officeAuctionAPI(request); if(['/api/jarvis/generator','/api/jarvis/generator/redeem','/api/jarvis/generator/history','/api/jarvis/generator/options'].includes(path))return masterKeyGenerator(request); if(path==='/api/jarvis/validate')return keyValidation(request); - if(path==='/api/politics/naibs'||path==='/api/politics/naibs/propose'||path==='/api/politics/naibs/vote')return naibCouncil(request); + if(path==='/api/politics/naibs'||path==='/api/politics/naibs/propose'||path==='/api/politics/naibs/vote'||path==='/api/politics/naibs/withdraw')return naibCouncil(request); if(path.startsWith('/api/jarvis/political-jobs'))return politicalJobs.api(request); if(['/api/jarvis/campaigns','/api/jarvis/campaigns/public'].includes(path))return electionCampaigns(request); if(path==='/api/war-exchange')return warExchange(request); diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index 5f9b4f61..36ad8408 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "177ce3976cdfc262862c146898ee459608d6acfe50590473d5c8b3aae74915d8", + "sourceHash": "a4dedf5da7944eec6a6d0416f55bedc33d7da0fe967be09b14349d243960bce7", "actions": [ { "id": "war.coalition-consent", @@ -531,6 +531,37 @@ "webIssue": false, "recordOnly": true }, + { + "id": "politics.naib-accord-withdraw", + "label": "POL & orders · Withdraw a sietch accord consent", + "version": 1, + "keyType": "organisation-action", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "dossierId", + "label": "Closed Council dossier UUID", + "type": "text", + "required": true + }, + { + "name": "requestId", + "label": "Withdrawal UUID", + "type": "text", + "required": true + } + ], + "effect": "Use the existing Council audit transaction to withdraw the current sietch from a funded, accepted and unexpired accord. Recheck current independent ownership and the original yes vote; mother control and successor ownership do not inherit consent. Record a single idempotent withdrawal event without deleting the historical vote, charging money or awarding Reputation. No arbitrary JARVIS key is issued by this ordinary Council event flow.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, { "id": "politics.naib-council-assembly", "label": "POL & orders · Fund an independent sietch Council proposal", @@ -544,6 +575,18 @@ "required": true, "maxLength": 80 }, + { + "name": "kind", + "label": "Registered Council decision", + "type": "select", + "required": true, + "options": [ + "decision", + "defense-coalition", + "water-sharing", + "desert-alliance" + ] + }, { "name": "requestId", "label": "Council request UUID", @@ -569,7 +612,7 @@ "required": true } ], - "effect": "FRE01 uses the existing24h Council, current independent Naib ownership and one institutional vote per recognised sietch. Reputation10,1000DM to Tax and200 Reputation points;24h seat cooldown survives ownership transfer. Keyed sietches fund their own active payment account; Basic sietches use the current legal owner’s active personal account. Source authority, balances, Reputation, ordinary scoped ESK key and complete dossier commit atomically. No free production fallback or extra charge/reward for voting. Personal election rights and Imperial appointment authority remain unchanged.", + "effect": "FRE01 uses the existing24h Council, current independent Naib ownership and one institutional vote per recognised sietch. Reputation10,1000DM to Tax and200 Reputation points;24h seat cooldown survives ownership transfer. Keyed sietches fund their own active payment account; Basic sietches use the current legal owner’s active personal account. Source authority, balances, Reputation, ordinary scoped ESK key and complete dossier commit atomically. FRE02:15000DM,400 Reputation,level25,7d cooldown and7d defensive accord. FRE03:2500DM,300 Reputation,level20,72h cooldown and7d water-sharing accord. FRE06:5000DM,500 Reputation,level30,7d cooldown and14d alliance. All use24h Council consent, frozen institutional electorate and the existing quorum rule. Only current sietches whose original Naib voted yes join; they may withdraw through the normal Council audit flow. No automatic war consent or delivery is fabricated. No free production fallback or extra charge/reward for voting. Personal election rights and Imperial appointment authority remain unchanged.", "fixedTargets": [], "webIssue": false, "recordOnly": true diff --git a/website/node/naib-council-accords.mjs b/website/node/naib-council-accords.mjs new file mode 100644 index 00000000..4fa046c9 --- /dev/null +++ b/website/node/naib-council-accords.mjs @@ -0,0 +1,28 @@ +import {naibProposal,NAIB_COUNCIL_DECISIONS} from '../control-panel/public/naib-council-policy.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +import {currentNaib,naibSeats} from './naib-membership.mjs'; +import {JarvisError} from './jarvis-listings.mjs'; +const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); +export async function readCurrentCouncilAccords(db,seats,actor,now){ + const policies=NAIB_COUNCIL_DECISIONS.filter(d=>d.durationMs),kinds=policies.map(d=>d.kind),since=now-Math.max(...policies.map(d=>d.durationMs)),rows=await db.query("SELECT d.* FROM jarvis_council_dossiers d JOIN jarvis_council_events e ON e.dossier_id=d.id AND e.event_type='decision_recorded' WHERE d.state='closed' AND d.result='yes' AND d.kind IN ("+kinds.map(()=>'?').join(',')+") AND e.created_at>? ORDER BY d.closes_at DESC,d.id LIMIT 1001",[...kinds,since]); + if(rows.length>1000||new Set(rows.map(d=>d.id)).size!==rows.length)throw new JarvisError('Council accord records require review.',503);if(!rows.length)return[]; + const votes=await db.query('SELECT dossier_id,clan_id,user_id,choice FROM jarvis_council_votes WHERE dossier_id IN ('+rows.map(()=>'?').join(',')+')',rows.map(d=>d.id));return readCouncilAccords(db,rows,seats,votes,actor,now); +} +export async function readCouncilAccords(db,dossiers,seats,votes,actor,now){ + const accords=[],current=new Map(seats.map(s=>[s.clan_id,s])); + for(const dossier of dossiers){const policy=naibProposal(dossier.kind);if(!policy?.durationMs||dossier.state!=='closed'||dossier.result!=='yes')continue; + const events=await db.query('SELECT actor_id,event_type,payload,created_at FROM jarvis_council_events WHERE dossier_id=? ORDER BY created_at,id',[dossier.id]),opened=events.find(e=>e.event_type==='proposal_recorded'),closed=events.find(e=>e.event_type==='decision_recorded');if(!opened||!closed)continue;const proof=JSON.parse(opened.payload),result=JSON.parse(closed.payload); + if(proof.decisionId!==policy.id||proof.agreementMs!==policy.durationMs||proof.funding?.feeMinor!==String(policy.feeMinor)||proof.funding.xp!==policy.xp||result.result!=='yes'||Number(closed.created_at)e.event_type==='pact_withdrawal').map(e=>JSON.parse(e.payload).clanId)),known=new Set(JSON.parse(dossier.electorate)),participants=votes.filter(v=>v.dossier_id===dossier.id&&v.choice==='yes'&&known.has(v.clan_id)&¤t.get(v.clan_id)?.user_id===v.user_id&&!withdrawn.has(v.clan_id)).map(v=>({id:v.clan_id,name:current.get(v.clan_id).clan_name,tag:current.get(v.clan_id).tag,own:v.user_id===actor.id})),endsAt=Number(closed.created_at)+policy.durationMs; + accords.push({id:dossier.id,decisionId:policy.id,kind:dossier.kind,title:dossier.title,terms:dossier.message,participants,startsAt:Number(closed.created_at),endsAt,state:now>=endsAt?'expired':participants.length<2?'insufficient-current-consent':'active',canWithdraw:nowp.own)}); + }return accords; +} +export async function withdrawCouncilAccord(db,actor,input,{clock=Date.now,event}={}){ + if(!input||Object.keys(input).sort().join(',')!=='confirmed,dossierId,requestId'||input.confirmed!==true||!uuid(input.dossierId)||!uuid(input.requestId))throw new JarvisError('Confirm leaving this Council accord.',400); + return db.transaction(async tx=>{const dossier=await tx.first('SELECT * FROM jarvis_council_dossiers WHERE id=? FOR UPDATE',[input.dossierId]);if(!dossier)throw new JarvisError('Council accord not found.',404);const seat=await currentNaib(tx,actor.id,{lock:true});if(!seat)throw new JarvisError('Current independent sietch ownership required.',403); + const history=await tx.query("SELECT actor_id,payload FROM jarvis_council_events WHERE dossier_id=? AND event_type='pact_withdrawal'",[dossier.id]),previous=history.find(h=>JSON.parse(h.payload).requestId===input.requestId);if(previous){if(previous.actor_id!==actor.id||JSON.parse(previous.payload).clanId!==seat.clan_id)throw new JarvisError('Withdrawal reference conflict.',409);return{withdrawn:true,replayed:true};} + const now=clock(),accord=(await readCouncilAccords(tx,[dossier],await naibSeats(tx),await tx.query('SELECT dossier_id,clan_id,user_id,choice FROM jarvis_council_votes WHERE dossier_id=?',[dossier.id]),actor,now))[0];if(!accord?.canWithdraw)throw new JarvisError('This sietch has no current consent to withdraw.',409); + await event(tx,dossier.id,actor.id,'pact_withdrawal',{requestId:input.requestId,clanId:seat.clan_id,decisionId:accord.decisionId},now);return{withdrawn:true,replayed:false}; + }); +} diff --git a/website/node/naib-council-api.mjs b/website/node/naib-council-api.mjs index 4fb5a1d7..061103c3 100644 --- a/website/node/naib-council-api.mjs +++ b/website/node/naib-council-api.mjs @@ -11,12 +11,12 @@ export function createNaibCouncilAPI(db,settings={},deps={}){ const actor=await auth(request);if(!actor)return reply({message:'Sign in first.'},401); if(!(await access(actor)).nodes.includes('web.menu.game'))throw new JarvisError('Game account access required.',403); if(request.method==='GET'&&url.pathname==='/api/politics/naibs')return reply(await service.context(actor)); - if(request.method!=='POST'||!['/api/politics/naibs/propose','/api/politics/naibs/vote'].includes(url.pathname))return reply({message:'Method not allowed.'},405); + if(request.method!=='POST'||!['/api/politics/naibs/propose','/api/politics/naibs/vote','/api/politics/naibs/withdraw'].includes(url.pathname))return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)throw new JarvisError('Invalid request origin.',403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))throw new JarvisError('JSON required.',415); const raw=await request.text();if(raw.length>16000)throw new JarvisError('Proposal too large.',413);let input;try{input=JSON.parse(raw);}catch{throw new JarvisError('Invalid Council request.');} if(!input||typeof input!=='object'||Array.isArray(input))throw new JarvisError('Invalid Council request.'); - return reply(await (url.pathname.endsWith('/vote')?service.vote(actor,input):service.propose(actor,input)),201); + return reply(await (url.pathname.endsWith('/vote')?service.vote(actor,input):url.pathname.endsWith('/withdraw')?service.withdraw(actor,input):service.propose(actor,input)),201); }catch(error){return reply({message:error instanceof JarvisError?error.message:'Council records are temporarily unavailable.'},error instanceof JarvisError?error.status:503);} }; } diff --git a/website/node/naib-council-funding.mjs b/website/node/naib-council-funding.mjs index 67be95dc..978d8df6 100644 --- a/website/node/naib-council-funding.mjs +++ b/website/node/naib-council-funding.mjs @@ -13,20 +13,21 @@ import {polProgressionStore} from './progression-pol.mjs'; import {readActiveXPSeason,lockXPAccount,saveXPAccount} from './progression-xp-store.mjs'; import {creditXP} from './progression-xp-ledger.mjs'; import {levelForXP,xpAtLevel} from './progression-definitions.mjs'; -import {NAIB_COUNCIL_DECISION as POLICY} from '../control-panel/public/naib-council-policy.mjs'; +import {NAIB_COUNCIL_DECISION as POLICY,NAIB_COUNCIL_DECISIONS,naibProposal} from '../control-panel/public/naib-council-policy.mjs'; const fail=(message,status=409)=>{throw new JarvisError(message,status);}; const accountsSQL='SELECT a.*,c.entity_id,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id'; export function createNaibCouncilFunding(raw,bank,keys,{clock=Date.now,authority=null,verifyStorage}={}){ if(typeof raw?.query!=='function')return{ready:async()=>fail('Council banking unavailable.',503),context:async()=>({...POLICY,required:true,available:false,canExecute:false,accounts:[],levelNow:0}),charge:async()=>fail('Council banking unavailable.',503)}; const db=boardReadStore(raw,raw),banking=atomicBankAccess(db,bank,{verifyStorage,centralTables:['jarvis_council_dossiers','jarvis_council_events','jarvis_council_proposal_locks','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts','organisation_keys','organisation_key_events','codex_instance_editions','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox']}); async function sources(tx,actor,seat){const r=boardReadStore(tx,db),deed=await readClanDeed(r,seat.clan_id);if(deed.owner?.id!==actor.id)fail('Current independent sietch ownership required.',403);const funding=entityId(deed.kind==='basic'?'person':'clan',deed.kind==='basic'?actor.id:seat.clan_id),b=banking.view(r),rights=await(authority||createPostbankAuthority(r,{bank:b,clock}))(actor,{bank:b});return(await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[funding])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));} - async function context(actor,seat){try{await banking.ready();if(!keys||!seat)throw Error('Council funding unavailable');const now=clock(),pol=polProgressionStore(db),season=await readActiveXPSeason(pol,now),row=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]),levelNow=levelForXP(Number(row?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null}),accounts=(await sources(db,actor,seat)).map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}));return{...POLICY,required:true,available:true,canExecute:levelNow>=POLICY.level&&accounts.some(a=>BigInt(a.availableMinor)>=BigInt(POLICY.feeMinor)),accounts,levelNow};}catch{return{...POLICY,required:true,available:false,canExecute:false,accounts:[],levelNow:0};}} - async function charge(original,{actor,seat,sourceAccount,requestId,dossierId,now=clock()}){ + async function context(actor,seat){try{await banking.ready();if(!keys||!seat)throw Error('Council funding unavailable');const now=clock(),pol=polProgressionStore(db),season=await readActiveXPSeason(pol,now),row=await pol.first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]),levelNow=levelForXP(Number(row?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null}),accounts=(await sources(db,actor,seat)).map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))}));return{policies:NAIB_COUNCIL_DECISIONS.map(d=>({...d,canExecute:levelNow>=d.level&&accounts.some(a=>BigInt(a.availableMinor)>=BigInt(d.feeMinor))})),...POLICY,required:true,available:true,canExecute:levelNow>=POLICY.level&&accounts.some(a=>BigInt(a.availableMinor)>=BigInt(POLICY.feeMinor)),accounts,levelNow};}catch{return{...POLICY,required:true,available:false,canExecute:false,accounts:[],levelNow:0};}} + async function charge(original,{actor,seat,sourceAccount,requestId,dossierId,kind='decision',now=clock()}){ + const policy=naibProposal(kind);if(!policy)fail('Registered Council policy required.',400); if(!keys||typeof sourceAccount!=='string'||!/^\d{1,12}$/.test(sourceAccount))fail('Choose an authorised sietch funding account.',400);const tx=boardReadStore(original,db),current=await currentNaib(tx,actor.id,{lock:true});if(current?.clan_id!==seat.clan_id)fail('Current independent sietch ownership required.',403); const b=banking.view(tx),taxMeta=await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!taxMeta)fail('Council Tax treasury unavailable.',503);await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[sourceAccount,taxMeta.id]); - const source=(await sources(tx,actor,seat)).find(a=>String(a.id)===sourceAccount),tax=await b.first('SELECT * FROM pb_accounts WHERE id=?',[taxMeta.id]),amount=BigInt(POLICY.feeMinor);if(!source||!tax||tax.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)9223372036854775807n)fail('Insufficient authorised sietch funds or unavailable treasury.'); - const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),state=await lockXPAccount(pol,actor.id,now);if(levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)||null}){const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,seat.clan_id,sourceAccount,requestId,dossierId])).digest('hex');await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[requestId,actor.id,source.id,tax.id,fingerprint,String(amount),'Council Assembly',now]);await new PostbankPayments(bank,null,{clock}).post(b,{id:requestId,actor_id:actor.id,amount_minor:String(amount)},source,tax,false);await saveXPAccount(pol,actor.id,creditXP(state,POLICY.xp,{capXP:Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base))}),season,keyId,'naib-council-decision',{decisionId:POLICY.id,dossierId,clanId:seat.clan_id,xp:POLICY.xp},now);receipt={keyId,feeMinor:String(amount),xp:POLICY.xp};}});return receipt; + const source=(await sources(tx,actor,seat)).find(a=>String(a.id)===sourceAccount),tax=await b.first('SELECT * FROM pb_accounts WHERE id=?',[taxMeta.id]),amount=BigInt(policy.feeMinor);if(!source||!tax||tax.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)9223372036854775807n)fail('Insufficient authorised sietch funds or unavailable treasury.'); + const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),state=await lockXPAccount(pol,actor.id,now);if(levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)||null}){const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,seat.clan_id,sourceAccount,requestId,dossierId])).digest('hex');await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[requestId,actor.id,source.id,tax.id,fingerprint,String(amount),policy.title,now]);await new PostbankPayments(bank,null,{clock}).post(b,{id:requestId,actor_id:actor.id,amount_minor:String(amount)},source,tax,false);await saveXPAccount(pol,actor.id,creditXP(state,policy.xp,{capXP:Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base))}),season,keyId,'naib-council-decision',{decisionId:policy.id,dossierId,clanId:seat.clan_id,xp:policy.xp},now);receipt={keyId,feeMinor:String(amount),xp:policy.xp};}});return receipt; } return{ready:banking.ready,context,charge}; } diff --git a/website/node/naib-council.mjs b/website/node/naib-council.mjs index c04b3e59..8c28b377 100644 --- a/website/node/naib-council.mjs +++ b/website/node/naib-council.mjs @@ -1,4 +1,5 @@ -import {NAIB_COUNCIL_DECISION as PAID_POLICY} from '../control-panel/public/naib-council-policy.mjs'; +import {readCurrentCouncilAccords,withdrawCouncilAccord} from './naib-council-accords.mjs'; +import {NAIB_COUNCIL_DECISION as PAID_POLICY,NAIB_COUNCIL_DECISIONS,naibProposal} from '../control-panel/public/naib-council-policy.mjs'; import {randomUUID,createHash} from 'node:crypto'; import {JarvisError} from './jarvis-listings.mjs'; import {naibSeats,currentNaib} from './naib-membership.mjs'; @@ -16,8 +17,9 @@ async function proposalAuthority(db,actor,now,{lock=false}={}){ const terms=await db.query("SELECT id FROM political_office_terms WHERE user_id=? AND kind='imperial' AND faction='imperium' AND office='emperor' AND outcome='winner' AND starts_at<=? AND expires_at>?"+(lock?' FOR UPDATE':''),[actor?.id,now,now]); return{seat,emperor:terms.length===1}; } -const proposalScope=(kind,seat)=>kind==='imperial-peace'?'imperial-peace':'sietch:'+seat.clan_id; +const proposalScope=(kind,seat)=>kind==='imperial-peace'?'imperial-peace':(kind==='decision'?'':kind+':')+'sietch:'+seat.clan_id; async function previousProposal(db,kind,userId){ + if(!['decision','imperial-peace'].includes(kind))return(await db.query('SELECT MAX(opens_at) proposed_at FROM jarvis_council_dossiers WHERE kind=? AND actor_id=?',[kind,userId]))[0]?.proposed_at??null; return (await db.query(kind==='imperial-peace'?"SELECT MAX(opens_at) proposed_at FROM jarvis_council_dossiers WHERE kind='imperial-peace'":"SELECT MAX(opens_at) proposed_at FROM jarvis_council_dossiers WHERE kind='decision' AND actor_id=?",kind==='imperial-peace'?[]:[userId]))[0]?.proposed_at??null; } export const councilChoices=kind=>kind==='imperial-peace'?['accept','reject','negotiate']:['yes','no']; @@ -40,19 +42,20 @@ export function createNaibCouncil(db,{clock=Date.now,billing=null}={}){ async context(actor){ const seats=await naibSeats(db),now=clock(),{seat,emperor}=await proposalAuthority(db,actor,now); const funding=db.naibCouncilPaidEnabled===true?(billing?await billing.context(actor,seat):{...PAID_POLICY,required:true,available:false,canExecute:false,accounts:[],levelNow:0}):null,proposalKinds=[]; - for(const kind of ['decision','imperial-peace']){ + for(const kind of ['decision','imperial-peace',...(db.naibCouncilPaidEnabled===true?NAIB_COUNCIL_DECISIONS.filter(d=>d.durationMs).map(d=>d.kind):[])]){ if(!seat&&(kind!=='imperial-peace'||!emperor))continue; - const scope=proposalScope(kind,seat),row=(await db.query('SELECT last_proposed_at FROM jarvis_council_proposal_locks WHERE scope_key=?',[scope]))[0],previous=await previousProposal(db,kind,actor.id); - const cooldownUntil=row?.last_proposed_at==null&&previous===null?null:Math.max(Number(row?.last_proposed_at??-COUNCIL_PROPOSAL_COOLDOWN_MS),Number(previous??-COUNCIL_PROPOSAL_COOLDOWN_MS))+COUNCIL_PROPOSAL_COOLDOWN_MS; - proposalKinds.push({kind,cooldownUntil,canPropose:(!cooldownUntil||now>=cooldownUntil)&&(kind!=='decision'||!funding||funding.canExecute)}); + const policy=naibProposal(kind),wait=policy?.cooldownMs||COUNCIL_PROPOSAL_COOLDOWN_MS,scope=proposalScope(kind,seat),row=(await db.query('SELECT last_proposed_at FROM jarvis_council_proposal_locks WHERE scope_key=?',[scope]))[0],previous=await previousProposal(db,kind,actor.id); + const cooldownUntil=row?.last_proposed_at==null&&previous===null?null:Math.max(Number(row?.last_proposed_at??-wait),Number(previous??-wait))+wait; + proposalKinds.push({kind,title:policy?.title||'Imperial Peace offer',decisionId:policy?.id||null,cooldownMs:wait,cooldownUntil,canPropose:(!cooldownUntil||now>=cooldownUntil)&&(!policy||!funding||(funding.policies?.find(d=>d.kind===kind)?.canExecute??funding.canExecute))}); } - const dossiers=await db.query('SELECT id,kind,title,message,opens_at,closes_at,state,result,electorate FROM jarvis_council_dossiers ORDER BY opens_at DESC,id LIMIT 100'); - const votes=await db.query('SELECT v.dossier_id,v.clan_id,v.choice FROM jarvis_council_votes v JOIN jarvis_council_dossiers d ON d.id=v.dossier_id WHERE d.id IN (SELECT recent.id FROM (SELECT id FROM jarvis_council_dossiers ORDER BY opens_at DESC,id LIMIT 100) recent)'); - return {funding,name:'Council of Naibs',house:'House of Arrakis',world:'Arrakduin',naib:!!seat,seatId:seat?.clan_id||null,proposalKinds,proposalCooldownMs:COUNCIL_PROPOSAL_COOLDOWN_MS,seats:seats.map(s=>({id:s.clan_id,name:s.clan_name,tag:s.tag,username:s.username,displayName:s.display_name||s.username})),dossiers:dossiers.map(d=>({id:d.id,reference:'JRV-NAIB-'+d.id,kind:d.kind,title:d.title,message:d.message,opensAt:Number(d.opens_at),closesAt:Number(d.closes_at),state:d.state,result:d.result,electorate:JSON.parse(d.electorate).length,choices:councilChoices(d.kind),ownVote:seat?votes.find(v=>v.dossier_id===d.id&&v.clan_id===seat.clan_id)?.choice||null:null,canVote:!!seat&&d.state==='open'&&nowv.dossier_id===d.id)):null})),powersAvailable:false}; + const dossiers=await db.query('SELECT id,request_id,kind,title,message,opens_at,closes_at,state,result,electorate FROM jarvis_council_dossiers ORDER BY opens_at DESC,id LIMIT 100'); + const votes=await db.query('SELECT v.dossier_id,v.clan_id,v.user_id,v.choice FROM jarvis_council_votes v JOIN jarvis_council_dossiers d ON d.id=v.dossier_id WHERE d.id IN (SELECT recent.id FROM (SELECT id FROM jarvis_council_dossiers ORDER BY opens_at DESC,id LIMIT 100) recent)'); + const accords=db.naibCouncilPaidEnabled===true?await readCurrentCouncilAccords(db,seats,actor,now):[]; + return {accords,funding,name:'Council of Naibs',house:'House of Arrakis',world:'Arrakduin',naib:!!seat,seatId:seat?.clan_id||null,proposalKinds,proposalCooldownMs:COUNCIL_PROPOSAL_COOLDOWN_MS,seats:seats.map(s=>({id:s.clan_id,name:s.clan_name,tag:s.tag,username:s.username,displayName:s.display_name||s.username})),dossiers:dossiers.map(d=>({id:d.id,reference:'JRV-NAIB-'+d.id,kind:d.kind,title:d.title,message:d.message,opensAt:Number(d.opens_at),closesAt:Number(d.closes_at),state:d.state,result:d.result,electorate:JSON.parse(d.electorate).length,choices:councilChoices(d.kind),ownVote:seat?votes.find(v=>v.dossier_id===d.id&&v.clan_id===seat.clan_id)?.choice||null:null,canVote:!!seat&&d.state==='open'&&nowv.dossier_id===d.id)):null})),powersAvailable:false}; }, async propose(actor,input){ - if(!uuid(actor?.id)||!uuid(input?.requestId)||input.confirmed!==true||!['decision','imperial-peace'].includes(input.kind)||typeof input.title!=='string'||!input.title.trim()||input.title.length>100||typeof input.message!=='string'||input.message.trim().length<20||input.message.length>4000||/[\x00-\x1f\x7f]/.test(input.title)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.message))throw new JarvisError('Confirm a Council proposal and its details.'); - const paid=db.naibCouncilPaidEnabled===true&&input.kind==='decision';if(paid){if(Object.keys(input).sort().join(',')!=='confirmed,kind,message,requestId,sourceAccount,title'||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount))throw new JarvisError('Choose funding and confirm the Council proposal.',400);if(!billing)throw new JarvisError('Council banking unavailable.',503);try{await billing.ready();}catch{throw new JarvisError('Council banking unavailable.',503);}} + if(!uuid(actor?.id)||!uuid(input?.requestId)||input.confirmed!==true||!(input.kind==='imperial-peace'||naibProposal(input.kind))||typeof input.title!=='string'||!input.title.trim()||input.title.length>100||typeof input.message!=='string'||input.message.trim().length<20||input.message.length>4000||/[\x00-\x1f\x7f]/.test(input.title)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.message))throw new JarvisError('Confirm a Council proposal and its details.'); + const policy=naibProposal(input.kind),paid=db.naibCouncilPaidEnabled===true&&!!policy,wait=policy?.cooldownMs||COUNCIL_PROPOSAL_COOLDOWN_MS;if(policy?.durationMs&&!paid)throw new JarvisError('Funded Council accords are unavailable.',503);if(paid){if(Object.keys(input).sort().join(',')!=='confirmed,kind,message,requestId,sourceAccount,title'||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount))throw new JarvisError('Choose funding and confirm the Council proposal.',400);if(!billing)throw new JarvisError('Council banking unavailable.',503);try{await billing.ready();}catch{throw new JarvisError('Council banking unavailable.',503);}} const title=input.title.trim(),message=input.message.trim(),fingerprint=createHash('sha256').update(JSON.stringify([actor.id,input.kind,title,message,...(paid?[input.sourceAccount]:[])])).digest('hex'); return db.transaction(async tx=>{ const now=clock(),{seat,emperor}=await proposalAuthority(tx,actor,now,{lock:true}); @@ -64,10 +67,10 @@ export function createNaibCouncil(db,{clock=Date.now,billing=null}={}){ // Legacy dossiers retain their actor/global wait. New proposals also bind // the sietch seat, keeping the wait after an ownership transfer. const previous=await previousProposal(tx,input.kind,actor.id); - const last=Math.max(Number(cooldown?.last_proposed_at??-COUNCIL_PROPOSAL_COOLDOWN_MS),Number(previous??-COUNCIL_PROPOSAL_COOLDOWN_MS)); - if(nows.clan_id);if(!electorate.length)throw new JarvisError('No recognised sietches are available.',409); - const id=randomUUID(),fundingReceipt=paid?await billing.charge(tx,{actor,seat,sourceAccount:input.sourceAccount,requestId:input.requestId,dossierId:id,now}):null;await tx.query("INSERT INTO jarvis_council_dossiers(id,request_id,actor_id,kind,title,message,fingerprint,electorate,opens_at,closes_at,state) VALUES(?,?,?,?,?,?,?,?,?,?,'open')",[id,input.requestId,actor.id,input.kind,title,message,fingerprint,JSON.stringify(electorate),now,now+86400000]);await tx.query('UPDATE jarvis_council_proposal_locks SET last_proposed_at=? WHERE scope_key=?',[now,scope]);await event(tx,id,actor.id,'proposal_recorded',{kind:input.kind,seats:electorate.length,cooldownUntil:now+COUNCIL_PROPOSAL_COOLDOWN_MS,gameplayEffect:false,...(fundingReceipt?{funding:fundingReceipt}:{})},now);return{id,replayed:false,...(fundingReceipt?{funding:fundingReceipt}:{})}; + const last=Math.max(Number(cooldown?.last_proposed_at??-wait),Number(previous??-wait)); + if(nows.clan_id);if(policy?.durationMs&&electorate.length<2)throw new JarvisError('A voluntary accord needs at least two recognised sietches.',409);if(!electorate.length)throw new JarvisError('No recognised sietches are available.',409); + const id=randomUUID(),fundingReceipt=paid?await billing.charge(tx,{actor,seat,sourceAccount:input.sourceAccount,requestId:input.requestId,dossierId:id,kind:input.kind,now}):null;await tx.query("INSERT INTO jarvis_council_dossiers(id,request_id,actor_id,kind,title,message,fingerprint,electorate,opens_at,closes_at,state) VALUES(?,?,?,?,?,?,?,?,?,?,'open')",[id,input.requestId,actor.id,input.kind,title,message,fingerprint,JSON.stringify(electorate),now,now+86400000]);await tx.query('UPDATE jarvis_council_proposal_locks SET last_proposed_at=? WHERE scope_key=?',[now,scope]);await event(tx,id,actor.id,'proposal_recorded',{kind:input.kind,seats:electorate.length,cooldownUntil:now+wait,sourceClanId:seat?.clan_id||null,decisionId:policy?.id||null,agreementMs:policy?.durationMs||null,gameplayEffect:false,...(fundingReceipt?{funding:fundingReceipt}:{})},now);return{id,replayed:false,...(fundingReceipt?{funding:fundingReceipt}:{})}; }); }, async vote(actor,input){ @@ -81,6 +84,7 @@ export function createNaibCouncil(db,{clock=Date.now,billing=null}={}){ await tx.query('INSERT INTO jarvis_council_votes(dossier_id,clan_id,user_id,choice,created_at) VALUES(?,?,?,?,?)',[dossier.id,seat.clan_id,actor.id,input.choice,now]);await event(tx,dossier.id,actor.id,'vote_received',{clanId:seat.clan_id},now);return{replayed:false}; }); }, + withdraw:(actor,input)=>withdrawCouncilAccord(db,actor,input,{clock,event}), async reconcile(){ const due=await db.query("SELECT id FROM jarvis_council_dossiers WHERE state='open' AND closes_at<=? ORDER BY closes_at,id LIMIT 100",[clock()]); for(const row of due)await db.transaction(async tx=>{const dossier=await tx.first('SELECT * FROM jarvis_council_dossiers WHERE id=? FOR UPDATE',[row.id]);if(dossier.state!=='open')return;const votes=await tx.query('SELECT clan_id,choice FROM jarvis_council_votes WHERE dossier_id=?',[dossier.id]),outcome=councilOutcome(dossier.kind,JSON.parse(dossier.electorate).length,votes);await tx.query("UPDATE jarvis_council_dossiers SET state='closed',result=? WHERE id=?",[outcome.result,dossier.id]);await event(tx,dossier.id,null,'decision_recorded',{...outcome,gameplayEffect:false},clock());}); diff --git a/website/tests/political-decisions.test.mjs b/website/tests/political-decisions.test.mjs index 99be6682..5e81af07 100644 --- a/website/tests/political-decisions.test.mjs +++ b/website/tests/political-decisions.test.mjs @@ -282,3 +282,12 @@ test('paid Council has no free production fallback and rejects foreign funding o test('Council journal failure rolls back its bank transfer, Reputation and ordinary scoped key',async()=>{const f=await paidNaibFixture();try{const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_paid_council BEFORE INSERT ON jarvis_council_dossiers BEGIN SELECT RAISE(ABORT,'Council journal failed');END");await assert.rejects(f.council.propose(f.people.Other,f.input()),/Council journal failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,500000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}); test('a keyed sietch funds its Council proposal from its own account rather than its owner’s personal account',async()=>{const f=await paidNaibFixture();try{const charter=await f.keys.issue({accountId:f.people.Other.id,keyType:'clan-founding',scopeId:'original',authorize:async()=>true});await f.keys.consume({accountId:f.people.Other.id,keyType:'clan-founding',code:charter.code,targetId:f.clanId,requestId:randomUUID(),apply:(tx,{keyId})=>tx.query("INSERT INTO site_clan_charters(clan_id,original_account_id,key_id,charter_kind,created_at) VALUES(?,?,?,'original',1)",[f.clanId,f.people.Other.id,keyId])});const source=await f.activate(f.people.Other,'clan',f.clanId);await f.db.query('UPDATE pb_accounts SET balance_minor=500000 WHERE id=?',[source.id]);const view=await f.council.context(f.people.Other);assert.equal(view.funding.accounts.some(a=>a.id===String(f.target.id)),false);await assert.rejects(f.council.propose(f.people.Other,f.input()),/Insufficient authorised/);await f.council.propose(f.people.Other,{...f.input(),sourceAccount:String(source.id)});assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[source.id])).balance_minor,400000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,500000);}finally{f.db.close();}}); test('Council Reputation and available funds are rechecked without charging ineligible proposals',async()=>{for(const reason of ['reputation','balance']){const f=await paidNaibFixture();try{if(reason==='reputation')await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=0 WHERE account_id=?',[f.people.Other.id]);else await f.db.query('UPDATE pb_accounts SET balance_minor=99999 WHERE id=?',[f.target.id]);assert.equal((await f.council.context(f.people.Other)).funding.canExecute,false);await assert.rejects(f.council.propose(f.people.Other,f.input()),reason==='reputation'?/Reputation level 10/:/Insufficient authorised/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}}); + +async function councilAccordFixture(){const f=await paidNaibFixture(),clans=[{id:f.clanId,actor:f.people.Other}];await f.db.query('UPDATE pb_accounts SET balance_minor=2000000 WHERE id=?',[f.target.id]);await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000 WHERE account_id=?',[f.people.Other.id]);for(const person of [f.people.Member,f.people.Owner]){const id=randomUUID(),link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[person.id]);await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,?,?,?,?,'arrakduin',?,1,1)",[id,person.username+' sietch',person.username.toLowerCase()+' sietch',person.username.toUpperCase(),'Native sietch',person.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[person.id,link.minecraft_uuid,id]);clans.push({id,actor:person});}return{...f,clans};} +test('three Council accords retain their exact prices, Reputation and per-sietch cooldowns',async()=>{for(const [kind,fee,xp,days]of [['defense-coalition',1500000,400,7],['water-sharing',250000,300,7],['desert-alliance',500000,500,14]]){const f=await councilAccordFixture();try{const input={...f.input(),kind},r=await f.council.propose(f.people.Other,input);assert.equal(r.funding.feeMinor,String(fee));assert.equal(r.funding.xp,xp);assert.equal((await f.council.propose(f.people.Other,input)).replayed,true);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,2000000-fee);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,50000+xp);assert.equal((await f.council.context(f.people.Other)).proposalKinds.find(p=>p.kind===kind).canPropose,false);await assert.rejects(f.council.propose(f.people.Other,{...f.input(),kind}),/cooldown/);for(const [i,clan]of f.clans.entries())await f.council.vote(clan.actor,{dossierId:r.id,choice:i===2?'no':'yes',confirmed:true});f.setTime(1000+86400000);await f.council.reconcile();const accord=(await f.council.context(f.people.Other)).accords[0];assert.equal(accord.state,'active');assert.equal(accord.participants.length,2);assert.equal(accord.endsAt,1000+86400000+days*86400000);assert.equal(accord.canWithdraw,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}}}); +test('Council accord withdrawal is voluntary, owner-checked and idempotent without changing votes or charging again',async()=>{const f=await councilAccordFixture();try{const r=await f.council.propose(f.people.Other,{...f.input(),kind:'water-sharing'});for(const [i,clan]of f.clans.entries())await f.council.vote(clan.actor,{dossierId:r.id,choice:i===2?'no':'yes',confirmed:true});f.setTime(1000+86400000);await f.council.reconcile();const input={dossierId:r.id,requestId:randomUUID(),confirmed:true};await assert.rejects(f.council.withdraw(f.people.Owner,input),/no current consent/);await assert.rejects(f.council.withdraw(f.people.Ceo,input),/independent sietch/);await f.council.withdraw(f.people.Other,input);assert.equal((await f.council.withdraw(f.people.Other,input)).replayed,true);const accord=(await f.council.context(f.people.Other)).accords[0];assert.equal(accord.participants.length,1);assert.equal(accord.state,'insufficient-current-consent');assert.equal(accord.canWithdraw,false);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_council_votes WHERE dossier_id=?',[r.id])).n,3);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first("SELECT COUNT(*) n FROM jarvis_council_events WHERE event_type='pact_withdrawal'")).n,1);}finally{f.db.close();}}); +test('accords require multiple sietches and an actual funded proof; ownership cannot inherit a former Naib’s consent',async()=>{const one=await paidNaibFixture();try{await assert.rejects(one.council.propose(one.people.Other,{...one.input(),kind:'water-sharing'}),/at least two/);assert.equal((await one.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{one.db.close();}const f=await councilAccordFixture();try{const r=await f.council.propose(f.people.Other,{...f.input(),kind:'desert-alliance'});for(const clan of f.clans.slice(0,2))await f.council.vote(clan.actor,{dossierId:r.id,choice:'yes',confirmed:true});f.setTime(1000+86400000);await f.council.reconcile();const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Ceo.id]);await f.db.query('UPDATE site_clans SET owner_id=? WHERE id=?',[f.people.Ceo.id,f.clans[1].id]);await f.db.query('UPDATE site_clan_members SET user_id=?,minecraft_uuid=? WHERE clan_id=?',[f.people.Ceo.id,link.minecraft_uuid,f.clans[1].id]);const changed=(await f.council.context(f.people.Ceo)).accords[0];assert.equal(changed.participants.length,1);assert.equal(changed.canWithdraw,false);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[r.funding.keyId]);assert.equal((await f.council.context(f.people.Other)).accords.length,0);}finally{f.db.close();}}); +test('withdrawal audit failure leaves the accord and its historical votes unchanged',async()=>{const f=await councilAccordFixture();try{const r=await f.council.propose(f.people.Other,{...f.input(),kind:'water-sharing'});for(const clan of f.clans.slice(0,2))await f.council.vote(clan.actor,{dossierId:r.id,choice:'yes',confirmed:true});f.setTime(1000+86400000);await f.council.reconcile();f.db.sqlite.exec("CREATE TRIGGER fail_pact_withdrawal BEFORE INSERT ON jarvis_council_events WHEN NEW.event_type='pact_withdrawal' BEGIN SELECT RAISE(ABORT,'withdrawal failed');END");await assert.rejects(f.council.withdraw(f.people.Other,{dossierId:r.id,requestId:randomUUID(),confirmed:true}),/withdrawal failed/);assert.equal((await f.council.context(f.people.Other)).accords[0].participants.length,2);}finally{f.db.close();}}); + +test('unfunded kinds, low quorum, ties and expired accord periods cannot establish active sietch consent',async()=>{for(const choices of [['yes'],['yes','no']]){const f=await councilAccordFixture();try{const r=await f.council.propose(f.people.Other,{...f.input(),kind:'water-sharing'});for(let i=0;i{const f=await councilAccordFixture();try{const r=await f.council.propose(f.people.Other,{...f.input(),title:'Desert Alliance'});assert.equal(r.funding.feeMinor,'100000');for(const clan of f.clans.slice(0,2))await f.council.vote(clan.actor,{dossierId:r.id,choice:'yes',confirmed:true});f.setTime(1000+86400000);await f.council.reconcile();assert.equal((await f.council.context(f.people.Other)).accords.length,0);}finally{f.db.close();}});