Merge pull request 'Unify consenting faith bonuses and funded office publications' (#570) from dev/MC:feature/pol-decision-consumers-20261124 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m50s

This commit is contained in:
unimatrix 2026-11-25 00:17:53 +00:00
commit be094dc81c
17 changed files with 165 additions and 43 deletions

View file

@ -1,13 +1,13 @@
import {randomUUID} from 'node:crypto';
import {identity} from '../node/auth.mjs';
import {accessFor} from '../node/permissions.mjs';
import {createPoliticsPreview} from './politics-preview.mjs';
import {proclamationDecisionId} from './public/political-decision-policy.mjs';
export const proclamationSchema=[`CREATE TABLE IF NOT EXISTS political_proclamations(id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL,scope VARCHAR(48) NOT NULL,title VARCHAR(120) NOT NULL,body TEXT NOT NULL,author_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL,version INTEGER NOT NULL DEFAULT 1,UNIQUE KEY proclamation_request(author_id,request_id),KEY scope_date(scope,created_at)) ENGINE=InnoDB`];
export async function initializeProclamations(db){for(const sql of proclamationSchema)await db.prepare(sql).run();}
export function proclamationInput(input){if(!input||input.confirmed!==true||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||''))throw Error('Confirm publication.');const title=String(input.title||'').trim(),body=String(input.body||'').trim();if(title.length<3||title.length>120||body.length<10||body.length>6000||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(title+body))throw Error('Use a title of 3–120 characters and a message of 10–6,000 characters.');return{requestId:input.requestId.toLowerCase(),title,body};}
export function proclamationScope(kind,context,rights){if(kind==='imperial')return{scope:'imperium',publish:context?.emperor===true};if(kind==='guild')return{scope:'spacing_guild',publish:rights.ranks.includes('guild_envoy')};if(kind==='house'&&context?.factionStatus==='verified'&&context.faction)return{scope:'house:'+context.faction,publish:context.houseLeader===true};return null;}
export function createProclamations(db,settings={},deps={}){
const auth=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u)),preview=deps.preview||createPoliticsPreview(db,settings),clock=deps.clock||Date.now,origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
const auth=deps.authenticate||(r=>identity(r,db)),access=deps.access||(u=>accessFor(db,u)),preview=deps.preview||createPoliticsPreview(db,settings),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
return async request=>{
const url=new URL(request.url),kind=url.searchParams.get('kind'),page=Number(url.searchParams.get('page')||1);
@ -15,15 +15,13 @@ export function createProclamations(db,settings={},deps={}){
if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);
if(request.method==='POST'&&(request.headers.get('origin')!==new URL(origin).origin||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||'')))return reply({message:'Invalid publication origin or format.'},403);
const user=await auth(request);if(!user)return reply({message:'Sign in first.'},401);const rights=await access(user);if(!rights.nodes.includes('web.menu.game'))return reply({message:'Realm access required.'},403);
if(request.method==='POST'&&kind==='imperial'&&deps.politicalDecisions){const raw=await request.text();if(raw.length>10000)return reply({message:'Message too large.'},413);try{const body=JSON.parse(raw);return reply(await deps.politicalDecisions.execute(user,{...body,decisionId:'IMP-04'}),201);}catch(e){return reply({message:e.status?e.message:'Publication was not confirmed. Refresh before retrying.'},e.status||503);}}
let input;if(request.method==='POST'){const raw=await request.text();if(raw.length>10000)return reply({message:'Message too large.'},413);try{input=proclamationInput(JSON.parse(raw));}catch(error){return reply({message:error.message},400);}}
async function publish(body,decisionId){if(!decisionId||!deps.politicalDecisions)return reply({message:'The funded publication service is unavailable. Nothing was published.'},503);if(!body||typeof body!=='object'||Array.isArray(body)||body.decisionId&&body.decisionId!==decisionId)return reply({message:'Publication office override rejected.'},400);try{return reply(await deps.politicalDecisions.execute(user,{...body,decisionId}),201);}catch(e){return reply({message:e.status?e.message:'Publication was not confirmed. Refresh before retrying.'},e.status||503);}}
let input;if(request.method==='POST'){const raw=await request.text();if(raw.length>10000)return reply({message:'Message too large.'},413);try{input=JSON.parse(raw);}catch{return reply({message:'Invalid publication.'},400);}if(kind!=='house')return publish(input,proclamationDecisionId(kind));}
const response=await preview(new Request(new URL('/api/politics/preview',origin),{headers:request.headers}));if(!response.ok)return reply({message:'Political authority unavailable.'},503);const context=await response.json(),current=await auth(request);if(!current||current.id!==user.id)return reply({message:'Account changed.'},403);const freshRights=await access(current);if(!freshRights.nodes.includes('web.menu.game'))return reply({message:'Access changed.'},403);
const target=proclamationScope(kind,context,freshRights);if(!target)return reply({message:'A verified House is required.'},403);
if(request.method==='POST'){
if(!target.publish)return reply({message:'Only the current office holder may publish here.'},403);
try{const id=randomUUID();await db.prepare('INSERT INTO political_proclamations(id,request_id,scope,title,body,author_id,created_at,version) VALUES(?,?,?,?,?,?,?,1)').bind(id,input.requestId,target.scope,input.title,input.body,user.id,clock()).run();return reply({ok:true,id},201);}catch(error){const old=await db.prepare('SELECT id,scope,title,body FROM political_proclamations WHERE author_id=? AND request_id=?').bind(user.id,input.requestId).first();if(old&&old.scope===target.scope&&old.title===input.title&&old.body===input.body)return reply({ok:true,id:old.id});if(old)return reply({message:'Publication identifier already used. Refresh.'},409);throw error;}
}
const decisionId=proclamationDecisionId(kind,context.faction);if(request.method==='POST')return publish(input,decisionId);
const total=Number((await db.prepare('SELECT COUNT(*) AS total FROM political_proclamations WHERE scope=?').bind(target.scope).first()).total);
const post=await db.prepare('SELECT p.id,p.title,p.body,p.created_at,p.version,u.username AS author FROM political_proclamations p JOIN site_accounts u ON u.id=p.author_id WHERE p.scope=? ORDER BY p.created_at DESC,p.id DESC LIMIT 1 OFFSET ?').bind(target.scope,page-1).first();
return reply({post:post||null,page,pages:Math.max(1,total),total,canPublish:target.publish});
let canPublish=false;if(decisionId&&deps.politicalDecisions)try{canPublish=(await deps.politicalDecisions.read(current,decisionId)).canManage===true;}catch{}
return reply({post:post||null,page,pages:Math.max(1,total),total,canPublish,decisionId});
};}

View file

@ -8,6 +8,6 @@ const related={
'IMP-04':{adapter:'proclamations',gap:'The existing proclamation publisher does not implement the v2.2 1,000 DM charge, six-hour cooldown or proposal XP award.'},
'FRE-01':{adapter:'createNaibCouncil',gap:'The independent Council vote already enforces current sietch deed, one vote per sietch, 24 hours, quorum and tie rejection. The v2.2 1,000 DM fee and quest XP award are not enabled.'}
};
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',SG:'Current Spacing Guild office deed',CLD:'Current clan delegate deed'};
export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status: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: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: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)?'Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically; existing publication/profile consumers display the result.':faithBlessing(d.id)?'Current Doci/Prior deed, target clan, expiry and cooldown are checked centrally; bonuses use funded quest consumers.':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:!!clanFaithDecision(d.id)||!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)})));
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'};
export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status: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: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: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)?'Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically; existing publication/profile consumers display the result.':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:!!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

@ -3,7 +3,7 @@ export function mountFaithBlessing(host,decisionId,{fetcher=fetch}={}){
const api=createUserAPI(fetcher),endpoint='/api/politics/faith-blessings',status=el('p','Reading your current faith appointment…'),label=el('label','Clan'),select=el('select'),review=el('p'),prepare=el('button','Review blessing'),confirm=el('button','Confirm blessing'),cancel=el('button','Cancel review'),refresh=el('button','Refresh');status.setAttribute('role','status');select.setAttribute('aria-label','Clan receiving this blessing');label.append(select);for(const b of [prepare,confirm,cancel,refresh])b.type='button';confirm.hidden=cancel.hidden=true;host.append(status,label,review,prepare,confirm,cancel,refresh);let choices=[],pending=null,busy=false,uncertain=false;
const selected=()=>choices.find(c=>c.id===select.value),definition=()=>selected()?.decisions.find(d=>d.catalogueId===decisionId);
function controls(){select.disabled=busy||!!pending;prepare.disabled=busy||!!pending||!definition()?.available;confirm.disabled=busy||!pending;cancel.disabled=busy||uncertain;refresh.disabled=busy;}
function describe(){const d=definition();status.textContent=!d?'No eligible clan and current Doci/Prior appointment found.':d.effect+' '+(d.available?'Ready.':'Next use: '+new Date(d.cooldownUntil).toLocaleString())+' Overlapping blessings remain at 2×.';controls();}
function describe(){const d=definition();status.textContent=!d?'No consenting clan and current faith leader/officer appointment found.':d.effect+' '+(d.available?'Ready.':'Next use: '+new Date(d.cooldownUntil).toLocaleString())+' Overlapping blessings remain at 2×.';controls();}
async function load(){busy=true;controls();try{const data=await api.request(endpoint);if(!host.isConnected)return;const old=select.value;choices=data.clans.filter(c=>c.decisions.some(d=>d.catalogueId===decisionId));select.replaceChildren();for(const c of choices){const option=el('option',c.name);option.value=c.id;select.append(option);}if(choices.some(c=>c.id===old))select.value=old;describe();}catch(e){status.textContent=e.message;}finally{busy=false;controls();}}
select.onchange=describe;prepare.onclick=()=>{if(!definition()?.available)return;pending={requestId:crypto.randomUUID(),decisionId:definition().id,clanId:select.value};review.textContent=definition().title+' for '+selected().name+'. Duration: '+definition().durationMs/60000+' minutes. Cooldown: '+definition().cooldownMs/3600000+' hours.';confirm.hidden=cancel.hidden=false;controls();};
cancel.onclick=()=>{if(uncertain)return;pending=null;confirm.hidden=cancel.hidden=true;review.textContent='';controls();};confirm.onclick=async()=>{if(!pending||busy)return;busy=true;controls();try{await api.request(endpoint,pending);pending=null;uncertain=false;confirm.hidden=cancel.hidden=true;review.textContent='Blessing recorded. Eligible quest rewards now use the active blessing.';await load();}catch(e){uncertain=!!e.uncertain;status.textContent=e.message+(uncertain?' Retry this same confirmation to recover its result.':'');if(!uncertain){pending=null;confirm.hidden=cancel.hidden=true;}}finally{busy=false;controls();}};refresh.onclick=load;load();

View file

@ -15,12 +15,12 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
async function load(){busy=true;controls();try{const data=await api.request(endpoint+'?decisionId='+encodeURIComponent(id)+(search?'&search='+encodeURIComponent(search.value):''));if(!host.isConnected)return;current=data;
const selected=account.value;account.replaceChildren();for(const a of data.accounts){const o=el('option',a.name+' · '+a.number+' · '+(Number(a.availableMinor)/100).toFixed(2)+' DM available');o.value=a.id;account.append(o);}if(data.accounts.some(a=>a.id===selected))account.value=selected;
if(recipient){const selected=recipient.value;recipient.replaceChildren();for(const r of data.recipients){const o=el('option',r.username);o.value=r.id;recipient.append(o);}if(data.recipients.some(r=>r.id===selected))recipient.value=selected;}
status.textContent=(data.canManage?'Current office verified. ':'Current elected office required. ')+(d.feeMinor/100).toFixed(2)+' DM from the selected office account · '+d.xp+' Reputation XP · Reputation level '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.');
status.textContent=(data.canManage?'Current office verified. ':'Current elected office required. ')+(d.feeMinor/100).toFixed(2)+' DM from the selected office account · '+d.xp+' Reputation points · Reputation level '+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==='proclamation'?{title:title.value,body:body.value}:{recipientId:recipient.value,citation:citation.value};
if(!account.value||d.kind==='proclamation'&&(title.value.trim().length<3||body.value.trim().length<10)||d.kind==='honour'&&(!recipient.value||citation.value.trim().length<3)){status.textContent='Choose funding and complete the announcement or citation.';return;}
pending={decisionId:id,requestId:crypto.randomUUID(),sourceAccount:account.value,...payload,confirmed:true};review.textContent='Confirm '+d.title+(recipient?' for '+recipient.selectedOptions[0].textContent:' “'+title.value.trim()+'”')+' · '+(d.feeMinor/100).toFixed(2)+' DM from '+account.selectedOptions[0].textContent+'. '+d.xp+' Reputation XP; cooldown '+d.cooldownMs/3600000+' hours.';confirm.hidden=false;controls();
pending={decisionId:id,requestId:crypto.randomUUID(),sourceAccount:account.value,...payload,confirmed:true};review.textContent='Confirm '+d.title+(recipient?' for '+recipient.selectedOptions[0].textContent:' “'+title.value.trim()+'”')+' · '+(d.feeMinor/100).toFixed(2)+' DM from '+account.selectedOptions[0].textContent+'. '+d.xp+' Reputation points; cooldown '+d.cooldownMs/3600000+' hours.';confirm.hidden=false;controls();
};
confirm.onclick=async()=>{if(busy||!pending)return;busy=true;controls();try{const receipt=await api.request(endpoint,pending);pending=null;confirm.hidden=true;review.textContent='Completed. J.A.R.V.I.S. reference: '+receipt.keyId;if(title){title.value='';body.value='';}if(citation)citation.value='';await load();}catch(e){status.textContent=e.message+(e.uncertain?' Retry this same confirmation to check or complete it without a second charge.':'');if(!e.uncertain){pending=null;confirm.hidden=true;}}finally{busy=false;controls();}};
refresh.onclick=load;if(find)find.onclick=load;load();

View file

@ -1,3 +1,4 @@
import {POLITICAL_DECISION_CATALOGUE} from '../political-decision-policy.mjs';
import {CLAN_FAITH_DECISIONS} from '../clan-faith-policy.mjs';
import {TRADE_DECISIONS} from '../world-trade-policy.mjs';
import {decisionCooldownMs} from '../action-cooldown-policy.mjs';
@ -379,7 +380,7 @@ export const MISSION_BRANCHES=[
];
export const DECISION_CATALOGUE=[
IMPERIAL_PASSAGE_DECISION,
...FAITH_BLESSING_CATALOGUE,
...FAITH_BLESSING_CATALOGUE.filter(d=>d.office==='NF'),
{
"id": "IMP-01",
"title": "Pax Imperialis",
@ -947,4 +948,4 @@ export const DECISION_CATALOGUE=[
"cost": "2,500 / 72h",
"office": "CLD"
}
,...TRADE_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE',spacing_guild:'SG'})[d.office],xp:0,cost:'0 / 7d',xpType:'pol',executionStatus:'world-trade-controller'}))].flatMap(decision=>decision.office==='BG'&&decision.id!=='BG-01'?[decision,{...decision,id:decision.id.replace('BG-','NF-'),office:'NF',copiedFrom:decision.id,title:decision.title.replaceAll('Sisterhood','Church'),effect:decision.effect.replaceAll('Sisterhood','Church')}]:[decision]).concat(CLAN_FAITH_DECISIONS.map(d=>({...d,office:d.office==='muad_dib'?'NF':'BG',cost:'0 / 24h',xpType:'pol',executionStatus:'clan-faith-controller'}))).map(decision=>Object.freeze({...decision,cooldownMs:decisionCooldownMs(decision)}));
,...POLITICAL_DECISION_CATALOGUE.filter(d=>d.id.endsWith('-PROCLAIM')),...TRADE_DECISIONS.map(d=>({...d,office:({atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',fremen:'FRE',spacing_guild:'SG'})[d.office],xp:0,cost:'0 / 7d',xpType:'pol',executionStatus:'world-trade-controller'}))].flatMap(decision=>decision.office==='BG'&&decision.id!=='BG-01'?[decision,{...decision,id:decision.id.replace('BG-','NF-'),office:'NF',copiedFrom:decision.id,title:decision.title.replaceAll('Sisterhood','Church'),effect:decision.effect.replaceAll('Sisterhood','Church')}]:[decision]).concat(CLAN_FAITH_DECISIONS.map(d=>({...d,office:d.office==='muad_dib'?'NF':'BG',cost:'0 / 24h',xpType:'pol',executionStatus:'clan-faith-controller'}))).map(decision=>Object.freeze({...decision,...POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id),...FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id),cooldownMs:FAITH_BLESSING_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??POLITICAL_DECISION_CATALOGUE.find(d=>d.id===decision.id)?.cooldownMs??decisionCooldownMs(decision)}));

View file

@ -1,3 +1,4 @@
import {faithBlessing} from '../faith-blessing-policy.mjs';
import {mountFaithInvitation} from './cp-v2-clan-faith.mjs';
import {mountWorldTrade} from './cp-v2-world-trade.mjs';
import {appendOfficeMissionPreview,appendOfficeMissionBanner,appendOfficeDecisionBanner,planningImage} from './cp-v2-war-planning.mjs';
@ -39,7 +40,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
const roster=el('div',undefined,'progression-roster');for(const member of members.slice(0,12)){const person=el('figure');const avatar=member.avatar||member.avatarUrl||(member.username?'https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username):null);if(avatar&&/^https:\/\//.test(avatar)){const img=el('img');img.src=avatar;img.alt='';person.append(img);}else person.append(image(CONTEXTS[activeContext][1]));person.append(el('figcaption',member.displayName||member.display_name||member.name||member.username||'Member'));roster.append(person);}if(!members.length)roster.append(image(CONTEXTS[activeContext][1]),el('p','Your verified roster and avatars will appear here. No sample memberships are assigned.'));gallery.append(roster);
}
function details(row,isDecision=false){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected '+(isDecision?'decision':'mission'));pane.append(image(isDecision?(POL_PLANNING_ART[officeCode]?.banner||'exchange-political-positions-v1.png'):artFor(branch)),el('small',row.id),el('h3',lore(row.title)),el('p',isDecision?lore(row.effect):row.title==='Repair Your Starter Kit'?'Collect four repair components and surrender the damaged Q0 kit to receive one intact kit.':'Complete the verified objective. Conditions and progress will be supplied by J.A.R.V.I.S.'));
if(isDecision&&['NF-08','NF-09','NF-10'].includes(row.id)){mountFaithBlessing(pane,row.id);return pane;}
if(isDecision&&faithBlessing(row.id)){mountFaithBlessing(pane,row.id);return pane;}
if(isDecision&&politicalDecision(row.id)){mountPoliticalDecision(pane,row.id);return pane;}
if(isDecision&&row.executionStatus==='clan-faith-controller'){mountFaithInvitation(pane,row.office==='NF'?'muad_dib':'veiled_concord');return pane;}
if(isDecision&&row.executionStatus==='world-trade-controller'){mountWorldTrade(pane,row.id);return pane;}
@ -60,7 +61,7 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false,
connectorObserver=new ResizeObserver(connect);connectorObserver.observe(tree);requestAnimationFrame(connect);
}
function renderDecisions(){if(activeContext==='politics')appendOfficeDecisionBanner(content,officeCode);if(activeContext==='politics'&&!manage){const live=el('div');content.append(live);disposePersonal=mountOfficeRebellionDecisions(live,{officeKey:organisation?.id||({IMP:'emperor',ATR:'atreides',HAR:'harkonnen',COR:'corrino',ORD:'ordos',FRE:'fremen',BG:'veiled_concord',NF:'muad_dib',SG:'spacing_guild',CLD:'clan_delegate'})[officeCode]});}const toolbar=el('div',undefined,'progression-toolbar'),search=el('input');search.type='search';search.placeholder='Search decisions';search.setAttribute('aria-label','Search decisions');search.value=query;search.oninput=()=>{query=search.value;renderDecisionsList();};toolbar.append(search);if(activeContext==='personal'&&xpKind==='pol'){const chooser=field('Questgiver',POL_QUEST_BRANCHES.map(b=>b.title));chooser.querySelector('select').selectedIndex=POL_QUEST_BRANCHES.findIndex(b=>b.id===polDecisionBranch);chooser.onchange=e=>{polDecisionBranch=POL_QUEST_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(chooser);}if((dashboard&&activeContext==='politics')||manage){const chooser=field('Office catalogue',OFFICES.map(([,name])=>name));chooser.querySelector('select').selectedIndex=OFFICES.findIndex(([id])=>id===officeCode);chooser.onchange=e=>{officeCode=OFFICES[e.target.selectedIndex][0];selected=null;render();};toolbar.append(chooser);}content.append(toolbar);const listHost=el('div');content.append(listHost);
function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',row.executionStatus==='clan-faith-controller'?'Invite a clan':row.executionStatus==='world-trade-controller'?'Review trade decision':politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':['NF-08','NF-09','NF-10'].includes(row.id)?'Prepare clan blessing':row.executionStatus==='war-exchange-controller'?'Manage war agreement':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList();
function renderDecisionsList(){listHost.replaceChildren();let rows=activeContext==='politics'||manage?[...DECISION_CATALOGUE.filter(d=>d.office===officeCode),...officeDecisionPreviews(officeCode)]:activeContext==='personal'&&xpKind==='pol'?(POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.decisions||[]):activeContext==='personal'?[{id:'P-MARK',title:'Equipment Mark eligibility',effect:'Level, materials and equipment restrictions remain necessary.',level:0,xp:0,cost:'Pending configuration'},{id:'P-RARITY',title:'Rarity enhancement eligibility',effect:'Use the existing rarity and Legendary upgrade policy.',level:0,xp:0,cost:'Pending configuration'},{id:'P-SEASON',title:'Seasonal completion entitlement',effect:'One non-tradable completion kit after all mandatory objectives.',level:0,xp:0,cost:'Earned entitlement'}]:[];rows=rows.filter(r=>(r.title+' '+r.effect).toLowerCase().includes(query.toLowerCase()));if(!rows.length){listHost.append(el('p','No decision definitions available for this selection. No authority is inferred.'));return;}selected=rows.find(r=>r.id===selected)?.id||rows[0].id;const layout=el('div',undefined,'progression-layout'),cards=el('div',undefined,'progression-decisions');for(const row of rows){const card=button('',()=>{selected=row.id;dossier.show(details(row,true),{title:lore(row.title),returnFocus:card});},'progression-decision');card.setAttribute('aria-haspopup','dialog');card.setAttribute('aria-pressed',String(row.id===selected));const art=activeContext==='politics'?POL_PLANNING_ART[officeCode]:activeContext==='personal'&&xpKind==='pol'?POL_PLANNING_ART[POL_QUEST_BRANCHES.find(b=>b.id===polDecisionBranch)?.office]:null;card.append(image(art?.banner||'exchange-political-positions-v1.png'),...(art?[planningImage(art.seal,art.title+' seal','pol-decision-seal')]:[]),el('small',row.id),el('strong',row.title),el('span',row.executionStatus==='clan-faith-controller'?'Invite a clan':row.executionStatus==='world-trade-controller'?'Review trade decision':politicalDecision(row.id)?'Review funded decision':row.id==='IMP-10'?'Manage House passage':faithBlessing(row.id)?'Prepare clan blessing':row.executionStatus==='war-exchange-controller'?'Manage war agreement':'View proposal · execution unavailable'));cards.append(card);}layout.append(cards);listHost.append(layout);}renderDecisionsList();
}
function render(){dossier.close();connectorObserver?.disconnect();disposePersonal?.();disposePersonal=null;notice.textContent=activeContext==='personal'&&!manage?(xpKind==='pol'?'Reputation missions use verified J.A.R.V.I.S. records and their system questgivers. Decision execution awaits configuration.':'Personal missions use verified J.A.R.V.I.S. records. Decision and organisation integrations remain in preview.'):'Connected decisions open a review and confirmation. Other proposals remain unavailable until their consumers are connected.';root.dataset.context=activeContext;notice.hidden=activeContext==='personal'&&!manage;nav.hidden=report.available&&activeContext==='personal'&&!manage;report.setNavigation(xpKind,tab);report.showBranches(activeContext==='personal');xpNav.replaceChildren();xpNav.hidden=activeContext!=='personal'||manage||report.available;if(!xpNav.hidden)for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const b=button(label,()=>{xpKind=kind;selected=null;render();});b.setAttribute('aria-pressed',String(kind===xpKind));xpNav.append(b);}contextNav.replaceChildren();for(const[id,[label]]of Object.entries(CONTEXTS)){const b=button(label,()=>{activeContext=id;selected=null;query='';render();});b.setAttribute('aria-pressed',String(id===activeContext));contextNav.append(b);}renderGallery();nav.replaceChildren();for(const[id,label]of [['missions',manage?'Mission Definitions':'Missions'],['decisions',manage?'Decision Definitions':'Decisions'],...(manage?[['rewards','Progression & Rewards']]:[]),['history','History']]){const b=button(label,()=>{tab=id;selected=null;render();});b.setAttribute('aria-pressed',String(tab===id));nav.append(b);}content.replaceChildren();if(activeContext==='clan'&&!manage){notice.hidden=true;disposePersonal=mountClanRebellions(content,{clanId:organisation?.id||null,embedded:true,view:tab,onDecisions:()=>{tab='decisions';render();}});return;}if(activeContext==='personal'&&!manage&&['missions','history'].includes(tab))disposePersonal=mountPersonalProgression(content,{view:tab,apiBase:xpKind==='pol'?'/api/progression/pol':'/api/progression',externalBranches:report.available,initialBranch:branch,onData:data=>report.setJournal(xpKind,data),onBranches:(rows,id)=>{branch=id;report.setBranches(rows,id);}});else if(tab==='missions')renderMissions();else if(tab==='decisions')renderDecisions();else if(tab==='rewards'){content.append(el('h3','Progression & Rewards'),field('Season cap',['70 · proposed']),field('Milestone announcements',['Halfway and completion only']),el('p','Rewards, XP curves, repair recipes and signing editions await backend review. No configuration writes enabled.'));}else content.append(el('h3','J.A.R.V.I.S. History'),el('p','Verified completion, claims, decisions and any staff overrides will appear here after integration. No sample audit records are shown.'));}
render();return()=>{dossier.dispose();connectorObserver?.disconnect();disposePersonal?.();report.dispose();root.remove();};

View file

@ -4,6 +4,6 @@ export const FAITH_BLESSINGS=Object.freeze([
{id:'holy-day',catalogueId:'NF-08',title:'Holy Day',role:'doci',xp:2,dm:1,durationMs:hour,cooldownMs:FAITH_DECISION_COOLDOWNS['holy-day'],effect:'Double Personal and Reputation quest XP for the selected clan for one hour.'},
{id:'sacred-bounty',catalogueId:'NF-09',title:'Sacred Bounty',role:'doci',xp:1,dm:2,durationMs:hour,cooldownMs:FAITH_DECISION_COOLDOWNS['sacred-bounty'],effect:'Double funded Reputation and R&D quest DM rewards for the selected clan for one hour.'},
{id:'prior-blessing',catalogueId:'NF-10',title:'Blessed by the Prior',role:'prior',xp:2,dm:1,durationMs:15*60_000,cooldownMs:FAITH_DECISION_COOLDOWNS['prior-blessing'],effect:'Double Personal and Reputation quest XP for your assigned clan for fifteen minutes.'}
].map(Object.freeze));
].flatMap(d=>[Object.freeze({...d,office:'muad_dib'}),Object.freeze({...d,id:({'holy-day':'sisterhood-discipline','sacred-bounty':'sisterhood-patronage','prior-blessing':'reverend-blessing'})[d.id],catalogueId:({'holy-day':'BG-01','sacred-bounty':'BG-03','prior-blessing':'BG-07'})[d.id],title:({'holy-day':'The Bene Gesserit Way','sacred-bounty':'Sisterhood Patronage','prior-blessing':"Sisterhood’s Favour"})[d.id],office:'veiled_concord'})]));
export const faithBlessing=id=>FAITH_BLESSINGS.find(d=>d.id===id||d.catalogueId===id)||null;
export const FAITH_BLESSING_CATALOGUE=Object.freeze(FAITH_BLESSINGS.map(d=>Object.freeze({id:d.catalogueId,title:d.title,effect:d.effect,office:'NF',level:0,xp:0,cost:'No charge / '+d.cooldownMs/86400_000+'d',cooldownMs:d.cooldownMs})));
export const FAITH_BLESSING_CATALOGUE=Object.freeze(FAITH_BLESSINGS.map(d=>Object.freeze({id:d.catalogueId,title:d.title,effect:d.effect,office:d.office==='muad_dib'?'NF':'BG',level:0,xp:0,cost:'No charge / '+d.cooldownMs/86400_000+'d',cooldownMs:d.cooldownMs})));

View file

@ -14,11 +14,12 @@ export const MASTER_KEY_TEMPLATES=[
action('company.subsidiary','Subsidiary founding','company-subsidiary',[field('parentCompanyId','Mother company'),field('recipient','Recipient')]),
action('company.royal','Royal company charter','staff-company-royal',[field('companyId','Company'),reference])]},
{id:'politics',label:'POL & orders',actions:[
action('faith.invitation','Invite a clan to a faith','entity-state',[field('decisionId','Faith decision','select',{options:['BG-CONVERT','NF-CONVERT']}),field('clanId','Active clan UUID'),field('requestId','Invitation UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createClanFaith.offer',executionStatus:'current-faith-officer-service',effect:'Current Royal faith leader or canonical appointed officer, Reputation 5, one invitation per office per 24 hours. Signed offer expires after 72 hours. It changes no clan faith, membership, owner, vote or account. Target-clan owner must separately consent; missionary laws are checked again on acceptance.'}),
action('faith.invitation','Invite a clan to a faith','entity-state',[field('decisionId','Faith decision','select',{options:['BG-CONVERT','NF-CONVERT']}),field('clanId','Active clan UUID'),field('requestId','Invitation UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createClanFaith.offer',executionStatus:'current-faith-officer-service',effect:'Current Royal faith leader or canonical appointed officer, Reputation 5, one invitation per office per 24 hours. Signed offer expires after 72 hours. It changes no clan faith, membership, owner, vote or account. Target-clan owner must separately consent; any configured missionary-law consumer is checked again on acceptance.'}),
action('faith.blessing','Consenting clan faith bonus','entity-state',[field('decisionId','Registered faith bonus','select',{options:['holy-day','sacred-bounty','prior-blessing','sisterhood-discipline','sisterhood-patronage','reverend-blessing']}),field('clanId','Consenting clan UUID'),field('requestId','Bonus UUID')],{version:2,webIssue:false,recordOnly:true,domainAdapter:'createFaithBlessings/faithMultipliers/validFaithReward',executionStatus:'current-faith-authority-and-owner-consent-service',effect:'Old Faith and New Faith share the existing clan XP/funded-DM bonus consumer. Revalidate the Royal office, current leader or assigned clan officer, owner-approved allegiance, source term and cooldown. Bonuses cap at twice the normal reward and expire with the source appointment. New reward proofs bind the accepted faith at claim time; a later lawful conversion cannot redirect or cancel an already earned queued payment. Existing pre-consent blessings retain only their original expiry and become inactive upon an opposing clan choice.'}),
action('progression.faith-service-policy','Consenting faith community quest policy','progression-policy',[],{version:6,webIssue:false,recordOnly:true,domainAdapter:'ensureFaithQuestPolicy/faithQuestEvidence',executionStatus:'verified-consent-evidence-consumer',effect:'Install six Old Faith and New Faith Reputation quests through policy:POL:S01:v6. Count one, three and five distinct currently consenting active clans invited by the current authorised faith specialist. Re-read the signed invitation and legal-owner consent, current faith and current authority at claim. Small separate Personal XP rewards; fixed DM queued from P&O to the faith office payment account. New research payments use the same transaction and Basic organisations route to the current legal owner; legacy payment receipts remain unchanged.'}),
action('faith.clan-consent','Clan owner faith decision','entity-state',[field('clanId','Current clan UUID'),field('offerId','Sealed invitation UUID'),field('choice','Clan choice','select',{options:['accept','decline']}),field('requestId','Consent UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createClanFaith.reply',executionStatus:'current-legal-clan-owner-only',effect:'Re-read the current clan deed, signed invitation and current faith mandate. Accepting records the clan’s single faith and a seven-day change cooldown. Declining leaves allegiance unchanged. Immutable owner consent, key, offer and faith update commit together; revoking the latest receipt never revives an older faith. No personal voting, membership, bank or ownership change.'}),
action('politics.world-trade','House levy or Guild embargo','entity-state',[field('decisionId','Registered trade decision'),field('requestId','Request UUID'),field('percent','House levy 0–5%','number',{required:false}),field('world','Embargo world','select',{required:false,options:['arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv']})],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createWorldTradeGovernance',executionStatus:'authenticated-office-trade-consumer',effect:'Current Royal elected House/Guild authority and Reputation checked again under transaction locks. House levy 1–5% (0 repeals), seven-day successor-safe cooldown. Guild embargo one world for 24h, seven-day global cooldown. Read creation PDC only; never infer from listing location or lore. No default activation, XP or balance issuance. Exchange stock is preserved, owned withdrawals and committed deliveries remain available. Seller tax and gross purchase settle with stock and exact native delivery on one bank transaction; immutable receipts prevent repeated levy.'}),
action('politics.ceremonial-decision','Funded political publication or recognition','entity-state',[field('decisionId','Registered decision','select',{options:['IMP-04','IMP-09','ATR-03','COR-03']}),field('sourceAccount','Authorised office funding account'),field('requestId','Request UUID'),field('title','Proclamation title','text',{required:false}),field('body','Proclamation message','textarea',{required:false}),field('recipientId','Honour recipient','text',{required:false}),field('citation','Honour citation','textarea',{required:false})],{webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute',executionStatus:'current-elected-office-only',effect:'Atomic office-account charge, fixed Reputation XP, ordinary system ESK instrument and existing publication/profile effect. IMP-04: level 5, 1000 DM, 100 Reputation XP, 6h office cooldown. IMP-09: level 20, 5000 DM, 300 XP, 48h. ATR-03/COR-03: level 20, 2500 DM, 300 XP, 72h. Recognition is cosmetic for 30 days; House recipients must belong to the corresponding House. No self-awards, ranks, appointments, votes or native permission changes. Request retries cannot charge twice; cooldown survives office succession.'}),
action('politics.ceremonial-decision','Funded political publication or recognition','entity-state',[field('decisionId','Registered decision','select',{options:['IMP-04','IMP-09','ATR-03','COR-03','ATR-PROCLAIM','HAR-PROCLAIM','COR-PROCLAIM','ORD-PROCLAIM','SG-PROCLAIM','BG-04','NF-04']}),field('sourceAccount','Authorised office funding account'),field('requestId','Request UUID'),field('title','Proclamation title','text',{required:false}),field('body','Proclamation message','textarea',{required:false}),field('recipientId','Honour recipient','text',{required:false}),field('citation','Honour citation','textarea',{required:false})],{webIssue:false,recordOnly:true,version:2,domainAdapter:'createPoliticalDecisions.execute',executionStatus:'current-elected-office-only',effect:'Atomic office-account charge, fixed Reputation XP, ordinary system ESK instrument and existing publication/profile effect. IMP-04: level 5, 1000 DM, 100 Reputation XP, 6h office cooldown. IMP-09: level 20, 5000 DM, 300 XP, 48h. ATR-03/COR-03: level 20, 2500 DM, 300 XP, 72h. House/Guild/faith proclamations: level 5, 500 DM, 50 Reputation points, 24h office cooldown, existing office-scoped archive. Legacy publication routes use this same funded consumer and cannot write for free. Recognition is cosmetic for 30 days; House recipients must belong to the corresponding House. No self-awards, ranks, appointments, votes or native permission changes. Request retries cannot charge twice; cooldown survives office succession.'}),
action('politics.rebellion','Declare open rebellion','quest',[field('clanId','Attacking clan'),field('officeKey','Elected office'),field('expectedTermId','Current office deed'),field('expectedHomeBlockId','Political office Home Block')],{webIssue:false,domainAdapter:'rebellionQuests.declare',executionStatus:'clan-leader-decision',effect:'Start a same-House rebellion after the previous clan key is 15 days old. Verified office Home Block victory grants the remaining term; defeat can place the clan under the office. First successful rebellion receives 5x additional base reward; verified Imperial counterchallenges receive 2x base.'}),
action('clan.homeblock-victory','Verified rebellion Home Block victory','quest-milestone',[field('questKeyId','Declared rebellion key'),field('eventId','Verified game capture event')],{webIssue:false,recordOnly:true,domainAdapter:'rebellionQuests.recordCapture',executionStatus:'trusted-game-producer-only',effect:'Signed game evidence consumed by the existing rebellion quest. No browser victory or Minecraft producer is included.'}),
action('politics.passive-order','Protected passive Order charter','staff-parent-link',[reference],{domainAdapter:'ensureCrysknifePassiveOrder',fixedTargets:['Order of the Crysknife','Emperor'],effect:'Convert the protected honorary Order to passive POL membership, retaining fixed memorial leadership, private boards and civic records. Mother authority is limited to MOTD and account.'}),

View file

@ -3,6 +3,17 @@ export const POLITICAL_DECISIONS=Object.freeze([
{id:'IMP-04',office:'emperor',title:'Imperial Proclamation',kind:'proclamation',level:5,xp:100,feeMinor:100000,cooldownMs:6*3600000},
{id:'IMP-09',office:'emperor',title:'Imperial Honour',kind:'honour',level:20,xp:300,feeMinor:500000,cooldownMs:48*3600000},
{id:'ATR-03',office:'atreides',house:'atreides',title:'Honour of the Duke',kind:'honour',level:20,xp:300,feeMinor:250000,cooldownMs:72*3600000},
{id:'COR-03',office:'corrino',house:'corrino',title:'Noble Recognition',kind:'honour',level:20,xp:300,feeMinor:250000,cooldownMs:72*3600000}
{id:'COR-03',office:'corrino',house:'corrino',title:'Noble Recognition',kind:'honour',level:20,xp:300,feeMinor:250000,cooldownMs:72*3600000},
...[
['ATR-PROCLAIM','atreides','Ducal Proclamation','house:atreides'],
['HAR-PROCLAIM','harkonnen','Baronial Directive','house:harkonnen'],
['COR-PROCLAIM','corrino','Court Proclamation','house:corrino'],
['ORD-PROCLAIM','ordos','Consortium Communiqué','house:ordos'],
['SG-PROCLAIM','spacing_guild','Guild Bulletin','spacing_guild'],
['BG-04','veiled_concord','Political Prophecy','house:veiled_concord'],
['NF-04','muad_dib','The Word of Muad’Dib','house:muad_dib']
].map(([id,office,title,scope])=>({id,office,title,scope,kind:'proclamation',level:5,xp:50,feeMinor:50000,cooldownMs:24*3600000}))
].map(d=>Object.freeze({...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.feeMinor/100).toLocaleString('en-GB')+' / '+d.cooldownMs/3600000+'h',effect: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.':'Thirty-day ceremonial profile recognition. No office, rank, vote or permission is granted.'})));

View file

@ -2,11 +2,12 @@ import {mountPoliticalDecision} from './cp-v2/cp-v2-political-decisions.mjs';
const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
export function proclamationBox(kind,{editor=false}={}){
const names={house:'Faction',imperial:'Imperial',guild:'Spacing Guild'},seals={house:'office-house_leader.png',imperial:'emperor-v1.png',guild:'guild-envoy-v1.png'};
const root=el('article');root.className='politics-card';const art=el('img');art.src='https://www.dunerealms.com/assets/seals/'+seals[kind];art.alt='';art.width=art.height=72;root.append(art,el('h3',names[kind]+(editor?' Message settings':' Proclamations')));const status=el('p');status.role='status';const content=el('div');root.append(status,content);let page=1,requestId=null,version=0;
const root=el('article');root.className='politics-card';const art=el('img');art.src='https://www.dunerealms.com/assets/seals/'+seals[kind];art.alt='';art.width=art.height=72;root.append(art,el('h3',names[kind]+(editor?' Message settings':' Proclamations')));const status=el('p');status.role='status';const content=el('div');root.append(status,content);let page=1,version=0;
async function load(){const serial=++version;try{const response=await fetch('/api/politics/proclamations?kind='+kind+'&page='+page,{cache:'no-store'}),data=await response.json();if(!root.isConnected||serial!==version)return;if(!response.ok)throw Error(data.message||'Messages unavailable.');content.replaceChildren();status.textContent='';
if(!editor){if(data.post){content.append(el('h4',data.post.title));const body=el('p',data.post.body);body.className='honour-citation';content.append(body,el('small','Issued by '+data.post.author+' · '+new Date(Number(data.post.created_at)).toLocaleString('en-GB',{timeZone:'UTC'})+' GMT'));}else content.append(el('p','No proclamations have been published yet.'));const nav=el('nav');nav.className='politics-pagination';for(const [label,step]of [['Newer',-1],['Older',1]]){const b=el('button',label);b.type='button';b.disabled=step<0?page===1:page>=data.pages;b.onclick=()=>{page+=step;load();};nav.append(b);}nav.append(el('span','Page '+page+' of '+data.pages));content.append(nav);}
if(editor||kind==='guild'&&data.canPublish){if(!data.canPublish){content.append(el('p','Publishing is reserved for the current '+(kind==='house'?'faction leader':kind==='imperial'?'Emperor':'Guild Envoy')+'.'));return;}
if(kind==='imperial'){mountPoliticalDecision(content,'IMP-04');return;} const form=el('form');form.className='politics-charter';const field=(name,tag,max)=>{const label=el('label',name),input=el(tag);input.required=true;input.maxLength=max;label.append(input);form.append(label);return input;};const title=field('Title','input',120),body=field('Message','textarea',6000);title.minLength=3;body.minLength=10;body.rows=5;const consent=el('label');consent.className='politics-accept';const check=el('input');check.type='checkbox';check.required=true;consent.append(check,el('span','I confirm publication to this proclamation archive.'));const submit=el('button','Publish proclamation');submit.type='submit';form.append(consent,submit);content.append(form);form.onsubmit=async event=>{event.preventDefault();if(!form.reportValidity())return;submit.disabled=true;requestId||=crypto.randomUUID();try{const r=await fetch('/api/politics/proclamations?kind='+kind,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({requestId,title:title.value,body:body.value,confirmed:check.checked})}),v=await r.json();if(!r.ok)throw Error(v.message||'Publication failed.');requestId=null;form.reset();status.textContent='Proclamation published and archived.';}catch(error){status.textContent=error.message;}finally{submit.disabled=false;}};}
if(editor||kind==='guild'&&data.canPublish){if(!data.canPublish){content.append(el('p','Publishing is reserved for the current '+(kind==='house'?'faction leader':kind==='imperial'?'Emperor':'Guild leader')+'.'));return;}
if(data.decisionId)mountPoliticalDecision(content,data.decisionId);else content.append(el('p','Funded publication is unavailable for this office.'));}
}catch(error){if(serial===version)status.textContent=error.message;}}
queueMicrotask(load);return root;
}

View file

@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"sourceHash": "dc02b5c58b8cd30002c592be3d5fb4142614d648f9c21f6ec76a7022c30a548b",
"sourceHash": "19e19b7887345eeca81b2d7dc1bb7c817f7f0b02432cf1d0ed7d5aa7a5ea744f",
"actions": [
{
"id": "war.coalition-consent",
@ -467,7 +467,52 @@
"required": true
}
],
"effect": "Current Royal faith leader or canonical appointed officer, Reputation 5, one invitation per office per 24 hours. Signed offer expires after 72 hours. It changes no clan faith, membership, owner, vote or account. Target-clan owner must separately consent; missionary laws are checked again on acceptance.",
"effect": "Current Royal faith leader or canonical appointed officer, Reputation 5, one invitation per office per 24 hours. Signed offer expires after 72 hours. It changes no clan faith, membership, owner, vote or account. Target-clan owner must separately consent; any configured missionary-law consumer is checked again on acceptance.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "faith.blessing",
"label": "POL & orders · Consenting clan faith bonus",
"version": 2,
"keyType": "entity-state",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "decisionId",
"label": "Registered faith bonus",
"type": "select",
"required": true,
"options": [
"holy-day",
"sacred-bounty",
"prior-blessing",
"sisterhood-discipline",
"sisterhood-patronage",
"reverend-blessing"
]
},
{
"name": "clanId",
"label": "Consenting clan UUID",
"type": "text",
"required": true
},
{
"name": "requestId",
"label": "Bonus UUID",
"type": "text",
"required": true
}
],
"effect": "Old Faith and New Faith share the existing clan XP/funded-DM bonus consumer. Revalidate the Royal office, current leader or assigned clan officer, owner-approved allegiance, source term and cooldown. Bonuses cap at twice the normal reward and expire with the source appointment. New reward proofs bind the accepted faith at claim time; a later lawful conversion cannot redirect or cancel an already earned queued payment. Existing pre-consent blessings retain only their original expiry and become inactive upon an opposing clan choice.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
@ -591,7 +636,7 @@
{
"id": "politics.ceremonial-decision",
"label": "POL & orders · Funded political publication or recognition",
"version": 1,
"version": 2,
"keyType": "entity-state",
"fields": [
{
@ -610,7 +655,14 @@
"IMP-04",
"IMP-09",
"ATR-03",
"COR-03"
"COR-03",
"ATR-PROCLAIM",
"HAR-PROCLAIM",
"COR-PROCLAIM",
"ORD-PROCLAIM",
"SG-PROCLAIM",
"BG-04",
"NF-04"
]
},
{
@ -650,7 +702,7 @@
"required": false
}
],
"effect": "Atomic office-account charge, fixed Reputation XP, ordinary system ESK instrument and existing publication/profile effect. IMP-04: level 5, 1000 DM, 100 Reputation XP, 6h office cooldown. IMP-09: level 20, 5000 DM, 300 XP, 48h. ATR-03/COR-03: level 20, 2500 DM, 300 XP, 72h. Recognition is cosmetic for 30 days; House recipients must belong to the corresponding House. No self-awards, ranks, appointments, votes or native permission changes. Request retries cannot charge twice; cooldown survives office succession.",
"effect": "Atomic office-account charge, fixed Reputation XP, ordinary system ESK instrument and existing publication/profile effect. IMP-04: level 5, 1000 DM, 100 Reputation XP, 6h office cooldown. IMP-09: level 20, 5000 DM, 300 XP, 48h. ATR-03/COR-03: level 20, 2500 DM, 300 XP, 72h. House/Guild/faith proclamations: level 5, 500 DM, 50 Reputation points, 24h office cooldown, existing office-scoped archive. Legacy publication routes use this same funded consumer and cannot write for free. Recognition is cosmetic for 30 days; House recipients must belong to the corresponding House. No self-awards, ranks, appointments, votes or native permission changes. Request retries cannot charge twice; cooldown survives office succession.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true

View file

@ -31,11 +31,11 @@ export async function faithAuthority(tx,office,actor,now,{clanId=null,lock=false
if(!faithPOL(office))return null;
let term;try{term=await officeDeedFor(tx,office,now,{lock});}catch(e){if([403,404,409].includes(e.status))return null;throw e;}
const holder=await officeAuthority(tx,{office},{id:term.user_id},now,lock);if(!holder||holder.termId!==term.id)return null;
if(actor.id===term.user_id)return{termId:term.id,clanIds:null};
if(actor.id===term.user_id)return{termId:term.id,clanIds:null,expiresAt:Number(term.expires_at)};
const appointments=(await activePoliticalAppointments(tx,{userId:actor.id,clock:()=>now})).filter(a=>a.office_key===office&&a.appointment_type==='job'&&a.role_key==='officer'&&a.title===faithPOL(office).roles.officer);
const general=appointments.find(a=>a.target_kind===null);if(general){if(lock)await tx.first('SELECT id FROM political_appointment_deeds WHERE id=? FOR UPDATE',[general.id]);return{termId:term.id,clanIds:null};}
const ids=[];for(const a of appointments){if(a.target_kind!=='clan'||clanId&&a.target_id!==clanId)continue;if(await tx.first('SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_id=?',[actor.id,a.target_id]))ids.push(a.target_id);}
return ids.length?{termId:term.id,clanIds:ids}:null;
const general=appointments.find(a=>a.target_kind===null);if(general){if(lock)await tx.first('SELECT id FROM political_appointment_deeds WHERE id=? FOR UPDATE',[general.id]);return{termId:term.id,clanIds:null,expiresAt:Math.min(Number(term.expires_at),Number(general.expires_at))};}
const ids=[];let expiresAt=0;for(const a of appointments){if(a.target_kind!=='clan'||clanId&&a.target_id!==clanId)continue;if(await tx.first('SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_id=?',[actor.id,a.target_id])){ids.push(a.target_id);expiresAt=Math.max(expiresAt,Number(a.expires_at));}}
return ids.length?{termId:term.id,clanIds:ids,expiresAt:Math.min(Number(term.expires_at),expiresAt)}:null;
}
async function legalClanOwner(tx,actor,clanId){await tx.first('SELECT id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[clanId]);const deed=await readClanDeed(tx,clanId);if(deed.owner?.id!==actor.id)fail('Only this clan’s current legal owner can choose its faith.',403);return deed;}
export function createClanFaith(base,keys,{clock=Date.now,isOutlawed=async()=>false}={}){

View file

@ -2,11 +2,20 @@ import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
import {currentOfficeController,entityParent} from './entity-relations.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';import {validUuid} from './game-link.mjs';
import {FAITH_BLESSINGS,faithBlessing} from '../control-panel/public/faith-blessing-policy.mjs';
import {faithAuthority,currentClanFaith} from './clan-faith.mjs';
import {boardReadStore} from './board-deed-source.mjs';
export const FAITH_BLESSING_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_faith_blessings(request_id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,decision_id VARCHAR(24) NOT NULL,clan_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,source_term_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null;
const fail=(message,status=409)=>{throw Object.assign(Error(message),{status});};
const proofSQL="SELECT b.*,k.id verified_key FROM jarvis_faith_blessings b JOIN organisation_keys k ON k.id=b.key_id AND k.key_type='entity-state' AND k.account_id=? AND k.scope_id=CONCAT('state:faith-blessing:',b.request_id) AND k.revoked_at IS NULL";
async function authority(db,actor,clanId,now,{lock=false}={}){
async function authority(db,actor,clanId,now,{lock=false,office='muad_dib'}={}){
db=boardReadStore(db,db);
if(office!=='muad_dib'){
if(!await first(db,'SELECT id FROM site_clans WHERE id=? AND active=1'+(lock?' FOR UPDATE':''),[clanId]))return null;
const a=await faithAuthority(db,office,actor,now,{clanId,lock});if(!a)return null;const term=await first(db,'SELECT user_id,expires_at FROM political_office_terms WHERE id=?'+(lock?' FOR UPDATE':''),[a.termId]);if(!term)return null;
if(term.user_id===actor.id)return{role:'doci',termId:a.termId,expiresAt:Number(term.expires_at)};
return await first(db,'SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_id=?',[actor.id,clanId])?{role:'prior',termId:a.termId,expiresAt:a.expiresAt}:null;
}
const charter=await first(db,"SELECT c.staff_key_id FROM political_office_charters c JOIN organisation_keys k ON k.id=c.staff_key_id AND k.key_type='staff-office-royal' AND k.scope_id='office:muad_dib' AND k.account_id=? AND k.used_at IS NOT NULL AND k.revoked_at IS NULL WHERE c.office_key='muad_dib' AND c.charter_kind='royal'"+(lock?' FOR UPDATE':''),[STAFF_OFFICE_ACCOUNT_ID]);if(!charter)return null;
const clan=await first(db,'SELECT id FROM site_clans WHERE id=? AND active=1'+(lock?' FOR UPDATE':''),[clanId]);if(!clan)return null;
const leader=await currentOfficeController(db,'muad_dib',now);
@ -15,12 +24,13 @@ async function authority(db,actor,clanId,now,{lock=false}={}){
}
async function previous(db,d,clanId){return first(db,'SELECT * FROM jarvis_faith_blessings WHERE decision_id=?'+(d.role==='prior'?' AND clan_id=?':'')+' ORDER BY created_at DESC,request_id DESC LIMIT 1',d.role==='prior'?[d.id,clanId]:[d.id]);}
export function createFaithBlessings(db,keys,{clock=Date.now}={}){
async function read(actor){const clans=await db.query('SELECT id,name FROM site_clans WHERE active=1 ORDER BY name LIMIT 1000'),choices=[];for(const clan of clans){const a=await authority(db,actor,clan.id,clock());if(!a)continue;const decisions=[];for(const d of FAITH_BLESSINGS){if(a.role!=='doci'&&d.role!=='prior')continue;const last=await previous(db,d,clan.id),until=last?Number(last.created_at)+d.cooldownMs:null;decisions.push({...d,available:!until||clock()>=until,cooldownUntil:until});}choices.push({...clan,role:a.role,decisions});}return{clans:choices,stacking:'Overlapping blessings cap at 2×; they do not multiply each other.'};}
async function read(actor){const clans=await db.query('SELECT id,name FROM site_clans WHERE active=1 ORDER BY name LIMIT 1000'),choices=[];for(const clan of clans){const decisions=[],authorities=new Map(),consent=db.clanFaithEnabled?await currentClanFaith(db,clan.id):null;for(const d of FAITH_BLESSINGS){if(consent&&consent.faith!==d.office)continue;if(!authorities.has(d.office))authorities.set(d.office,await authority(db,actor,clan.id,clock(),{office:d.office}));const a=authorities.get(d.office);if(!a||a.role!=='doci'&&d.role!=='prior')continue;const last=await previous(db,d,clan.id),until=last?Number(last.created_at)+d.cooldownMs:null;decisions.push({...d,available:!until||clock()>=until,cooldownUntil:until});}if(decisions.length)choices.push({...clan,role:authorities.get(decisions[0].office)?.role,decisions});}return{clans:choices,stacking:'Overlapping blessings cap at 2×; they do not multiply each other.'};}
async function grant(actor,input){
if(!input||Object.keys(input).sort().join(',')!=='clanId,decisionId,requestId'||!validUuid(input.requestId)||!validUuid(input.clanId)||!faithBlessing(input.decisionId))fail('Choose a registered blessing and clan.',400);const d=faithBlessing(input.decisionId);
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:faith-blessing:'+input.requestId,authorize:async(tx,{keyId})=>{
const now=clock(),a=await authority(tx,actor,input.clanId,now,{lock:true});if(!a||a.role!=='doci'&&d.role!=='prior')fail('Current Doci or assigned Prior authority required.',403);
const now=clock(),a=await authority(tx,actor,input.clanId,now,{lock:true,office:d.office});if(!a||a.role!=='doci'&&d.role!=='prior')fail('Current faith leader or assigned officer authority required.',403);
const existing=await first(tx,'SELECT * FROM jarvis_faith_blessings WHERE request_id=?',[input.requestId]);if(existing){if(existing.actor_id!==actor.id||existing.clan_id!==input.clanId||existing.decision_id!==d.id)fail('Blessing reference already used.');return;}
if(db.clanFaithEnabled&&(await currentClanFaith(tx,input.clanId)).faith!==d.office)fail('The clan’s legal owner must first accept this faith.',403);
const last=await previous(tx,d,input.clanId);if(last&&now<Number(last.created_at)+d.cooldownMs)fail('This blessing is still on cooldown.');
await tx.query('INSERT INTO jarvis_faith_blessings(request_id,key_id,decision_id,clan_id,actor_id,source_term_id,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,keyId,d.id,input.clanId,actor.id,a.termId,now,Math.min(now+d.durationMs,a.expiresAt)]);
}});return{ok:true,requestId:input.requestId,...await read(actor)};
@ -28,13 +38,20 @@ export function createFaithBlessings(db,keys,{clock=Date.now}={}){
return{read,grant};
}
async function memberClans(db,accountId){const rows=await db.query('SELECT m.clan_id FROM site_clan_members m JOIN site_clans c ON c.id=m.clan_id AND c.active=1 WHERE m.user_id=?',[accountId]),scopes=new Set();for(const row of rows){let id=row.clan_id;const seen=new Set();for(let n=0;n<32;n++){if(seen.has(id))throw Error('Clan hierarchy cycle');seen.add(id);scopes.add(id);let parent=await entityParent(db,'clan',id);if(!parent){const legacy=await first(db,'SELECT parent_clan_id FROM site_clan_deeds WHERE clan_id=?',[id]);if(legacy?.parent_clan_id)parent={parent_kind:'clan',parent_id:legacy.parent_clan_id};}if(!parent||parent.parent_kind!=='clan')break;if(n===31)throw Error('Clan hierarchy too deep');id=parent.parent_id;}}return[...scopes];}
async function consentCutoff(db){const row=await first(db,"SELECT used_at FROM organisation_keys WHERE account_id=? AND key_type='progression-policy' AND scope_id='policy:POL:S01:v6' AND used_at IS NOT NULL",[STAFF_OFFICE_ACCOUNT_ID]);return row?Number(row.used_at):null;}
export async function faithMultipliers(base,db,accountId,{clock=Date.now}={}){
const out={xp:1,dm:1,xpProof:null,dmProof:null};if(!base.faithBlessingsEnabled)return out;const clans=await memberClans(db,accountId);if(!clans.length)return out;const now=clock(),rows=await db.query(proofSQL+" JOIN site_clans c ON c.id=b.clan_id AND c.active=1 JOIN political_office_terms t ON t.id=b.source_term_id AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? WHERE b.clan_id IN ("+clans.map(()=>'?').join(',')+') AND b.created_at<=? AND b.expires_at>? ORDER BY b.created_at DESC,b.request_id DESC',[STAFF_OFFICE_ACCOUNT_ID,now,now,...clans,now,now]);
for(const r of rows){const d=faithBlessing(r.decision_id);if(!d)throw Error('Unknown blessing record');for(const kind of ['xp','dm'])if(d[kind]>out[kind]){out[kind]=d[kind];out[kind+'Proof']={keyId:r.key_id,clanId:r.clan_id,accountId,occurredAt:now,multiplier:d[kind]};}}return out;
const cutoff=base.clanFaithEnabled?await consentCutoff(db):null,memberFaiths=new Set();let hasExplicitFaith=false;
if(base.clanFaithEnabled)for(const m of await db.query('SELECT clan_id FROM site_clan_members WHERE user_id=?',[accountId])){const c=await currentClanFaith(db,m.clan_id);if(c.requestId)hasExplicitFaith=true;if(c.faith)memberFaiths.add(c.faith);}
for(const r of rows){const d=faithBlessing(r.decision_id);if(!d)throw Error('Unknown blessing record');let consent=null;
if(base.clanFaithEnabled){consent=await currentClanFaith(db,r.clan_id);if(consent.requestId&&consent.faith!==d.office||hasExplicitFaith&&!memberFaiths.has(d.office))continue;if(consent.faith!==d.office&&(cutoff===null||Number(r.created_at)>=cutoff))continue;if(consent.faith===d.office&&!memberFaiths.has(d.office))continue;}
for(const kind of ['xp','dm'])if(d[kind]>out[kind]){out[kind]=d[kind];out[kind+'Proof']={keyId:r.key_id,clanId:r.clan_id,accountId,occurredAt:now,multiplier:d[kind],...(consent?.faith===d.office?{faithConsentRequestId:consent.requestId}:{})};}}return out;
}
export async function validFaithReward(db,proof,{accountId,claimedAt}){
if(!proof||proof.accountId!==accountId||proof.multiplier!==2||!Number.isSafeInteger(proof.occurredAt)||proof.occurredAt>claimedAt||claimedAt-proof.occurredAt>30000)return false;
const row=await first(db,proofSQL+' WHERE b.key_id=? AND b.clan_id=? FOR UPDATE',[STAFF_OFFICE_ACCOUNT_ID,proof.keyId,proof.clanId]);return !!row&&faithBlessing(row.decision_id)?.dm===2&&Number(row.created_at)<=proof.occurredAt&&Number(row.expires_at)>proof.occurredAt;
const row=await first(db,proofSQL+' WHERE b.key_id=? AND b.clan_id=? FOR UPDATE',[STAFF_OFFICE_ACCOUNT_ID,proof.keyId,proof.clanId]);if(!row||faithBlessing(row.decision_id)?.dm!==2||Number(row.created_at)>proof.occurredAt||Number(row.expires_at)<=proof.occurredAt)return false;
const cutoff=await consentCutoff(db);if(!proof.faithConsentRequestId)return cutoff===null||Number(row.created_at)<cutoff;
const consent=await first(db,"SELECT c.request_id,c.faith_key,k.id verified_key FROM jarvis_faith_consents c LEFT JOIN organisation_keys k ON k.id=c.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:clan-faith:',c.request_id) AND k.revoked_at IS NULL WHERE c.clan_id=? AND c.choice='accept' AND c.created_at<=? ORDER BY c.created_at DESC,c.request_id DESC LIMIT 1 FOR UPDATE",[STAFF_OFFICE_ACCOUNT_ID,proof.clanId,proof.occurredAt]);return !!consent?.verified_key&&consent.request_id===proof.faithConsentRequestId&&consent.faith_key===faithBlessing(row.decision_id).office;
}
export function faithAward(award,boost){
if(boost.xp===1&&boost.dm===1)return award;

View file

@ -84,7 +84,7 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(d.feeMinor),xp:d.xp,expiresAt,cooldownUntil:now+d.cooldownMs};
await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[requestId,actor.id,source.id,tax.id,digest,String(amount),d.title,now]);
await new PostbankPayments(bank,null,{clock}).post(b,{id:requestId,actor_id:actor.id,amount_minor:String(amount)},source,tax,false);
if(d.kind==='proclamation')await tx.query("INSERT INTO political_proclamations(id,request_id,scope,title,body,author_id,created_at,version) VALUES(?,?,'imperium',?,?,?,?,1)",[effectId,requestId,payload.title,payload.body,actor.id,now]);
if(d.kind==='proclamation')await tx.query('INSERT INTO political_proclamations(id,request_id,scope,title,body,author_id,created_at,version) VALUES(?,?,?,?,?,?,?,1)',[effectId,requestId,d.scope||'imperium',payload.title,payload.body,actor.id,now]);
const updated=creditXP(state,d.xp,{capXP:Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base))});
await saveXPAccount(pol,actor.id,updated,season,keyId,'political-decision',{decisionId:d.id,termId:holder.termId,xp:d.xp},now);
await tx.query('INSERT INTO jarvis_political_decisions(request_id,key_id,decision_id,office_key,term_id,actor_id,recipient_id,input_hash,payload_json,receipt_json,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',[requestId,keyId,d.id,d.office,holder.termId,actor.id,payload.recipientId||null,digest,JSON.stringify(payload),JSON.stringify(receipt),now,expiresAt]);

View file

@ -0,0 +1,28 @@
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {clanFaithFixture} from './clan-faith-fixture.mjs';
import {FAITH_BLESSING_SCHEMA,createFaithBlessings,faithMultipliers,validFaithReward} from '../node/faith-blessings.mjs';
import {ensureFaithQuestPolicy} from '../node/progression-pol.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs';
test('parallel faith blessings require owner consent and retain historical reward proof after a later lawful conversion',async()=>{
const f=await clanFaithFixture();try{
await f.db.query(FAITH_BLESSING_SCHEMA);f.db.faithBlessingsEnabled=true;await ensureFaithQuestPolicy(f.db,f.keys,{clock:f.clock});await f.db.query("UPDATE organisation_keys SET used_at=? WHERE account_id=? AND scope_id='policy:POL:S01:v6'",[f.clock(),STAFF_OFFICE_ACCOUNT_ID]);
const service=createFaithBlessings(f.db,f.keys,{clock:f.clock}),request=id=>({decisionId:id,requestId:randomUUID(),clanId:f.clan});
await assert.rejects(service.grant(f.people.Owner,request('holy-day')),/first accept/);
const offer=f.offer('BG-CONVERT');await f.service.offer(f.people.Ceo,offer);await f.service.reply(f.people.Other,f.reply(offer.requestId));
const production=createFaithBlessings({...f.db,first:undefined,query:f.db.query.bind(f.db)},f.keys,{clock:f.clock});assert.equal((await production.read(f.people.Ceo)).clans[0].decisions.length,3);
await assert.rejects(service.grant(f.people.Owner,request('holy-day')),/first accept/);await assert.rejects(service.grant(f.people.Owner,request('sisterhood-patronage')),/authority/);
await service.grant(f.people.Ceo,request('sisterhood-patronage'));const boost=await faithMultipliers(f.db,f.db,f.people.Member.id,{clock:f.clock});assert.equal(boost.dm,2);assert.equal(boost.xp,1);assert.ok(boost.dmProof.faithConsentRequestId);
const valid=proof=>validFaithReward(f.db,proof,{accountId:f.people.Member.id,claimedAt:1000});assert.equal(await valid(boost.dmProof),true);assert.equal(await valid({...boost.dmProof,faithConsentRequestId:randomUUID()}),false);const {faithConsentRequestId:_,...stripped}=boost.dmProof;assert.equal(await valid(stripped),false);
f.setTime(1000+7*86400000);const next=f.offer();await f.service.offer(f.people.Owner,next);await f.service.reply(f.people.Other,f.reply(next.requestId));assert.equal(await valid(boost.dmProof),true);
await assert.rejects(service.grant(f.people.Ceo,request('sisterhood-discipline')),/first accept/);await service.grant(f.people.Owner,request('holy-day'));assert.equal((await faithMultipliers(f.db,f.db,f.people.Member.id,{clock:f.clock})).xp,2);
}finally{f.db.close();}
});
test('new faith officers cannot grant a bonus beyond their appointment and existing pre-consent blessings keep only their original term',async()=>{
const f=await clanFaithFixture();try{
await f.db.query(FAITH_BLESSING_SCHEMA);f.db.faithBlessingsEnabled=true;const service=createFaithBlessings(f.db,f.keys,{clock:f.clock});f.db.clanFaithEnabled=false;await service.grant(f.people.Owner,{decisionId:'holy-day',requestId:randomUUID(),clanId:f.clan});assert.equal((await faithMultipliers(f.db,f.db,f.people.Member.id,{clock:f.clock})).xp,2);
f.setTime(1001);await ensureFaithQuestPolicy(f.db,f.keys,{clock:f.clock});await f.db.query("UPDATE organisation_keys SET used_at=? WHERE account_id=? AND scope_id='policy:POL:S01:v6'",[f.clock(),STAFF_OFFICE_ACCOUNT_ID]);f.db.clanFaithEnabled=true;assert.equal((await faithMultipliers(f.db,f.db,f.people.Member.id,{clock:f.clock})).xp,2);
const offer=f.offer('BG-CONVERT');await f.service.offer(f.people.Ceo,offer);await f.service.reply(f.people.Other,f.reply(offer.requestId));assert.equal((await faithMultipliers(f.db,f.db,f.people.Member.id,{clock:f.clock})).xp,1);
await f.db.query("INSERT INTO political_appointment_deeds(id,office_key,source_term_id,user_id,role_key,title,appointment_type,target_kind,target_id,starts_at,expires_at,issuer_id,request_id) VALUES(?,'veiled_concord',?,?,'officer','Reverend Mother','job','clan',?,0,2000,?,?)",[randomUUID(),f.terms.veiled_concord,f.people.Member.id,f.clan,f.people.Ceo.id,randomUUID()]);
await service.grant(f.people.Member,{decisionId:'reverend-blessing',requestId:randomUUID(),clanId:f.clan});assert.equal((await f.db.first("SELECT expires_at FROM jarvis_faith_blessings WHERE decision_id='reverend-blessing'")).expires_at,2000);assert.equal((await faithMultipliers(f.db,f.db,f.people.Member.id,{clock:f.clock})).xp,2);f.setTime(2000);assert.equal((await faithMultipliers(f.db,f.db,f.people.Member.id,{clock:f.clock})).xp,1);
}finally{f.db.close();}
});

View file

@ -21,7 +21,7 @@ async function fixture(office='emperor'){
const entity={id:entityId('office',office==='emperor'?'emperor':'leader:'+office),kind:'office',key:office==='emperor'?'emperor':'leader:'+office,name:o.name,canView:true,canActivate:true,canPay:true},authority=async()=>({entities:[entity]});
await new PostbankService(f.db,authority).activate(f.people.Owner,{entityId:entity.id,packageKey:'pb_civic',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const source=await f.db.first("SELECT * FROM pb_accounts WHERE type_code='107'");await f.db.query('UPDATE pb_accounts SET balance_minor=2000000 WHERE id=?',[source.id]);await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_tax_treasury','979','Tax',0,'active',1)");
const service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority,clock:()=>now});
const input=(decisionId='IMP-04')=>({decisionId,requestId:randomUUID(),sourceAccount:String(source.id),confirmed:true,...(decisionId==='IMP-04'?{title:'A public proclamation',body:'A message to the people of the realm.'}:{recipientId:f.people.Other.id,citation:'Recognised for service to the realm.'})});
const input=(decisionId='IMP-04')=>({decisionId,requestId:randomUUID(),sourceAccount:String(source.id),confirmed:true,...(POLITICAL_DECISIONS.find(d=>d.id===decisionId)?.kind==='proclamation'?{title:'A public proclamation',body:'A message to the people of the realm.'}:{recipientId:f.people.Other.id,citation:'Recognised for service to the realm.'})});
return{...f,service,pol,source,term,input,authority,setTime:n=>now=n};
}
test('catalogue prices, Reputation requirements and XP agree with connected policy',()=>{for(const d of POLITICAL_DECISIONS){const row=DECISION_CATALOGUE.find(r=>r.id===d.id);assert.equal(row.level,d.level);assert.equal(row.xp,d.xp);const [dm,hours]=row.cost.replaceAll(',','').split(' / ');assert.equal(Number(dm)*100,d.feeMinor);assert.equal(Number(hours.replace('h',''))*3600000,d.cooldownMs);}});
@ -56,6 +56,18 @@ test('legacy Imperial publisher delegates to paid decision and cannot bypass its
const route=createProclamations(f.db,{}, {politicalDecisions:f.service,authenticate:async()=>f.people.Owner,access:async()=>({nodes:['web.menu.game']})}),request=input=>new Request('https://cp.dunerealms.com/api/politics/proclamations?kind=imperial',{method:'POST',headers:{origin:'https://cp.dunerealms.com','content-type':'application/json'},body:JSON.stringify(input)});
assert.equal((await route(request(f.input()))).status,201);assert.equal((await route(request(f.input()))).status,409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
}finally{f.db.close();}});
test('House, Guild and faith proclamations retain their own archives, fixed fees and successor-safe cooldowns',async()=>{
for(const d of POLITICAL_DECISIONS.filter(d=>d.kind==='proclamation'&&d.office!=='emperor')){const f=await fixture(d.office);try{
const input=f.input(d.id);await f.service.execute(f.people.Owner,input);const post=await f.db.first('SELECT scope FROM political_proclamations');assert.equal(post.scope,d.scope);assert.equal((await f.db.first('SELECT amount_minor FROM pb_orders')).amount_minor,50000);await assert.rejects(f.service.execute(f.people.Owner,f.input(d.id)),/cooldown/);
}finally{f.db.close();}}
});
test('legacy House and Guild publishers cannot bypass fees, office scope or cooldown, and never fall back to a free write',async()=>{
for(const [office,id,kind]of [['atreides','ATR-PROCLAIM','house'],['spacing_guild','SG-PROCLAIM','guild']]){const f=await fixture(office);try{
const deps={politicalDecisions:f.service,authenticate:async()=>f.people.Owner,access:async()=>({nodes:['web.menu.game'],ranks:[]}),preview:async()=>Response.json({faction:office,factionStatus:'verified',houseLeader:true})},route=createProclamations(f.db,{},deps),request=body=>new Request('https://cp.dunerealms.com/api/politics/proclamations?kind='+kind,{method:'POST',headers:{origin:'https://cp.dunerealms.com','content-type':'application/json'},body:JSON.stringify(body)});
assert.equal((await route(request({...f.input(id),decisionId:'IMP-04'}))).status,400);assert.equal((await route(request(f.input(id)))).status,201);assert.equal((await route(request(f.input(id)))).status,409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);
const offline=createProclamations(f.db,{}, {...deps,politicalDecisions:null});assert.equal((await offline(request(f.input(id)))).status,503);const archived=await offline(new Request('https://cp.dunerealms.com/api/politics/proclamations?kind='+kind));assert.equal(archived.status,200);const data=await archived.json();assert.equal(data.total,1);assert.equal(data.canPublish,false);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,1);
}finally{f.db.close();}}
});
test('Imperial and Corrino recognitions use fixed fees, existing profile markup and no self-award',async()=>{for(const [office,id]of [['emperor','IMP-09'],['corrino','COR-03']]){const f=await fixture(office);try{
if(office==='corrino')await f.db.query("INSERT INTO site_character_choices SELECT minecraft_uuid,'corrino' FROM site_game_links WHERE user_id=?",[f.people.Other.id]);
const receipt=await f.service.execute(f.people.Owner,f.input(id));assert.equal(receipt.feeMinor,office==='emperor'?'500000':'250000');const honours=await politicalHonours(f.db,f.people.Other.id,1000);assert.equal(honours.length,1);assert.match(honours[0].seal,/\/seals\/.+\.png$/);const html=honourMarkup([{...honours[0],citation:'<script>bad</script>'}]);assert.match(html,/CEREMONIAL HONOUR/);assert.match(html,/&lt;script&gt;/);assert.doesNotMatch(html,/<script>/);

View file

@ -1,3 +1,3 @@
import test from 'node:test';import assert from 'node:assert/strict';import {MISSION_BRANCHES,DECISION_CATALOGUE} from '../control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs';
test('accepted design includes all nine personal branches, repair quest and private discovery placeholder',()=>{assert.equal(MISSION_BRANCHES.filter(b=>/^[a-i]$/.test(b.id)).length,9);const equipment=MISSION_BRANCHES.find(b=>b.id==='h').missions;assert.match(equipment[0].title,/faction kit/i);assert.equal(equipment[1].title,'Repair Your Starter Kit');assert.equal(MISSION_BRANCHES.find(b=>b.id==='c').missions.length,8);assert(MISSION_BRANCHES.find(b=>b.id==='discoveries').missions.every(m=>m.hidden&&m.optional));assert(MISSION_BRANCHES.find(b=>b.id==='i').missions.filter(m=>/Sell/.test(m.title)).every(m=>m.optional));const ids=MISSION_BRANCHES.flatMap(b=>b.missions.map(m=>m.id));assert.equal(new Set(ids).size,ids.length);});
test('decision catalogue keeps five to ten distinct proposals per office, including consenting faith invitations',()=>{assert.equal(DECISION_CATALOGUE.length,81);assert.equal(new Set(DECISION_CATALOGUE.map(d=>d.id)).size,81);assert.deepEqual(Object.fromEntries(['IMP','ATR','HAR','COR','ORD','FRE','BG','NF','SG','CLD'].map(id=>[id,DECISION_CATALOGUE.filter(d=>d.office===id).length])),{IMP:10,ATR:8,HAR:8,COR:8,ORD:8,FRE:8,BG:8,NF:10,SG:8,CLD:5});assert(DECISION_CATALOGUE.some(d=>d.id==='NF-CONVERT'));assert(!DECISION_CATALOGUE.some(d=>d.id==='NF-01'));assert.equal(DECISION_CATALOGUE.find(d=>d.id==='IMP-01').level,50);assert(DECISION_CATALOGUE.every(d=>Number.isInteger(d.level)&&d.level>=0&&Number.isInteger(d.xp)&&d.xp>=0&&d.cost));});
test('decision catalogue keeps five to ten distinct proposals per office, including consenting faith invitations',()=>{assert.equal(DECISION_CATALOGUE.length,86);assert.equal(new Set(DECISION_CATALOGUE.map(d=>d.id)).size,86);assert.deepEqual(Object.fromEntries(['IMP','ATR','HAR','COR','ORD','FRE','BG','NF','SG','CLD'].map(id=>[id,DECISION_CATALOGUE.filter(d=>d.office===id).length])),{IMP:10,ATR:9,HAR:9,COR:9,ORD:9,FRE:8,BG:8,NF:10,SG:9,CLD:5});assert(DECISION_CATALOGUE.some(d=>d.id==='NF-CONVERT'));assert(!DECISION_CATALOGUE.some(d=>d.id==='NF-01'));assert.equal(DECISION_CATALOGUE.find(d=>d.id==='IMP-01').level,50);assert(DECISION_CATALOGUE.every(d=>Number.isInteger(d.level)&&d.level>=0&&Number.isInteger(d.xp)&&d.xp>=0&&d.cost));});