Merge pull request 'Keep Council proposal cooldowns across ownership changes' (#579) from dev/MC:feature/council-proposal-cooldowns-20261125 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m50s
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m50s
This commit is contained in:
commit
2716317838
3 changed files with 74 additions and 9 deletions
|
|
@ -15,10 +15,14 @@ export function mountNaibCouncil(host){
|
|||
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.'));
|
||||
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;
|
||||
for(const [value,text]of [['decision','Council proposal'],['imperial-peace','Imperial Peace offer']]){const option=el('option',text);option.value=value;kind.append(option);}if(!data.naib){kind.value='imperial-peace';kind.disabled=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 cooldownNotice=el('p');form.append(cooldownNotice);
|
||||
const refreshProposal=()=>{const policy=available.find(p=>p.kind===kind.value);send.disabled=busy||!policy?.canPropose;cooldownNotice.textContent=!policy?'Only a current Naib or the Emperor can submit an eligible proposal.':policy.canPropose?'One proposal per sietch every 24 hours. Imperial Peace offers share one Council-wide 24-hour cooldown.':'Available again '+new Date(policy.cooldownUntil).toLocaleString('en-GB',{timeZone:'UTC'})+' UTC.';};
|
||||
kind.onchange=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,send])field.disabled=value;kind.disabled=value||!data.naib;};
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity())return;const input={requestId,kind:kind.value,title:title.value,message:message.value,confirmed:confirm.checked};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);}}};
|
||||
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};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'));
|
||||
powers.append(el('h3','Council powers'),el('p','Political powers are awaiting a separate design. No gameplay action is available from this page.'));
|
||||
|
|
|
|||
|
|
@ -1,12 +1,23 @@
|
|||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {JarvisError} from './jarvis-listings.mjs';
|
||||
import {naibSeats,currentNaib} from './naib-membership.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`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_council_dossiers(id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,kind VARCHAR(24) NOT NULL,title VARCHAR(100) NOT NULL,message TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,electorate TEXT NOT NULL,opens_at BIGINT NOT NULL,closes_at BIGINT NOT NULL,state VARCHAR(24) NOT NULL,result VARCHAR(24) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_council_votes(dossier_id CHAR(36) NOT NULL,clan_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,choice VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(dossier_id,clan_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
||||
`CREATE TABLE IF NOT EXISTS jarvis_council_events(id CHAR(36) PRIMARY KEY,dossier_id CHAR(36) NOT NULL,actor_id CHAR(36) NULL,event_type VARCHAR(24) NOT NULL,payload TEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
|
||||
];
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
async function proposalAuthority(db,actor,now,{lock=false}={}){
|
||||
const seat=await currentNaib(db,actor?.id,{lock});
|
||||
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;
|
||||
async function previousProposal(db,kind,userId){
|
||||
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'];
|
||||
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);
|
||||
|
|
@ -28,20 +39,35 @@ export function createNaibCouncil(db,{clock=Date.now}={}){
|
|||
const event=(tx,id,actor,type,payload,now)=>tx.query('INSERT INTO jarvis_council_events(id,dossier_id,actor_id,event_type,payload,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),id,actor,type,JSON.stringify(payload),now]);
|
||||
return Object.freeze({
|
||||
async context(actor){
|
||||
const seats=await naibSeats(db),seat=seats.find(s=>s.user_id===actor.id),now=clock();
|
||||
const seats=await naibSeats(db),now=clock(),{seat,emperor}=await proposalAuthority(db,actor,now);
|
||||
const proposalKinds=[];
|
||||
for(const kind of ['decision','imperial-peace']){
|
||||
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});
|
||||
}
|
||||
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 {name:'Council of Naibs',house:'House of Arrakis',world:'Arrakduin',naib:!!seat,seatId:seat?.clan_id||null,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'&&now<Number(d.closes_at)&&JSON.parse(d.electorate).includes(seat.clan_id),tally:d.state==='closed'?councilOutcome(d.kind,JSON.parse(d.electorate).length,votes.filter(v=>v.dossier_id===d.id)):null})),powersAvailable:false};
|
||||
return {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'&&now<Number(d.closes_at)&&JSON.parse(d.electorate).includes(seat.clan_id),tally:d.state==='closed'?councilOutcome(d.kind,JSON.parse(d.electorate).length,votes.filter(v=>v.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 title=input.title.trim(),message=input.message.trim(),fingerprint=createHash('sha256').update(JSON.stringify([actor.id,input.kind,title,message])).digest('hex');
|
||||
return db.transaction(async tx=>{
|
||||
const now=clock(),seat=await currentNaib(tx,actor.id,{lock:true});
|
||||
if(!seat){const emperor=input.kind==='imperial-peace'?await tx.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>? FOR UPDATE",[actor.id,now,now]):[];if(emperor.length!==1)throw new JarvisError('A current Naib deed is required; the Emperor may only submit an Imperial Peace offer.',403);}
|
||||
const now=clock(),{seat,emperor}=await proposalAuthority(tx,actor,now,{lock:true});
|
||||
if(!seat&&!(input.kind==='imperial-peace'&&emperor))throw new JarvisError('A current Naib deed is required; the Emperor may only submit an Imperial Peace offer.',403);
|
||||
const scope=proposalScope(input.kind,seat);
|
||||
await tx.query('INSERT INTO jarvis_council_proposal_locks(scope_key) VALUES(?) ON DUPLICATE KEY UPDATE scope_key=VALUES(scope_key)',[scope]);
|
||||
const cooldown=await tx.first('SELECT last_proposed_at FROM jarvis_council_proposal_locks WHERE scope_key=? FOR UPDATE',[scope]);
|
||||
const prior=await tx.first('SELECT id,fingerprint FROM jarvis_council_dossiers WHERE request_id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.fingerprint!==fingerprint)throw new JarvisError('Proposal reference already used.',409);return{id:prior.id,replayed:true};}
|
||||
// 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(now<last+COUNCIL_PROPOSAL_COOLDOWN_MS)throw new JarvisError('This Council proposal is on its 24-hour cooldown.',409);
|
||||
const electorate=(await naibSeats(tx)).map(s=>s.clan_id);if(!electorate.length)throw new JarvisError('No recognised sietches are available.',409);
|
||||
const id=randomUUID();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 event(tx,id,actor.id,'proposal_recorded',{kind:input.kind,seats:electorate.length,gameplayEffect:false},now);return{id,replayed:false};
|
||||
const id=randomUUID();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},now);return{id,replayed:false};
|
||||
});
|
||||
},
|
||||
async vote(actor,input){
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import test from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {BankFixture} from './postbank-fixture.mjs';
|
||||
import {NAIB_COUNCIL_SCHEMA,createNaibCouncil,councilOutcome} from '../node/naib-council.mjs';
|
||||
import {NAIB_COUNCIL_SCHEMA,COUNCIL_PROPOSAL_COOLDOWN_MS,createNaibCouncil,councilOutcome} from '../node/naib-council.mjs';
|
||||
import {currentNaib} from '../node/naib-membership.mjs';
|
||||
import {createNaibCouncilAPI} from '../node/naib-council-api.mjs';
|
||||
import {validateCandidature,voteCapacity,electionScope,electionDates} from '../control-panel/public/election-rules.mjs';
|
||||
|
|
@ -25,6 +25,41 @@ async function fixture(){
|
|||
const central={query:db.query.bind(db),transaction:db.transaction.bind(db),batch:statements=>db.transaction(async tx=>{const results=[];for(const statement of statements)results.push(await statement.run({execute:async(sql,args)=>[await tx.query(sql.replace(/ FOR SHARE/g,''),args)]}));return results;})};let now=1000;const service=createNaibCouncil(central,{clock:()=>now});return{db,central,service,people,setTime:v=>now=v,close:()=>db.close()};
|
||||
}
|
||||
const proposal=()=>({requestId:randomUUID(),kind:'decision',title:'Water reserves',message:'Preserve our water reserves for the sietches.',confirmed:true});
|
||||
|
||||
test('proposal cooldown follows the sietch, permits independent seats and allows exact safe retries',async()=>{
|
||||
const f=await fixture();try{
|
||||
const [a,b,,,heir]=f.people,input=proposal();
|
||||
const attempts=await Promise.allSettled([f.service.propose(a,input),f.service.propose(a,proposal())]);
|
||||
assert.equal(attempts.filter(r=>r.status==='fulfilled').length,1);
|
||||
assert.equal(attempts.find(r=>r.status==='rejected').reason.status,409);
|
||||
assert.equal((await f.service.propose(a,input)).replayed,true);
|
||||
let view=await f.service.context(a);assert.equal(view.proposalKinds.find(p=>p.kind==='decision').canPropose,false);
|
||||
assert.equal(view.proposalKinds.find(p=>p.kind==='decision').cooldownUntil,1000+COUNCIL_PROPOSAL_COOLDOWN_MS);
|
||||
await f.service.propose(b,proposal());
|
||||
await f.db.query('UPDATE site_clans SET owner_id=? WHERE id=?',[heir.id,a.clan]);
|
||||
await f.db.query('UPDATE site_clan_members SET user_id=?,minecraft_uuid=? WHERE clan_id=?',[heir.id,heir.player,a.clan]);
|
||||
await assert.rejects(()=>f.service.propose(heir,proposal()),e=>e.status===409&&/cooldown/.test(e.message));
|
||||
assert.equal((await f.service.context(a)).proposalKinds.length,0);
|
||||
assert.equal((await f.service.context(heir)).proposalKinds.find(p=>p.kind==='decision').canPropose,false);
|
||||
f.setTime(1000+COUNCIL_PROPOSAL_COOLDOWN_MS);
|
||||
await f.service.propose(heir,proposal());
|
||||
assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_council_dossiers')).n,3);
|
||||
}finally{f.close();}
|
||||
});
|
||||
|
||||
test('Imperial Peace wait is Council-wide and legacy proposals remain on cooldown',async()=>{
|
||||
const f=await fixture();try{
|
||||
const [a,b]=f.people,input={...proposal(),kind:'imperial-peace'};
|
||||
await f.service.propose(a,input);
|
||||
await assert.rejects(()=>f.service.propose(b,{...proposal(),kind:'imperial-peace'}),e=>e.status===409);
|
||||
await f.service.propose(b,proposal());
|
||||
await f.db.query('DELETE FROM jarvis_council_proposal_locks');
|
||||
assert.equal((await f.service.context(a)).proposalKinds.find(p=>p.kind==='imperial-peace').canPropose,false);
|
||||
await assert.rejects(()=>f.service.propose(b,{...proposal(),kind:'imperial-peace'}),e=>e.status===409);
|
||||
await assert.rejects(()=>f.service.propose(b,proposal()),e=>e.status===409);
|
||||
assert.equal((await f.service.propose(a,input)).replayed,true);
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('Council uses only active Arrakduin owners; ownership transfer cannot manufacture a second sietch vote',async()=>{
|
||||
const f=await fixture();try{
|
||||
const [a,b,,outsider,replacement]=f.people;assert.equal((await f.service.context(a)).seats.length,3);assert.equal(await currentNaib(f.central,outsider.id),null);
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff