Merge pull request 'Connect Guild transport agreements and Corrino advisory representation' (#598) from dev/MC:feature/guild-transport-agreements-20261125 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 3m15s

This commit is contained in:
unimatrix 2026-11-25 05:18:40 +00:00
commit b24def4629
9 changed files with 97 additions and 15 deletions

View file

@ -13,7 +13,7 @@ const related={
const authority={IMP:'Current Emperor deed',ATR:'Current Aerdrecht House office deed',HAR:'Current Harkveen House office deed',COR:'Current Korenholt House office deed',ORD:'Current Oordwijk House office deed',FRE:'Current recognised sietch deed; independent Council',BG:'Current Veiled Concord office deed',NF:'Current Church of Muad’Dib office deed',SG:'Current Spacing Guild office deed',CLD:'Current clan delegate deed'};
function paidDecisionGap(id){
const kind=politicalDecision(id)?.kind,base='Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically. ';
return base+(kind==='organisation-passage'?'The signed charter is consumed at Guild quote, boarding and arrival for current direct organisation members.72h maximum, clipped to the original Imperial mandate. Revocation, expiry or leaving removes permission; normal fares and embargoes remain in force.':kind==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'&&politicalDecision(id).agreementMode==='petition'?'A confidential petition requires a signed response from its original receiving Royal holder within72h. Acknowledgement is historical receipt only; hearings, votes and concession changes require separate authorised actions. No bank, vote, ownership or war rights change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder or legal company owner. Acceptance or refusal requires that same current mandate or company ownership, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.');
return base+(kind==='organisation-passage'?'The signed charter is consumed at Guild quote, boarding and arrival for current direct organisation members.72h maximum, clipped to the original Imperial mandate. Revocation, expiry or leaving removes permission; normal fares and embargoes remain in force.':kind==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'&&politicalDecision(id).agreementMode==='representation'?'The receiving Royal holder signs within72h. Acceptance and an actual observer appointment commit together, clipped to14d and both source terms. Projection rejects revoked source/response proofs or either ended mandate. No leadership or bank authority moves.':kind==='agreement'&&politicalDecision(id).agreementMode==='petition'?'A confidential petition requires a signed response from its original receiving Royal holder within72h. Acknowledgement is historical receipt only; hearings, votes and concession changes require separate authorised actions. No bank, vote, ownership or war rights change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder or legal company owner. Acceptance or refusal requires that same current mandate or company ownership, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.');
}
export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status:naibDecision(d.id)||houseFaithDecision(d.id)||clanFaithDecision(d.id)||tradeDecision(d.id)||politicalDecision(d.id)||d.id==='IMP-10'||faithBlessing(d.id)?'active':'design',currency:'DM',amountConversion:1,authority:authority[d.office],conditions:'Current unexpired and unrevoked deed, eligible target and all stated effect conditions must be checked by the domain consumer. Level and XP do not grant office authority.',costCooldown:d.cost,effect:d.effect,level:d.level,proposedXP:d.xp,adapter:naibDecision(d.id)?'createNaibCouncil / createNaibCouncilFunding':houseFaithDecision(d.id)?'createHouseFaithLaws / missionaryFaithOutlawed':clanFaithDecision(d.id)?'createClanFaith.offer / reply':tradeDecision(d.id)?'createWorldTradeGovernance / createGameExchangeService / createGuildService':politicalDecision(d.id)?'createPoliticalDecisions':faithBlessing(d.id)?'createFaithBlessings / faithAward':d.id==='IMP-10'?'createImperialPassage / createGuildService':related[d.id]?.adapter||null,gap:naibDecision(d.id)?'Current independent sietch deed, Reputation'+naibDecision(d.id).level+','+naibDecision(d.id).feeMinor/100+'DM from its active account or the legal Basic owner,'+naibDecision(d.id).xp+' Reputation and'+naibDecision(d.id).cooldownMs/3600000+'h seat cooldown. Fee, signed key, proposal electorate and reward commit together. No free production fallback; one Council vote per current sietch. Personal election votes are unchanged.':houseFaithDecision(d.id)?'Royal House authority and Reputation checked before a sealed 48-hour personal referendum. Seven-day office cooldown survives succession; quorum and strict majority required. Only future invitations and clan-owner acceptance are gated by the latest live law; existing allegiance and earned rewards remain unchanged.':clanFaithDecision(d.id)?'Current faith officer can invite; only the receiving clan’s legal owner can consent. Daily invitation and seven-day clan-change cooldowns are enforced; no membership or rights move.':tradeDecision(d.id)?'Current Royal office and Reputation, immutable creation-world metadata, seven-day cooldown, retained stock and atomic seller-funded bank levy; no default activation.':politicalDecision(d.id)?paidDecisionGap(d.id):faithBlessing(d.id)?'Current faith leader/officer deed, owner-approved clan allegiance, appointment expiry and cooldown are checked centrally. Old Faith and New Faith use the same capped bonus consumer; historical queued rewards retain their claim-time consent proof.':d.id==='IMP-10'?'Native House selection replaces the prior grant; seven-day office cooldown and current Emperor deed are checked centrally.':related[d.id]?.gap||'No complete registered domain consumer implements this exact target, price, cooldown, duration and effect. Execution remains unavailable.',repeatability:'Only after the stated cooldown; no implied stacking or automatic renewal.',executionEnabled:!!naibDecision(d.id)||!!houseFaithDecision(d.id)||!!clanFaithDecision(d.id)||!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)})));
export const decisionAudit=id=>DECISION_AUDIT.find(row=>row.id===id)||null;

View file

@ -6,7 +6,7 @@ export function mountPoliticalAgreements(host,{fetcher=fetch}={}){
async function load(){if(busy)return;busy=true;refresh.disabled=true;try{const data=await api.request('/api/politics/agreements');if(!root.isConnected)return;list.replaceChildren();status.textContent=data.agreements.length?'Only proposals addressed to you or issued by you are shown.':'No proposals or petitions for your current account.';
for(const a of data.agreements){const card=el('article'),title=el('h4',a.title),terms=el('p',a.terms),state=el('p',a.sourceOffice.replaceAll('_',' ')+' → '+(a.targetName||a.targetOffice.replaceAll('_',' '))+' · '+a.state),deadline=el('p',(a.mode==='petition'&&a.respondedAt?'Responded: ':a.endsAt?'Ends: ':'Reply before: ')+new Date(a.mode==='petition'&&a.respondedAt||a.endsAt||a.responseUntil).toLocaleString());card.append(title,terms,state,deadline,el('small','J.A.R.V.I.S. reference: '+a.reference));
if(a.canReply){const review=el('p'),confirm=el('button','Confirm response'),cancel=el('button','Cancel'),accept=el('button',a.mode==='petition'?'Review acknowledgement':'Review acceptance'),decline=el('button','Review refusal');for(const b of [confirm,cancel,accept,decline])b.type='button';confirm.hidden=cancel.hidden=true;let pending=null;
const prepare=choice=>{pending={proposalId:a.id,requestId:crypto.randomUUID(),choice,confirmed:true};review.textContent=(choice==='accept'?(a.mode==='petition'?'Acknowledge receipt of':'Accept'):'Decline')+' “'+a.title+'”? This does not change votes, offices, ownership, travel or war participation.';confirm.hidden=cancel.hidden=false;accept.disabled=decline.disabled=true;};accept.onclick=()=>prepare('accept');decline.onclick=()=>prepare('decline');cancel.onclick=()=>{pending=null;review.textContent='';confirm.hidden=cancel.hidden=true;accept.disabled=decline.disabled=false;};
const prepare=choice=>{pending={proposalId:a.id,requestId:crypto.randomUUID(),choice,confirmed:true};review.textContent=(choice==='accept'?(a.mode==='petition'?'Acknowledge receipt of':'Accept'):'Decline')+' “'+a.title+'”? '+(a.mode==='representation'?'Acceptance creates the requested temporary observer appointment. It grants no leadership, bank, election, ownership or war authority.':'This does not change votes, offices, ownership, travel or war participation.');confirm.hidden=cancel.hidden=false;accept.disabled=decline.disabled=true;};accept.onclick=()=>prepare('accept');decline.onclick=()=>prepare('decline');cancel.onclick=()=>{pending=null;review.textContent='';confirm.hidden=cancel.hidden=true;accept.disabled=decline.disabled=false;};
confirm.onclick=async()=>{if(!pending||busy)return;busy=true;confirm.disabled=cancel.disabled=refresh.disabled=true;try{await api.request('/api/politics/agreements',pending);pending=null;busy=false;await load();}catch(error){status.textContent=error.message+(error.uncertain?' Retry this same response to check its recorded result.':'');if(!error.uncertain)cancel.onclick();}finally{busy=false;confirm.disabled=cancel.disabled=refresh.disabled=false;}};
card.append(accept,decline,review,confirm,cancel);
}list.append(card);

View file

@ -10,7 +10,7 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
const account=field('Office funding account','select');let title,body,recipient,citation,search,find,startsAt,endsAt,percent,houseSelect,clanSelect,grantAmount,grantReason,officeSelect,organisationSelect;
if(d.kind==='organisation-passage'){organisationSelect=field('Receiving organisation','select');form.append(el('p','Current direct members receive up to72 hours of Arrakis permission, ending with the Imperial mandate. Normal fares, boarding windows and Guild embargoes remain in force. Mother control does not substitute for membership.'));}
else if(d.kind==='ballot'){title=field('Resolution title','input');title.maxLength=100;body=field('Resolution and consultation terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p',d.electorate==='houses'?'One institutional vote per current Royal Great House. A resolution does not automatically change laws or personal voting rights.':'One institutional vote per native Caladan clan, exercised by its current legal owner. The result is nonbinding and does not consume personal election votes.'));}
else if(d.kind==='agreement'){officeSelect=field(d.targetKind==='company'?'Receiving company':'Receiving political office','select');title=field('Proposal title','input');title.maxLength=100;body=field(d.agreementMode==='petition'?'Petition and requested action':'Confidential diplomatic terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p',d.agreementMode==='petition'?'Request a signed response from the original receiving Royal office holder within 72 hours. Acknowledgement records receipt only. Hearings, votes, grants and concession changes require their own authorised actions.':'The receiving current legal company owner or Royal office holder must consent within 72 hours. Accepted terms last at most '+d.durationMs/86400000+' days and end with '+(d.targetKind==='company'?'the issuing mandate or a change of company ownership':'either mandate')+'. No votes, ownership, war, bank or travel rights are transferred.'));}
else if(d.kind==='agreement'){officeSelect=field(d.targetKind==='company'?'Receiving company':'Receiving political office','select');title=field('Proposal title','input');title.maxLength=100;body=field(d.agreementMode==='petition'?'Petition and requested action':'Confidential diplomatic terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p',d.agreementMode==='representation'?'The receiving Royal holder can accept within72 hours to appoint you as Court Advisory Representative with the existing observer role for at most14 days. Both original mandates and signed proofs must remain valid. This grants no leadership, bank, election, ownership or war authority.':d.agreementMode==='petition'?'Request a signed response from the original receiving Royal office holder within 72 hours. Acknowledgement records receipt only. Hearings, votes, grants and concession changes require their own authorised actions.':'The receiving current legal company owner or Royal office holder must consent within 72 hours. Accepted terms last at most '+d.durationMs/86400000+' days and end with '+(d.targetKind==='company'?'the issuing mandate or a change of company ownership':'either mandate')+'. No votes, ownership, war, bank or travel rights are transferred.'));}
else if(d.kind==='proclamation'){title=field('Title','input');title.maxLength=120;title.minLength=3;body=field('Official message','textarea');body.maxLength=6000;body.minLength=10;body.rows=6;}
else if(d.kind==='event'){title=field('Session title','input');title.maxLength=100;body=field('Purpose and invitation','textarea');body.maxLength=2000;body.rows=4;startsAt=field('Start time (UTC)','input');endsAt=field('End time (UTC)','input');startsAt.type=endsAt.type='datetime-local';form.append(el('p','Schedule at least one minute ahead and no more than 30 days ahead. The session must finish before your mandate ends and last at most '+(d.maxEventMs||86400000)/3600000+' hours. It appears in the existing political calendar.'));if(d.id==='SG-06')form.append(el('p','This convenes voluntary mediation. Participants must separately approve any treaty, coalition or peace through its existing consent flow.'));}
else if(d.kind==='tariff'){percent=field('Guild surcharge','select');for(let n=0;n<=5;n++){const o=el('option',n===0?'0% · repeal':n+'%');o.value=String(n);percent.append(o);}form.append(el('p','Applies to new Guild bookings for seven days, while this mandate remains current. Confirmed fares remain unchanged. It does not open blocked routes or change smuggler fares.'));}

View file

@ -21,7 +21,8 @@ export const MASTER_KEY_TEMPLATES=[
action('politics.company-consortium','Ordos confidential company consortium','entity-state',[field('decisionId','Company agreement','select',{options:['ORD-02']}),field('sourceAccount','Authorised Ordos funding account'),field('targetCompanyId','Receiving active company UUID'),field('title','Proposal title'),field('terms','Confidential commercial terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements / readCompanyDeed',executionStatus:'current-ordos-office-and-original-company-owner-consent',effect:'Current Royal Ordos holder,Reputation35,5000DM,600 Reputation and7d cooldown. Reuse the confidential bilateral proposal flow, with72h response by a different current legal owner of an active company. CEO or mother-company control never substitutes for ownership. Accepted terms last at most14d, clipped to the source mandate, and end on ownership change. Separate typed company reply proofs preserve existing office replies without altering their table. No ownership, corporate control, bank, vote or war rights change.'}),
action('politics.organisation-passage','Imperial organisation travel charter','entity-state',[field('sourceAccount','Imperial office funding account'),field('targetKind','Organisation kind','select',{options:['clan','company']}),field('targetId','Current organisation UUID'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions / hasOrganisationPassage / createGuildService',executionStatus:'current-imperial-office-funded-organisational-passage',effect:'IMP-02 charges10000DM, awards250 Reputation at level15, with24h office cooldown. Current direct clan/company members receive up to72h Arrakis permission, ending with the issuing Emperor mandate. Guild quotes, boarding and arrival verify current membership and signed charter. No mother membership, free fare, embargo bypass or military rights.'}),
action('politics.clan-petition','Clan Delegate petition','entity-state',[field('decisionId','Petition','select',{options:['CLD-01','CLD-03','CLD-05']}),field('sourceAccount','Authorised Clan Delegate office account'),field('targetOffice','Receiving Royal office'),field('title','Petition title'),field('terms','Petition and requested action','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-delegate-funded-signed-petition-response',effect:'Three fixed Clan Delegate policies use their published office fee, Reputation requirement and successor-safe cooldown. Another current Royal holder has72h to acknowledge or decline. Both original mandates must cover the response window. A signed acknowledgement remains history; it does not create a hearing, vote, concession, grant, appointment or war.'}),
action('politics.diplomatic-proposal','Confidential diplomatic proposal','entity-state',[field('decisionId','Diplomatic decision','select',{options:['ATR-05','COR-06','ORD-05','BG-05','NF-05']}),field('sourceAccount','Authorised office funding account'),field('targetOffice','Receiving Royal office'),field('title','Proposal title'),field('terms','Confidential diplomatic terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-officeholder-bilateral-consent-consumer',effect:'Five fixed diplomatic policies charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.'}),
action('politics.advisory-representation','Corrino advisory representation petition','entity-state',[field('sourceAccount','Authorised Corrino office account'),field('targetOffice','Receiving Royal office'),field('title','Petition title'),field('terms','Requested advisory representation','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions / createPoliticalAgreements / appointPoliticalInTransaction / activePoliticalAppointments',executionStatus:'signed-receiving-mandate-temporary-observer-deed',effect:'COR-07:Rep50,5000DM,1200 Reputation,7d office cooldown. A different Royal holder has72h to accept or decline. Acceptance atomically issues a real observer appointment, at most14d, clipped to both original mandates. Revoked proofs or either ended mandate remove its membership projection. An existing target-office appointment is preserved rather than replaced. No leadership, bank, election, ownership or war authority moves.'}),
action('politics.diplomatic-proposal','Confidential diplomatic proposal','entity-state',[field('decisionId','Diplomatic decision','select',{options:['ATR-05','COR-06','ORD-05','BG-05','NF-05','SG-01']}),field('sourceAccount','Authorised office funding account'),field('targetOffice','Receiving Royal office'),field('title','Proposal title'),field('terms','Confidential diplomatic terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-officeholder-bilateral-consent-consumer',effect:'Six fixed diplomatic policies, including the seven-day Guild Transport Mandate, charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.'}),
action('politics.diplomatic-response','Accept or refuse a diplomatic proposal','entity-state',[field('proposalId','Proposal UUID'),field('choice','Response','select',{options:['accept','decline']}),field('requestId','Response UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalAgreements.reply',executionStatus:'original-receiving-officeholder-consent-consumer',effect:'Only the original receiving current Royal mandate can accept or refuse a live72h proposal. Recheck both original mandates and the unrevoked signed proposal under the same transaction; record one signed response. Exact retries return the original receipt; conflicting responses, changed holders, expired or revoked proposals cannot manufacture acceptance. No further payment or Reputation is issued for replying.'}),
action('politics.clan-development-grant','Office clan development allocation','entity-state',[field('decisionId','Registered development grant','select',{options:['ATR-01','ATR-04','HAR-02','COR-02','COR-04','NF-03']}),field('sourceAccount','Authorised House funding account'),field('clanId','Receiving clan UUID'),field('amountMinor','Development allocation in DM minor units','number',{min:10000}),field('reason','Development purpose','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalClanGrants / organisationRewardRoute',executionStatus:'current-house-office-and-current-clan-deed-consumer',effect:'House development policies re-read the native clan homeworld, current legal deed, active receiving bank account and authorised House source. Atreides Patronage is exactly10,000 DM; other published grants range from100 DM to their15,000/25,000 DM cap. Basic clans route to their current legal owner, keyed clans to their own account; mother control never substitutes for that owner. Actual funded amount scales Reputation up to the catalogue cap. Existing balanced bank transfer, immutable purpose, ordinary key and Reputation commit together; safe retries retain the original payment recipient. Church sponsorship additionally requires current signed New Faith consent, caps funding at10,000 DM and pays a separate2,500 DM Tax admin fee; grant, fee and proportional Reputation commit or roll back together, with a7d cooldown. No P&O issuance, account activation, construction completion, inventory progress or ownership change is fabricated.'}),
action('politics.guild-mediation','Convene Guild mediation','entity-state',[field('decisionId','Mediation decision','select',{options:['SG-06']}),field('sourceAccount','Authorised Guild funding account'),field('title','Session title'),field('description','Dispute and invitation','textarea'),field('startsAt','Start UTC timestamp','number'),field('endsAt','End UTC timestamp','number'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createRealmEventRecord',executionStatus:'current-guild-officeholder-calendar-consumer',effect:'Current Royal Guild holder, Reputation35,5,000 DM office fee and600 Reputation points. A72h successor-safe cooldown; schedule voluntary mediation for at most72h, entirely within the source mandate and at most30 days ahead. Reuse the political EVT calendar and its existing management rights. Fee, calendar history, Reputation and ordinary key commit atomically. No automatic peace, treaty, war, coalition or participant consent is fabricated; participants use the existing mutual agreement flows.'}),

View file

@ -7,6 +7,7 @@ export const POLITICAL_DECISIONS=Object.freeze([
['CLD-05','Demand Representation',30,500,250000,72]
].map(([id,title,level,xp,feeMinor,hours])=>({id,office:'clan_delegate',title,level,xp,feeMinor,cooldownMs:hours*3600000,kind:'agreement',agreementMode:'petition',responseMs:72*3600000,durationMs:0})),
...[
['SG-01','spacing_guild','Guild Transport Mandate',25,400,500000,72,7],
['ATR-05','atreides','Diplomatic Envoy',30,500,250000,48,7],
['COR-06','corrino','Dynastic Alliance',35,600,500000,168,14],
['ORD-05','ordos','Shadow Negotiation',40,750,250000,72,7],
@ -14,6 +15,7 @@ export const POLITICAL_DECISIONS=Object.freeze([
['NF-05','muad_dib','Whispered Alliance',35,600,500000,168,7]
].map(([id,office,title,level,xp,feeMinor,hours,days])=>({id,office,title,level,xp,feeMinor,cooldownMs:hours*3600000,kind:'agreement',responseMs:72*3600000,durationMs:days*86400000})),
{id:'ORD-02',office:'ordos',title:'Secret Consortium',kind:'agreement',targetKind:'company',level:35,xp:600,feeMinor:500000,cooldownMs:7*86400000,responseMs:72*3600000,durationMs:14*86400000},
{id:'COR-07',office:'corrino',title:'Claim to Influence',kind:'agreement',agreementMode:'representation',level:50,xp:1200,feeMinor:500000,cooldownMs:7*86400000,responseMs:72*3600000,durationMs:14*86400000},
{id:'IMP-05',office:'emperor',title:'Convene Landsraad',kind:'ballot',electorate:'houses',level:25,xp:400,feeMinor:500000,cooldownMs:72*3600000,ballotMs:72*3600000},
{id:'ATR-02',office:'atreides',title:'Council of Caladan',kind:'ballot',electorate:'clans',ballotWorld:'caladan',level:15,xp:250,feeMinor:200000,cooldownMs:48*3600000,ballotMs:48*3600000},
{id:'NF-03',office:'muad_dib',title:'Church Patronage',kind:'clan-grant',grantFaith:'muad_dib',level:25,xp:400,feeMinor:250000,grantMinMinor:10000,grantMaxMinor:1000000,cooldownMs:7*86400000},
@ -47,4 +49,4 @@ export const POLITICAL_DECISIONS=Object.freeze([
].map(d=>Object.freeze({...d,durationMs:d.durationMs??(d.kind==='honour'?30*86400000:null)})));
export const politicalDecision=id=>POLITICAL_DECISIONS.find(d=>d.id===id)||null;
export function proclamationDecisionId(kind,faction){return kind==='imperial'?'IMP-04':kind==='guild'?'SG-PROCLAIM':kind==='house'?({atreides:'ATR-PROCLAIM',harkonnen:'HAR-PROCLAIM',corrino:'COR-PROCLAIM',ordos:'ORD-PROCLAIM',veiled_concord:'BG-04',muad_dib:'NF-04'})[faction]||null:null;}
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG',clan_delegate:'CLD'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount')+(d.feeMinor?' + '+(d.feeMinor/100).toLocaleString('en-GB')+' admin':''):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='organisation-passage'?'Grant current members of one active clan or company sanctioned Arrakis passage for at most72 hours and no longer than the issuing Imperial mandate. Normal fares, boarding windows and Guild embargoes still apply; no membership or military rights change.':d.kind==='ballot'?'Open a '+d.ballotMs/3600000+'-hour nonbinding resolution vote. '+(d.electorate==='houses'?'One seat for each currently occupied Royal Great House office. Its original mandate must still be current to vote.':'One seat for each current native Caladan clan, exercised by its legal owner; mother control does not confer a seat.')+' Frozen electorate; more-than-half participation and strict majority required. Ties fail. Personal election votes are untouched.':d.kind==='agreement'?d.agreementMode==='petition'?'Send a confidential petition to another current Royal office holder for a signed response within 72 hours. Acknowledgement records receipt only; any hearing, vote, grant, concession change or war still needs its own authorised action. An answered petition remains a historical record.':(d.targetKind==='company'?'Send a confidential proposal to an active company. Its current legal owner must consent within 72 hours.':'Send a confidential diplomatic proposal to another current Royal office holder, who must consent within 72 hours.')+' Accepted terms last '+d.durationMs/86400000+' days at most and end with '+(d.targetKind==='company'?'the issuing mandate or a change of company ownership':'either mandate')+'. This records diplomatic terms without moving votes, ownership, military allegiance or bank rights.':d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+(d.grantFaith?' from the Church to a clan with current signed New Faith consent. A separate 2,500 DM administrative fee goes to Tax.':' from this House to a current clan on its native world.')+' Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG',clan_delegate:'CLD'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount')+(d.feeMinor?' + '+(d.feeMinor/100).toLocaleString('en-GB')+' admin':''):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='organisation-passage'?'Grant current members of one active clan or company sanctioned Arrakis passage for at most72 hours and no longer than the issuing Imperial mandate. Normal fares, boarding windows and Guild embargoes still apply; no membership or military rights change.':d.kind==='ballot'?'Open a '+d.ballotMs/3600000+'-hour nonbinding resolution vote. '+(d.electorate==='houses'?'One seat for each currently occupied Royal Great House office. Its original mandate must still be current to vote.':'One seat for each current native Caladan clan, exercised by its legal owner; mother control does not confer a seat.')+' Frozen electorate; more-than-half participation and strict majority required. Ties fail. Personal election votes are untouched.':d.kind==='agreement'?d.agreementMode==='representation'?'Petition another current Royal office holder for advisory representation. Within72h that holder can consent to an observer appointment lasting at most14 days, clipped to both mandates. It ends if either original mandate or signed proof ceases. No leadership, bank, vote, military or ownership authority is granted.':d.agreementMode==='petition'?'Send a confidential petition to another current Royal office holder for a signed response within 72 hours. Acknowledgement records receipt only; any hearing, vote, grant, concession change or war still needs its own authorised action. An answered petition remains a historical record.':(d.targetKind==='company'?'Send a confidential proposal to an active company. Its current legal owner must consent within 72 hours.':'Send a confidential diplomatic proposal to another current Royal office holder, who must consent within 72 hours.')+' Accepted terms last '+d.durationMs/86400000+' days at most and end with '+(d.targetKind==='company'?'the issuing mandate or a change of company ownership':'either mandate')+'. This records diplomatic terms without moving votes, ownership, military allegiance or bank rights.':d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+(d.grantFaith?' from the Church to a clan with current signed New Faith consent. A separate 2,500 DM administrative fee goes to Tax.':' from this House to a current clan on its native world.')+' Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));

View file

@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"sourceHash": "f6ae84ebe5a6cefb5a20d7650431e4cfa55c9aeb44b6c674e35691674616abcb",
"sourceHash": "26bc66dc745a13fe3e960e2bb91fa5747a75f98162389e1f354a7135c66f047b",
"actions": [
{
"id": "war.coalition-consent",
@ -782,6 +782,55 @@
"webIssue": false,
"recordOnly": true
},
{
"id": "politics.advisory-representation",
"label": "POL & orders · Corrino advisory representation petition",
"version": 1,
"keyType": "entity-state",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "sourceAccount",
"label": "Authorised Corrino office account",
"type": "text",
"required": true
},
{
"name": "targetOffice",
"label": "Receiving Royal office",
"type": "text",
"required": true
},
{
"name": "title",
"label": "Petition title",
"type": "text",
"required": true
},
{
"name": "terms",
"label": "Requested advisory representation",
"type": "textarea",
"required": true
},
{
"name": "requestId",
"label": "Request UUID",
"type": "text",
"required": true
}
],
"effect": "COR-07:Rep50,5000DM,1200 Reputation,7d office cooldown. A different Royal holder has72h to accept or decline. Acceptance atomically issues a real observer appointment, at most14d, clipped to both original mandates. Revoked proofs or either ended mandate remove its membership projection. An existing target-office appointment is preserved rather than replaced. No leadership, bank, election, ownership or war authority moves.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "politics.diplomatic-proposal",
"label": "POL & orders · Confidential diplomatic proposal",
@ -805,7 +854,8 @@
"COR-06",
"ORD-05",
"BG-05",
"NF-05"
"NF-05",
"SG-01"
]
},
{
@ -839,7 +889,7 @@
"required": true
}
],
"effect": "Five fixed diplomatic policies charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.",
"effect": "Six fixed diplomatic policies, including the seven-day Guild Transport Mandate, charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true

View file

@ -8,6 +8,7 @@ import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {validUuid} from './game-link.mjs';
import {readCompanyDeed} from './company-deeds.mjs';
import {identity} from './auth.mjs';
import {appointPoliticalInTransaction,activePoliticalAppointments} from './political-appointments.mjs';
export const POLITICAL_AGREEMENT_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_political_agreement_replies(decision_request CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,term_id CHAR(36) NOT NULL,choice VARCHAR(12) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export const POLITICAL_COMPANY_REPLY_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_political_company_replies(decision_request CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,key_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,company_id CHAR(36) NOT NULL,choice VARCHAR(12) NOT NULL,input_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
const replyTable=d=>d.targetKind==='company'?'jarvis_political_company_replies':'jarvis_political_agreement_replies';
@ -44,8 +45,9 @@ export function createPoliticalAgreements(raw,keys,{clock=Date.now}={}){
const replyValid=reply?.verified_key&&reply.actor_id===v.a.targetActorId&&(v.d.targetKind==='company'?reply.company_id===v.a.targetCompanyId:reply.term_id===v.a.targetTermId)&&['accept','decline'].includes(reply.choice)&&Number(reply.created_at)>=Number(row.created_at)&&Number(reply.created_at)<v.a.responseUntil&&reply.input_hash===hash([reply.actor_id,row.request_id,reply.choice]);
const petition=v.d.agreementMode==='petition';
const endsAt=!petition&&replyValid&&reply.choice==='accept'?Math.min(Number(reply.created_at)+v.a.durationMs,v.a.mandateUntil):null;
const state=petition&&replyValid?(reply.choice==='accept'?'acknowledged':'declined'):!v.mandates?'mandate-ended':reply&&!replyValid?'response-unavailable':replyValid?(reply.choice==='decline'?'declined':now<endsAt?'accepted':'expired'):now<v.a.responseUntil?'pending':'expired';
return{id:row.request_id,mode:petition?'petition':'agreement',respondedAt:replyValid?Number(reply.created_at):null,title:v.payload.title,terms:v.payload.terms,decisionId:v.d.id,sourceOffice:v.d.office,targetOffice:v.a.targetOffice||null,targetName:v.a.targetName||PUBLIC_OFFICES.find(o=>o.key===v.a.targetOffice)?.scope||v.a.targetOffice,responseUntil:v.a.responseUntil,endsAt,state,canReply:state==='pending'&&actor.id===v.a.targetActorId,reference:row.key_id};
let state=petition&&replyValid?(reply.choice==='accept'?'acknowledged':'declined'):!v.mandates?'mandate-ended':reply&&!replyValid?'response-unavailable':replyValid?(reply.choice==='decline'?'declined':now<endsAt?'accepted':'expired'):now<v.a.responseUntil?'pending':'expired';
if(v.d.agreementMode==='representation'&&state==='accepted'){const appointment=await tx.first("SELECT id FROM political_appointment_deeds WHERE request_id=? AND appointment_type='political-adviser' AND revoked_at IS NULL",[reply.request_id]);if(!appointment||(await activePoliticalAppointments(tx,{userId:row.actor_id,clock:()=>now})).every(a=>a.id!==appointment.id))state='representation-ended';}
return{id:row.request_id,mode:petition?'petition':v.d.agreementMode==='representation'?'representation':'agreement',respondedAt:replyValid?Number(reply.created_at):null,title:v.payload.title,terms:v.payload.terms,decisionId:v.d.id,sourceOffice:v.d.office,targetOffice:v.a.targetOffice||null,targetName:v.a.targetName||PUBLIC_OFFICES.find(o=>o.key===v.a.targetOffice)?.scope||v.a.targetOffice,responseUntil:v.a.responseUntil,endsAt,state,canReply:state==='pending'&&actor.id===v.a.targetActorId,reference:row.key_id};
}
async function read(actor){const rows=await db.query('SELECT * FROM jarvis_political_decisions WHERE actor_id=? OR recipient_id=? ORDER BY created_at DESC,request_id DESC LIMIT 100',[actor.id,actor.id]),items=[];for(const row of rows){const item=await projection(db,row,actor,clock());if(item)items.push(item);}return{agreements:items};}
async function reply(actor,input){
@ -56,7 +58,13 @@ export function createPoliticalAgreements(raw,keys,{clock=Date.now}={}){
if(old){if(old.request_id!==input.requestId||old.input_hash!==digest||old.actor_id!==actor.id)fail('This proposal already has a response.');return{ok:true,replayed:true,reference:old.key_id};}
const v=await verified(tx,row,now);if(!v||!v.mandates||now>=v.a.responseUntil)fail('The proposal or one of its mandates has expired.');
const source=await holder(tx,v.d.office,{id:row.actor_id},now,true),target=v.d.targetKind==='company'?await company(tx,v.a.targetCompanyId,{lock:true}):await holder(tx,v.a.targetOffice,actor,now,true);if(source?.termId!==row.term_id||(v.d.targetKind==='company'?target?.userId!==actor.id:target?.termId!==v.a.targetTermId))fail('Both original mandates must still be current.',403);
let reference;await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-agreement-reply:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{reference=keyId;await tx.query('INSERT INTO '+replyTable(v.d)+' VALUES(?,?,?,?,?,?,?,?)',[row.request_id,input.requestId,keyId,actor.id,v.d.targetKind==='company'?v.a.targetCompanyId:target.termId,input.choice,digest,now]);}});return{ok:true,replayed:false,reference};
let reference;await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-agreement-reply:'+input.requestId,transactionStore:tx,authorize:async(_,{keyId})=>{reference=keyId;await tx.query('INSERT INTO '+replyTable(v.d)+' VALUES(?,?,?,?,?,?,?,?)',[row.request_id,input.requestId,keyId,actor.id,v.d.targetKind==='company'?v.a.targetCompanyId:target.termId,input.choice,digest,now]);
if(v.d.agreementMode==='representation'&&input.choice==='accept'){
if((await activePoliticalAppointments(tx,{userId:row.actor_id,clock:()=>now})).some(a=>a.office_key===v.a.targetOffice))fail('This applicant already has a current appointment in the receiving office.');
const appointment=await appointPoliticalInTransaction(tx,actor,{officeKey:v.a.targetOffice,userId:row.actor_id,requestId:input.requestId,type:'job',title:'Court Advisory Representative',expiresAt:Math.min(now+v.a.durationMs,v.a.mandateUntil)},{clock:()=>now});
await tx.query("UPDATE political_appointment_deeds SET role_key='observer',appointment_type='political-adviser' WHERE id=?",[appointment.id]);
}
}});return{ok:true,replayed:false,reference};
});
}
return{targets,create,read,reply};

View file

@ -1,6 +1,8 @@
import {faithAppointmentRole} from '../control-panel/public/faith-pol-policy.mjs';
import {randomUUID} from 'node:crypto';import {PUBLIC_OFFICES} from './public-government.mjs';import {JarvisError} from './jarvis-listings.mjs';
import {currentNaib} from './naib-membership.mjs';
import {currentOfficeController} from './entity-relations.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
export const POLITICAL_APPOINTMENT_SCHEMA=[
`CREATE TABLE IF NOT EXISTS political_appointment_deeds(id CHAR(36) PRIMARY KEY,office_key VARCHAR(32) NOT NULL,source_term_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,role_key VARCHAR(64) NOT NULL,title VARCHAR(100) NOT NULL,appointment_type VARCHAR(24) NOT NULL,target_kind VARCHAR(16) NULL,target_id VARCHAR(36) NULL,starts_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,revoked_at BIGINT NULL,issuer_id CHAR(36) NOT NULL,request_id CHAR(36) NOT NULL UNIQUE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS political_appointment_events(id CHAR(36) PRIMARY KEY,deed_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,event_type VARCHAR(24) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
@ -43,5 +45,11 @@ export function createPoliticalAppointments(central,{clock=Date.now}={}){
}
export async function activePoliticalAppointments(central,{userId=null,clock=Date.now}={}){
const now=clock(),args=[now,now,now,now];if(userId)args.push(userId);
return central.query("SELECT d.id,d.office_key,d.user_id,d.role_key,d.title,d.appointment_type,d.target_kind,d.target_id,d.starts_at,d.expires_at,a.username,a.display_name FROM political_appointment_deeds d JOIN political_office_terms t ON t.id=d.source_term_id JOIN site_accounts a ON a.id=d.user_id WHERE d.revoked_at IS NULL AND d.starts_at<=? AND d.expires_at>? AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? AND a.password_hash NOT LIKE '!%'"+(userId?' AND d.user_id=?':'')+' ORDER BY d.office_key,d.title,d.id',args);
const rows=await central.query("SELECT d.id,d.office_key,d.user_id,d.role_key,d.title,d.appointment_type,d.target_kind,d.target_id,d.starts_at,d.expires_at,a.username,a.display_name FROM political_appointment_deeds d JOIN political_office_terms t ON t.id=d.source_term_id JOIN site_accounts a ON a.id=d.user_id WHERE d.revoked_at IS NULL AND d.starts_at<=? AND d.expires_at>? AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? AND a.password_hash NOT LIKE '!%'"+(userId?' AND d.user_id=?':'')+' ORDER BY d.office_key,d.title,d.id',args),result=[];
for(const row of rows){if(row.appointment_type==='political-adviser'&&!await advisorySourceCurrent(central,row,now))continue;result.push(row);}return result;
}
async function advisorySourceCurrent(db,deed,now){
const rows=await db.query("SELECT p.actor_id,p.term_id,p.office_key,p.request_id,reply.request_id response_request,reply.actor_id response_actor,reply.term_id response_term FROM political_appointment_deeds a JOIN jarvis_political_agreement_replies reply ON reply.request_id=a.request_id AND reply.choice='accept' AND reply.actor_id=a.issuer_id AND reply.term_id=a.source_term_id JOIN jarvis_political_decisions p ON p.request_id=reply.decision_request AND p.decision_id='COR-07' AND p.actor_id=a.user_id AND p.recipient_id=a.issuer_id JOIN organisation_keys source_key ON source_key.id=p.key_id AND source_key.account_id=? AND source_key.key_type='entity-state' AND source_key.scope_id=CONCAT('state:political-decision:',p.request_id) AND source_key.revoked_at IS NULL JOIN organisation_keys reply_key ON reply_key.id=reply.key_id AND reply_key.account_id=? AND reply_key.key_type='entity-state' AND reply_key.scope_id=CONCAT('state:political-agreement-reply:',reply.request_id) AND reply_key.revoked_at IS NULL JOIN political_office_charters charter ON charter.office_key=p.office_key AND charter.charter_kind='royal' JOIN organisation_keys charter_key ON charter_key.id=charter.staff_key_id AND charter_key.key_type='staff-office-royal' AND charter_key.scope_id=CONCAT('office:',p.office_key) AND charter_key.account_id=? AND charter_key.used_at IS NOT NULL AND charter_key.revoked_at IS NULL JOIN political_office_charters receiver_charter ON receiver_charter.office_key=a.office_key AND receiver_charter.charter_kind='royal' JOIN organisation_keys receiver_key ON receiver_key.id=receiver_charter.staff_key_id AND receiver_key.key_type='staff-office-royal' AND receiver_key.scope_id=CONCAT('office:',a.office_key) AND receiver_key.account_id=? AND receiver_key.used_at IS NOT NULL AND receiver_key.revoked_at IS NULL WHERE a.id=?",[STAFF_OFFICE_ACCOUNT_ID,STAFF_OFFICE_ACCOUNT_ID,STAFF_OFFICE_ACCOUNT_ID,STAFF_OFFICE_ACCOUNT_ID,deed.id]);
if(rows.length!==1)return false;const p=rows[0],[source,target]=await Promise.all([currentOfficeController(db,p.office_key,now),currentOfficeController(db,deed.office_key,now)]);return source?.userId===p.actor_id&&source.termId===p.term_id&&target?.userId===p.response_actor&&target.termId===p.response_term;
}

View file

@ -19,7 +19,7 @@ import {createPoliticalClanGrants} from '../node/political-clan-grants.mjs';
import {initializeClans} from '../control-panel/clans.mjs';
import {POLITICAL_AGREEMENT_SCHEMA,POLITICAL_COMPANY_REPLY_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs';
import {initializeClanFaith,createClanFaith} from '../node/clan-faith.mjs';
import {POLITICAL_APPOINTMENT_SCHEMA} from '../node/political-appointments.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(''));
@ -260,13 +260,26 @@ test('petitions reject expired recipients and forged prices, and never treat a r
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('five 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']]){const f=await diplomacyFixture(office);try{
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');