MC/website/tests/political-decisions.test.mjs
2026-11-27 23:43:05 +00:00

376 lines
125 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {NAIB_COUNCIL_SCHEMA,createNaibCouncil} from '../node/naib-council.mjs';
import {hasOrganisationPassage} from '../node/imperial-organisation-passage.mjs';
import {createNaibPetitions,NAIB_PETITION_POLICY} from '../node/naib-petitions.mjs';
import {createNaibCouncilAPI} from '../node/naib-council-api.mjs';
import {createPoliticalReviews,createPoliticalReviewAPI,POLITICAL_REVIEW_PUBLICATION_SCHEMA} from '../node/political-reviews.mjs';
import {applicationSchema} from '../control-panel/election-applications.mjs';
import {roundSchema} from '../control-panel/election-rounds.mjs';
import {createNaibCouncilFunding} from '../node/naib-council-funding.mjs';
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {companyFixture} from './company-deed-fixture.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs';
import {createPoliticalDecisions,createPoliticalDecisionAPI,politicalHonours,POLITICAL_DECISION_SCHEMA,decisionInput,politicalDecisionReader} from '../node/political-decisions.mjs';
import {initializePOLProgression,polProgressionStore} from '../node/progression-pol.mjs';
import {PUBLIC_OFFICES} from '../node/public-government.mjs';
import {POLITICAL_DECISIONS} from '../control-panel/public/political-decision-policy.mjs';
import {DECISION_CATALOGUE} from '../control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs';
import {PostbankService} from '../node/postbank-service.mjs';import {entityId} from '../node/postbank-authority.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
import {createProclamations} from '../control-panel/proclamations.mjs';
import {honourMarkup} from '../node/honours.mjs';
import {atomicBankAccess} from '../node/atomic-bank-access.mjs';
import {EVENT_SCHEMA} from '../node/jarvis-events.mjs';
import {currentGuildSurcharge,currentGuildDiscount} from '../node/guild-tariff-policy.mjs';
import {createPoliticalClanGrants} from '../node/political-clan-grants.mjs';
import {initializeClans} from '../control-panel/clans.mjs';
import {POLITICAL_AGREEMENT_SCHEMA,POLITICAL_COMPANY_REPLY_SCHEMA,POLITICAL_PERSON_REPLY_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs';
import {initializeClanFaith,createClanFaith} from '../node/clan-faith.mjs';
import {POLITICAL_APPOINTMENT_SCHEMA,activePoliticalAppointments} from '../node/political-appointments.mjs';
import {POLITICAL_CONSULTATION_SCHEMA,createPoliticalConsultations,createPoliticalConsultationAPI} from '../node/political-consultations.mjs';
async function fixture(office='emperor',extra={}){
const f=await companyFixture(),old=f.db.query.bind(f.db);f.db.query=(sql,args=[])=>old(sql.replace(/,\s*KEY \w+\([^)]*\)/g,''),args);f.db.sqlite.function('CONCAT',{varargs:true},(...args)=>args.join(''));
f.db.sqlite.exec('ALTER TABLE political_office_terms ADD COLUMN id TEXT;ALTER TABLE political_office_terms ADD COLUMN kind TEXT;CREATE TABLE political_office_charters(office_key TEXT PRIMARY KEY,charter_kind TEXT,staff_key_id TEXT);CREATE TABLE site_character_choices(minecraft_uuid TEXT PRIMARY KEY,faction TEXT);');
await f.db.query(POLITICAL_DECISION_SCHEMA);await f.db.query(POLITICAL_AGREEMENT_SCHEMA);await f.db.query(POLITICAL_COMPANY_REPLY_SCHEMA);await f.db.query(POLITICAL_PERSON_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await f.db.query(sql);f.db.politicalDecisionsEnabled=true;
f.db.sqlite.exec('CREATE TABLE political_proclamations(id TEXT PRIMARY KEY,request_id TEXT,scope TEXT,title TEXT,body TEXT,author_id TEXT,created_at INT,version INT);');
await initializePOLProgression(f.db);let now=1000;const pol=polProgressionStore(f.db);await pol.query("INSERT INTO jarvis_progression_seasons VALUES('S01',0,9999999999,0,25,'active',1)");await pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,10000,10000,28,1,0)',[f.people.Owner.id]);
const grant=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+office,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:grant.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[office,'royal',keyId])});
const o=PUBLIC_OFFICES.find(o=>o.key===office),term=randomUUID();await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[term,f.people.Owner.id,o.kind,o.faction,o.office]);
const entity={id:entityId('office',office==='emperor'?'emperor':'leader:'+office),kind:'office',key:office==='emperor'?'emperor':'leader:'+office,name:o.name,canView:true,canActivate:true,canPay:true},authority=async()=>({entities:[entity]});
await new PostbankService(f.db,authority).activate(f.people.Owner,{entityId:entity.id,packageKey:'pb_civic',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const source=await f.db.first("SELECT * FROM pb_accounts WHERE type_code='107'");await f.db.query('UPDATE pb_accounts SET balance_minor=2000000 WHERE id=?',[source.id]);await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_tax_treasury','979','Tax',0,'active',1)");
const service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority,clock:()=>now,...extra});
const input=(decisionId='IMP-04')=>({decisionId,requestId:randomUUID(),sourceAccount:String(source.id),confirmed:true,...(POLITICAL_DECISIONS.find(d=>d.id===decisionId)?.kind==='proclamation'?{title:'A public proclamation',body:'A message to the people of the realm.'}:POLITICAL_DECISIONS.find(d=>d.id===decisionId)?.kind==='report'?{}:{recipientId:f.people.Other.id,citation:'Recognised for service to the realm.'})});
return{...f,service,pol,source,term,input,authority,clock:()=>now,setTime:n=>now=n};
}
async function grantFixture(office='atreides'){
const f=await fixture(office);f.db.sqlite.exec('DROP TABLE site_clan_members;DROP TABLE site_clans;');await initializeClans(f.db,{mysql:false});
const clanId=randomUUID(),home={atreides:'kaladam',harkonnen:'giedermark',corrino:'kaiterhof',muad_dib:'kaladam'}[office];await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,'Development Clan','development clan','DEV','Our clan',?,?,1,1)",[clanId,home,f.people.Other.id]);
const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Other.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[f.people.Other.id,link.minecraft_uuid,clanId]);
async function activate(person,kind='person',key=person.id){const entity={id:entityId(kind,key),kind,key,name:'Receiving account',canView:true,canActivate:true,canPay:true,charterKind:kind==='clan'?'original':null};await new PostbankService(f.db,async()=>({entities:[entity]})).activate(person,{entityId:entity.id,packageKey:kind==='clan'?'pb_connect':'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});return f.db.first('SELECT a.* FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=?',[entity.id]);}
const target=await activate(f.people.Other),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,clanGrants:createPoliticalClanGrants(f.db)});
return{...f,service,clanId,target,activate,grant:(decisionId='ATR-01',amountMinor=1000000)=>({decisionId,requestId:randomUUID(),sourceAccount:String(f.source.id),clanId,amountMinor,reason:'Develop the clan’s water and transport infrastructure.',confirmed:true})};
}
async function reviewFixture(office='harkonnen'){const f=await fixture(office);await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000');await f.db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);f.db.sqlite.exec('CREATE TABLE site_profiles(user_id TEXT PRIMARY KEY,bio TEXT);');for(const sql of [...applicationSchema,...roundSchema])await f.db.query(sql.replace(/ ENGINE=InnoDB/g,'').replace(/UNIQUE KEY \w+\s*\(/g,'UNIQUE('));const target=PUBLIC_OFFICES.find(o=>o.key===(office==='corrino'?'atreides':'corrino')),targetTerm=randomUUID();await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[targetTerm,f.people.Other.id,target.kind,target.faction,target.office]);const candidateId=randomUUID();await f.db.query("INSERT INTO political_applications VALUES(?,?,?,?,'house','atreides',?,'A public campaign, not private correspondence.','submitted',1)",[candidateId,'APP-HSE-2026-000001',f.people.Other.id,randomUUID(),Date.parse('2026-12-13T15:00:00Z')]);await f.db.query('INSERT INTO site_profiles VALUES(?,?)',[f.people.Other.id,'Public biography <b>render as plain text</b>']);const reviews=createPoliticalReviews(f.db,f.keys,{clock:f.clock,verifyStorage:async()=>true}),service=createPoliticalDecisions(f.db,f.db,f.keys,{clock:f.clock,authority:f.authority,verifyStorage:async()=>null,politicalReports:reviews});return{...f,reviews,service,candidateId,targetTerm,targetOffice:target.key,review:id=>({decisionId:id,requestId:randomUUID(),sourceAccount:String(f.source.id),confirmed:true,...(POLITICAL_DECISIONS.find(d=>d.id===id).reviewKind==='candidate'?{candidateId}:{targetOffice:target.key})}),publish:reviewId=>({reviewId,requestId:randomUUID(),confirmed:true})};}
test('six political reviews use the real public register projections with fixed prices, expiry and original-holder privacy',async()=>{for(const[office,id]of[['harkonnen','HAR-05'],['corrino','COR-05'],['veiled_concord','BG-02'],['muad_dib','NF-02'],['veiled_concord','BG-06'],['muad_dib','NF-06']]){const f=await reviewFixture(office);try{const d=POLITICAL_DECISIONS.find(d=>d.id===id),input=f.review(id),options=await f.service.read(f.people.Owner,id);assert(options.canExecute,id);assert(options.reviewTargets.some(t=>t.id===(d.reviewKind==='candidate'?f.candidateId:f.targetOffice)));const result=await f.service.execute(f.people.Owner,input);assert.equal(result.feeMinor,String(d.feeMinor));assert.equal(result.xp,d.xp);assert.equal(result.report.schema,'pol-public-review-v1');assert.equal(result.report.target.kind,d.reviewKind);assert.equal(result.expiresAt,1000+d.durationMs);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,result.keyId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);let saved=(await f.service.read(f.people.Owner,id)).report;assert.equal(saved.canPublish,!!d.canExpose);if(d.reviewKind==='office')assert.equal(saved.target.holder.username,f.people.Other.username);else{assert.equal(saved.target.name,f.people.Other.username+' Character');assert.match(saved.target.bio,/Public biography/);assert.equal(saved.target.publicId,'APP-HSE-2026-000001');}f.setTime(result.expiresAt);assert.equal((await f.service.read(f.people.Owner,id)).report,null);}finally{f.db.close();}}});
test('an office review is an immutable factual snapshot and no successor inherits its private compilation',async()=>{const f=await reviewFixture();try{const input=f.review('HAR-05');await f.service.execute(f.people.Owner,input);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Member.id,f.targetTerm]);assert.equal((await f.service.read(f.people.Owner,'HAR-05')).report.target.holder.username,f.people.Other.username);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Other.id,f.term]);assert.equal((await f.service.read(f.people.Other,'HAR-05')).report,null);assert.equal((await f.service.read(f.people.Owner,'HAR-05')).report,null);}finally{f.db.close();}});
test('factual exposure publishes once in the existing proclamation archive with no extra fee, reward or user-supplied accusation',async()=>{const f=await reviewFixture('veiled_concord');try{const input=f.review('BG-06'),r=await f.service.execute(f.people.Owner,input),startXP=(await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp;assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,0);const publish=f.publish(input.requestId),result=await f.reviews.publish(f.people.Owner,publish);assert.equal((await f.reviews.publish(f.people.Owner,publish)).reference,result.reference);const row=await f.db.first('SELECT * FROM political_proclamations');assert.equal(row.scope,'house:veiled_concord');assert.match(row.body,/makes no allegation of misconduct/);assert.match(row.body,/Public Government Register/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,startXP);assert.equal((await f.service.read(f.people.Owner,'BG-06')).report.canPublish,false);await assert.rejects(f.reviews.publish(f.people.Owner,f.publish(input.requestId)),/already has a publication/);await assert.rejects(f.reviews.publish(f.people.Owner,{...publish,body:'An invented accusation'}),/Review and confirm/);assert.equal(r.report.target.state,'occupied');}finally{f.db.close();}});
test('publication is original-holder and unexpired-proof only, and its archive/key failure rolls back together',async()=>{for(const change of['expiry','source-key','source-term','journal']){const f=await reviewFixture('muad_dib');try{const input=f.review('NF-06'),r=await f.service.execute(f.people.Owner,input);await assert.rejects(f.reviews.publish(f.people.Member,f.publish(input.requestId)),/cannot be published/);if(change==='expiry')f.setTime(r.expiresAt);if(change==='source-key')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[r.keyId]);if(change==='source-term')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.term]);if(change==='journal')f.db.sqlite.exec("CREATE TRIGGER fail_review_publication BEFORE INSERT ON jarvis_political_review_publications BEGIN SELECT RAISE(ABORT,'publication journal failed');END");const keys=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;await assert.rejects(f.reviews.publish(f.people.Owner,f.publish(input.requestId)),change==='journal'?/publication journal failed/:/expired/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,keys);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}}});
test('candidate reviews exclude closed records, truncate long public text explicitly and never consume election votes',async()=>{const f=await reviewFixture('veiled_concord');try{await f.db.query('UPDATE site_profiles SET bio=?',['x'.repeat(8000)]);const input=f.review('BG-02'),r=await f.service.execute(f.people.Owner,input);assert.equal(r.report.target.bio.length,2000);assert.equal(r.report.target.textTruncated,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_round_candidates')).n,0);await assert.rejects(f.reviews.publish(f.people.Owner,f.publish(input.requestId)),/cannot be published/);await f.db.query("UPDATE political_applications SET status='withdrawn'");f.setTime(1000+48*3600000);await assert.rejects(f.service.execute(f.people.Owner,f.review('BG-02')),/current public candidate/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}});
test('paid review failure rolls back fee and Reputation, while the publication API keeps origin and payload checks',async()=>{const f=await reviewFixture('veiled_concord');try{const input=f.review('BG-06'),keys=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_review BEFORE INSERT ON jarvis_political_decisions BEGIN SELECT RAISE(ABORT,'review journal failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/review journal failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,50000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,keys);const api=createPoliticalReviewAPI(f.db,f.reviews,{authenticate:async()=>f.people.Owner}),post=(body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/reviews/publish',{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(body)}));assert.equal((await post(f.publish(input.requestId),'https://example.invalid')).status,403);assert.equal((await post({...f.publish(input.requestId),actorId:f.people.Member.id})).status,400);}finally{f.db.close();}});
test('catalogue prices, Reputation requirements and XP agree with connected policy',()=>{for(const d of POLITICAL_DECISIONS){const row=DECISION_CATALOGUE.find(r=>r.id===d.id);assert.equal(row.level,d.level);assert.equal(row.xp,d.xp);const [dm,hours]=row.cost.replaceAll(',','').split(' / ');if(['guild-subsidy','exchange-incentive'].includes(d.kind)){assert.equal(dm,'Pool amount');assert.equal(d.poolMaxMinor,2000000);}else if(d.kind==='clan-grant'){assert(d.grantMinMinor>=10000&&d.grantMaxMinor>=d.grantMinMinor);assert.equal(dm,(d.grantMinMinor===d.grantMaxMinor?String(d.grantMaxMinor/100):'Grant amount')+(d.feeMinor?' + '+d.feeMinor/100+' admin':''));}else assert.equal(Number(dm)*100,d.feeMinor);assert.equal(Number(hours.replace('h',''))*3600000,d.cooldownMs);}});
test('House development grants fund the legal Basic owner through the existing balanced bank transfer once',async()=>{
const f=await grantFixture();try{
const view=await f.service.read(f.people.Owner,'ATR-01');assert.deepEqual(view.clans,[{id:f.clanId,name:'Development Clan'}]);const input=f.grant(),r=await f.service.execute(f.people.Owner,input);assert.equal(r.grant.basicFallback,true);assert.equal(r.grant.recipientKind,'person');assert.equal(r.feeMinor,'1000000');assert.equal(r.xp,200);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,r.keyId);
assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,1000000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,1000000);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_tax_treasury'")).balance_minor,0);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10200);
}finally{f.db.close();}
});
test('native world, legal owner changes, grant bounds and current office funding are rechecked at execution',async()=>{
const f=await grantFixture();try{
await f.service.read(f.people.Owner,'ATR-01');await f.db.query("UPDATE site_clans SET home_world='kaiterhof' WHERE id=?",[f.clanId]);await assert.rejects(f.service.execute(f.people.Owner,f.grant()),/eligible clan/);await f.db.query("UPDATE site_clans SET home_world='kaladam',owner_id=? WHERE id=?",[f.people.Member.id,f.clanId]);const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Member.id]);await f.db.query('UPDATE site_clan_members SET user_id=?,minecraft_uuid=? WHERE clan_id=?',[f.people.Member.id,link.minecraft_uuid,f.clanId]);const newOwner=await f.activate(f.people.Member);
await assert.rejects(f.service.execute(f.people.Owner,f.grant('ATR-01',999999)),/published budget/);await assert.rejects(f.service.execute(f.people.Owner,{...f.grant(),sourceAccount:String(f.target.id)}),/authorised office/);const r=await f.service.execute(f.people.Owner,f.grant());assert.equal(r.grant.basicFallback,true);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[newOwner.id])).balance_minor,1000000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);
}finally{f.db.close();}
});
test('an original clan receives its development allocation in its own account instead of its owner account',async()=>{
const f=await grantFixture();try{
const grant=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:grant.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 target=await f.activate(f.people.Other,'clan',f.clanId),r=await f.service.execute(f.people.Owner,f.grant());assert.equal(r.grant.basicFallback,false);assert.equal(r.grant.recipientKind,'clan');assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[target.id])).balance_minor,1000000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);
}finally{f.db.close();}
});
test('a mother clan controller cannot replace the Basic child’s legal owner as grant recipient',async()=>{
const f=await grantFixture();try{
const parent=randomUUID();await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,'Mother Clan','mother clan','MOTHER','Parent','kaladam',?,1,1)",[parent,f.people.Owner.id]);const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Owner.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[f.people.Owner.id,link.minecraft_uuid,parent]);await f.db.query('INSERT INTO site_clan_deeds(clan_id,parent_clan_id,updated_at) VALUES(?,?,1)',[f.clanId,parent]);
await f.service.execute(f.people.Owner,f.grant());assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,1000000);assert.equal((await f.db.first('SELECT owner_id FROM site_clans WHERE id=?',[f.clanId])).owner_id,f.people.Other.id);
}finally{f.db.close();}
});
test('Harkonnen and Corrino grants use their own native worlds and unavailable recipient accounts cost nothing',async()=>{
for(const [office,id]of [['harkonnen','HAR-02'],['corrino','COR-02']]){const f=await grantFixture(office);try{
const input=f.grant(id,1500000);await f.db.query("UPDATE pb_accounts SET state='closed' WHERE client_number=?",[f.target.client_number]);await assert.rejects(f.service.execute(f.people.Owner,input),/no active payment/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);await f.db.query("UPDATE pb_accounts SET state='active' WHERE id=?",[f.target.id]);const r=await f.service.execute(f.people.Owner,input);assert.equal(r.xp,250);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,1500000);
}finally{f.db.close();}}
});
test('variable grants scale Reputation to real funding and a receipt failure rolls back both balances and the reward',async()=>{
const f=await grantFixture();try{
const input=f.grant('ATR-04',250000),keys=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_clan_grant BEFORE INSERT ON jarvis_political_decisions BEGIN SELECT RAISE(ABORT,'grant receipt failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/grant receipt failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,keys);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);f.db.sqlite.exec('DROP TRIGGER fail_clan_grant');const r=await f.service.execute(f.people.Owner,input);assert.equal(r.xp,40);assert.equal(r.feeMinor,'250000');assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10040);
}finally{f.db.close();}
});
test('Guild mediation reuses the political calendar with a bounded 72-hour session and no unilateral peace',async()=>{
const f=await fixture('spacing_guild');try{
await f.pol.query('UPDATE jarvis_progression_accounts SET total_xp=100000,effective_xp=100000');for(const sql of EVENT_SCHEMA)await f.db.query(sql);
const input={decisionId:'SG-06',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Trade mediation',description:'Voluntary mediation between the two named Houses.',startsAt:100000,endsAt:100000+72*3600000,confirmed:true};
await assert.rejects(f.service.execute(f.people.Owner,{...input,endsAt:input.endsAt+1}),/at most 72/);const result=await f.service.execute(f.people.Owner,input),event=await f.db.first('SELECT * FROM jarvis_events WHERE id=?',[result.eventId]);assert.equal(event.scope_id,'spacing_guild');assert.equal(event.ends_at-event.starts_at,72*3600000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,1500000);assert.equal((await f.service.execute(f.people.Owner,input)).eventId,result.eventId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_events')).n,1);
}finally{f.db.close();}
});
test('preferred Guild House fares are fixed, non-stacking and replaced rather than revived across grants',async()=>{
const f=await fixture('spacing_guild');try{
const input=id=>({decisionId:id,requestId:randomUUID(),sourceAccount:String(f.source.id),confirmed:true,house:'atreides'});await assert.rejects(f.service.execute(f.people.Owner,{...input('SG-02'),house:'company'}),/native House/);await assert.rejects(f.service.execute(f.people.Owner,{...input('SG-02'),percent:100}),/Review/);
await f.service.execute(f.people.Owner,input('SG-02'));await f.service.execute(f.people.Owner,input('SG-07'));assert.equal(await currentGuildDiscount(f.db,'atreides',1000),25);assert.equal(await currentGuildDiscount(f.db,'corrino',1000),0);
f.setTime(1000+48*3600000);const next=await f.service.execute(f.people.Owner,{...input('SG-02'),house:'corrino'});assert.equal(await currentGuildDiscount(f.db,'atreides',1000+48*3600000),10);assert.equal(await currentGuildDiscount(f.db,'corrino',1000+48*3600000),25);
await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[next.keyId]);assert.equal(await currentGuildDiscount(f.db,'corrino',1000+48*3600000),0);assert.equal(await currentGuildDiscount(f.db,'atreides',1000+48*3600000),10);
await f.db.query("UPDATE political_office_terms SET outcome='resigned' WHERE id=?",[f.term]);assert.equal(await currentGuildDiscount(f.db,'atreides',1000+48*3600000),0);
}finally{f.db.close();}
});
test('Guild surcharge requires its live signed mandate and never revives an old tariff after repeal or revocation',async()=>{
const f=await fixture('spacing_guild');try{
await f.pol.query('UPDATE jarvis_progression_accounts SET total_xp=100000,effective_xp=100000');const input={decisionId:'SG-05',requestId:randomUUID(),sourceAccount:String(f.source.id),confirmed:true,percent:5};
await assert.rejects(f.service.execute(f.people.Owner,{...input,percent:6}),/0 to 5/);await assert.rejects(f.service.execute(f.people.Owner,{...input,world:'arrakis'}),/Review/);
const receipt=await f.service.execute(f.people.Owner,input);assert.equal(await currentGuildSurcharge(f.db,1000),5);assert.equal(await currentGuildSurcharge(f.db,receipt.expiresAt),0);
await f.db.query("UPDATE political_office_terms SET outcome='resigned' WHERE id=?",[f.term]);assert.equal(await currentGuildSurcharge(f.db,1000),0);await f.db.query("UPDATE political_office_terms SET outcome='winner' WHERE id=?",[f.term]);
f.setTime(1000+7*86400000);const repeal=await f.service.execute(f.people.Owner,{...input,requestId:randomUUID(),percent:0});assert.equal(await currentGuildSurcharge(f.db,1000+7*86400000),0);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[repeal.keyId]);assert.equal(await currentGuildSurcharge(f.db,1000+7*86400000),0);
}finally{f.db.close();}
});
test('Church diplomatic favour lasts seven days, uses only Church funding and grants no office or self-award',async()=>{
const f=await fixture('muad_dib');try{
const input=f.input('NF-07');await assert.rejects(f.service.execute(f.people.Owner,{...input,recipientId:f.people.Owner.id}),/another active/);const receipt=await f.service.execute(f.people.Owner,input);assert.equal(receipt.expiresAt,1000+7*86400000);assert.equal(receipt.cooldownUntil,1000+72*3600000);assert.equal(receipt.feeMinor,'250000');
const honours=await politicalHonours(f.db,f.people.Other.id,1000);assert.equal(honours.length,1);assert.equal(honours[0].title,'Church’s Favour');assert.match(honours[0].seal,/new-faith/);assert.equal((await politicalHonours(f.db,f.people.Other.id,receipt.expiresAt)).length,0);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);assert.equal((await politicalHonours(f.db,f.people.Other.id,1000)).length,0);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,1);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10250);
}finally{f.db.close();}
});
test('a funded court audience uses the existing political calendar atomically and cannot replay or outlive its mandate',async()=>{
const f=await fixture('corrino');try{
for(const sql of EVENT_SCHEMA)await f.db.query(sql);const input={decisionId:'COR-01',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Court audience',description:'Diplomatic audience for our House envoys.',startsAt:100000,endsAt:200000,confirmed:true};
const receipt=await f.service.execute(f.people.Owner,input);assert.ok(receipt.eventId);const row=await f.db.first('SELECT * FROM jarvis_events WHERE id=?',[receipt.eventId]);assert.equal(row.scope_kind,'politics');assert.equal(row.scope_id,'corrino');assert.equal(row.request_id,input.requestId);assert.equal(row.starts_at,100000);assert.equal(row.state,'scheduled');
assert.equal((await f.service.execute(f.people.Owner,input)).eventId,receipt.eventId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_events')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries WHERE order_id=?',[input.requestId])).n,2);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10200);
await assert.rejects(f.service.execute(f.people.Owner,{...input,endsAt:300000}),/reference/);
f.setTime(1000+86400000);const later={...input,requestId:randomUUID(),startsAt:1000+86400000+60000,endsAt:1000+86400000+3600000};await f.db.query('UPDATE political_office_terms SET expires_at=? WHERE id=?',[later.startsAt+1,f.term]);await assert.rejects(f.service.execute(f.people.Owner,later),/mandate ends/);
}finally{f.db.close();}
});
test('failed calendar history and invalid audience dates cannot take fees or grant Reputation',async()=>{
const f=await fixture('corrino');try{
for(const sql of EVENT_SCHEMA)await f.db.query(sql);const input={decisionId:'COR-01',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Court audience',description:'An official audience with House envoys.',startsAt:100000,endsAt:200000,confirmed:true};
await assert.rejects(f.service.execute(f.people.Owner,{...input,startsAt:1}),/one minute/);await assert.rejects(f.service.execute(f.people.Owner,{...input,endsAt:100000+86400001}),/at most/);
const keys=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_audience_history BEFORE INSERT ON jarvis_event_history BEGIN SELECT RAISE(ABORT,'calendar history failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/calendar history failed/);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_events')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,keys);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10000);
}finally{f.db.close();}
});
test('the original calendar writer receives only verified bank event tables, leaving central decision tables in place',async()=>{
const seen=[],raw={query:async sql=>{seen.push(sql);return[];},first:async sql=>{seen.push(sql);return null;}},adapter=atomicBankAccess({},{},{verifyStorage:async()=>'bankdata',bankTables:['jarvis_events','jarvis_event_history']});await adapter.ready();
await adapter.view(raw).query('SELECT id FROM jarvis_events');await adapter.view(raw).query('SELECT id FROM jarvis_event_history');await adapter.view(raw).query('SELECT id FROM jarvis_political_decisions');
assert.deepEqual(seen,['SELECT id FROM `bankdata`.`jarvis_events`','SELECT id FROM `bankdata`.`jarvis_event_history`','SELECT id FROM jarvis_political_decisions']);assert.throws(()=>atomicBankAccess({},null,{bankTables:['arbitrary.name']}),/Fixed bank table/);
});
test('market reports use the paid decision transaction and safe retries return the original snapshot',async()=>{
let reads=0;const snapshot={schema:'pol-market-report-v1',observedAt:1000,listedStacks:2,units:'64',askingValueMinor:'10000',byWorld:[]};
const f=await fixture('ordos',{marketReports:{ready:async()=>true,report:async()=>{reads++;return snapshot;}}});try{
const input=f.input('ORD-03'),receipt=await f.service.execute(f.people.Owner,input);assert.deepEqual(receipt.report,snapshot);assert.equal((await f.service.execute(f.people.Owner,input)).replayed,true);assert.equal(reads,1);
assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,1750000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10400);
const view=await f.service.read(f.people.Owner,'ORD-03');assert.deepEqual(view.report,snapshot);assert.equal(view.canExecute,false);assert.equal((await f.service.read(f.people.Other,'ORD-03')).report,null);
await assert.rejects(f.service.execute(f.people.Owner,{...input,report:{invented:true}}),/Review/);
}finally{f.db.close();}
});
test('native reports keep the original transaction without rewriting qualified tables or metadata literals',async()=>{
const f=await fixture('ordos',{verifyStorage:async()=>'main',marketReports:{ready:async()=>true,report:async tx=>{
const row=(await tx.query("SELECT 'pb_guild_passages' marker"))[0];assert.equal(row.marker,'pb_guild_passages');
await tx.query('SELECT id FROM `main`.`pb_accounts` LIMIT 1');return{schema:'pol-market-report-v1',observedAt:1000,byWorld:[]};
}}});try{const result=await f.service.execute(f.people.Owner,f.input('ORD-03'));assert.equal(result.ok,true);assert.equal(result.report.schema,'pol-market-report-v1');}finally{f.db.close();}
});
test('a failed report source or receipt journal leaves fees, Reputation and keys unchanged',async()=>{
let unavailable=true;const f=await fixture('spacing_guild',{marketReports:{ready:async()=>{if(unavailable)throw Error('Unavailable');},report:async()=>{if(unavailable)throw Object.assign(Error('Unavailable'),{status:503});return{schema:'pol-market-report-v1',observedAt:1000,byWorld:[]};}}});try{
await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=100000,total_xp=100000');assert.equal((await f.service.read(f.people.Owner,'SG-04')).canExecute,false);const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;
await assert.rejects(f.service.execute(f.people.Owner,f.input('SG-04')),/Unavailable/);unavailable=false;
f.db.sqlite.exec("CREATE TRIGGER reject_report BEFORE INSERT ON jarvis_political_decisions BEGIN SELECT RAISE(ABORT,'receipt failed');END");await assert.rejects(f.service.execute(f.people.Owner,f.input('SG-04')),/receipt failed/);
assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,100000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);
}finally{f.db.close();}
});
test('proclamation payment, publication, XP and key roll back together; concurrent identical retries post once',async()=>{const f=await fixture();try{
const input=f.input();f.db.sqlite.exec("CREATE TRIGGER fail_decision BEFORE INSERT ON jarvis_political_decisions BEGIN SELECT RAISE(ABORT,'journal unavailable');END;");await assert.rejects(f.service.execute(f.people.Owner,input),/journal unavailable/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,0);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10000);f.db.sqlite.exec('DROP TRIGGER fail_decision');
const [one,two]=await Promise.all([f.service.execute(f.people.Owner,input),f.service.execute(f.people.Owner,input)]);assert.equal(one.keyId,two.keyId);assert.equal(two.replayed,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries WHERE order_id=?',[input.requestId])).n,2);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10100);
await assert.rejects(f.service.execute(f.people.Owner,{...input,title:'Changed request'}),/reference/);assert.equal((await f.service.read(f.people.Owner,'IMP-04')).canExecute,false);
await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Ceo.id,f.term]);await assert.rejects(f.service.execute(f.people.Ceo,f.input()),/cooldown/);
f.setTime(1000+6*3600000);await f.pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,10000,10000,28,1,0)',[f.people.Ceo.id]);await f.service.execute(f.people.Ceo,f.input());
}finally{f.db.close();}});
test('staff role cannot replace office authority; Reputation, funding, charter and active season are checked',async()=>{const f=await fixture();try{
await assert.rejects(f.service.execute({...f.people.Other,role:'owner'},f.input()),/office holder/);
await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=0,total_xp=0');await assert.rejects(f.service.execute(f.people.Owner,f.input()),/Reputation/);await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=10000,total_xp=10000');
await assert.rejects(f.service.execute(f.people.Owner,{...f.input(),sourceAccount:'99999'}),/authorised/);await f.db.query('UPDATE pb_accounts SET balance_minor=0 WHERE id=?',[f.source.id]);await assert.rejects(f.service.execute(f.people.Owner,f.input()),/funds/);await f.db.query('UPDATE pb_accounts SET balance_minor=2000000 WHERE id=?',[f.source.id]);
await f.pol.query("UPDATE jarvis_progression_seasons SET state='closed'");await assert.rejects(f.service.execute(f.people.Owner,f.input()),/active season/);await f.pol.query("UPDATE jarvis_progression_seasons SET state='active'");
await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=(SELECT staff_key_id FROM political_office_charters)');await assert.rejects(f.service.execute(f.people.Owner,f.input()),/office holder/);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
}finally{f.db.close();}});
test('House honours require a different current House player, expire exactly at 30 days and respect key revocation',async()=>{const f=await fixture('atreides');try{
const input=f.input('ATR-03');await assert.rejects(f.service.execute(f.people.Owner,input),/active player/);const uuid=(await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Other.id])).minecraft_uuid;await f.db.query("INSERT INTO site_character_choices VALUES(?,'atreides')",[uuid]);
await assert.rejects(f.service.execute(f.people.Owner,{...input,requestId:randomUUID(),recipientId:f.people.Owner.id}),/active player/);
const receipt=await f.service.execute(f.people.Owner,input);assert.equal((await politicalHonours(f.db,f.people.Other.id,1000)).length,1);assert.equal((await politicalHonours(f.db,f.people.Other.id,receipt.expiresAt-1)).length,1);assert.equal((await politicalHonours(f.db,f.people.Other.id,receipt.expiresAt)).length,0);
await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);assert.equal((await politicalHonours(f.db,f.people.Other.id,1000)).length,0);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_political_decisions')).n,1);
}finally{f.db.close();}});
test('API rejects cross-origin writes, user overrides, unknown fields and unconfirmed requests',async()=>{const f=await fixture();try{
const api=createPoliticalDecisionAPI(f.db,f.service,{authenticate:async()=>f.people.Owner,access:async()=>({nodes:['web.menu.game']})}),req=(body,origin='https://cp.dunerealms.com')=>new Request('https://cp.dunerealms.com/api/politics/decisions',{method:'POST',headers:{origin,'content-type':'application/json'},body:JSON.stringify(body)});
assert.equal((await api(req(f.input(),'https://evil.invalid'))).status,403);assert.equal((await api(req({...f.input(),actorId:f.people.Owner.id}))).status,400);assert.equal((await api(req({...f.input(),confirmed:false}))).status,400);assert.equal((await api(new Request('https://cp.dunerealms.com/api/politics/decisions?decisionId=IMP-04&actorId=x'))).status,400);
for(const field of ['feeMinor','xp','office','expiresAt'])assert.throws(()=>decisionInput({...f.input(),[field]:0}));assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_political_decisions')).n,0);
}finally{f.db.close();}});
test('legacy Imperial publisher delegates to paid decision and cannot bypass its cooldown',async()=>{const f=await fixture();try{
const route=createProclamations(f.db,{}, {politicalDecisions:f.service,authenticate:async()=>f.people.Owner,access:async()=>({nodes:['web.menu.game']})}),request=input=>new Request('https://cp.dunerealms.com/api/politics/proclamations?kind=imperial',{method:'POST',headers:{origin:'https://cp.dunerealms.com','content-type':'application/json'},body:JSON.stringify(input)});
assert.equal((await route(request(f.input()))).status,201);assert.equal((await route(request(f.input()))).status,409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
}finally{f.db.close();}});
test('House, Guild and faith proclamations retain their own archives, fixed fees and successor-safe cooldowns',async()=>{
for(const d of POLITICAL_DECISIONS.filter(d=>d.kind==='proclamation'&&d.office!=='emperor')){const f=await fixture(d.office);try{
const input=f.input(d.id);await f.service.execute(f.people.Owner,input);const post=await f.db.first('SELECT scope FROM political_proclamations');assert.equal(post.scope,d.scope);assert.equal((await f.db.first('SELECT amount_minor FROM pb_orders')).amount_minor,50000);await assert.rejects(f.service.execute(f.people.Owner,f.input(d.id)),/cooldown/);
}finally{f.db.close();}}
});
test('legacy House and Guild publishers cannot bypass fees, office scope or cooldown, and never fall back to a free write',async()=>{
for(const [office,id,kind]of [['atreides','ATR-PROCLAIM','house'],['spacing_guild','SG-PROCLAIM','guild']]){const f=await fixture(office);try{
const deps={politicalDecisions:f.service,authenticate:async()=>f.people.Owner,access:async()=>({nodes:['web.menu.game'],ranks:[]}),preview:async()=>Response.json({faction:office,factionStatus:'verified',houseLeader:true})},route=createProclamations(f.db,{},deps),request=body=>new Request('https://cp.dunerealms.com/api/politics/proclamations?kind='+kind,{method:'POST',headers:{origin:'https://cp.dunerealms.com','content-type':'application/json'},body:JSON.stringify(body)});
assert.equal((await route(request({...f.input(id),decisionId:'IMP-04'}))).status,400);assert.equal((await route(request(f.input(id)))).status,201);assert.equal((await route(request(f.input(id)))).status,409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
const offline=createProclamations(f.db,{}, {...deps,politicalDecisions:null});assert.equal((await offline(request(f.input(id)))).status,503);const archived=await offline(new Request('https://cp.dunerealms.com/api/politics/proclamations?kind='+kind));assert.equal(archived.status,200);const data=await archived.json();assert.equal(data.total,1);assert.equal(data.canPublish,false);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,1);
}finally{f.db.close();}}
});
test('Imperial and Corrino recognitions use fixed fees, existing profile markup and no self-award',async()=>{for(const [office,id]of [['emperor','IMP-09'],['corrino','COR-03']]){const f=await fixture(office);try{
if(office==='corrino')await f.db.query("INSERT INTO site_character_choices SELECT minecraft_uuid,'corrino' FROM site_game_links WHERE user_id=?",[f.people.Other.id]);
const receipt=await f.service.execute(f.people.Owner,f.input(id));assert.equal(receipt.feeMinor,office==='emperor'?'500000':'250000');const honours=await politicalHonours(f.db,f.people.Other.id,1000);assert.equal(honours.length,1);assert.match(honours[0].seal,/\/seals\/.+\.png$/);const html=honourMarkup([{...honours[0],citation:'<script>bad</script>'}]);assert.match(html,/CEREMONIAL HONOUR/);assert.match(html,/&lt;script&gt;/);assert.doesNotMatch(html,/<script>/);
}finally{f.db.close();}}});
test('separate MySQL hosts fail before any mutation or qualified-table access',async()=>{
let writes=0;const db={first:async()=>({db:'central',host:'central-host',port:3306,server_id:1}),query:async()=>{writes++;return[];}},bank={first:async()=>({db:'bank',host:'another-host',port:3306,server_id:2})};await assert.rejects(atomicBankAccess(db,bank).ready(),/One transactional bank server/);assert.equal(writes,0);
});
test('production central adapter needs only query, prepare and transaction, without a first convenience method',async()=>{const f=await fixture();try{
const central={...f.db,first:undefined,transaction:f.db.transaction.bind(f.db)},service=createPoliticalDecisions(central,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:()=>1000});assert.equal((await service.read(f.people.Owner,'IMP-04')).canManage,true);assert.equal((await service.execute(f.people.Owner,f.input())).ok,true);
}finally{f.db.close();}});
test('debit authority snapshots retain the existing transaction connection rather than opening a second pool connection',async()=>{
const tx={query:async()=>[{id:'locked'}],first:async()=>({id:'locked'})},base={readSnapshot:async()=>{throw Error('A second connection would observe stale authority');}};
const reader=politicalDecisionReader(tx,base);assert.equal(await reader.readSnapshot(async r=>(await r.prepare('SELECT id FROM political_office_terms').first()).id),'locked');
});
async function diplomacyFixture(office='atreides'){
const f=await fixture(office),targetOffice=office==='corrino'?'atreides':'corrino',target=PUBLIC_OFFICES.find(o=>o.key===targetOffice),targetTerm=randomUUID();await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000');
const grant=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+targetOffice,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:grant.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[targetOffice,'royal',keyId])});
await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[targetTerm,f.people.Other.id,target.kind,target.faction,target.office]);
const agreements=createPoliticalAgreements(f.db,f.keys,{clock:f.clock}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,agreements});
return{...f,agreements,service,targetOffice,targetTerm,proposal:(decisionId='ATR-05')=>({decisionId,requestId:randomUUID(),sourceAccount:String(f.source.id),targetOffice,title:'A diplomatic understanding',terms:'Both offices agree to maintain an open channel for peaceful diplomacy.',confirmed:true}),reply:(proposalId,choice='accept')=>({proposalId,choice,requestId:randomUUID(),confirmed:true})};
}
async function organisationPassageFixture(){const f=await fixture();f.db.sqlite.exec('ALTER TABLE site_clan_members ADD COLUMN minecraft_uuid TEXT;');const companyId=await f.create(),clanId=randomUUID();await f.db.query("INSERT INTO site_clans VALUES(?,'Passage clan',?,1)",[clanId,f.people.Owner.id]);const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Other.id]);await f.db.query("INSERT INTO site_clan_members VALUES(?,?,'member',?)",[clanId,f.people.Other.id,link.minecraft_uuid]);await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,1)',[companyId,f.people.Other.id]);return{...f,companyId,clanId,permit:(targetKind='company',targetId=companyId)=>({decisionId:'IMP-02',requestId:randomUUID(),sourceAccount:String(f.source.id),targetKind,targetId,confirmed:true})};}
test('Imperial organisational travel is paid once, current-member-only and removed by expiry, revocation or succession',async()=>{
for(const kind of ['clan','company'])for(const change of ['leave','expiry','key','emperor']){const f=await organisationPassageFixture();try{const id=kind==='clan'?f.clanId:f.companyId,input=f.permit(kind,id),r=await f.service.execute(f.people.Owner,input);assert.equal(r.feeMinor,'1000000');assert.equal(r.xp,250);assert.equal(r.organisationPassage.expiresAt,1000+72*3600000);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,r.keyId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal(await hasOrganisationPassage(f.db,f.people.Other,1000),true);assert.equal(await hasOrganisationPassage(f.db,f.people.Ceo,1000),false);
if(change==='leave')await f.db.query('DELETE FROM '+(kind==='clan'?'site_clan_members WHERE clan_id':'site_company_members WHERE company_id')+'=? AND user_id=?',[id,f.people.Other.id]);if(change==='key')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[r.keyId]);if(change==='emperor')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.term]);assert.equal(await hasOrganisationPassage(f.db,f.people.Other,change==='expiry'?r.organisationPassage.expiresAt:1000),false);
}finally{f.db.close();}}
});
test('Imperial permits clip to the current term, reject inactive targets and preserve ordinary funding rollback',async()=>{const f=await organisationPassageFixture();try{
await f.db.query("UPDATE corrino_companies SET status='pending' WHERE id=?",[f.companyId]);await assert.rejects(f.service.execute(f.people.Owner,f.permit()),/active organisation/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query("UPDATE corrino_companies SET status='active' WHERE id=?",[f.companyId]);await f.db.query('UPDATE political_office_terms SET expires_at=2000 WHERE id=?',[f.term]);const input=f.permit(),r=await f.service.execute(f.people.Owner,input);assert.equal(r.expiresAt,2000);assert.equal(await hasOrganisationPassage(f.db,f.people.Other,2000),false);await assert.rejects(f.service.execute(f.people.Owner,f.permit()),/cooldown/);
}finally{f.db.close();}});
test('a revoked newest organisation charter cannot revive an older signed charter',async()=>{const f=await organisationPassageFixture();try{await f.service.execute(f.people.Owner,f.permit());f.setTime(1000+86400000);const next=await f.service.execute(f.people.Owner,f.permit());await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[next.keyId]);assert.equal(await hasOrganisationPassage(f.db,f.people.Other,f.clock()),false);}finally{f.db.close();}});
test('three Clan Delegate petitions charge their fixed fee once and retain signed acknowledgement as history',async()=>{
for(const id of ['CLD-01','CLD-03','CLD-05']){const f=await diplomacyFixture('clan_delegate');try{
const d=POLITICAL_DECISIONS.find(d=>d.id===id),input=f.proposal(id),before=await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id]);
const receipt=await f.service.execute(f.people.Owner,input);assert.equal(receipt.agreement.durationMs,0);assert.equal(receipt.feeMinor,String(d.feeMinor));assert.equal(receipt.xp,d.xp);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,receipt.keyId);
assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,before.balance_minor-d.feeMinor);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
await assert.rejects(f.service.execute(f.people.Owner,f.proposal(id)),/cooldown/i);
const response=f.reply(input.requestId),answer=await f.agreements.reply(f.people.Other,response);assert.equal((await f.agreements.reply(f.people.Other,response)).reference,answer.reference);
let item=(await f.agreements.read(f.people.Owner)).agreements[0];assert.equal(item.mode,'petition');assert.equal(item.state,'acknowledged');assert.equal(item.respondedAt,1000);assert.equal(item.endsAt,null);assert.equal(item.canReply,false);
await f.db.query("UPDATE political_office_terms SET outcome='ended'");f.setTime(1000+30*86400000);item=(await f.agreements.read(f.people.Owner)).agreements[0];assert.equal(item.state,'acknowledged');assert.equal((await f.agreements.read(f.people.Member)).agreements.length,0);
assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,2);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_entity_relations')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
}finally{f.db.close();}}
});
test('petitions reject expired recipients and forged prices, and never treat a revoked answer as acknowledgement',async()=>{
const f=await diplomacyFixture('clan_delegate');try{
await assert.rejects(f.service.execute(f.people.Owner,{...f.proposal('CLD-01'),feeMinor:0}),/Review and confirm/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
const input=f.proposal('CLD-01');await f.service.execute(f.people.Owner,input);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Member.id,f.targetTerm]);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/expired/);await assert.rejects(f.agreements.reply(f.people.Member,f.reply(input.requestId)),/not addressed/);
await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Other.id,f.targetTerm]);const answer=await f.agreements.reply(f.people.Other,f.reply(input.requestId));await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[answer.reference]);const item=(await f.agreements.read(f.people.Owner)).agreements[0];assert.equal(item.state,'response-unavailable');assert.equal(item.canReply,false);
}finally{f.db.close();}
});
test('petition refusal remains a historical signed response, while unanswered petitions expire',async()=>{
const f=await diplomacyFixture('clan_delegate');try{const first=f.proposal('CLD-01'),second=f.proposal('CLD-03');await f.service.execute(f.people.Owner,first);await f.service.execute(f.people.Owner,second);await f.agreements.reply(f.people.Other,f.reply(first.requestId,'decline'));f.setTime(1000+72*3600000);const items=(await f.agreements.read(f.people.Owner)).agreements;assert.equal(items.find(i=>i.id===first.requestId).state,'declined');assert.equal(items.find(i=>i.id===second.requestId).state,'expired');await assert.rejects(f.agreements.reply(f.people.Other,f.reply(second.requestId)),/expired/);}finally{f.db.close();}
});
test('six diplomatic decisions deliver confidential proposals and require the original receiving mandate to consent',async()=>{
for(const [office,id]of [['atreides','ATR-05'],['corrino','COR-06'],['ordos','ORD-05'],['veiled_concord','BG-05'],['muad_dib','NF-05'],['spacing_guild','SG-01']]){const f=await diplomacyFixture(office);try{
const before=BigInt((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor),d=POLITICAL_DECISIONS.find(d=>d.id===id),input=f.proposal(id);assert((await f.service.read(f.people.Owner,id)).diplomacyTargets.some(o=>o.id===f.targetOffice));
const receipt=await f.service.execute(f.people.Owner,input);assert.equal(receipt.agreement.targetActorId,f.people.Other.id);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,receipt.keyId);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,Number(before-BigInt(d.feeMinor)));assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
assert.equal((await f.agreements.read(f.people.Member)).agreements.length,0);let view=(await f.agreements.read(f.people.Other)).agreements[0];assert.equal(view.state,'pending');assert.equal(view.canReply,true);const response=f.reply(input.requestId);await assert.rejects(f.agreements.reply(f.people.Member,response),/not addressed/);const replied=await f.agreements.reply(f.people.Other,response);assert.equal((await f.agreements.reply(f.people.Other,response)).reference,replied.reference);view=(await f.agreements.read(f.people.Owner)).agreements[0];assert.equal(view.state,'accepted');assert.equal(view.endsAt,1000+d.durationMs);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,2);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_entity_relations')).n,0);
}finally{f.db.close();}}
});
async function representationFixture(){const f=await diplomacyFixture('corrino');for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await f.db.query(sql);f.db.sqlite.exec('CREATE TABLE IF NOT EXISTS political_office_locks(scope TEXT PRIMARY KEY);');return f;}
test('accepted Corrino representation creates one real observer deed and disappears with either mandate or proof',async()=>{
for(const change of ['source-term','receiving-term','proposal-key','reply-key','source-charter','receiving-charter','expiry']){const f=await representationFixture();try{
const input=f.proposal('COR-07'),r=await f.service.execute(f.people.Owner,input);assert.equal(r.feeMinor,'500000');assert.equal(r.xp,1200);assert.equal((await activePoliticalAppointments(f.db,{clock:f.clock})).length,0);
const answer=f.reply(input.requestId),reply=await f.agreements.reply(f.people.Other,answer);assert.equal((await f.agreements.reply(f.people.Other,answer)).reference,reply.reference);let deeds=await activePoliticalAppointments(f.db,{clock:f.clock});assert.equal(deeds.length,1);assert.equal(deeds[0].user_id,f.people.Owner.id);assert.equal(deeds[0].office_key,f.targetOffice);assert.equal(deeds[0].role_key,'observer');assert.equal(deeds[0].appointment_type,'political-adviser');assert.equal(Number(deeds[0].expires_at),1000+14*86400000);
if(change==='source-term'||change==='receiving-term')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[change==='source-term'?f.term:f.targetTerm]);if(change==='proposal-key'||change==='reply-key')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[change==='proposal-key'?r.keyId:reply.reference]);if(change.endsWith('charter'))await f.db.query("UPDATE organisation_keys SET revoked_at=1 WHERE id=(SELECT staff_key_id FROM political_office_charters WHERE office_key=?)",[change==='source-charter'?'corrino':f.targetOffice]);if(change==='expiry')f.setTime(1000+14*86400000);
assert.equal((await activePoliticalAppointments(f.db,{clock:f.clock})).length,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_appointment_deeds')).n,1);
}finally{f.db.close();}}
});
test('advisory refusal creates no membership and failed appointment journal rolls back the signed response',async()=>{const f=await representationFixture();try{const input=f.proposal('COR-07');await f.service.execute(f.people.Owner,input);const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_adviser BEFORE INSERT ON political_appointment_events BEGIN SELECT RAISE(ABORT,'appointment journal failed');END");await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/appointment journal failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_appointment_deeds')).n,0);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'pending');f.db.sqlite.exec('DROP TRIGGER fail_adviser');await f.agreements.reply(f.people.Other,f.reply(input.requestId,'decline'));assert.equal((await activePoliticalAppointments(f.db,{clock:f.clock})).length,0);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'declined');}finally{f.db.close();}});
test('advisory representation preserves an existing office member role rather than replacing it',async()=>{const f=await representationFixture();try{const input=f.proposal('COR-07');await f.service.execute(f.people.Owner,input);await f.db.query("INSERT INTO political_appointment_deeds(id,office_key,source_term_id,user_id,role_key,title,appointment_type,starts_at,expires_at,issuer_id,request_id) VALUES(?,?,?,?,'custom-role','Existing Councillor','job',0,9999999999,?,?)",[randomUUID(),f.targetOffice,f.targetTerm,f.people.Owner.id,f.people.Other.id,randomUUID()]);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/already has a current appointment/);const deeds=await activePoliticalAppointments(f.db,{clock:f.clock});assert.equal(deeds.length,1);assert.equal(deeds[0].role_key,'custom-role');assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'pending');}finally{f.db.close();}});
test('revoking an advisory appointment removes its membership and marks its accepted proposal as ended',async()=>{const f=await representationFixture();try{const input=f.proposal('COR-07');await f.service.execute(f.people.Owner,input);await f.agreements.reply(f.people.Other,f.reply(input.requestId));assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].state,'accepted');await f.db.query('UPDATE political_appointment_deeds SET revoked_at=1000');assert.equal((await activePoliticalAppointments(f.db,{clock:f.clock})).length,0);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].state,'representation-ended');}finally{f.db.close();}});
test('diplomatic refusal, response deadlines, revoked proposals and changed mandates cannot manufacture acceptance',async()=>{
for(const change of ['decline','deadline','receiver','source','revoked']){const f=await diplomacyFixture();try{
const input=f.proposal(),receipt=await f.service.execute(f.people.Owner,input),response=f.reply(input.requestId,change==='decline'?'decline':'accept');
if(change==='deadline')f.setTime(receipt.agreement.responseUntil);if(change==='receiver')await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Member.id,f.targetTerm]);if(change==='source')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.term]);if(change==='revoked')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);
if(change==='decline'){await f.agreements.reply(f.people.Other,response);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].state,'declined');}else await assert.rejects(f.agreements.reply(f.people.Other,response),/expired/);
}finally{f.db.close();}}
});
test('diplomatic receipt and response failures roll back fees, Reputation, keys and acceptance',async()=>{
const f=await diplomacyFixture();try{
const input=f.proposal(),start=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_diplomacy BEFORE INSERT ON jarvis_political_decisions BEGIN SELECT RAISE(ABORT,'proposal journal failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/proposal journal failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,start);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,50000);f.db.sqlite.exec('DROP TRIGGER fail_diplomacy');await f.service.execute(f.people.Owner,input);
const count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_response BEFORE INSERT ON jarvis_political_agreement_replies BEGIN SELECT RAISE(ABORT,'response journal failed');END");await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/response journal failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'pending');
}finally{f.db.close();}
});
test('diplomacy input rejects office impersonation, self approval and short mandates before charging',async()=>{
const f=await diplomacyFixture();try{
await assert.rejects(f.service.execute(f.people.Owner,{...f.proposal(),targetOffice:'atreides'}),/another registered/);await assert.rejects(f.service.execute(f.people.Owner,{...f.proposal(),actorId:f.people.Other.id}),/Review and confirm/);await f.db.query('UPDATE political_office_terms SET expires_at=? WHERE id=?',[2000,f.targetTerm]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/full proposal response/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
const api=createPoliticalAgreementAPI(f.db,f.agreements,{authenticate:async()=>f.people.Other}),input=f.reply(randomUUID());const post=(body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/agreements',{method:'POST',headers:{origin},body:JSON.stringify(body)}));assert.equal((await post(input,'https://example.invalid')).status,403);assert.equal((await post({...input,userId:f.people.Owner.id})).status,400);
}finally{f.db.close();}
});
test('a revoked diplomatic response never restores acceptance or reopens a decided proposal',async()=>{const f=await diplomacyFixture();try{const input=f.proposal();await f.service.execute(f.people.Owner,input);const response=f.reply(input.requestId),receipt=await f.agreements.reply(f.people.Other,response);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.reference]);const item=(await f.agreements.read(f.people.Other)).agreements[0];assert.equal(item.state,'response-unavailable');assert.equal(item.canReply,false);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId,'decline')),/already has a response/);}finally{f.db.close();}});
test('accepted diplomacy expires at its fixed duration and cannot be accepted by a holder acting on both sides',async()=>{const f=await diplomacyFixture();try{await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Owner.id,f.targetTerm]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/different current/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Other.id,f.targetTerm]);const input=f.proposal();await f.service.execute(f.people.Owner,input);await f.agreements.reply(f.people.Other,f.reply(input.requestId));f.setTime(1000+7*86400000);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].state,'expired');}finally{f.db.close();}});
test('Baron’s Favour reuses House profile honours with seven-day expiry, fixed funding and no self or foreign House award',async()=>{const f=await fixture('harkonnen');try{await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000');const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Other.id]);await f.db.query('INSERT INTO site_character_choices VALUES(?,?)',[link.minecraft_uuid,'harkonnen']);const input=f.input('HAR-07');await assert.rejects(f.service.execute(f.people.Owner,{...input,recipientId:f.people.Owner.id}),/another active/);const r=await f.service.execute(f.people.Owner,input);assert.equal(r.expiresAt,1000+7*86400000);assert.equal(r.xp,1200);assert.equal(r.feeMinor,'500000');assert.equal((await politicalHonours(f.db,f.people.Other.id,r.expiresAt)).length,0);}finally{f.db.close();}});
async function sponsorshipFixture(){const f=await grantFixture('muad_dib');for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await f.db.query(sql);await initializeClanFaith(f.db);const faith=createClanFaith(f.db,f.keys,{clock:f.clock});const offer={decisionId:'NF-CONVERT',clanId:f.clanId,requestId:randomUUID(),confirmed:true};await faith.offer(f.people.Owner,offer);const response={offerId:offer.requestId,clanId:f.clanId,requestId:randomUUID(),choice:'accept',confirmed:true};await faith.reply(f.people.Other,response);return{...f,consent:response.requestId};}
test('Church sponsorship pays the signed consenting clan and a separate Tax admin fee atomically without minting money',async()=>{const f=await sponsorshipFixture();try{const input=f.grant('NF-03',1000000),before=(await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,view=await f.service.read(f.people.Owner,'NF-03');assert.equal(view.clans[0].id,f.clanId);const r=await f.service.execute(f.people.Owner,input);assert.equal(r.feeMinor,'1250000');assert.equal(r.adminFeeMinor,'250000');assert.equal(r.grant.amountMinor,'1000000');assert.equal(r.xp,400);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,r.keyId);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,750000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,1000000);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_tax_treasury'")).balance_minor,250000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,before+2);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);}finally{f.db.close();}});
test('sponsorship rechecks current faith consent and total funding before either transfer',async()=>{for(const failure of ['consent','funds']){const f=await sponsorshipFixture();try{if(failure==='consent')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=(SELECT key_id FROM jarvis_faith_consents WHERE request_id=?)',[f.consent]);else await f.db.query('UPDATE pb_accounts SET balance_minor=1000000 WHERE id=?',[f.source.id]);await assert.rejects(f.service.execute(f.people.Owner,f.grant('NF-03',1000000)),failure==='consent'?/eligible clan/:/Insufficient funds/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}});
test('failed sponsorship administration rolls back the grant, fee, key and Reputation as one decision',async()=>{const f=await sponsorshipFixture();try{const tax=await f.db.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'"),count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec('CREATE TRIGGER fail_sponsorship_fee BEFORE INSERT ON pb_entries WHEN NEW.account_id='+Number(tax.id)+" AND NEW.amount_minor>0 BEGIN SELECT RAISE(ABORT,'administration failed');END");await assert.rejects(f.service.execute(f.people.Owner,f.grant('NF-03',1000000)),/administration failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10000);}finally{f.db.close();}});
async function consultationFixture(){const f=await grantFixture(),clans=[{id:f.clanId,actor:f.people.Other}];for(const person of [f.people.Member,f.people.Owner]){const id=randomUUID(),link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[person.id]);await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,?,?,?,?,'kaladam',?,1,1)",[id,person.username+' clan',person.username.toLowerCase()+' clan',person.username.toUpperCase(),'Native clan',person.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[person.id,link.minecraft_uuid,id]);clans.push({id,actor:person});}const consultations=createPoliticalConsultations(f.db,f.keys,{clock:f.clock}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,consultations});f.db.sqlite.exec('CREATE TABLE personal_vote_sentinel(amount INT);INSERT INTO personal_vote_sentinel VALUES(17)');return{...f,clans,consultations,service,ballot:()=>({decisionId:'ATR-02',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Council water consultation',terms:'Consult native clans about the next water distribution priorities.',confirmed:true}),vote:(ballotId,clan,choice='yes')=>({ballotId,seatKey:'clan:'+clan.id,choice,requestId:randomUUID(),confirmed:true})};}
test('Caladan consultation charges once and gives each native clan one independent institutional vote',async()=>{const f=await consultationFixture();try{const input=f.ballot(),r=await f.service.execute(f.people.Owner,input);assert.equal(r.ballot.seats.length,3);assert.equal(r.ballot.closesAt,1000+48*3600000);assert.equal(r.feeMinor,'200000');assert.equal(r.xp,250);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,r.keyId);const vote=f.vote(input.requestId,f.clans[0]);await assert.rejects(f.consultations.vote(f.people.Member,vote),/independent institutional/);const receipt=await f.consultations.vote(f.people.Other,vote);assert.equal((await f.consultations.vote(f.people.Other,vote)).reference,receipt.reference);await assert.rejects(f.consultations.vote(f.people.Other,f.vote(input.requestId,f.clans[0],'no')),/already voted/);assert.equal((await f.consultations.read(f.people.Ceo)).ballots[0].canVote,false);assert.equal((await f.db.first('SELECT amount FROM personal_vote_sentinel')).amount,17);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}});
test('consultation closes with frozen quorum, strict majority and immutable result; ties and low participation fail',async()=>{for(const [choices,expected]of [[['yes'],'no_quorum'],[['yes','no'],'not_adopted'],[['yes','yes','no'],'yes']]){const f=await consultationFixture();try{const input=f.ballot(),r=await f.service.execute(f.people.Owner,input);for(let i=0;i<choices.length;i++)await f.consultations.vote(f.clans[i].actor,f.vote(input.requestId,f.clans[i],choices[i]));f.setTime(r.ballot.closesAt);await assert.rejects(f.consultations.vote(f.people.Owner,f.vote(input.requestId,f.clans[2])),/no longer open|already voted/);assert.equal((await f.consultations.reconcile()).closed,1);const before=(await f.consultations.read(f.people.Owner)).ballots[0];assert.equal(before.tally.result,expected);assert.equal(before.tally.quorum,2);await f.db.query("UPDATE site_clans SET active=0 WHERE id=?",[f.clans[0].id]);assert.deepEqual((await f.consultations.read(f.people.Owner)).ballots[0].tally,before.tally);assert.equal((await f.consultations.reconcile()).closed,0);}finally{f.db.close();}}});
test('mother control cannot vote for a client clan and revoked votes cannot be replaced or counted',async()=>{const f=await consultationFixture();try{const input=f.ballot();await f.service.execute(f.people.Owner,input);await f.db.query('INSERT INTO site_clan_deeds(clan_id,parent_clan_id,updated_at) VALUES(?,?,1)',[f.clanId,f.clans[2].id]);await assert.rejects(f.consultations.vote(f.people.Owner,f.vote(input.requestId,f.clans[0])),/independent institutional/);const receipt=await f.consultations.vote(f.people.Other,f.vote(input.requestId,f.clans[0]));await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.reference]);const own=(await f.consultations.read(f.people.Other)).ballots[0];assert.equal(own.ownSeats[0].vote,'recorded-invalid');assert.equal(own.canVote,false);assert.equal(own.participation,0);}finally{f.db.close();}});
test('consultation and vote journal failures roll back payments, Reputation and scoped keys',async()=>{const f=await consultationFixture();try{const input=f.ballot(),count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_consultation BEFORE INSERT ON jarvis_political_consultations BEGIN SELECT RAISE(ABORT,'consultation failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/consultation failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);f.db.sqlite.exec('DROP TRIGGER fail_consultation');await f.service.execute(f.people.Owner,input);const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_institutional_vote BEFORE INSERT ON jarvis_political_consultation_votes BEGIN SELECT RAISE(ABORT,'vote journal failed');END");await assert.rejects(f.consultations.vote(f.people.Other,f.vote(input.requestId,f.clans[0])),/vote journal failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_political_consultation_votes')).n,0);}finally{f.db.close();}});
test('Landsraad snapshots occupied Royal Great Houses and current mandates alone can cast each House vote',async()=>{const f=await diplomacyFixture('emperor');try{const consultations=createPoliticalConsultations(f.db,f.keys,{clock:f.clock}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,consultations}),input={decisionId:'IMP-05',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Landsraad deliberation',terms:'Deliberate the priorities of the Great Houses without changing election rights.',confirmed:true};const r=await service.execute(f.people.Owner,input);assert.deepEqual(r.ballot.seats.map(s=>s.id),['corrino']);assert.equal(r.ballot.closesAt,1000+72*3600000);const vote={ballotId:input.requestId,seatKey:'office:corrino',choice:'yes',requestId:randomUUID(),confirmed:true};await assert.rejects(consultations.vote(f.people.Owner,vote),/independent institutional/);await consultations.vote(f.people.Other,vote);f.setTime(r.ballot.closesAt);await consultations.reconcile();assert.equal((await consultations.read(f.people.Owner)).ballots[0].tally.result,'yes');}finally{f.db.close();}});
test('consultation API rejects foreign writes, identity overrides and invalid input without votes',async()=>{const f=await consultationFixture();try{const api=createPoliticalConsultationAPI(f.db,f.consultations,{authenticate:async()=>f.people.Other}),input=f.vote(randomUUID(),f.clans[0]),post=(body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/consultations',{method:'POST',headers:{origin},body:JSON.stringify(body)}));assert.equal((await post(input,'https://example.invalid')).status,403);assert.equal((await post({...input,actorId:f.people.Owner.id})).status,400);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_political_consultation_votes')).n,0);}finally{f.db.close();}});
test('late consultation workers retain a valid deadline result after natural mandate expiry',async()=>{const f=await consultationFixture();try{const input=f.ballot(),deadline=1000+48*3600000;await f.db.query('UPDATE political_office_terms SET expires_at=? WHERE id=?',[deadline+1,f.term]);await f.service.execute(f.people.Owner,input);for(const clan of f.clans.slice(0,2))await f.consultations.vote(clan.actor,f.vote(input.requestId,clan));f.setTime(deadline+120000);await f.consultations.reconcile();assert.equal((await f.consultations.read(f.people.Owner)).ballots[0].tally.result,'yes');}finally{f.db.close();}});
async function companyAgreementFixture(){const f=await fixture('ordos');await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000');f.actor('Other');const companyId=await f.create(),agreements=createPoliticalAgreements(f.db,f.keys,{clock:f.clock}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,agreements});return{...f,companyId,agreements,service,proposal:()=>({decisionId:'ORD-02',requestId:randomUUID(),sourceAccount:String(f.source.id),targetCompanyId:companyId,title:'Confidential consortium',terms:'Discuss a voluntary fourteen-day commercial understanding with the company.',confirmed:true}),reply:proposalId=>({proposalId,choice:'accept',requestId:randomUUID(),confirmed:true})};}
test('Ordos confidential company agreement requires the legal owner and reuses the signed bilateral flow',async()=>{const f=await companyAgreementFixture();try{const view=await f.service.read(f.people.Owner,'ORD-02');assert(view.diplomacyTargets.some(c=>c.id===f.companyId));const input=f.proposal(),r=await f.service.execute(f.people.Owner,input);assert.equal(r.agreement.targetCompanyId,f.companyId);assert.equal(r.agreement.durationMs,14*86400000);assert.equal(r.feeMinor,'500000');await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/not addressed/);const response=f.reply(input.requestId);await f.agreements.reply(f.people.Other,response);assert.equal((await f.agreements.reply(f.people.Other,response)).replayed,true);const item=(await f.agreements.read(f.people.Owner)).agreements[0];assert.equal(item.state,'accepted');assert.equal(item.targetName,'Test Enterprise');assert.equal(item.endsAt,1000+14*86400000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.db.first('SELECT owner_account_id FROM site_company_deeds WHERE company_id=?',[f.companyId])).owner_account_id,f.people.Other.id);}finally{f.db.close();}});
test('company ownership changes cannot transfer confidential pending consent to a successor or a CEO',async()=>{const f=await companyAgreementFixture();try{const input=f.proposal();await f.service.execute(f.people.Owner,input);await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,1)',[f.companyId,f.people.Ceo.id]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Ceo.id,f.companyId]);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/expired/);await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/not addressed/);assert.equal((await f.agreements.read(f.people.Ceo)).agreements.length,0);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].canReply,false);}finally{f.db.close();}});
test('inactive or self-owned companies cannot take an agreement fee; failed company replies roll back their key',async()=>{const f=await companyAgreementFixture();try{await f.db.query("UPDATE corrino_companies SET status='pending' WHERE id=?",[f.companyId]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/active company/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query("UPDATE corrino_companies SET status='active' WHERE id=?",[f.companyId]);await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,1)',[f.companyId,f.people.Owner.id]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Owner.id,f.companyId]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/different current legal owner/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Other.id,f.companyId]);const input=f.proposal();await f.service.execute(f.people.Owner,input);const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_company_response BEFORE INSERT ON jarvis_political_company_replies BEGIN SELECT RAISE(ABORT,'company response failed');END");await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/company response failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,before);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'pending');}finally{f.db.close();}});
async function paidNaibFixture(){const f=await grantFixture();for(const sql of NAIB_COUNCIL_SCHEMA)await f.db.query(sql);await f.db.query("UPDATE site_clans SET home_world='arrakduin' WHERE id=?",[f.clanId]);await f.db.query('UPDATE pb_accounts SET balance_minor=500000 WHERE id=?',[f.target.id]);await f.pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,10000,10000,28,1,0)',[f.people.Other.id]);f.db.naibCouncilPaidEnabled=true;const billing=createNaibCouncilFunding(f.db,f.db,f.keys,{clock:f.clock,verifyStorage:async()=>null,authority:async actor=>({entities:[{id:entityId('person',actor.id),canPay:true},{id:entityId('clan',f.clanId),canPay:actor.id===f.people.Other.id}]})}),council=createNaibCouncil(f.db,{clock:f.clock,billing});return{...f,billing,council,input:()=>({requestId:randomUUID(),kind:'decision',title:'Sietch water assembly',message:'Consult the recognised sietches about our water reserves.',sourceAccount:String(f.target.id),confirmed:true})};}
async function naibPetitionFixture(){const f=await paidNaibFixture(),office=PUBLIC_OFFICES.find(o=>o.key==='emperor'),emperorTerm=randomUUID(),charter=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:emperor',authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:charter.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query("INSERT INTO political_office_charters VALUES('emperor','royal',?)",[keyId])});await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[emperorTerm,f.people.Ceo.id,office.kind,office.faction,office.office]);const petitions=createNaibPetitions(f.db,f.keys,f.billing,{clock:f.clock}),agreements=createPoliticalAgreements(f.db,f.keys,{clock:f.clock,petitions});return{...f,petitions,agreements,emperorTerm,petition:()=>({requestId:randomUUID(),sourceAccount:String(f.target.id),title:'Voice of our sietch',message:'Please hear the water and spice concerns of our independent sietch.',confirmed:true}),reply:(proposalId,choice='accept')=>({proposalId,choice,requestId:randomUUID(),confirmed:true})};}
test('Voice of Arrakis is privately delivered through existing signatures and paid once by the actual independent sietch owner',async()=>{const f=await naibPetitionFixture();try{const view=await f.petitions.context(f.people.Other);assert.equal(view.canExecute,true);assert.equal(view.level,15);assert.equal(view.feeMinor,100000);assert.equal(NAIB_PETITION_POLICY.xp,250);const input=f.petition(),receipt=await f.petitions.propose(f.people.Other,input);assert.equal((await f.petitions.propose(f.people.Other,input)).reference,receipt.reference);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,400000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10250);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_council_dossiers')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.agreements.read(f.people.Owner)).agreements.length,0);let item=(await f.agreements.read(f.people.Ceo)).agreements[0];assert.equal(item.mode,'petition');assert.equal(item.decisionId,'FRE-07');assert.equal(item.canReply,true);await assert.rejects(f.agreements.reply(f.people.Member,f.reply(input.requestId)),/not addressed/);const reply=f.reply(input.requestId),answer=await f.agreements.reply(f.people.Ceo,reply);assert.equal((await f.agreements.reply(f.people.Ceo,reply)).reference,answer.reference);item=(await f.agreements.read(f.people.Other)).agreements[0];assert.equal(item.state,'acknowledged');assert.equal(item.endsAt,null);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.petitions.context(f.people.Other)).canExecute,false);}finally{f.db.close();}});
test('private sietch petitions reject expired or changed original mandates and revoked source proofs',async()=>{for(const change of ['owner','emperor','charter','key','deadline']){const f=await naibPetitionFixture();try{const input=f.petition(),r=await f.petitions.propose(f.people.Other,input);if(change==='owner')await f.db.query('UPDATE site_clans SET owner_id=? WHERE id=?',[f.people.Member.id,f.clanId]);if(change==='emperor')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.emperorTerm]);if(change==='charter')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=(SELECT staff_key_id FROM political_office_charters WHERE office_key=?)',['emperor']);if(change==='key')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[r.reference]);if(change==='deadline')f.setTime(1000+72*3600000);await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/expired/);assert.equal((await f.agreements.read(f.people.Member)).agreements.length,0);}finally{f.db.close();}}});
test('petition storage failures roll back sietch fees, Reputation and ordinary keys; replies never create gameplay powers',async()=>{const f=await naibPetitionFixture();try{const before=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_petition BEFORE INSERT ON jarvis_naib_petitions BEGIN SELECT RAISE(ABORT,'petition journal failed');END");await assert.rejects(f.petitions.propose(f.people.Other,f.petition()),/petition 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);f.db.sqlite.exec('DROP TRIGGER fail_petition');const input=f.petition();await f.petitions.propose(f.people.Other,input);const count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_petition_reply BEFORE INSERT ON jarvis_political_agreement_replies BEGIN SELECT RAISE(ABORT,'petition response failed');END");await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId)),/petition response failed/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'pending');f.db.sqlite.exec('DROP TRIGGER fail_petition_reply');await f.agreements.reply(f.people.Ceo,f.reply(input.requestId,'decline'));assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'declined');assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_office_terms')).n,2);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_entity_relations')).n,0);}finally{f.db.close();}});
test('petitions require legal Naib authority, sufficient Reputation, published fields and a full receiving term',async()=>{const f=await naibPetitionFixture();try{await assert.rejects(f.petitions.propose(f.people.Owner,f.petition()),/independent sietch/);await assert.rejects(f.petitions.propose(f.people.Other,{...f.petition(),clanId:f.clanId}),/Review the petition/);await assert.rejects(f.council.propose(f.people.Other,{...f.input(),kind:'petition'}),/private Voice/);await f.db.query('UPDATE political_office_terms SET expires_at=2000 WHERE id=?',[f.emperorTerm]);await assert.rejects(f.petitions.propose(f.people.Other,f.petition()),/full72-hour/);await f.db.query('UPDATE political_office_terms SET expires_at=9999999999 WHERE id=?',[f.emperorTerm]);await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=0,total_xp=0 WHERE account_id=?',[f.people.Other.id]);await assert.rejects(f.petitions.propose(f.people.Other,f.petition()),/Reputation level 15/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});
test('the private petition API enforces origin and rejects supplied identities while acknowledgements remain historical',async()=>{const f=await naibPetitionFixture();try{const api=createNaibCouncilAPI(f.db,{}, {authenticate:async()=>f.people.Other,access:async()=>({nodes:['web.menu.game']}),billing:f.billing,petitions:f.petitions}),call=(input,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/naibs/petition',{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(input)}));assert.equal((await call(f.petition(),'https://example.invalid')).status,403);assert.equal((await call({...f.petition(),actorId:f.people.Owner.id})).status,400);const input=f.petition();assert.equal((await call(input)).status,201);await f.agreements.reply(f.people.Ceo,f.reply(input.requestId));await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.emperorTerm]);f.setTime(1000+10*86400000);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'acknowledged');}finally{f.db.close();}});
test('sietch ownership changes retain the petition cooldown and cannot inherit its private history or a revoked answer',async()=>{const f=await naibPetitionFixture();try{const input=f.petition();await f.petitions.propose(f.people.Other,input);const answer=await f.agreements.reply(f.people.Ceo,f.reply(input.requestId));await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[answer.reference]);assert.equal((await f.agreements.read(f.people.Other)).agreements[0].state,'response-unavailable');await assert.rejects(f.agreements.reply(f.people.Ceo,f.reply(input.requestId,'decline')),/already has a response/);await f.db.query('UPDATE site_clans SET owner_id=? WHERE id=?',[f.people.Member.id,f.clanId]);const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Member.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[f.people.Member.id,link.minecraft_uuid,f.clanId]);assert.equal((await f.petitions.context(f.people.Member)).cooldownUntil,1000+48*3600000);await assert.rejects(f.petitions.propose(f.people.Member,f.petition()),/cooldown/);assert.equal((await f.agreements.read(f.people.Member)).agreements.length,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}});
test('paid Naib assembly preserves independent seats and pays its fixed fee and Reputation exactly once',async()=>{const f=await paidNaibFixture();try{const view=await f.council.context(f.people.Other);assert.equal(view.funding.required,true);assert.equal(view.funding.feeMinor,100000);assert.equal(view.funding.levelNow,28);assert(view.funding.accounts.some(a=>a.id===String(f.target.id)));const input=f.input(),r=await f.council.propose(f.people.Other,input);assert.equal(r.funding.feeMinor,'100000');assert.equal(r.funding.xp,200);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,400000);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_tax_treasury'")).balance_minor,100000);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10200);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);await f.council.vote(f.people.Other,{dossierId:r.id,choice:'yes',confirmed:true});assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Other.id])).total_xp,10200);await assert.rejects(f.council.propose(f.people.Other,f.input()),/cooldown/);}finally{f.db.close();}});
test('paid Council has no free production fallback and rejects foreign funding or client-side price overrides',async()=>{const f=await paidNaibFixture();try{const input=f.input();await assert.rejects(createNaibCouncil(f.db,{clock:f.clock}).propose(f.people.Other,input),/banking unavailable/);await assert.rejects(f.council.propose(f.people.Other,{...input,sourceAccount:String(f.source.id)}),/Insufficient authorised/);await assert.rejects(f.council.propose(f.people.Other,{...input,feeMinor:1}),/Choose funding/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_council_dossiers')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});
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<choices.length;i++)await f.council.vote(f.clans[i].actor,{dossierId:r.id,choice:choices[i],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();}}const f=await councilAccordFixture();try{f.db.naibCouncilPaidEnabled=false;await assert.rejects(f.council.propose(f.people.Other,{...f.input(),kind:'water-sharing'}),/unavailable/);f.db.naibCouncilPaidEnabled=true;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();const accord=(await f.council.context(f.people.Other)).accords[0];f.setTime(accord.endsAt);assert.equal((await f.council.context(f.people.Other)).accords[0].state,'expired');await assert.rejects(f.council.withdraw(f.people.Other,{dossierId:r.id,requestId:randomUUID(),confirmed:true}),/no current consent/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}});
test('writing an alliance title in an ordinary cheaper Council proposal cannot create the registered accord effect',async()=>{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();}});
test('Imperial Steward uses a paid verified nomination, separate candidate consent, replacement and no Council authority',async()=>{const f=await diplomacyFixture('emperor');try{for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await f.db.query(sql);f.db.sqlite.exec('CREATE TABLE IF NOT EXISTS political_office_locks(scope TEXT PRIMARY KEY);');const proposal=person=>({decisionId:'IMP-03',requestId:randomUUID(),sourceAccount:String(f.source.id),targetPersonId:person.id,title:'The Imperial Steward',terms:'Maintain the administrative records and advise the Imperial court.',confirmed:true});const candidates=await f.service.read(f.people.Owner,'IMP-03');assert.ok(candidates.canExecute);assert.ok(candidates.diplomacyTargets.some(p=>p.id===f.people.Member.id));assert.ok(!candidates.diplomacyTargets.some(p=>p.id===f.people.Owner.id));await assert.rejects(f.service.execute(f.people.Owner,proposal(f.people.Owner)),/different active eligible recipient/);const input=proposal(f.people.Member),receipt=await f.service.execute(f.people.Owner,input);assert.equal(receipt.feeMinor,'500000');assert.equal(receipt.xp,500);assert.equal((await activePoliticalAppointments(f.db,{clock:f.clock})).length,0);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId)),/not addressed/);const reply=f.reply(input.requestId);await f.agreements.reply(f.people.Member,reply);assert.equal((await f.agreements.reply(f.people.Member,reply)).replayed,true);const [first]=await activePoliticalAppointments(f.db,{clock:f.clock});assert.equal(first.office_key,'emperor');assert.equal(first.role_key,'steward');assert.equal(first.appointment_type,'imperial-steward');assert.equal((await f.agreements.read(f.people.Member)).agreements[0].state,'accepted');f.setTime(1000+48*3600000);const next=proposal(f.people.Other);await f.service.execute(f.people.Owner,next);await f.agreements.reply(f.people.Other,f.reply(next.requestId));const [second]=await activePoliticalAppointments(f.db,{clock:f.clock});assert.equal(second.user_id,f.people.Other.id);assert.equal((await f.db.first('SELECT revoked_at FROM political_appointment_deeds WHERE id=?',[first.id])).revoked_at,f.clock());assert.equal((await f.agreements.read(f.people.Member)).agreements[0].state,'appointment-ended');await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.term]);assert.equal((await activePoliticalAppointments(f.db,{clock:f.clock})).length,0);}finally{f.db.close();}});
import {currentPax,paxBlocksWar} from '../node/imperial-pax.mjs';
async function paxFixture(){const f=await diplomacyFixture('emperor');f.db.sqlite.exec('DROP TABLE site_clan_members;DROP TABLE site_clans;');await initializeClans(f.db,{mysql:false});for(const sql of NAIB_COUNCIL_SCHEMA)await f.db.query(sql);f.db.paxEnabled=true;await f.db.query('UPDATE pb_accounts SET balance_minor=7000000 WHERE id=?',[f.source.id]);const clans=[];for(const person of [f.people.Member,f.people.Ceo]){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(),'Independent 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]);await f.pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,50000,50000,63,1,0)',[person.id]);clans.push({id,person});}const consultations=createPoliticalConsultations(f.db,f.keys,{clock:f.clock}),council=createNaibCouncil(f.db,{clock:f.clock,keys:f.keys}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,consultations});const input={decisionId:'IMP-01',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Pax Imperialis',terms:'The Imperial throne offers a voluntary temporary peace on Arrakis.',confirmed:true};return {...f,clans,consultations,council,service,input};}
test('Pax Imperialis pays once, opens separate real House and Council ballots, limits new Arrakis agreements only among consenters',async()=>{const f=await paxFixture();try{const receipt=await f.service.execute(f.people.Owner,f.input);assert.equal(receipt.feeMinor,'5000000');assert.equal(receipt.xp,1500);assert.equal(receipt.ballot.paxDossierId,f.input.requestId);assert.equal((await f.service.execute(f.people.Owner,f.input)).keyId,receipt.keyId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal(await currentPax(f.db,f.clock()),null);await f.consultations.vote(f.people.Other,{ballotId:f.input.requestId,seatKey:'office:'+f.targetOffice,choice:'yes',requestId:randomUUID(),confirmed:true});for(const c of f.clans)await f.council.vote(c.person,{dossierId:f.input.requestId,choice:'accept',confirmed:true});f.setTime(1000+86400000);await f.consultations.reconcile();await f.council.reconcile();const pact=await currentPax(f.db,f.clock());assert.equal(pact.endsAt,f.clock()+72*3600000);assert.equal(pact.clans.length,2);const block={startsAt:f.clock()+3600000,endsAt:f.clock()+7200000};assert.equal(await paxBlocksWar(f.db,[{kind:'clan',id:f.clans[0].id},{kind:'politics',id:f.targetOffice}],block,f.clock()),true);assert.equal(await paxBlocksWar(f.db,[{kind:'clan',id:f.clans[0].id},{kind:'clan',id:randomUUID()}],block,f.clock()),false);assert.equal(await paxBlocksWar(f.db,[{kind:'politics',id:'emperor'},{kind:'politics',id:f.targetOffice}],block,f.clock()),false);assert.equal(await currentPax(f.db,pact.endsAt),null);}finally{f.db.close();}});
test('a genuinely rejected paid Pax enables free once-per-declaration Reputation only for currently eligible rejecting Naibs',async()=>{const f=await paxFixture();try{await f.service.execute(f.people.Owner,f.input);await f.consultations.vote(f.people.Other,{ballotId:f.input.requestId,seatKey:'office:'+f.targetOffice,choice:'yes',requestId:randomUUID(),confirmed:true});for(const c of f.clans)await f.council.vote(c.person,{dossierId:f.input.requestId,choice:'reject',confirmed:true});f.setTime(1000+86400000);await f.consultations.reconcile();await f.council.reconcile();assert.equal(await currentPax(f.db,f.clock()),null);const p=f.clans[0].person;assert.deepEqual((await f.council.context(p)).rejections,[f.input.requestId]);const claim={dossierId:f.input.requestId,requestId:randomUUID(),confirmed:true};await assert.rejects(f.council.rejectPax(f.people.Other,claim),/current sietch/);assert.equal((await f.council.rejectPax(p,claim)).xp,1200);assert.equal((await f.council.rejectPax(p,claim)).replayed,true);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[p.id])).total_xp,51200);assert.deepEqual((await f.council.context(p)).rejections,[]);await assert.rejects(f.council.rejectPax(p,{...claim,requestId:randomUUID()}),/already recorded/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}});
import {createGuildSubsidies,verifyGuildSubsidy,GUILD_SUBSIDY_SCHEMA} from '../node/guild-subsidy.mjs';
import {createGuildService,GUILD_SCHEMA} from '../node/game-guild.mjs';
async function guildSubsidyFixture(){const f=await fixture('spacing_guild');for(const sql of GUILD_SUBSIDY_SCHEMA)await f.db.query(sql);await f.db.query(GUILD_SCHEMA.replace(/,INDEX guild_pending\([^)]*\)/,''));await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_game_treasury','999','Game treasury',0,'active',1)");f.db.guildSubsidyEnabled=true;const user={...f.people.Other,uuid:randomUUID(),faction:'atreides',version:1,keyId:randomUUID()},entity={id:entityId('person',user.id),kind:'person',key:user.id,name:'Traveller',canView:true,canPay:true,canActivate:true},authority=async()=>({entities:[entity]});await new PostbankService(f.db,authority).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const passenger=await f.db.first('SELECT a.* FROM pb_accounts a JOIN pb_clients c ON a.client_number=c.client_number WHERE c.entity_id=?',[entity.id]);await f.db.query('UPDATE pb_accounts SET balance_minor=50000 WHERE id=?',[passenger.id]);const subsidies=createGuildSubsidies(f.db,{verify:(p,n)=>verifyGuildSubsidy(f.db,p,n),clock:f.clock});let preferred=0;const guild=createGuildService(f.db,{authority,resolve:async()=>user,clock:f.clock,discount:async()=>preferred,subsidies});const input={decisionId:'SG-03',requestId:randomUUID(),sourceAccount:String(f.source.id),amountMinor:2000000,confirmed:true};const board=price=>({uuid:user.uuid,requestId:randomUUID(),keyId:user.keyId,version:1,fareMinor:price,destination:'caladan'});return {...f,user,passenger,subsidies,guild,input,board,preferred:v=>preferred=v};}
test('Guild subsidy reserves the named office funds and pays only actual completed journeys with nonstacking fares and unused release',async()=>{const f=await guildSubsidyFixture();try{const receipt=await f.service.execute(f.people.Owner,f.input);assert.equal(receipt.subsidy.amountMinor,'2000000');assert.equal(receipt.xp,300);assert.equal(receipt.feeMinor,'0');assert.equal((await f.service.execute(f.people.Owner,f.input)).keyId,receipt.keyId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2000000);f.preferred(10);assert.equal((await f.guild.quote(f.user.uuid)).fareMinor,9000);f.preferred(0);const quote=await f.guild.quote(f.user.uuid);assert.equal(quote.fareMinor,8000);assert.equal(quote.subsidyMinor,2000);const ticket=f.board(quote.fareMinor);await f.guild.board(ticket);assert.equal((await f.db.first('SELECT pending_minor FROM pb_guild_subsidies')).pending_minor,2000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.guild.arrive(f.user.uuid,'caladan');await f.guild.arrive(f.user.uuid,'caladan');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,2);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_game_treasury'")).balance_minor,10000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.passenger.id])).balance_minor,42000);assert.equal((await f.db.first('SELECT spent_minor FROM pb_guild_subsidies')).spent_minor,2000);f.setTime(receipt.expiresAt);await f.subsidies.expire();const source=await f.db.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[f.source.id]);assert.deepEqual({...source},{balance_minor:1998000,reserved_minor:0});assert.equal((await f.guild.quote(f.user.uuid)).fareMinor,10000);}finally{f.db.close();}});
test('revocation releases unused Guild subsidy funds but preserves a confirmed pending fare, and expiry releases an unused ticket',async()=>{const f=await guildSubsidyFixture();try{const receipt=await f.service.execute(f.people.Owner,f.input);await f.guild.board(f.board(8000));await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);await f.subsidies.expire();assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2000);assert.equal((await f.guild.quote(f.user.uuid)).fareMinor,10000);f.setTime(1000+120001);await f.guild.expire();assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});
import {readFileSync} from 'node:fs';import {originPayload} from './native-origin-fixture.mjs';
import {createExchangeIncentives,verifyExchangeIncentive,EXCHANGE_INCENTIVE_SCHEMA} from '../node/exchange-incentive.mjs';import {createGameExchangeService} from '../node/game-exchange-service.mjs';
async function incentiveFixture(){const f=await fixture('ordos');for(const sql of EXCHANGE_INCENTIVE_SCHEMA)await f.db.query(sql);f.db.exchangeIncentiveEnabled=true;const users=[f.people.Member,f.people.Other].map(u=>({...u,uuid:randomUUID()})),entities=users.map(u=>({id:entityId('person',u.id),kind:'person',key:u.id,name:u.username,canView:true,canPay:true,canActivate:true})),authority=async actor=>({entities:entities.filter(e=>e.key===actor.id)});for(let i=0;i<users.length;i++)await new PostbankService(f.db,authority).activate(users[i],{entityId:entities[i].id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const account=async i=>(await f.db.first('SELECT a.id FROM pb_accounts a JOIN pb_clients c ON a.client_number=c.client_number WHERE c.entity_id=?',[entities[i].id])).id;await f.db.query('UPDATE pb_accounts SET balance_minor=50000 WHERE id=?',[await account(0)]);f.db.sqlite.exec("ATTACH DATABASE ':memory:' AS dunegameplay;CREATE TABLE dunegameplay.dune_exchange_listings(id INTEGER PRIMARY KEY,seller TEXT,seller_name TEXT,origin TEXT,category TEXT,material TEXT,quantity INT,price TEXT,payload TEXT,display_name TEXT);CREATE TABLE dunegameplay.dune_exchange_sales(id INTEGER PRIMARY KEY,listing_id INT,seller TEXT,seller_name TEXT,buyer TEXT,buyer_name TEXT,material TEXT,display_name TEXT,quantity INT,unit_price TEXT,total_price TEXT,origin TEXT);");const schema=readFileSync(new URL('../integrations/game-exchange-schema.sql',import.meta.url),'utf8').replace(/--[^\n]*\n/g,'').replaceAll('CREATE TABLE IF NOT EXISTS dune_','CREATE TABLE IF NOT EXISTS dunegameplay.dune_').replace(/,\s*INDEX exchange_delivery_pending\([^)]*\)/g,'').replaceAll(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','');f.db.sqlite.exec(schema);for(const [id,payload]of [[1,originPayload('sigma_draconis_iv')],[2,originPayload('arrakis')],[3,null]])await f.db.query('INSERT INTO dunegameplay.dune_exchange_listings VALUES(?,?,?,?,?,?,?,?,?,?)',[id,users[1].uuid,users[1].username,'sigma_draconis_iv','ores','DIAMOND',3,'100.00',payload,'Diamond']);const incentives=createExchangeIncentives(f.db,{verify:(pool,n)=>verifyExchangeIncentive(f.db,pool,n),clock:f.clock}),exchange=createGameExchangeService(f.db,{gameSchema:'dunegameplay',authority,resolveSeller:async uuid=>users.find(u=>u.uuid===uuid),clock:f.clock,incentives});const input={decisionId:'ORD-04',requestId:randomUUID(),sourceAccount:String(f.source.id),amountMinor:2000000,confirmed:true};const buy=id=>({requestId:randomUUID(),listingId:String(id),amount:1,priceMinor:10000});return {...f,users,account,incentives,exchange,input,buy};}
test('Ordos incentive pays a bounded rebate only on native verified goods, without changing seller price or inventing delivery',async()=>{const f=await incentiveFixture();try{const r=await f.service.execute(f.people.Owner,f.input);assert.equal(r.incentive.amountMinor,'2000000');assert.equal(r.xp,300);assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2000000);const a=f.buy(1),p=await f.exchange.buy(f.users[0],f.users[0].uuid,a);assert.equal(p.rebateMinor,1000);assert.equal(p.totalMinor,10000);assert.equal(p.sellerNetMinor,10000);assert.equal((await f.exchange.buy(f.users[0],f.users[0].uuid,a)).rebateMinor,1000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[await f.account(0)])).balance_minor,41000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[await f.account(1)])).balance_minor,10000);for(const id of [2,3])assert.equal((await f.exchange.buy(f.users[0],f.users[0].uuid,f.buy(id))).rebateMinor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_exchange_incentive_rebates')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM dunegameplay.dune_exchange_deliveries')).n,3);f.setTime(r.expiresAt);await f.incentives.expire();assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,0);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,1999000);}finally{f.db.close();}});
test('Exchange delivery/history rollback also rolls back reserved pool spending and rebate',async()=>{const f=await incentiveFixture();try{await f.service.execute(f.people.Owner,f.input);f.db.sqlite.exec("CREATE TRIGGER dunegameplay.fail_incentive_sale BEFORE INSERT ON dune_exchange_sales BEGIN SELECT RAISE(ABORT,'history fault');END;");await assert.rejects(f.exchange.buy(f.users[0],f.users[0].uuid,f.buy(1)),/history fault/);assert.equal((await f.db.first('SELECT spent_minor FROM pb_exchange_incentive_pools')).spent_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_exchange_incentive_rebates')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});