import {randomUUID,createHash} from 'node:crypto'; import {JarvisError} from './jarvis-listings.mjs'; import {naibSeats,currentNaib} from './naib-membership.mjs'; export const NAIB_COUNCIL_SCHEMA=[ `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); export const councilChoices=kind=>kind==='imperial-peace'?['accept','reject','negotiate']:['yes','no']; export function councilOutcome(kind,seats,votes){ if(!Number.isInteger(seats)||seats<1||votes.length>seats||new Set(votes.map(v=>v.clan_id)).size!==votes.length||votes.some(v=>!councilChoices(kind).includes(v.choice)))throw new JarvisError('Council vote records require review.',409); const quorum=Math.floor(seats/2)+1,counts=Object.fromEntries(councilChoices(kind).map(choice=>[choice,votes.filter(v=>v.choice===choice).length])); const winner=Object.keys(counts).find(choice=>counts[choice]>votes.length/2); return {quorum,participation:votes.length,counts,result:votes.length? ORDER BY starts_at,id LIMIT 100",[now,now]);let ended=0; for(const row of terms)await db.transaction(async tx=>{ await tx.query('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',['naib_chair:arrakis']);await tx.first('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',['naib_chair:arrakis']); const term=await tx.first('SELECT * FROM political_office_terms WHERE id=? FOR UPDATE',[row.id]);if(term.outcome!=='winner'||await currentNaib(tx,term.user_id,{lock:true}))return; const flowId=randomUUID();await tx.query("UPDATE political_office_terms SET outcome='ineligible',expires_at=? WHERE id=?",[now,term.id]); await tx.query("INSERT INTO political_succession_flows(id,source_term_id,kind,faction,office,reason,state,created_at) VALUES(?,?,?,?,?,'sietch_transfer','queued',?)",[flowId,term.id,term.kind,term.faction,term.office,now]); await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),term.id,'eligibility_ended',JSON.stringify({successorFlowId:flowId,reason:'current-sietch-deed-required'}),now]);ended++; });return{ended}; } 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 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'&&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 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 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};} 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}; }); }, async vote(actor,input){ if(!uuid(actor?.id)||!uuid(input?.dossierId)||input.confirmed!==true)throw new JarvisError('Confirm your Council vote.'); 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 dossier not found.',404); const now=clock(),seat=await currentNaib(tx,actor.id,{lock:true});if(!seat||!JSON.parse(dossier.electorate).includes(seat.clan_id))throw new JarvisError('A current participating sietch deed is required.',403); if(!councilChoices(dossier.kind).includes(input.choice))throw new JarvisError('Choose a Council decision.'); const prior=await tx.first('SELECT choice FROM jarvis_council_votes WHERE dossier_id=? AND clan_id=?',[dossier.id,seat.clan_id]);if(prior){if(prior.choice!==input.choice)throw new JarvisError('This sietch has already voted.',409);return{replayed:true};} if(dossier.state!=='open'||now>=Number(dossier.closes_at))throw new JarvisError('Council voting is closed.',409); 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}; }); }, 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());}); return{closed:due.length}; } }); }