From a3efa01d4444da36ebe98424337ceb362d628052 Mon Sep 17 00:00:00 2001 From: Dev Date: Wed, 25 Nov 2026 04:25:53 +0100 Subject: [PATCH] Connect Ordos company accords to current legal owner consent --- .../public/cp-v2/cp-v2-decision-audit.mjs | 2 +- .../cp-v2/cp-v2-political-agreements.mjs | 2 +- .../cp-v2/cp-v2-political-decisions.mjs | 6 +- .../public/jarvis-master-keys.mjs | 1 + .../public/political-decision-policy.mjs | 3 +- website/control-panel/server.mjs | 4 +- .../osticket/dev-jarvis-catalogue.json | 60 ++++++++++++++++++- website/node/political-agreements.mjs | 28 +++++---- website/node/political-decisions.mjs | 8 +-- website/tests/political-decisions.test.mjs | 9 ++- 10 files changed, 96 insertions(+), 27 deletions(-) diff --git a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs index 2d187979..47eba509 100644 --- a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs @@ -12,7 +12,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==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder. Acceptance or refusal requires that same current Royal mandate, 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==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder or legal company owner. Acceptance or refusal requires that same current mandate or company ownership, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.'); } export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status: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: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: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:!!houseFaithDecision(d.id)||!!clanFaithDecision(d.id)||!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)}))); export const decisionAudit=id=>DECISION_AUDIT.find(row=>row.id===id)||null; diff --git a/website/control-panel/public/cp-v2/cp-v2-political-agreements.mjs b/website/control-panel/public/cp-v2/cp-v2-political-agreements.mjs index 17e1c17b..97084ca3 100644 --- a/website/control-panel/public/cp-v2/cp-v2-political-agreements.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-political-agreements.mjs @@ -4,7 +4,7 @@ export function mountPoliticalAgreements(host,{fetcher=fetch}={}){ const root=el('section',undefined,'cp-political-agreement-inbox'),heading=el('h3','Diplomatic proposals'),status=el('p','Reading your diplomatic proposals…'),list=el('div'),refresh=el('button','Refresh proposals'),api=createUserAPI(fetcher); status.setAttribute('role','status');refresh.type='button';root.append(heading,status,list,refresh);host.append(root);let busy=false; 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 diplomatic proposals 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.targetOffice.replaceAll('_',' ')+' · '+a.state),deadline=el('p',(a.endsAt?'Ends: ':'Reply before: ')+new Date(a.endsAt||a.responseUntil).toLocaleString());card.append(title,terms,state,deadline,el('small','J.A.R.V.I.S. reference: '+a.reference)); + 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.endsAt?'Ends: ':'Reply before: ')+new Date(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','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'?'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;}; 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;}}; diff --git a/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs b/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs index d930f9f2..acbe8a34 100644 --- a/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs @@ -9,7 +9,7 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){ function field(title,tag){const label=el('label',title),input=el(tag);label.append(input);form.append(label);fields.push(input);return input;} const account=field('Office funding account','select');let title,body,recipient,citation,search,find,startsAt,endsAt,percent,houseSelect,clanSelect,grantAmount,grantReason,officeSelect; 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('Receiving political office','select');title=field('Proposal title','input');title.maxLength=100;body=field('Confidential diplomatic terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p','The receiving current Royal office holder must consent within 72 hours. Accepted terms last at most '+d.durationMs/86400000+' days and end with 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('Confidential diplomatic terms','textarea');body.minLength=20;body.maxLength=4000;body.rows=6;form.append(el('p','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.'));} @@ -31,9 +31,9 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){ if(d.kind==='clan-grant')status.textContent=(data.canManage?'Current office verified. ':'Current office required. ')+(d.grantMinMinor/100).toFixed(2)+'–'+(d.grantMaxMinor/100).toFixed(2)+' DM development allocation'+(d.feeMinor?' + '+(d.feeMinor/100).toFixed(2)+' DM administrative fee':'')+'; up to '+d.xp+' Reputation points, proportional to the funded amount. Reputation '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.'); }catch(e){status.textContent=e.message;}finally{busy=false;controls();}} prepare.onclick=()=>{ - const payload=d.kind==='ballot'?{title:title.value,terms:body.value}:d.kind==='agreement'?{targetOffice:officeSelect.value,title:title.value,terms:body.value}:d.kind==='proclamation'?{title:title.value,body:body.value}:d.kind==='event'?{title:title.value,description:body.value,startsAt:Date.parse(startsAt.value+'Z'),endsAt:Date.parse(endsAt.value+'Z')}:d.kind==='clan-grant'?{clanId:clanSelect.value,amountMinor:Math.round(Number(grantAmount.value)*100),reason:grantReason.value}:d.kind==='guild-discount'?{house:houseSelect.value}:d.kind==='tariff'?{percent:Number(percent.value)}:d.kind==='report'?{}:{recipientId:recipient.value,citation:citation.value}; + const payload=d.kind==='ballot'?{title:title.value,terms:body.value}:d.kind==='agreement'?{...(d.targetKind==='company'?{targetCompanyId:officeSelect.value}:{targetOffice:officeSelect.value}),title:title.value,terms:body.value}:d.kind==='proclamation'?{title:title.value,body:body.value}:d.kind==='event'?{title:title.value,description:body.value,startsAt:Date.parse(startsAt.value+'Z'),endsAt:Date.parse(endsAt.value+'Z')}:d.kind==='clan-grant'?{clanId:clanSelect.value,amountMinor:Math.round(Number(grantAmount.value)*100),reason:grantReason.value}:d.kind==='guild-discount'?{house:houseSelect.value}:d.kind==='tariff'?{percent:Number(percent.value)}:d.kind==='report'?{}:{recipientId:recipient.value,citation:citation.value}; if(d.kind==='ballot'&&(title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Complete the resolution title and terms.';return;} - if(d.kind==='agreement'&&(!officeSelect.value||title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Choose a receiving office and complete the proposal title and terms.';return;} + if(d.kind==='agreement'&&(!officeSelect.value||title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Choose a recipient and complete the proposal title and terms.';return;} if(d.kind==='clan-grant'&&(!clanSelect.value||!grantAmount.reportValidity()||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinord.grantMaxMinor||grantReason.value.trim().length<10)){status.textContent='Choose a receiving clan, published grant amount and development purpose.';return;} if(!account.value||['proclamation','event'].includes(d.kind)&&(title.value.trim().length<3||body.value.trim().length<10)||d.kind==='event'&&(!Number.isSafeInteger(payload.startsAt)||!Number.isSafeInteger(payload.endsAt)||payload.startsAt({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:'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}, @@ -40,4 +41,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'})[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==='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'?'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 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'})[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==='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.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.'}))); diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 991fcf96..793a1d39 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -4,7 +4,7 @@ import {initializeClanFaith,createClanFaithAPI,createClanFaith} from '../node/cl import {initializeHouseFaith,createHouseFaithAPI,createHouseFaithLaws,missionaryFaithOutlawed} from '../node/house-faith-laws.mjs'; import {createPoliticalMarketReports} from '../node/political-market-reports.mjs'; import {POLITICAL_CONSULTATION_SCHEMA,createPoliticalConsultations,createPoliticalConsultationAPI} from '../node/political-consultations.mjs'; -import {POLITICAL_AGREEMENT_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs'; +import {POLITICAL_AGREEMENT_SCHEMA,POLITICAL_COMPANY_REPLY_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs'; import {createPoliticalClanGrants} from '../node/political-clan-grants.mjs'; import {initializeWorldTrade,createWorldTradeAPI} from '../node/world-trade-governance.mjs'; import {publicWelcomeContext} from '../node/welcome-context.mjs'; @@ -584,7 +584,7 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);await db.query(POLITICAL_COMPANY_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'political_consultations',slot:now=>Math.floor(now/60000)*60000,run:()=>createPoliticalConsultations(db,organisationKeys).reconcile()},{key:'house_faith_ballots',slot:now=>Math.floor(now/60000)*60000,run:()=>createHouseFaithLaws(db,organisationKeys).reconcile()},{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'organisation_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createOrganisationFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP}; diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index a335fa75..fe275b5e 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "6d2a3b4d5fb8cd165486c7848285106db837346c24a237cab670b1c86d18fdaa", + "sourceHash": "2e74e986f3266c8872473684f5e2a28dadf53ba4688544f7f464d74df779890d", "actions": [ { "id": "war.coalition-consent", @@ -531,6 +531,64 @@ "webIssue": false, "recordOnly": true }, + { + "id": "politics.company-consortium", + "label": "POL & orders · Ordos confidential company consortium", + "version": 1, + "keyType": "entity-state", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "decisionId", + "label": "Company agreement", + "type": "select", + "required": true, + "options": [ + "ORD-02" + ] + }, + { + "name": "sourceAccount", + "label": "Authorised Ordos funding account", + "type": "text", + "required": true + }, + { + "name": "targetCompanyId", + "label": "Receiving active company UUID", + "type": "text", + "required": true + }, + { + "name": "title", + "label": "Proposal title", + "type": "text", + "required": true + }, + { + "name": "terms", + "label": "Confidential commercial terms", + "type": "textarea", + "required": true + }, + { + "name": "requestId", + "label": "Request UUID", + "type": "text", + "required": true + } + ], + "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.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, { "id": "politics.diplomatic-proposal", "label": "POL & orders · Confidential diplomatic proposal", diff --git a/website/node/political-agreements.mjs b/website/node/political-agreements.mjs index 2d2db9b9..b53b77bf 100644 --- a/website/node/political-agreements.mjs +++ b/website/node/political-agreements.mjs @@ -6,8 +6,11 @@ import {PUBLIC_OFFICES} from './public-government.mjs'; import {currentOfficeController} from './entity-relations.mjs'; 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'; 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'; const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});}; const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'); export function createPoliticalAgreements(raw,keys,{clock=Date.now}={}){ @@ -20,38 +23,39 @@ export function createPoliticalAgreements(raw,keys,{clock=Date.now}={}){ if(!h||h.userId===actor.id)fail('A different current Royal office holder must receive this proposal.',403); return h; } - async function targets(tx,d,actor,now){const rows=[];for(const o of PUBLIC_OFFICES){if(o.key===d.office)continue;const target=await currentOfficeController(tx,o.key,now);if(target&&target.userId!==actor.id&&await holder(tx,o.key,{id:target.userId},now))rows.push({id:o.key,name:o.scope});}return rows;} + async function company(tx,id,{lock=false}={}){tx=boardReadStore(tx,db);if(lock)await tx.first('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[id]);try{const deed=await readCompanyDeed(tx,id);const owner=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=site_accounts.id)",[deed.company.owner_account_id]);return deed.company.status==='active'&&owner?{userId:deed.company.owner_account_id,bindingId:id,name:deed.company.name}:null;}catch{return null;}} + async function targets(tx,d,actor,now){if(d.targetKind==='company'){return tx.query("SELECT c.id,c.name FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_company_members m ON m.company_id=c.id AND m.user_id=d.owner_account_id JOIN site_accounts a ON a.id=d.owner_account_id WHERE c.status='active' AND d.owner_account_id<>? AND a.password_hash NOT LIKE '!%' ORDER BY c.name,c.id LIMIT 1000",[actor.id]);}const rows=[];for(const o of PUBLIC_OFFICES){if(o.key===d.office)continue;const target=await currentOfficeController(tx,o.key,now);if(target&&target.userId!==actor.id&&await holder(tx,o.key,{id:target.userId},now))rows.push({id:o.key,name:o.scope});}return rows;} async function create(tx,{d,actor,payload,holder:source,now}){ - const target=await resolve(tx,d,actor,payload.targetOffice,now),sourceTerm=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[source.termId]),responseUntil=now+d.responseMs,mandateUntil=Math.min(Number(sourceTerm?.expires_at||0),target.expiresAt); + tx=boardReadStore(tx,db);const target=d.targetKind==='company'?await company(tx,payload.targetCompanyId,{lock:true}):await resolve(tx,d,actor,payload.targetOffice,now);if(!target||target.userId===actor.id)fail('Choose an active company with a different current legal owner.',403);const sourceTerm=await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[source.termId]),responseUntil=now+d.responseMs,mandateUntil=Math.min(Number(sourceTerm?.expires_at||0),target.expiresAt??Number(sourceTerm?.expires_at||0)); if(mandateUntil<=responseUntil)fail('Both mandates must extend beyond the full proposal response window.'); - return{targetOffice:payload.targetOffice,targetActorId:target.userId,targetTermId:target.termId,responseUntil,mandateUntil,durationMs:d.durationMs}; + return{...(d.targetKind==='company'?{targetKind:'company',targetCompanyId:payload.targetCompanyId,targetName:target.name}:{targetOffice:payload.targetOffice,targetTermId:target.termId}),targetActorId:target.userId,responseUntil,mandateUntil,durationMs:d.durationMs}; } async function verified(tx,row,now){ const d=politicalDecision(row?.decision_id);if(!d||d.kind!=='agreement')return null; const key=await tx.first("SELECT id FROM organisation_keys WHERE id=? AND account_id=? AND key_type='entity-state' AND scope_id=? AND revoked_at IS NULL",[row.key_id,STAFF_OFFICE_ACCOUNT_ID,'state:political-decision:'+row.request_id]);if(!key)return null; const receipt=JSON.parse(row.receipt_json),payload=JSON.parse(row.payload_json),a=receipt.agreement; - if(!a||a.targetOffice!==payload.targetOffice||a.targetActorId!==row.recipient_id||a.responseUntil!==Number(row.created_at)+d.responseMs||a.durationMs!==d.durationMs||!validUuid(a.targetTermId)||!Number.isSafeInteger(a.mandateUntil))return null; - const source=await holder(tx,d.office,{id:row.actor_id},now),target=await holder(tx,a.targetOffice,{id:a.targetActorId},now); - return{d,a,payload,mandates:source?.termId===row.term_id&&target?.termId===a.targetTermId}; + if(!a||(d.targetKind==='company'?a.targetKind!=='company'||a.targetCompanyId!==payload.targetCompanyId||!validUuid(a.targetCompanyId):a.targetOffice!==payload.targetOffice||!validUuid(a.targetTermId))||a.targetActorId!==row.recipient_id||a.responseUntil!==Number(row.created_at)+d.responseMs||a.durationMs!==d.durationMs||!Number.isSafeInteger(a.mandateUntil))return null; + const source=await holder(tx,d.office,{id:row.actor_id},now),target=d.targetKind==='company'?await company(tx,a.targetCompanyId):await holder(tx,a.targetOffice,{id:a.targetActorId},now); + return{d,a,payload,mandates:source?.termId===row.term_id&&(d.targetKind==='company'?target?.userId===a.targetActorId:target?.termId===a.targetTermId)}; } async function projection(tx,row,actor,now){ if(![row.actor_id,row.recipient_id].includes(actor.id))return null;const v=await verified(tx,row,now);if(!v)return null; - const reply=await tx.first('SELECT r.*,k.id verified_key FROM jarvis_political_agreement_replies r LEFT JOIN organisation_keys k ON k.id=r.key_id AND k.account_id=? AND k.key_type=\'entity-state\' AND k.scope_id=CONCAT(\'state:political-agreement-reply:\',r.request_id) AND k.revoked_at IS NULL WHERE r.decision_request=?',[STAFF_OFFICE_ACCOUNT_ID,row.request_id]); - const replyValid=reply?.verified_key&&reply.actor_id===v.a.targetActorId&&reply.term_id===v.a.targetTermId&&['accept','decline'].includes(reply.choice)&&Number(reply.created_at)>=Number(row.created_at)&&Number(reply.created_at)=Number(row.created_at)&&Number(reply.created_at)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){ if(!input||Object.keys(input).sort().join(',')!=='choice,confirmed,proposalId,requestId'||input.confirmed!==true||!validUuid(input.requestId)||!validUuid(input.proposalId)||!['accept','decline'].includes(input.choice))fail('Review and confirm this proposal response.',400); if(!keys||!raw.transaction)fail('Agreement records unavailable.',503); return raw.transaction(async original=>{const tx=boardReadStore(original,db),now=clock(),row=await tx.first('SELECT * FROM jarvis_political_decisions WHERE request_id=? FOR UPDATE',[input.proposalId]);if(!row||row.recipient_id!==actor.id)fail('This proposal is not addressed to your office.',403); - const digest=hash([actor.id,input.proposalId,input.choice]),old=await tx.first('SELECT * FROM jarvis_political_agreement_replies WHERE decision_request=? OR request_id=? FOR UPDATE',[row.request_id,input.requestId]); + const policy=politicalDecision(row.decision_id);if(policy?.kind!=='agreement')fail('Registered agreement required.',400);const digest=hash([actor.id,input.proposalId,input.choice]),old=await tx.first('SELECT * FROM '+replyTable(policy)+' WHERE decision_request=? OR request_id=? FOR UPDATE',[row.request_id,input.requestId]); 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=await holder(tx,v.a.targetOffice,actor,now,true);if(source?.termId!==row.term_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 jarvis_political_agreement_replies VALUES(?,?,?,?,?,?,?,?)',[row.request_id,input.requestId,keyId,actor.id,target.termId,input.choice,digest,now]);}});return{ok:true,replayed:false,reference}; + 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}; }); } return{targets,create,read,reply}; diff --git a/website/node/political-decisions.mjs b/website/node/political-decisions.mjs index 7367a1ec..e15ee34a 100644 --- a/website/node/political-decisions.mjs +++ b/website/node/political-decisions.mjs @@ -25,11 +25,11 @@ const fingerprint=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex' const funding=d=>entityId('office',d.office==='emperor'?'emperor':'leader:'+d.office); export function politicalDecisionReader(tx,base){const reader=boardReadStore(tx,base);if(tx!==base)reader.readSnapshot=async work=>work(reader);return reader;} export function decisionInput(input){ - const d=politicalDecision(input?.decisionId),fields=d?.kind==='ballot'?'confirmed,decisionId,requestId,sourceAccount,terms,title':d?.kind==='agreement'?'confirmed,decisionId,requestId,sourceAccount,targetOffice,terms,title':d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?'confirmed,decisionId,requestId,sourceAccount':'citation,confirmed,decisionId,recipientId,requestId,sourceAccount'; + const d=politicalDecision(input?.decisionId),fields=d?.kind==='ballot'?'confirmed,decisionId,requestId,sourceAccount,terms,title':d?.kind==='agreement'?(d.targetKind==='company'?'confirmed,decisionId,requestId,sourceAccount,targetCompanyId,terms,title':'confirmed,decisionId,requestId,sourceAccount,targetOffice,terms,title'):d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?'confirmed,decisionId,requestId,sourceAccount':'citation,confirmed,decisionId,recipientId,requestId,sourceAccount'; if(!d||!input||Object.keys(input).sort().join(',')!==fields||!validUuid(input.requestId)||input.confirmed!==true||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount))fail('Review and confirm a registered decision and its funding account.',400); const clean=(value,min,max)=>{if(typeof value!=='string'||value.trim().lengthmax||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))fail('Invalid announcement or citation.',400);return value.replaceAll('\r\n','\n').trim();}; - const payload=d.kind==='ballot'?{title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='agreement'?{targetOffice:input.targetOffice,title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?{}:{recipientId:input.recipientId,citation:clean(input.citation,3,2000)}; - if(d.kind==='agreement'&&(!PUBLIC_OFFICES.some(o=>o.key===payload.targetOffice)||payload.targetOffice===d.office))fail('Choose another registered political office.',400); + const payload=d.kind==='ballot'?{title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='agreement'?{...(d.targetKind==='company'?{targetCompanyId:input.targetCompanyId}:{targetOffice:input.targetOffice}),title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?{}:{recipientId:input.recipientId,citation:clean(input.citation,3,2000)}; + if(d.kind==='agreement'&&(d.targetKind==='company'?!validUuid(payload.targetCompanyId):!PUBLIC_OFFICES.some(o=>o.key===payload.targetOffice)||payload.targetOffice===d.office))fail('Choose another registered political office.',400); if(d.kind==='clan-grant'&&(!validUuid(payload.clanId)||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinord.grantMaxMinor))fail('Choose an eligible clan and a grant within the published budget.',400); if(d.kind==='guild-discount'&&!TRADE_WORLDS.some(w=>w.house===payload.house))fail('Choose a native House for the preferred fare.',400); if(d.kind==='tariff'&&(!Number.isInteger(payload.percent)||payload.percent<0||payload.percent>5))fail('Choose a Guild surcharge from 0 to 5 percent.',400); @@ -51,7 +51,7 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){ // The production central pool exposes prepared reads rather than first(). // Keep every transaction callback on its original connection. db={...boardReadStore(db,db),transaction:db.transaction.bind(db)}; - const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','jarvis_political_agreement_replies','jarvis_political_consultations','jarvis_political_consultation_votes','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','jarvis_clan_faith','jarvis_faith_consents','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']}); + const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','jarvis_political_agreement_replies','jarvis_political_consultations','jarvis_political_consultation_votes','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','jarvis_clan_faith','jarvis_faith_consents','corrino_companies','site_company_deeds','site_company_members','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']}); async function accounts(tx,actor,d){const b=banking.view(tx),r=politicalDecisionReader(tx,db),authority=deps.authority||createPostbankAuthority(r,{bank:b,clock});const rights=await authority(actor,{bank:b});return(await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[funding(d)])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));} const eventBanking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,bankTables:['jarvis_events','jarvis_event_history']}); async function recipients(tx,actor,d,search=''){ diff --git a/website/tests/political-decisions.test.mjs b/website/tests/political-decisions.test.mjs index d89829fc..5a63b31d 100644 --- a/website/tests/political-decisions.test.mjs +++ b/website/tests/political-decisions.test.mjs @@ -14,14 +14,14 @@ 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,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.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_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);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await f.db.query(sql);f.db.politicalDecisionsEnabled=true; + await f.db.query(POLITICAL_DECISION_SCHEMA);await f.db.query(POLITICAL_AGREEMENT_SCHEMA);await f.db.query(POLITICAL_COMPANY_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])}); @@ -268,3 +268,8 @@ test('Landsraad snapshots occupied Royal Great Houses and current mandates alone 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();}});