diff --git a/AGENTS.md b/AGENTS.md index 44bb0c56..ff0eeb11 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,3 +76,8 @@ Current priority: implement and test the server-only dev-key executor, starting - Group at least three genuine user requests in a batch; do not count individual technical edits as separate requests. War is one request, POL missions and POL decisions are the other two requests in the current batch. - Include the scope checklist, verification plan, PR/commit and actual live-release evidence in that ticket. Update its progress and complete it only when its stated scope is actually live and verified. - Placeholder pages must be explicitly marked as previews and include all appropriate DuneRealms artwork. Preserve working actions while the remaining consumers are built. + +## Latest owner override (24 November 2026) + +- The owner explicitly said “negeer tickets” and “just do it” for continuing backend work. Skip dev-ticket creation and approval; do not block implementation on support tickets. This supersedes the earlier ticket-first requirement. +- Preserve the colleague’s design work. Continue the three backend requests: war system, POL missions, POL decisions. diff --git a/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs index ff6063dd..1e499914 100644 --- a/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs @@ -15,7 +15,7 @@ const date=n=>new Date(n).toLocaleString(undefined,{dateStyle:'medium',timeStyle // The server supplies all state, eligibility and rewards. The browser sends only // the selected definition and its displayed revision, never XP or counters. -export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,initialBranch='a'}={}){ +export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,initialBranch='a',allowedBranches=null,artwork=null}={}){ const controller=new AbortController(),status=el('p','Opening your mission journal…','progression-notice'),body=el('div'); status.setAttribute('role','status');host.replaceChildren(status,body); let active=true,data=null,branch=initialBranch,selected=null,busy=false,uncertain=false,page=1,loadSequence=0,connectorObserver=null; @@ -30,7 +30,7 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api const sequence=++loadSequence; try{ const fresh=await api(view==='history'?'/history?page='+page:'');if(!active||sequence!==loadSequence)return; - data=fresh;uncertain=false;requestIds.clear();if(view!=='history')onData(fresh);render(); + data=allowedBranches&&Array.isArray(fresh.quests)?{...fresh,quests:fresh.quests.filter(q=>allowedBranches.includes(q.branch)),branches:fresh.branches?.filter(b=>allowedBranches.includes(b.id))}:fresh;uncertain=false;requestIds.clear();if(view!=='history')onData(fresh);render(); message(view==='history'?'Your recorded J.A.R.V.I.S. activity.':data.state==='active'?'Only verified objectives can be claimed. Unconnected gameplay objectives remain pending.':'The next season has not opened yet.');status.hidden=data.state==='active'||view==='history'; }catch(error){if(!active||sequence!==loadSequence)return;message(error.message);body.replaceChildren(button('Reload journal',load));} } @@ -58,9 +58,9 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api select.value=branch;select.onchange=()=>{branch=select.value;selected=null;render();};onBranches(availableBranches.filter(b=>data.quests.some(q=>q.branch===b.id)),branch);if(!externalBranches)body.append(select); const rows=data.quests.filter(q=>q.branch===branch).map(q=>({...q,channel:questChannel(q.executionRequirements)}));selected=rows.find(q=>q.id===selected)?.id||null; const layout=el('div',undefined,'progression-layout'),tree=el('div',undefined,'progression-tree');tree.setAttribute('aria-label','Mission tree'); - for(const row of rows){const card=button('',()=>{selected=row.id;detailOpen=true;render();});card.className='progression-mission';card.dataset.missionId=row.id;card.dataset.channel=row.channel==='website'?'website':'shared';card.setAttribute('aria-pressed',String(row.id===selected));card.setAttribute('aria-haspopup','dialog');card.append(image(questArtwork(row.channel)),el('strong',row.title),el('span',labels[row.state]||'Awaiting verification','progression-badge'));tree.append(card);} + for(const row of rows){const card=button('',()=>{selected=row.id;detailOpen=true;render();});card.className='progression-mission';card.dataset.missionId=row.id;card.dataset.channel=row.channel==='website'?'website':'shared';card.setAttribute('aria-pressed',String(row.id===selected));card.setAttribute('aria-haspopup','dialog');card.append(image(artwork||questArtwork(row.channel)),el('strong',row.title),el('span',labels[row.state]||'Awaiting verification','progression-badge'));tree.append(card);} layout.append(tree);const row=rows.find(q=>q.id===selected); - if(row&&detailOpen){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected mission');pane.append(image(questArtwork(row.channel)),el('small',row.id),el('h3',row.title),el('small',row.channel==='website'?'Website quest':'Website / Minecraft quest')); + if(row&&detailOpen){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected mission');pane.append(image(artwork||questArtwork(row.channel)),el('small',row.id),el('h3',row.title),el('small',row.channel==='website'?'Website quest':'Website / Minecraft quest')); if(uncertain){const feedback=el('p',status.textContent,'progression-notice');feedback.setAttribute('role','alert');pane.append(feedback);}const guide=questGuidance(row);pane.append(el('h4','How to complete'),el('p',guide.objective),el('h4','Where'),el('p',guide.where));if(guide.connected===false&&row.state!=='claimed')pane.append(el('p',guide.verification,'progression-notice'));if(row.issuerName)pane.append(el('small','Questgiver · '+row.issuerName));if(row.recipe){pane.append(el('h4','Recipe · '+row.recipe.world));const table=el('table',undefined,'progression-recipe');table.setAttribute('aria-label','Elytra crafting recipe');for(const cells of row.recipe.grid){const tr=el('tr');for(const cell of cells)tr.append(el('td',cell));table.append(tr);}pane.append(table,el('p','Very Rare · MK XI · Craft on Arrakis'));} const source=data.sources?.sources?.find(s=>s.metrics?.includes(row.metric)); const quantity=value=>row.metric?.endsWith('-minor')?(value/100).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2})+' DM':value.toLocaleString(); diff --git a/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs b/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs index cf49238b..24e5bec1 100644 --- a/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs @@ -1,4 +1,5 @@ import {ELYTRA_BRANCH} from './cp-v2-elytra-quests.mjs'; +import {WAR_QUEST_BRANCH} from './cp-v2-war-quests.mjs'; // Server-owned content shared with the existing quest and POL Decision interfaces. // Reward amounts, decision costs and timings require explicit configuration. const freeze=v=>{if(v&&typeof v==='object'){Object.values(v).forEach(freeze);Object.freeze(v);}return v;}; @@ -1098,8 +1099,9 @@ export const POL_QUEST_BRANCHES=freeze([ } ] }, - ELYTRA_BRANCH + ELYTRA_BRANCH, + WAR_QUEST_BRANCH ]); const gameplayMetrics=new Set(['pol-smuggler-introduction','pol-sabotage','pol-water-supply','pol-spice-transport','pol-sietch-service','pol-verified-route','pol-route-service','pol-sealed-cargo','pol-restricted-delivery','pol-alternate-route','pol-opposed-delivery','pol-ghost-cargo','pol-escort','pol-interdiction','pol-cargo-recovery','pol-protection','pol-commissioned-recovery','pol-discreet-logistics','pol-protected-delivery']); -export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b.quests.map((q,index)=>Object.freeze({...q,issuer:b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:b.issuerName||({smugglers:"Esmar Tuek",clan:"Gurney Halleck",company:"Roma Atani"})[b.id],objective:q.objective,xp:q.xp??150+index*50,executionRequirements:Object.freeze({website:true,minecraft:gameplayMetrics.has(q.metric)||q.branch==='elytra'})})))); +export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b.quests.map((q,index)=>Object.freeze({...q,issuer:b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:b.issuerName||({smugglers:"Esmar Tuek",clan:"Gurney Halleck",company:"Roma Atani"})[b.id],objective:q.objective,xp:q.xp??150+index*50,executionRequirements:Object.freeze({website:true,minecraft:gameplayMetrics.has(q.metric)||['elytra','war-service'].includes(q.branch)})})))); export function polBranch(id){return POL_QUEST_BRANCHES.find(b=>b.id===id||b.office===id)||null;} diff --git a/website/control-panel/public/cp-v2/cp-v2-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-progression.mjs index f5da47fe..7cec384b 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-progression.mjs @@ -1,4 +1,4 @@ -import {appendOfficeMissionPreview,appendOfficeDecisionBanner,planningImage} from './cp-v2-war-planning.mjs'; +import {appendOfficeMissionPreview,appendOfficeMissionBanner,appendOfficeDecisionBanner,planningImage} from './cp-v2-war-planning.mjs'; import {POL_PLANNING_ART,officeDecisionPreviews} from './cp-v2-war-planning-content.mjs'; import {mountPoliticalDecision} from './cp-v2-political-decisions.mjs'; import {politicalDecision} from '../political-decision-policy.mjs'; @@ -40,12 +40,13 @@ export function mountProgressionDesign(host,{context='personal',dashboard=false, if(isDecision&&['NF-08','NF-09','NF-10'].includes(row.id)){mountFaithBlessing(pane,row.id);return pane;} if(isDecision&&politicalDecision(row.id)){mountPoliticalDecision(pane,row.id);return pane;} if(isDecision&&row.id==='IMP-10'){mountImperialPassage(pane);return pane;} + if(isDecision&&row.executionStatus==='war-exchange-controller'){const link=el('a','Open War Exchange →');link.href='#household/war-exchange';pane.append(el('p','Current organisation authority is checked on every action. Both organisations approve alliances; all sides must choose the same hour. Changes clear previous calendar consent. No DM or XP is awarded for a proposal.'),link);return pane;} const dl=el('dl');for(const[label,value]of isDecision&&row.planned?[['Authority','Current political office · eligibility checked on connection'],['Timing','All sides agree the same calendar hour'],['Cooldown','Awaiting configuration'],['Status','Coming soon']]:isDecision&&row.xpType==='pol'?[['Authority','Current deed'],['Funding','Configured reward pool required'],['Scope',row.rewardScope],['Status','Awaiting configuration']]:isDecision?[['Authority','Current deed · checked on execution'],['Level',String(row.level)],['XP',row.xp+' · proposal'],['Cost / cooldown',row.cost+' · handover values'],['Currency','DM · same numerical handover values; no charge enabled']]:[['Progress','Not connected'],['Season','Season 1 · design'],['Completion',row.optional?'Optional / prestige':'Required objective'],['Reward','Configured reward · pending review']])dl.append(el('dt',label),el('dd',value));pane.append(dl); if(isDecision){const audit=decisionAudit(row.id);if(audit)pane.append(el('p',audit.authority+'. '+audit.gap,'progression-notice'));} if(row.title==='Repair Your Starter Kit'){const parts=el('div',undefined,'progression-repair');for(const item of STARTER_REPAIR_PARTS){const part=el('figure');part.append(image(item.art),el('figcaption',item.name+' × '+item.quantity));parts.append(part);}pane.append(el('p','Your '+STARTER_KIT_POLICY.tier+' faction kit starts with '+STARTER_KIT_POLICY.remainingDurabilityBps/100+'% durability. Collect all four parts and return that damaged kit for one intact replacement. Minecraft collection and surrender must be verified.'),parts);} if(isDecision)pane.append(field('Target',['Select eligible target · preview']));const action=button(isDecision?'Execute decision · pending integration':'Claim reward · pending integration');action.disabled=true;pane.append(action,el('p','J.A.R.V.I.S. dossier · no live execution reference exists yet.','progression-muted'));return pane; } - function renderMissions(){if(activeContext==='politics'){appendOfficeMissionPreview(content,{officeCode,dialog:dossier});return;}const toolbar=el('div',undefined,'progression-toolbar'),select=field('Mission branch',MISSION_BRANCHES.map(b=>b.title)),season=field('Season',['Season 1','Season archive · preview']);select.querySelector('select').selectedIndex=MISSION_BRANCHES.findIndex(b=>b.id===branch);select.onchange=e=>{branch=MISSION_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(select,season);content.append(toolbar); + function renderMissions(){if(activeContext==='politics'){if(manage){appendOfficeMissionPreview(content,{officeCode,dialog:dossier});return;}appendOfficeMissionBanner(content,officeCode);const branch=POL_QUEST_BRANCHES.find(b=>b.office===officeCode),journal=el('div');content.append(journal);disposePersonal=mountPersonalProgression(journal,{apiBase:'/api/progression/pol',initialBranch:branch?.id||'war-service',allowedBranches:[branch?.id,'war-service'].filter(Boolean),artwork:POL_PLANNING_ART[officeCode]?.banner});return;}const toolbar=el('div',undefined,'progression-toolbar'),select=field('Mission branch',MISSION_BRANCHES.map(b=>b.title)),season=field('Season',['Season 1','Season archive · preview']);select.querySelector('select').selectedIndex=MISSION_BRANCHES.findIndex(b=>b.id===branch);select.onchange=e=>{branch=MISSION_BRANCHES[e.target.selectedIndex].id;selected=null;render();};toolbar.append(select,season);content.append(toolbar); if(activeContext==='personal'){const stats=el('div',undefined,'progression-stats');stats.append(el('strong','XP & level · awaiting connection'),el('span','Season cap 70 · proposed'),el('span','Halfway & completion milestones'),el('progress'));content.append(stats);}else{const info=el('p',activeContext==='politics'?'Office objectives are supplemental. Holding office is never required for personal seasonal completion.':'Organisation mission tree · shared component; organisation-specific objectives await definition.','progression-notice');content.append(info);} const b=MISSION_BRANCHES.find(b=>b.id===branch)||MISSION_BRANCHES[0],rows=activeContext==='personal'?b.missions:activeContext==='politics'?DECISION_CATALOGUE.filter(d=>d.office===officeCode).map(d=>({id:'MISSION-'+d.id,title:d.title+' · office objective',optional:true})):[]; const layout=el('div',undefined,'progression-layout'),tree=el('div',undefined,'progression-tree');tree.setAttribute('aria-label','Mission tree');if(!rows.length){tree.append(image(CONTEXTS[activeContext][1]),el('h3','Organisation mission tree'),el('p','The roster, tree, objectives and reward panel are ready for shared definitions. Personal mission requirements are not copied onto organisations.'));layout.append(tree);content.append(layout);return;} @@ -55,7 +56,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',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':'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',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 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();}; diff --git a/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs b/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs index d097563a..1e0bd6ba 100644 --- a/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs @@ -3,6 +3,9 @@ const live=(objective,where,verification)=>({objective,where,verification,connected:true}); const pending=(objective,where)=>({objective,where,verification:'Gameplay connection coming soon; this objective cannot yet be verified.',connected:false}); export const QUEST_GUIDANCE=Object.freeze({ + 'pol-war-deployment':live('Be enrolled in the frozen roster of an agreed campaign when its shared calendar hour begins. Publishing or viewing a proposal does not count.','Clan / POL CP → War Exchange → Roster and shared calendar','Prepared campaign with a started calendar hour and your verified Minecraft identity'), + 'pol-war-capture':live('Capture an enemy Home Block in person during the agreed campaign. Stay on the enrolled side and interact with the registered objective.','Ingame → Active war Home Block objective','Original authenticated native capture receipt'), + 'pol-war-victory':live('Capture at least one Home Block for the winning side and finish the campaign. Wait for its J.A.R.V.I.S. conquest deed settlement, then refresh this journal.','War Exchange → Campaign report → Conquest deeds updated','Consumed victory instrument matching the completed campaign and your capture'), onboarding:live('Complete account onboarding and link your Minecraft account to this website account.','My Account → Account Center','Verified linked account and completed onboarding'), faction:live('Choose and confirm your House. The choice must belong to the Minecraft account linked to your website account.','Imperial Codex → Your House, or the website House selector','Current central House selection'), profile:live('Set your display name and save a biography of at least 10 characters. Choosing a House alone does not complete your profile.','My Account → Profile','Saved display name and biography'), diff --git a/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs b/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs index 1b538e27..f949035c 100644 --- a/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-war-exchange.mjs @@ -26,6 +26,23 @@ export function mountWarExchange(host,{kind='clan',scopeId=null,fetcher=fetch}={ const proposal=row(id);if(!proposal)return;calendar?.destroy();calendar=null;currentId=id;selected=proposal.selections.find(s=>s.partyKey===warPartyKey(context))?.startsAt??null;let rosterDirty=false; const pane=el('section',undefined,'war-exchange-detail'),state=el('p',warProposalFacts(proposal).join(' · ')),teams=el('div',undefined,'war-exchange-teams'),area=el('div',undefined,'promotion-calendar'),choice=el('p'),confirm=el('button','Select this block'),withdraw=el('button','Withdraw proposal');confirm.type=withdraw.type='button'; pane.append(el('p',proposal.message),state,teams);for(let i=0;is.partyKey===warPartyKey(party)),card=el('article',undefined,'election-panel');card.dataset.side=String(i+1);card.append(el('strong',party.name),el('p',slot?date(slot.startsAt):'No block selected'));teams.append(card);} + const named=proposal.parties.some(p=>warPartyKey(p)===warPartyKey(context)); + if(proposal.mode!=='clan'){ + const allies=el('fieldset',undefined,'war-roster');allies.append(el('legend','Coalition agreements'),el('p','Both organisations must approve. Every change clears the saved rosters and calendar choices.')); + for(const agreement of proposal.coalitions||[]){ + const side=proposal.parties.find(p=>warPartyKey(p)===agreement.sideKey),ally=data.parties.find(p=>warPartyKey(p)===warPartyKey(agreement.ally));if(!side||!ally)continue; + const row=el('article',undefined,'election-panel');row.append(el('strong',ally.name+' → '+side.name),el('p',agreement.accepted?'Both organisations approved':'Awaiting both current authorities')); + if(proposal.state==='open'&&[agreement.sideKey,warPartyKey(agreement.ally)].includes(warPartyKey(context)))for(const [accept,label]of [[true,'Approve coalition'],[false,'Remove agreement']]){const action=el('button',label);action.type='button';action.disabled=busy||uncertain;action.onclick=async()=>{action.disabled=true;if(await write({action:'ally',id,revision:proposal.revision,side:{kind:side.kind,id:side.id},ally:agreement.ally,accept})&&active)await open(id);};row.append(action);} + allies.append(row); + } + if(proposal.state==='open'){ + const side=el('select'),ally=el('select'),invite=el('button',named?'Propose alliance':'Request to join side');side.setAttribute('aria-label','Coalition side');ally.setAttribute('aria-label','Allied organisation');invite.type='button'; + for(const p of proposal.parties.filter(p=>!named||warPartyKey(p)===warPartyKey(context))){const o=el('option',p.name);o.value=warPartyKey(p);side.append(o);} + for(const p of data.parties.filter(p=>!proposal.parties.some(r=>warPartyKey(r)===warPartyKey(p))&&(!named?warPartyKey(p)===warPartyKey(context):true)&&(p.id!=='emperor'||proposal.mode==='world'))){const o=el('option',p.name);o.value=warPartyKey(p);ally.append(o);} + invite.disabled=busy||uncertain||!side.options.length||!ally.options.length;invite.onclick=async()=>{const a=data.parties.find(p=>warPartyKey(p)===ally.value),s=proposal.parties.find(p=>warPartyKey(p)===side.value);if(!a||!s)return;invite.disabled=true;if(await write({action:'ally',id,revision:proposal.revision,side:{kind:s.kind,id:s.id},ally:{kind:a.kind,id:a.id},accept:true})&&active)await open(id);};allies.append(side,ally,invite); + } + pane.append(allies); + } if(proposal.roster){ const roster=el('fieldset',undefined,'war-roster'),count=el('p'),save=el('button','Save roster'),selectedPlayers=new Set(proposal.roster.selected),checks=[]; roster.append(el('legend','Your war roster'),el('p','Members of your mother clan and client clans. Save changes before choosing the calendar hour; changes clear every side’s previous calendar choice.')); @@ -43,7 +60,7 @@ export function mountWarExchange(host,{kind='clan',scopeId=null,fetcher=fetch}={ pane.append(el('p','Scheduled: '+date(proposal.block.startsAt)),el('p','Combat deployment and capture reports will appear here when the game bridge is connected.')); const progress=el('progress');progress.max=100;progress.removeAttribute('value');progress.setAttribute('aria-label','Awaiting verified war progress');pane.append(progress); } - const paint=()=>{choice.textContent=rosterDirty?'Save your roster changes before selecting a calendar block.':selected===null?'Choose a future hour on the calendar.':'Your selected block: '+date(selected);confirm.disabled=busy||uncertain||rosterDirty||proposal.state!=='open'||selected===null||selected<=Date.now();withdraw.disabled=busy||uncertain||!['open','scheduled'].includes(proposal.state)||!!proposal.block&&proposal.block.startsAt<=Date.now();};paint(); + const paint=()=>{choice.textContent=!named?'Your coalition leader selects the shared calendar hour.':rosterDirty?'Save your roster changes before selecting a calendar block.':selected===null?'Choose a future hour on the calendar.':'Your selected block: '+date(selected);confirm.disabled=!named||busy||uncertain||rosterDirty||proposal.state!=='open'||selected===null||selected<=Date.now();withdraw.disabled=!named||busy||uncertain||!['open','scheduled'].includes(proposal.state)||!!proposal.block&&proposal.block.startsAt<=Date.now();};paint(); confirm.onclick=async()=>{if(selected===null)return;confirm.disabled=withdraw.disabled=true;if(await write({action:'select',id,revision:proposal.revision,startsAt:selected,endsAt:selected+WAR_BLOCK_MS})&&active)await open(id);else if(active)paint();}; withdraw.onclick=async()=>{withdraw.disabled=confirm.disabled=true;if(await write({action:'withdraw',id,revision:proposal.revision})&&active){dossier.close();activate('history');}else if(active)paint();}; dossier.show(pane,{title:proposal.title}); diff --git a/website/control-panel/public/cp-v2/cp-v2-war-planning-content.mjs b/website/control-panel/public/cp-v2/cp-v2-war-planning-content.mjs index 0d154166..792a236e 100644 --- a/website/control-panel/public/cp-v2/cp-v2-war-planning-content.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-war-planning-content.mjs @@ -31,6 +31,6 @@ export function officeDecisionPreviews(code){ const office=POL_PLANNING_ART[code]||POL_PLANNING_ART.IMP,branch=POL_QUEST_BRANCHES.find(b=>b.office===code); const planned=[['WORLD','Propose a World Campaign','Prepare a world-war proposal and seek the other side’s agreement.'],['ROSTER','Approve the War Roster','Choose eligible military-clan and client-clan members within the scenario limit.'],['ALLIES','Invite Allied Clans','Prepare coalition or hired-clan terms for an agreed campaign.'],['COALITION','Choose a Universal Coalition','Prepare your world’s preferred side: Empire, Rebellion or Countercoalition.'],['FAITH','Choose a Side in the War of Faith','Review support for the Guild, Church or independent world coalition.']]; if(code==='IMP')planned.push(['INTERVENE','Imperial Intervention','Support one side in a world war and substitute the Imperial Home Block province. Clan wars are excluded.']); - return [...(branch?.decisions||[]),...planned.map(([id,title,effect])=>({id:'PREVIEW-WAR-'+code+'-'+id,office:code,title,effect,planned:true,xpType:'pol',rewardScope:'war',executionStatus:'coming-soon'}))]; + return [...(branch?.decisions||[]),...planned.map(([id,title,effect])=>({id:'WAR-'+code+'-'+id,office:code,title,effect,planned:false,xpType:'pol',rewardScope:'war',executionStatus:'war-exchange-controller'}))]; } export const planningArtAssets=()=>[...new Set([...WAR_PLANS.flatMap(p=>[p.art,p.seal]),...Object.values(POL_PLANNING_ART).flatMap(p=>[p.banner,p.seal])])]; diff --git a/website/control-panel/public/cp-v2/cp-v2-war-planning.mjs b/website/control-panel/public/cp-v2/cp-v2-war-planning.mjs index 3687db10..b71b1590 100644 --- a/website/control-panel/public/cp-v2/cp-v2-war-planning.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-war-planning.mjs @@ -18,6 +18,7 @@ export function appendOfficeMissionPreview(host,{officeCode='IMP',dialog}={}){ root.append(grid);host.append(root);return root; } export function appendOfficeDecisionBanner(host,officeCode){planningStyles();const office=POL_PLANNING_ART[officeCode]||POL_PLANNING_ART.IMP;host.append(banner(office.banner,office.title+' · Decisions','Open a decision to review its effect. Connected actions keep their normal confirmation; planned actions are marked unavailable.'));} +export function appendOfficeMissionBanner(host,officeCode){planningStyles();const office=POL_PLANNING_ART[officeCode]||POL_PLANNING_ART.IMP;host.append(banner(office.banner,office.title+' · Missions','Verified Reputation missions · campaign service uses agreed deployment, native captures and settled victory.'));} export function mountWarPlanning(host,{kind='clan',scopeId=null}={}){ planningStyles();const overview=el('section'),coalitions=el('section'),reports=el('section'); const {root}=createCPV2Page({shellHost:host,title:'War Room',description:'Campaign plans, coalitions and Home Block provinces.',artwork:'seals/emperor-v1.png',tabs:[{id:'scenarios',label:'War scenarios',artwork:'nav-clan-v2.webp',content:overview},{id:'coalitions',label:'Sides & rosters',artwork:'seals/office-landsraad.png',content:coalitions},{id:'reports',label:'Campaign reports',artwork:'nav-manual-v2.webp',content:reports}]}); diff --git a/website/control-panel/public/cp-v2/cp-v2-war-quests.mjs b/website/control-panel/public/cp-v2/cp-v2-war-quests.mjs new file mode 100644 index 00000000..3e8c3c45 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-war-quests.mjs @@ -0,0 +1,5 @@ +export const WAR_QUEST_BRANCH=Object.freeze({id:'war-service',title:'Campaign service',issuer:'thufir_hawat',issuerName:'Thufir Hawat',theme:'Agreed deployment, verified Home Block capture and victory',quests:[ + {id:'POL-WAR-01',title:'Answer the Muster',objective:'Be included in the frozen roster of a unanimously agreed war when its calendar hour begins. Publishing a proposal alone does not count.',metric:'pol-war-deployment',xp:150}, + {id:'POL-WAR-02',title:'Secure a Province',objective:'During an agreed war, capture an enemy Home Block in person. Only a verified server capture counts.',metric:'pol-war-capture',xp:200}, + {id:'POL-WAR-03',title:'A Settled Victory',objective:'Capture at least one province for the winning side and finish the campaign. The victory must complete its J.A.R.V.I.S. deed settlement.',metric:'pol-war-victory',xp:250} + ].map((q,i)=>Object.freeze({...q,target:1,requires:i?['POL-WAR-0'+i]:[],requiresAny:[],branch:'war-service',season:'S01',revision:1,optional:false,verifiedOnly:true,xpType:'pol',executionRequirements:{website:true,minecraft:true}})),decisions:[]}); diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 97447a15..ca298d24 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -4,7 +4,7 @@ export const STAFF_KEY_FIELDS=Object.freeze([{name:'ticketId',label:'Ban / suppo const action=(id,label,keyType,fields,extra={})=>({id,label,keyType,fields:[...STAFF_KEY_FIELDS,...fields],version:1,...extra}); const reference=field('reference','Reason / decision reference','text',{required:false}); export const MASTER_KEY_TEMPLATES=[ - {id:'war',label:'War Exchange',actions:[action('war.calendar-agreement','War proposal and calendar agreement','entity-state',[field('proposalId','Proposal UUID'),field('party','Current clan or political side'),field('mode','War mode'),field('roster','Verified current-branch players','array'),field('startsAt','Shared calendar hour','number'),field('requestId','Request UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createWarExchange',executionStatus:'authenticated-proposal-calendar-service',effect:'Separate proposal register; reuse Exchange cards and existing EVT calendar records. Only current named clan/POL authorities may choose their own hour. Clan authorities can select verified mother/client members before agreement. A roster change clears all calendar consent; membership is revalidated on agreement and the roster then freezes. Two or three matching blocks schedule once; partial or different selections never schedule. Withdrawal cancels the linked event before start. No personal ownership transfer, live combat, money movement or invented capture progress.'}),action('war.military-affiliation','MILCLAN temporary supermother','staff-parent-link',[field('operationId','Campaign or appointment UUID'),field('childKind','Clan or company'),field('childId','Existing mother UUID'),field('parentId','Political office key'),field('sourceKeyId','Verified political deed UUID'),field('requestId','Operation UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createMilitaryAffiliations/projectMilitaryClans',executionStatus:'verified-office-adapter-rollout-gated',effect:'Retain owners, heirs and nested client branches. Install one operation-owned parent edge and restore its previous edge on ordinary end. Skip restoration after a subsequent conquest or other parent instruction. Read current Royal POL charters, terms and appointed members. A system parent-link instrument temporarily attaches only an owned mother; expiry consumes a separate scoped instrument and restores the previous edge. Native military counterparts reuse POL art, Home Block and bank reference without duplicate primary memberships or new accounts. MILITARY_PROJECTION_ENABLED remains off until coordinated native0.5.33 rollout; no website issuance or arbitrary parent writes.'}),action('war.homeblock-capture','Verified campaign province capture','entity-state',[field('campaignId','Prepared campaign UUID'),field('eventId','Native capture event UUID'),field('provinceId','Registered Home Block UUID'),field('claimRevision','Current claim revision','number'),field('expectedRevision','Campaign revision','number')],{webIssue:false,recordOnly:true,domainAdapter:'createWarCaptureService',executionStatus:'clan-native-adapter-rollout-gated',effect:'Only a prepared, unanimously scheduled campaign can advance. Revalidate the native actor, server, position and current Home Block through a required trusted verifier. Persist one receipt and revision and update province colours. In universal/religious wars the Imperial final province stays hidden and immune until one challenger holds every other province; once revealed it remains visible through counterattacks. Clan native capture, read-only war menus and key-backed conquest settlement are connected behind WAR_BRIDGE_ENABLED. Larger political coalition wars are not connected yet.'}),action('war.conquest-settlement','Settle a verified clan campaign victory','staff-parent-link',[field('campaignId','Completed campaign UUID'),field('sourceHash','Immutable victory digest'),field('winnerId','Winning mother clan UUID')],{webIssue:false,domainAdapter:'createClanWarConquests',executionStatus:'verified-system-consumer-rollout-gated',effect:'Read only a stored native campaign victory. Revalidate current charters, owners and Home Blocks, issue one scoped system parent-link key, and consume it atomically through the existing conquest/deed primitive. Preserve original owners, primary memberships and every nested client link. A bank-side outbox safely retries the same instrument after an interruption; no balance or payroll action.'})]}, + {id:'war',label:'War Exchange',actions:[action('war.coalition-consent','Approve a political coalition','entity-state',[field('proposalId','Proposal UUID'),field('side','Declared political side'),field('ally','Current clan or political organisation'),field('accept','Approve or withdraw','boolean'),field('revision','Proposal revision','number'),field('requestId','Request UUID')],{webIssue:false,recordOnly:true,domainAdapter:'changeWarCoalition',executionStatus:'authenticated-war-exchange-service',effect:'Each organisation signs only for itself through its current deed authority. Both must agree before scheduling; changes clear rosters and calendar choices. A current Emperor can intervene on either world-war side and substitute the Imperial province. The Guild includes the Emperor in religious war. Immutable request receipts make retries safe; no browser command, cash movement or unilateral foreign signature.'}),action('progression.war-service-policy','Campaign Reputation quest policy','progression-policy',[],{version:5,webIssue:false,recordOnly:true,domainAdapter:'ensureWarQuestPolicy/warQuestEvidence',executionStatus:'verified-campaign-evidence-consumer',effect:'Install the three campaign-service Reputation quests through policy:POL:S01:v5. Credit only a frozen agreed deployment, an original native capture and a consumed victory settlement bound to the current Minecraft identity and season. Claims re-read the original evidence. Default XP is 150/200/250, existing Mentat modifiers apply, Personal XP and configured funding remain separate. No browser-supplied progress or default DM issuance.'}),action('war.calendar-agreement','War proposal and calendar agreement','entity-state',[field('proposalId','Proposal UUID'),field('party','Current clan or political side'),field('mode','War mode'),field('roster','Verified current-branch players','array'),field('startsAt','Shared calendar hour','number'),field('requestId','Request UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createWarExchange',executionStatus:'authenticated-proposal-calendar-service',effect:'Separate proposal register; reuse Exchange cards and existing EVT calendar records. Only current named clan/POL authorities may choose their own hour. Clan authorities can select verified mother/client members before agreement. A roster change clears all calendar consent; membership is revalidated on agreement and the roster then freezes. Two or three matching blocks schedule once; partial or different selections never schedule. Withdrawal cancels the linked event before start. No personal ownership transfer, live combat, money movement or invented capture progress.'}),action('war.military-affiliation','MILCLAN temporary supermother','staff-parent-link',[field('operationId','Campaign or appointment UUID'),field('childKind','Clan or company'),field('childId','Existing mother UUID'),field('parentId','Political office key'),field('sourceKeyId','Verified political deed UUID'),field('requestId','Operation UUID')],{webIssue:false,recordOnly:true,domainAdapter:'createMilitaryAffiliations/projectMilitaryClans',executionStatus:'verified-office-adapter-rollout-gated',effect:'Retain owners, heirs and nested client branches. Install one operation-owned parent edge and restore its previous edge on ordinary end. Skip restoration after a subsequent conquest or other parent instruction. Read current Royal POL charters, terms and appointed members. A system parent-link instrument temporarily attaches only an owned mother; expiry consumes a separate scoped instrument and restores the previous edge. Native military counterparts reuse POL art, Home Block and bank reference without duplicate primary memberships or new accounts. MILITARY_PROJECTION_ENABLED gates the coordinated native projection; no website issuance or arbitrary parent writes.'}),action('war.homeblock-capture','Verified campaign province capture','entity-state',[field('campaignId','Prepared campaign UUID'),field('eventId','Native capture event UUID'),field('provinceId','Registered Home Block UUID'),field('claimRevision','Current claim revision','number'),field('expectedRevision','Campaign revision','number')],{webIssue:false,recordOnly:true,domainAdapter:'createWarCaptureService',version:2,executionStatus:'verified-native-campaign-service',effect:'Only a prepared, unanimously scheduled campaign can advance. Revalidate the native actor, server, position and current Home Block through a required trusted verifier. Persist one receipt and revision and update province colours. In universal/religious wars the Imperial final province stays hidden and immune until one challenger holds every other province; once revealed it remains visible through counterattacks. Clan native capture, read-only war menus and key-backed conquest settlement are connected behind WAR_BRIDGE_ENABLED. World, universal and religious campaigns resolve current POL mandates, military members, allied clan branches and physical Home Blocks through the existing authenticated bridge.'}),action('war.conquest-settlement','Settle a verified campaign victory','staff-parent-link',[field('campaignId','Completed campaign UUID'),field('sourceHash','Immutable victory digest'),field('winnerId','Winning mother clan UUID')],{webIssue:false,domainAdapter:'createClanWarConquests',version:2,executionStatus:'verified-system-consumer',effect:'Read only a stored native campaign victory. Revalidate current charters, owners and Home Blocks, issue one scoped system parent-link key, and consume it atomically through the existing conquest/deed primitive. Preserve original owners, primary memberships and every nested client link. A bank-side outbox safely retries the same instrument after an interruption; Political victories use the same instrument; losing mother clans retain their nested clients. A defeated Imperial final province transfers the current office term and retains its former holder’s mother estates under the Imperial institution. No balance or payroll action.'})]}, {id:'clan',label:'Clan',actions:[ action('clan.clear-protected-rosters','Clear protected clan rosters','clan-administration',[reference],{webIssue:true,permission:'web.jarvis.clans.reset',effect:'Remove members and owner from Vaerkring and Veiled Concord. Preserve clans, claims, POL and Crysknife.',fixedTargets:['Vaerkring','Veiled Concord']}), action('clan.original','Original clan charter','clan-founding',[]), diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index cf160a44..94f0991a 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -38,7 +38,7 @@ import {createDeedPurchases} from '../node/deed-purchases.mjs'; import {createRebellionQuests,initializeRebellionRewards} from '../node/rebellion-quests.mjs'; import {createRebellionAPI} from '../node/rebellion-api.mjs'; import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs'; -import {initializePOLProgression,ensurePOLProgressionPolicy,ensurePOLRepeatablePolicy,ensureElytraQuestPolicy,polProgressionStore} from '../node/progression-pol.mjs'; +import {initializePOLProgression,ensurePOLProgressionPolicy,ensurePOLRepeatablePolicy,ensureElytraQuestPolicy,ensureWarQuestPolicy,polProgressionStore} from '../node/progression-pol.mjs'; import {initializeSystemCharacters} from '../node/system-characters.mjs'; import {initializeEntityState} from '../node/entity-state-keys.mjs'; import {createDMPaint} from './dmpaint.mjs'; @@ -264,7 +264,7 @@ export function createPanel(db,settings={},dependencies={}){ const auctionRuntime=dependencies.officeAuctionRuntime||createOfficeAuctionRuntime(db,dependencies.bankDatabase||null);const politicalActions=createPoliticalActions(db,{enabled:!!auctionRuntime,origin});const officeAuctionAPI=createOfficeAuctionAPI(db,dependencies.bankDatabase||null,auctionRuntime,settings,dependencies.officeAuctionAPI); const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); const progression=createProgressionAPI(db,{...progressionRuntime,origin}); - const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys):null); + const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys,{bank:dependencies.bankDatabase||null}):null); const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null}),organisations:actor=>readGameMemberships(db,actor),identity:actor=>readGamePublicIdentity(db,actor)})}); const gameStarter=dependencies.organisationKeys?createGameStarterKit(db,dependencies.organisationKeys,settings):null; const gameResearch=dependencies.organisationKeys?createGameResearch(db,dependencies.organisationKeys):null; @@ -562,7 +562,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);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 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);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 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:'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:'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/docs/WAR-POL-CAMPAIGNS.md b/website/docs/WAR-POL-CAMPAIGNS.md new file mode 100644 index 00000000..6de7e869 --- /dev/null +++ b/website/docs/WAR-POL-CAMPAIGNS.md @@ -0,0 +1,44 @@ +# Campaign backend + +The existing War Exchange, calendar, native bridge and system parent-link +consumer support clan (2 × 8), world (2 × 16), universal (3 × 86) and religious +(3 × 86) campaigns. No new game tunnel or command execution endpoint is added. + +Political sides require current occupied Royal offices, verified Minecraft +identities and registered physical Home Blocks. Coalition partners each approve +their own agreement. Changing an alliance or roster clears all calendar choices. +All named sides must choose the same future hour. Overlapping players and Home +Blocks cannot be deployed in another simultaneous campaign. + +Universal conflicts place the Empire first. Religious conflicts place Guild, +Church, independent world in that order; the Emperor joins the Guild. The Emperor +may join a world campaign on either side with mutual consent, substituting its +Home Block for that side's principal province. Clan wars exclude intervention. +The universal/religious Imperial finale is hidden and immune until a challenger +owns every other province, then stays revealed through counterattacks. + +Original clan ownership, primary membership and nested client links are retained. +Completed conquest consumes one existing system parent-link instrument. Political +victory reparents losing clan mothers, not every child. Imperial defeat additionally +transfers the remaining current office term to the winning political controller +and retains the former Emperor's personal mother estates under the Imperial +institution. Expiry of an old military affiliation cannot undo a conquest edge. +No balances, payroll or historical election results are rewritten. + +POL campaign-service missions use the existing quest and Reputation engine: +enrolment in an agreed campaign at its start (150 base XP), a native capture +(200), and a capture for the winning side with consumed victory settlement (250). +The separate v5 policy preserves existing configured rewards and season dates. +Claims re-read the original evidence; private generic game activity submissions +cannot assert war progress. Existing Mentat/faith modifiers still apply. There +is no automatic DM award for opening proposals, calendar choices or invitations. + +POL mission panels use the real journal with office artwork. War decisions open +the authenticated War Exchange controller. Existing proclamation, honour, passage +and faith consumers retain their authority, funding and cooldowns. Other proposed +intelligence, sabotage and cargo-contract mechanics remain explicitly unavailable +until their actual domain consumers exist; this release does not fabricate them. + +Deployment requires `WAR_BRIDGE_ENABLED=true` and the existing generic native +campaign consumer. An unregistered office Home Block is a prerequisite failure, +not grounds to invent a location or start a demonstration war in production. diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index 761d7bda..896e3acb 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,7 +1,81 @@ { "schemaVersion": 1, - "sourceHash": "f89b64fc9ac6102b9e05483113e1385dd2a5edfc9bd43ebbe949b6da387b23e7", + "sourceHash": "b0634684051ae5075b5ddc009b6f70baa126f09cc684db1eae0c3c6a6e812c6e", "actions": [ + { + "id": "war.coalition-consent", + "label": "War Exchange · Approve a political coalition", + "version": 1, + "keyType": "entity-state", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "proposalId", + "label": "Proposal UUID", + "type": "text", + "required": true + }, + { + "name": "side", + "label": "Declared political side", + "type": "text", + "required": true + }, + { + "name": "ally", + "label": "Current clan or political organisation", + "type": "text", + "required": true + }, + { + "name": "accept", + "label": "Approve or withdraw", + "type": "boolean", + "required": true + }, + { + "name": "revision", + "label": "Proposal revision", + "type": "number", + "required": true + }, + { + "name": "requestId", + "label": "Request UUID", + "type": "text", + "required": true + } + ], + "effect": "Each organisation signs only for itself through its current deed authority. Both must agree before scheduling; changes clear rosters and calendar choices. A current Emperor can intervene on either world-war side and substitute the Imperial province. The Guild includes the Emperor in religious war. Immutable request receipts make retries safe; no browser command, cash movement or unilateral foreign signature.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, + { + "id": "progression.war-service-policy", + "label": "War Exchange · Campaign Reputation quest policy", + "version": 5, + "keyType": "progression-policy", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + } + ], + "effect": "Install the three campaign-service Reputation quests through policy:POL:S01:v5. Credit only a frozen agreed deployment, an original native capture and a consumed victory settlement bound to the current Minecraft identity and season. Claims re-read the original evidence. Default XP is 150/200/250, existing Mentat modifiers apply, Personal XP and configured funding remain separate. No browser-supplied progress or default DM issuance.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, { "id": "war.calendar-agreement", "label": "War Exchange · War proposal and calendar agreement", @@ -107,7 +181,7 @@ "required": true } ], - "effect": "Retain owners, heirs and nested client branches. Install one operation-owned parent edge and restore its previous edge on ordinary end. Skip restoration after a subsequent conquest or other parent instruction. Read current Royal POL charters, terms and appointed members. A system parent-link instrument temporarily attaches only an owned mother; expiry consumes a separate scoped instrument and restores the previous edge. Native military counterparts reuse POL art, Home Block and bank reference without duplicate primary memberships or new accounts. MILITARY_PROJECTION_ENABLED remains off until coordinated native0.5.33 rollout; no website issuance or arbitrary parent writes.", + "effect": "Retain owners, heirs and nested client branches. Install one operation-owned parent edge and restore its previous edge on ordinary end. Skip restoration after a subsequent conquest or other parent instruction. Read current Royal POL charters, terms and appointed members. A system parent-link instrument temporarily attaches only an owned mother; expiry consumes a separate scoped instrument and restores the previous edge. Native military counterparts reuse POL art, Home Block and bank reference without duplicate primary memberships or new accounts. MILITARY_PROJECTION_ENABLED gates the coordinated native projection; no website issuance or arbitrary parent writes.", "fixedTargets": [], "webIssue": false, "recordOnly": true @@ -115,7 +189,7 @@ { "id": "war.homeblock-capture", "label": "War Exchange · Verified campaign province capture", - "version": 1, + "version": 2, "keyType": "entity-state", "fields": [ { @@ -156,15 +230,15 @@ "required": true } ], - "effect": "Only a prepared, unanimously scheduled campaign can advance. Revalidate the native actor, server, position and current Home Block through a required trusted verifier. Persist one receipt and revision and update province colours. In universal/religious wars the Imperial final province stays hidden and immune until one challenger holds every other province; once revealed it remains visible through counterattacks. Clan native capture, read-only war menus and key-backed conquest settlement are connected behind WAR_BRIDGE_ENABLED. Larger political coalition wars are not connected yet.", + "effect": "Only a prepared, unanimously scheduled campaign can advance. Revalidate the native actor, server, position and current Home Block through a required trusted verifier. Persist one receipt and revision and update province colours. In universal/religious wars the Imperial final province stays hidden and immune until one challenger holds every other province; once revealed it remains visible through counterattacks. Clan native capture, read-only war menus and key-backed conquest settlement are connected behind WAR_BRIDGE_ENABLED. World, universal and religious campaigns resolve current POL mandates, military members, allied clan branches and physical Home Blocks through the existing authenticated bridge.", "fixedTargets": [], "webIssue": false, "recordOnly": true }, { "id": "war.conquest-settlement", - "label": "War Exchange · Settle a verified clan campaign victory", - "version": 1, + "label": "War Exchange · Settle a verified campaign victory", + "version": 2, "keyType": "staff-parent-link", "fields": [ { @@ -193,7 +267,7 @@ "required": true } ], - "effect": "Read only a stored native campaign victory. Revalidate current charters, owners and Home Blocks, issue one scoped system parent-link key, and consume it atomically through the existing conquest/deed primitive. Preserve original owners, primary memberships and every nested client link. A bank-side outbox safely retries the same instrument after an interruption; no balance or payroll action.", + "effect": "Read only a stored native campaign victory. Revalidate current charters, owners and Home Blocks, issue one scoped system parent-link key, and consume it atomically through the existing conquest/deed primitive. Preserve original owners, primary memberships and every nested client link. A bank-side outbox safely retries the same instrument after an interruption; Political victories use the same instrument; losing mother clans retain their nested clients. A defeated Imperial final province transfers the current office term and retains its former holder’s mother estates under the Imperial institution. No balance or payroll action.", "fixedTargets": [], "webIssue": false, "recordOnly": false diff --git a/website/node/game-wars.mjs b/website/node/game-wars.mjs index cef708a9..847defef 100644 --- a/website/node/game-wars.mjs +++ b/website/node/game-wars.mjs @@ -7,13 +7,19 @@ import {campaignPhase,warCampaignReport} from './war-campaign-model.mjs'; import {createClanWarConquests} from './war-conquests.mjs'; import {drainWarSettlements} from './war-settlement-jobs.mjs'; import {boardReadStore} from './board-deed-source.mjs'; +import {buildPoliticalCampaignSnapshot,politicalTeam,currentPoliticalCampaign} from './war-political-rosters.mjs'; +import {politicalConquestAuthority,settlePoliticalConquest} from './war-political-conquests.mjs'; const fail=message=>{throw Object.assign(Error(message),{status:409});}; async function charters(db){return (await db.prepare('SELECT clan_id,key_id FROM site_clan_charters ORDER BY clan_id LIMIT 501').all()).results;} export function createClanCampaignResolver(db,{readState=()=>readGameNativeState(db)}={}){ - return async proposal=>proposal.mode==='clan'?buildClanCampaignSnapshot(await readState(),proposal.parties,await charters(db),proposal.rosters):null; + return async proposal=>proposal.mode==='clan'?buildClanCampaignSnapshot(await readState(),proposal.parties,await charters(db),proposal.rosters):buildPoliticalCampaignSnapshot(await readState(),proposal,await charters(db)); } export function createClanRosterResolver(db,{readState=()=>readGameNativeState(db)}={}){ - return async(party,mode,selection=null)=>{ + return async(party,mode,selection=null,proposal=null)=>{ + if(party.kind==='politics'&&mode!=='clan'&&proposal?.parties?.some(p=>p.kind===party.kind&&p.id===party.id)){ + const {team}=politicalTeam(await readState(),party,mode,proposal.allies||[],selection); + return {capacity:mode==='world'?16:86,selected:team.roster.map(m=>m.uuid),candidates:[...team.roster,...team.reserves]}; + } if(party.kind!=='clan'||mode!=='clan')return null; const branch=clanWarBranch((await readState()).clans,party.id); if(branch[0].protected)fail('Protected official clans cannot enter clan wars.'); @@ -23,6 +29,7 @@ export function createClanRosterResolver(db,{readState=()=>readGameNativeState(d } export function currentClanCampaign(campaign,state,keys){ + if(campaign.mode!=='clan')return currentPoliticalCampaign(campaign,state,keys); const validPlayers=new Set(); for(const team of campaign.teams){ if(team.party?.kind!=='clan')fail('This campaign requires its political coalition adapter.'); @@ -38,9 +45,12 @@ export function currentClanCampaign(campaign,state,keys){ } export function createClanWarSettlementAdapter(db,store,keys,{clock=Date.now}={}){ - return createClanWarConquests(db,keys,{clock,readWinningCampaign:async id=>{const row=await store.first('SELECT snapshot_json FROM jarvis_war_campaigns WHERE id=?',[id]);return row?JSON.parse(row.snapshot_json):null;},verifySnapshot:async(tx,campaign)=>{ + return createClanWarConquests(db,keys,{clock,settlePolitical:settlePoliticalConquest,readWinningCampaign:async id=>{const row=await store.first('SELECT snapshot_json FROM jarvis_war_campaigns WHERE id=?',[id]);return row?JSON.parse(row.snapshot_json):null;},verifySnapshot:async(tx,campaign)=>{ + for(const term of campaign.teams.flatMap(t=>(t.mandates||[]).map(m=>m.termId)).sort())await tx.first('SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[term]); + for(const clan of [...new Set(campaign.teams.flatMap(t=>(t.clanDeeds||[]).map(c=>c.id)))].sort())await tx.first('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[clan]); const reader=boardReadStore(tx,db);reader.readSnapshot=undefined; const state=await readGameNativeState(reader,{clock}),deeds=await tx.query('SELECT clan_id,key_id FROM site_clan_charters ORDER BY clan_id LIMIT 501');currentClanCampaign(campaign,state,deeds); + if(campaign.mode!=='clan')return politicalConquestAuthority(tx,campaign,state); const winner=await tx.first('SELECT owner_id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[campaign.winnerSideId]);if(!winner)fail('Winning clan deed unavailable.'); return {winnerId:campaign.winnerSideId,winnerOwnerId:winner.owner_id,loserIds:campaign.teams.filter(t=>t.id!==campaign.winnerSideId).map(t=>t.id)}; }}); diff --git a/website/node/office-deed-transfer.mjs b/website/node/office-deed-transfer.mjs index 8430f316..8e23b3de 100644 --- a/website/node/office-deed-transfer.mjs +++ b/website/node/office-deed-transfer.mjs @@ -5,7 +5,7 @@ const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12} // transaction. Election and auction source records are never rewritten here. export async function transferOfficeDeed(tx,{termId,sourceTermId,officeKey,winnerId,playerUuid,sourceId,method,now}){ const office=PUBLIC_OFFICES.find(o=>o.key===officeKey); - if(!office||![termId,sourceTermId,winnerId,playerUuid,sourceId].every(uuid)||method!=='rebellion'||!Number.isSafeInteger(now))throw TypeError('Invalid office deed transfer'); + if(!office||![termId,sourceTermId,winnerId,playerUuid,sourceId].every(uuid)||!['rebellion','war'].includes(method)||!Number.isSafeInteger(now))throw TypeError('Invalid office deed transfer'); const scope=office.kind+':'+office.faction;await tx.query('INSERT INTO political_office_locks(scope) VALUES(?) ON DUPLICATE KEY UPDATE scope=VALUES(scope)',[scope]);await tx.first('SELECT scope FROM political_office_locks WHERE scope=? FOR UPDATE',[scope]); const prior=await tx.first('SELECT * FROM political_office_terms WHERE round_id=?',[sourceId]); if(prior){if(prior.id!==termId||prior.user_id!==winnerId||prior.kind!==office.kind||prior.faction!==office.faction)throw Error('Office transfer reference conflict');return {termId:prior.id,replayed:true};} @@ -14,6 +14,6 @@ export async function transferOfficeDeed(tx,{termId,sourceTermId,officeKey,winne const source=active[0],person=await tx.first("SELECT a.id FROM site_accounts a JOIN site_game_links g ON g.user_id=a.id WHERE a.id=? AND LOWER(g.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','system_account','memorial')",[winnerId,playerUuid.toLowerCase()]);if(!person)throw Error('Current personal winner identity required'); await tx.query("UPDATE political_office_terms SET outcome='superseded',expires_at=? WHERE id=?",[now,sourceTermId]); await tx.query("INSERT INTO political_office_terms(id,kind,faction,election_start,round_id,application_id,user_id,player_uuid,office,starts_at,expires_at,outcome,streak) VALUES(?,?,?,?,?,NULL,?,?,?,?,?,'winner',0)",[termId,office.kind,office.faction,source.election_start,sourceId,winnerId,playerUuid.toLowerCase(),office.office,now,source.expires_at]); - for(const [id,event,payload]of [[sourceTermId,'superseded_by_rebellion',{successorTermId:termId,sourceId}],[termId,'rebellion_awarded',{previousTermId:sourceTermId,previousHolderId:source.user_id,sourceId,method}]])await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,event,JSON.stringify(payload),now]); + for(const [id,event,payload]of [[sourceTermId,'superseded_by_'+method,{successorTermId:termId,sourceId}],[termId,method+'_awarded',{previousTermId:sourceTermId,previousHolderId:source.user_id,sourceId,method}]])await tx.query('INSERT INTO political_office_events(id,term_id,event,payload,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,event,JSON.stringify(payload),now]); return {termId,previousTermId:sourceTermId,expiresAt:Number(source.expires_at),replayed:false}; } diff --git a/website/node/progression-pol-runtime.mjs b/website/node/progression-pol-runtime.mjs index 48d437f0..d0533df8 100644 --- a/website/node/progression-pol-runtime.mjs +++ b/website/node/progression-pol-runtime.mjs @@ -12,7 +12,8 @@ import {currentResearchDefinitions,researchEvidence,authorizeResearchClaim} from import {RESEARCH_COOLDOWN_MS} from '../control-panel/public/organisation-research-policy.mjs'; import {awardResearch} from './organisation-research-rewards.mjs'; import {faithMultipliers,faithAward} from './faith-blessings.mjs'; -export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyObservation=null}={}){ +import {warQuestEvidence} from './war-quest-evidence.mjs'; +export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyObservation=null,bank=null}={}){ const observer=Object.freeze({internal:'pol-key-source-reader'}); const resolvePlayer=async id=>(await central.query("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null; const authorizePlayer=async(actor,store)=>{ @@ -32,6 +33,7 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO const season=seasons[0],input={accountId:actor.id,minecraftUuid:links[0].minecraft_uuid.toLowerCase(),seasonId:season.season_id,startsAt:Number(season.starts_at),endsAt:Number(season.ends_at),now,lock},activity=await verifiedPOLActivities(store,keys,input); if(central.polRepeatablesEnabled){const deaths=await verifiedPOLDeathTotals(store,keys,input);for(const [metric,value]of deaths.totals)activity.totals.set(metric,value);activity.proofIds.push(...deaths.proofIds);} if(central.organisationResearchEnabled){const research=await researchEvidence(store,actor.id,season.season_id);for(const [metric,value]of research.totals)activity.totals.set(metric,value);activity.proofIds.push(...research.proofIds);} + if(bank){const war=await warQuestEvidence(bank,store,input);for(const [metric,value]of war.totals)activity.totals.set(metric,value);activity.proofIds.push(...war.proofIds);} applyElytraAlternative(activity.totals);return {...activity,season}; } const adapters={clock,authorizePlayer,authorizeIssuer,resolvePlayer, diff --git a/website/node/progression-pol.mjs b/website/node/progression-pol.mjs index 40fcbdc6..452dfd80 100644 --- a/website/node/progression-pol.mjs +++ b/website/node/progression-pol.mjs @@ -49,3 +49,5 @@ export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionP export const ensurePOLRepeatablePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:2},definitions:repeatablePolicyDefinitions()}); export const ensureElytraQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:4},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='elytra')}); + +export const ensureWarQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:5},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='war-service')}); diff --git a/website/node/quest-activity-events.mjs b/website/node/quest-activity-events.mjs index 74a9dba6..c99453e4 100644 --- a/website/node/quest-activity-events.mjs +++ b/website/node/quest-activity-events.mjs @@ -4,7 +4,7 @@ import {createHash} from 'node:crypto'; import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; import {createSystemCharacters} from './system-characters.mjs'; import {POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs'; -const activityDefinition=metric=>POL_QUEST_DEFINITIONS.find(d=>d.metric===metric)||POL_REPEATABLES.find(d=>['SPICE','CARGO'].includes(d.key)&&d.metric===metric); +const activityDefinition=metric=>POL_QUEST_DEFINITIONS.find(d=>d.metric===metric&&d.branch!=='war-service')||POL_REPEATABLES.find(d=>['SPICE','CARGO'].includes(d.key)&&d.metric===metric); const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex'); const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null; diff --git a/website/node/war-campaign-model.mjs b/website/node/war-campaign-model.mjs index ce9d1c3f..70440ac7 100644 --- a/website/node/war-campaign-model.mjs +++ b/website/node/war-campaign-model.mjs @@ -9,7 +9,7 @@ const homeChunk=home=>({x:Math.floor(home.position.x/16),z:Math.floor(home.posit // Internal server model. Callers supply an authenticated, current deed/claim // snapshot, never browser-provided province ownership or player rosters. -export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces}){ +export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces,coalitions=[]}){ const policy=WAR_MODES[mode]; if(!uuid(id)||!policy||!Number.isSafeInteger(startsAt)||startsAt<0||startsAt%3600000!==0||endsAt!==startsAt+3600000||!Array.isArray(teams)||teams.length!==policy.parties||!Array.isArray(provinces)||!provinces.length||provinces.length>500)reject('Invalid campaign snapshot.'); const sideIds=new Set(),players=new Set(); @@ -29,6 +29,7 @@ export function createWarCampaign({id,mode,startsAt,endsAt,teams,provinces}){ if(imperial>1||new Set(provinces.map(p=>p.id)).size!==provinces.length||teams.some(t=>!provinces.some(p=>p.sideId===t.id)))reject('Every side needs distinct registered provinces.'); if(['universal','religious'].includes(mode)&&imperial!==1)reject('This campaign requires the protected Imperial final province.'); const result={id,mode,startsAt,endsAt,revision:1,teams:clone(teams),provinces:provinces.map(p=>({...clone(p),ownerSideId:p.sideId})),captures:[],winnerSideId:null,imperialUnlockedAt:null}; + if(mode!=='clan')result.coalitions=clone(coalitions); for(const team of result.teams)for(const member of team.roster)member.uuid=member.uuid.toLowerCase(); return result; } diff --git a/website/node/war-coalitions.mjs b/website/node/war-coalitions.mjs new file mode 100644 index 00000000..cafd6308 --- /dev/null +++ b/website/node/war-coalitions.mjs @@ -0,0 +1,32 @@ +import {warPartyKey} from '../control-panel/public/war-exchange-policy.mjs'; +import {randomUUID} from 'node:crypto'; +export const WAR_COALITION_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_war_coalitions(proposal_id CHAR(36) NOT NULL,side_key VARCHAR(50) NOT NULL,ally_kind VARCHAR(12) NOT NULL,ally_id VARCHAR(36) NOT NULL,side_actor_id CHAR(36) NULL,ally_actor_id CHAR(36) NULL,updated_at BIGINT NOT NULL,PRIMARY KEY(proposal_id,ally_kind,ally_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; +const fail=message=>{throw Object.assign(Error(message),{status:409});}; +export async function readWarCoalitions(store,id,{authorize=null,requireAgreement=false}={}){ + const rows=await store.query('SELECT * FROM jarvis_war_coalitions WHERE proposal_id=? ORDER BY side_key,ally_kind,ally_id',[id]),result=[]; + for(const row of rows){const [kind,...rest]=row.side_key.split(':'),side={kind,id:rest.join(':')},ally={kind:row.ally_kind,id:row.ally_id};let accepted=!!row.side_actor_id&&!!row.ally_actor_id; + if(accepted&&authorize)accepted=!!await authorize({id:row.side_actor_id},side.kind,side.id)&&!!await authorize({id:row.ally_actor_id},ally.kind,ally.id); + if(requireAgreement&&!accepted)fail('Every coalition invitation needs current approval from both organisations.');result.push({sideKey:row.side_key,ally,accepted}); + }return result; +} +export async function changeWarCoalition(tx,{proposal,input,actor,authorize,choices,now}){ + const intent={requestId:input.requestId,party:input.party,side:input.side,ally:input.ally,accept:input.accept}; + const history=await tx.query("SELECT actor_id,details FROM jarvis_war_history WHERE proposal_id=? AND action='coalition-consent'",[proposal.id]); + const previous=history.find(h=>JSON.parse(h.details).intent.requestId===input.requestId); + if(previous){const saved=JSON.parse(previous.details);if(previous.actor_id!==actor.id||JSON.stringify(saved.intent)!==JSON.stringify(intent))fail('Coalition reference conflict.');return {...saved.result,replayed:true};} + if(proposal.state!=='open'||proposal.mode==='clan'||Number(proposal.revision)!==input.revision)fail('Coalition terms are editable only on a current open political proposal.'); + const parties=JSON.parse(proposal.parties_json),side=parties.find(p=>warPartyKey(p)===warPartyKey(input.side||{})),ally=choices.find(p=>warPartyKey(p)===warPartyKey(input.ally||{})); + if(!side||!ally||parties.some(p=>warPartyKey(p)===warPartyKey(ally))||!['politics','clan'].includes(ally.kind))fail('Choose an independent clan or political office and a declared side.'); + if(ally.id==='emperor'&&proposal.mode!=='world')fail('The Emperor already has a fixed side in this scenario.'); + const acting=warPartyKey(input.party),sideKey=warPartyKey(side),allyKey=warPartyKey(ally);if(![sideKey,allyKey].includes(acting)||!await authorize(actor,input.party.kind,input.party.id))fail('Only the side and invited organisation may change this agreement.'); + const old=await tx.first('SELECT * FROM jarvis_war_coalitions WHERE proposal_id=? AND ally_kind=? AND ally_id=? FOR UPDATE',[proposal.id,ally.kind,ally.id]); + if(!old&&(await tx.query('SELECT ally_id FROM jarvis_war_coalitions WHERE proposal_id=?',[proposal.id])).length>=32)fail('This coalition register is full.'); + if(old&&old.side_key!==sideKey)fail('This organisation already has a proposal on another side. Leave it before switching sides.'); + if(typeof input.accept!=='boolean')fail('Confirm or withdraw your coalition consent.'); + if(!input.accept){if(old)await tx.query('DELETE FROM jarvis_war_coalitions WHERE proposal_id=? AND ally_kind=? AND ally_id=?',[proposal.id,ally.kind,ally.id]);} + else{const sideActor=acting===sideKey?actor.id:old?.side_actor_id||null,allyActor=acting===allyKey?actor.id:old?.ally_actor_id||null;await tx.query('INSERT INTO jarvis_war_coalitions VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE side_actor_id=VALUES(side_actor_id),ally_actor_id=VALUES(ally_actor_id),updated_at=VALUES(updated_at)',[proposal.id,sideKey,ally.kind,ally.id,sideActor,allyActor,now]);} + await tx.query('DELETE FROM jarvis_war_slots WHERE proposal_id=?',[proposal.id]);await tx.query('DELETE FROM jarvis_war_rosters WHERE proposal_id=?',[proposal.id]);await tx.query('UPDATE jarvis_war_proposals SET revision=revision+1,updated_at=? WHERE id=?',[now,proposal.id]); + const result={sideKey,ally:{kind:ally.kind,id:ally.id},accepted:!!input.accept&&!!(acting===sideKey||old?.side_actor_id)&&!!(acting===allyKey||old?.ally_actor_id)}; + await tx.query('INSERT INTO jarvis_war_history VALUES(?,?,?,?,?,?)',[randomUUID(),proposal.id,actor.id,'coalition-consent',JSON.stringify({intent,result}),now]); + return result; +} diff --git a/website/node/war-conquests.mjs b/website/node/war-conquests.mjs index a0ffee27..4edfb4f0 100644 --- a/website/node/war-conquests.mjs +++ b/website/node/war-conquests.mjs @@ -10,13 +10,14 @@ const stableId=(id,label)=>{const h=hash([id,label]);return h.slice(0,8)+'-'+h.s // Existing system parent-link key issuance/consumption owns every domain write. // The bank-side outbox only carries the immutable campaign ID, never a command. -export function createClanWarConquests(db,keys,{readWinningCampaign,verifySnapshot,clock=Date.now}={}){ +export function createClanWarConquests(db,keys,{readWinningCampaign,verifySnapshot,settlePolitical=null,clock=Date.now}={}){ if(!keys||typeof readWinningCampaign!=='function'||typeof verifySnapshot!=='function')throw TypeError('Verified campaign and current deed adapters are required.'); const load=(store,request)=>first(store,'SELECT * FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[request,ACTION]); return async campaignId=>{ if(!uuid(campaignId))fail('Invalid campaign reference.'); const campaign=await readWinningCampaign(campaignId); - if(!campaign||campaign.id!==campaignId||campaign.mode!=='clan'||!campaign.winnerSideId||campaign.teams.length!==2||campaign.teams.some(t=>t.party?.kind!=='clan'||t.party.id!==t.id)||!campaign.captures.length||campaign.captures.at(-1).sideId!==campaign.winnerSideId||!campaign.provinces.every(p=>p.ownerSideId===campaign.winnerSideId))fail('A verified completed clan campaign is required.'); + const political=campaign&&['world','universal','religious'].includes(campaign.mode); + if(!campaign||campaign.id!==campaignId||!campaign.winnerSideId||!campaign.teams.some(t=>t.id===campaign.winnerSideId)||!campaign.provinces.length||!campaign.captures.length||campaign.captures.at(-1).sideId!==campaign.winnerSideId||!campaign.provinces.every(p=>p.ownerSideId===campaign.winnerSideId)||(!political&&(campaign.mode!=='clan'||campaign.teams.length!==2||campaign.teams.some(t=>t.party?.kind!=='clan'||t.party.id!==t.id)))||(political&&(typeof settlePolitical!=='function'||campaign.teams.some(t=>t.party?.kind!=='politics'))))fail('A verified completed campaign is required.'); const requestId=stableId(campaignId,'conquest'),scopeId='war-conquest:'+campaignId,sourceHash=hash(campaign),fields={campaignId,winnerId:campaign.winnerSideId,sourceHash},encoded=JSON.stringify(fields); const existing=await load(db,requestId); if(existing){if(existing.fields_json!==encoded)fail('The recorded conquest source changed.');if(existing.state==='applied')return {keyId:existing.key_id,state:'applied',replayed:true,...JSON.parse(existing.manifest_json).receipt};} @@ -38,8 +39,9 @@ export function createClanWarConquests(db,keys,{readWinningCampaign,verifySnapsh await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',code:available.code,targetId:campaign.winnerSideId,requestId,apply:async(tx,{keyId,scopeId:scope})=>{ const locked=await load(tx,requestId);if(scope!==scopeId||locked?.key_id!==keyId||locked.state!=='issued'||locked.fields_json!==encoded)fail('The conquest instrument changed.'); const authority=await verify(tx); - for(const loser of authority.loserIds)await setEntityParent(tx,{childKind:'clan',childId:loser,parentKind:'clan',parentId:authority.winnerId,origin:'conquest',keyId,requestId:stableId(campaignId,'parent:'+loser),actorId:authority.winnerOwnerId,now:clock()}); - const receipt={winnerId:authority.winnerId,loserIds:authority.loserIds,settledAt:clock(),sourceHash}; + const result=political?await settlePolitical(tx,{campaign,authority,keyId,requestId,now:clock()}):null; + if(!political)for(const loser of authority.loserIds)await setEntityParent(tx,{childKind:'clan',childId:loser,parentKind:'clan',parentId:authority.winnerId,origin:'conquest',keyId,requestId:stableId(campaignId,'parent:'+loser),actorId:authority.winnerOwnerId,now:clock()}); + const receipt={winnerId:authority.winnerId,loserIds:authority.loserIds,...result,settledAt:clock(),sourceHash}; await tx.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=?",[JSON.stringify({...JSON.parse(locked.manifest_json),receipt}),keyId]); }}); const done=await load(db,requestId);if(done?.state!=='applied')fail('Conquest settlement remains pending.'); diff --git a/website/node/war-exchange.mjs b/website/node/war-exchange.mjs index 688bc4de..9ec87c55 100644 --- a/website/node/war-exchange.mjs +++ b/website/node/war-exchange.mjs @@ -4,8 +4,11 @@ import {createEventAuthority,eventInput} from './jarvis-events.mjs'; import {createRealmEventRecord} from './realm-event-records.mjs'; import {readWarCampaignReport,cancelPreparedWarCampaign,prepareWarCampaign} from './war-campaign-store.mjs'; import {PUBLIC_OFFICES} from './public-government.mjs'; +import {WAR_COALITION_SCHEMA,readWarCoalitions,changeWarCoalition} from './war-coalitions.mjs'; +import {politicalWarParties} from './war-political-rosters.mjs'; import {WAR_BLOCK_MS,WAR_MODES,warPartyKey,agreedWarBlock} from '../control-panel/public/war-exchange-policy.mjs'; export const WAR_EXCHANGE_SCHEMA=[ + WAR_COALITION_SCHEMA, `CREATE TABLE IF NOT EXISTS jarvis_war_calendar_guard(id INTEGER PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, `CREATE TABLE IF NOT EXISTS jarvis_war_proposals(id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,scope_kind VARCHAR(12) NOT NULL,scope_id VARCHAR(36) NOT NULL,mode VARCHAR(16) NOT NULL,title VARCHAR(100) NOT NULL,message TEXT NOT NULL,parties_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,revision INTEGER NOT NULL,calendar_event_id CHAR(36) NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, `CREATE TABLE IF NOT EXISTS jarvis_war_slots(proposal_id CHAR(36) NOT NULL,party_key VARCHAR(50) NOT NULL,starts_at BIGINT NOT NULL,ends_at BIGINT NOT NULL,actor_id CHAR(36) NOT NULL,request_id CHAR(36) NOT NULL UNIQUE,created_at BIGINT NOT NULL,PRIMARY KEY(proposal_id,party_key)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, @@ -39,13 +42,15 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent if(!context)return reply({contexts,parties:choices,proposals:[],context:null,canManage:false}); if(kind&&id&&!contexts.some(p=>p.kind===kind&&p.id===id))fail('Current clan or political deed required.',403); const proposals=await store.query('SELECT * FROM jarvis_war_proposals ORDER BY created_at DESC,id LIMIT 501');if(proposals.length>500)fail('Narrow the war proposal register.',409); - const visible=proposals.filter(r=>JSON.parse(r.parties_json).some(p=>warPartyKey(p)===warPartyKey(context))),result=[]; + const invited=await store.query('SELECT proposal_id FROM jarvis_war_coalitions WHERE ally_kind=? AND ally_id=?',[context.kind,context.id]); + const visible=proposals.filter(r=>context.kind==='politics'&&r.mode!=='clan'&&r.state==='open'||JSON.parse(r.parties_json).some(p=>warPartyKey(p)===warPartyKey(context))||invited.some(a=>a.proposal_id===r.id)),result=[]; for(const p of visible){ const proposal=project(p,await store.query('SELECT * FROM jarvis_war_slots WHERE proposal_id=?',[p.id]));proposal.campaignReport=await readWarCampaignReport(store,p.id,clock()); + proposal.coalitions=await readWarCoalitions(store,p.id,{authorize}); if(resolveRoster&&p.state==='open'){ const saved=await store.first('SELECT selection_json FROM jarvis_war_rosters WHERE proposal_id=? AND party_key=?',[p.id,warPartyKey(context)]); // Only the acting side sees its verified identities. Opposing rosters stay private. - proposal.roster=await resolveRoster(context,p.mode); + proposal.roster=await resolveRoster(context,p.mode,undefined,{...proposal,allies:proposal.coalitions.filter(a=>a.accepted)}); if(proposal.roster&&saved){const selection=JSON.parse(saved.selection_json),available=new Set(proposal.roster.candidates.map(m=>m.uuid));proposal.roster.selected=selection;proposal.roster.needsReview=selection.some(id=>!available.has(id));} } result.push(proposal); @@ -56,7 +61,7 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent if(url.search||request.headers.get('origin')!==origin)fail('Origin rejected.',403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))fail('JSON required.',415); const raw=await request.text();if(raw.length>12000)fail('Proposal too large.',413);let input;try{input=JSON.parse(raw);}catch{fail('Invalid proposal.');} - if(!input||!['publish','select','withdraw','roster'].includes(input.action)||!uuid(input.requestId)||!validParty(input.party))fail('Choose a current organisation and request.'); + if(!input||!['publish','select','withdraw','roster','ally'].includes(input.action)||!uuid(input.requestId)||!validParty(input.party))fail('Choose a current organisation and request.'); if(!await authorize(actor,input.party.kind,input.party.id))fail('Current clan or political deed required.',403); const choices=await parties(); return reply(await store.transaction(async tx=>{ @@ -68,7 +73,9 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent if(input.action==='publish'){ if(!Object.hasOwn(WAR_MODES,input.mode)||!Array.isArray(input.parties)||input.parties.length!==WAR_MODES[input.mode].parties||!input.parties.every(validParty)||new Set(input.parties.map(warPartyKey)).size!==input.parties.length||!input.parties.some(p=>warPartyKey(p)===warPartyKey(input.party))||typeof input.title!=='string'||input.title.trim().length<3||input.title.length>100||typeof input.message!=='string'||input.message.length>1000||/[\x00-\x1f\x7f]/.test(input.title)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(input.message))fail('Review the war mode, parties, title and terms.'); if(input.mode==='clan'&&input.parties.some(p=>p.kind!=='clan')||input.mode!=='clan'&&input.parties.some(p=>p.kind!=='politics'))fail('Clan wars require clans; larger wars require political sides.'); - const selected=input.parties.map(p=>choices.find(c=>warPartyKey(c)===warPartyKey(p)));if(selected.some(p=>!p))fail('An organisation is no longer available.',409); + if(input.mode!=='clan')politicalWarParties(input.mode,input.parties); + let selected=input.parties.map(p=>choices.find(c=>warPartyKey(c)===warPartyKey(p)));if(selected.some(p=>!p))fail('An organisation is no longer available.',409); + if(input.mode!=='clan')selected=politicalWarParties(input.mode,selected); const encoded=JSON.stringify(selected),prior=await tx.first('SELECT * FROM jarvis_war_proposals WHERE request_id=? FOR UPDATE',[input.requestId]); if(prior){if(prior.actor_id!==actor.id||prior.scope_kind!==input.party.kind||prior.scope_id!==input.party.id||prior.mode!==input.mode||prior.title!==input.title.trim()||prior.message!==input.message||prior.parties_json!==encoded)fail('Proposal reference conflict.',409);return {proposal:project(prior,await tx.query('SELECT * FROM jarvis_war_slots WHERE proposal_id=?',[prior.id])),replayed:true};} const id=randomUUID(),now=clock();await tx.query("INSERT INTO jarvis_war_proposals VALUES(?,?,?,?,?,?,?,?,?,'open',1,NULL,?,?)",[id,input.requestId,actor.id,input.party.kind,input.party.id,input.mode,input.title.trim(),input.message,encoded,now,now]);await audit(tx,id,actor,'published',{parties:selected,mode:input.mode}); @@ -76,7 +83,14 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent } if(!uuid(input.id)||!Number.isSafeInteger(input.revision))fail('Choose a current proposal.'); const current=await tx.first('SELECT * FROM jarvis_war_proposals WHERE id=? FOR UPDATE',[input.id]);if(!current)fail('Proposal unavailable.',404); - const members=JSON.parse(current.parties_json);if(!members.some(p=>warPartyKey(p)===warPartyKey(input.party)))fail('Only a named party can respond.',403); + const members=JSON.parse(current.parties_json); + if(input.action==='ally'){ + if(!validParty(input.side)||!validParty(input.ally))fail('Choose current coalition organisations.'); + const result=await changeWarCoalition(tx,{proposal:current,input,actor,authorize,choices,now:clock()}); + return {proposal:project(await tx.first('SELECT * FROM jarvis_war_proposals WHERE id=?',[current.id])),...result}; + } + if(!members.some(p=>warPartyKey(p)===warPartyKey(input.party)))fail('Only a named party can respond.',403); + const coalitionProposal={id:current.id,parties:members,allies:(await readWarCoalitions(tx,current.id,{authorize})).filter(a=>a.accepted)}; const selected=await tx.query('SELECT * FROM jarvis_war_slots WHERE proposal_id=?',[current.id]); if(input.action==='roster'){ if(!Array.isArray(input.players)||input.players.length<1||input.players.length>86||input.players.some(p=>!uuid(p))||new Set(input.players).size!==input.players.length)fail('Choose a unique verified player roster.'); @@ -84,7 +98,7 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent const prior=history.find(h=>JSON.parse(h.details).requestId===input.requestId); if(prior){const d=JSON.parse(prior.details);if(prior.actor_id!==actor.id||d.partyKey!==key||JSON.stringify(d.players)!==JSON.stringify(input.players))fail('Roster reference conflict.',409);return {proposal:project(current,selected),replayed:true};} if(Number(current.revision)!==input.revision||current.state!=='open')fail('The roster is frozen after agreement. Refresh before responding.',409); - if(!resolveRoster||!await resolveRoster(input.party,current.mode,input.players))fail('Roster selection is not available for this war mode.',409); + if(!resolveRoster||!await resolveRoster(input.party,current.mode,input.players,coalitionProposal))fail('Roster selection is not available for this war mode.',409); await tx.query('INSERT INTO jarvis_war_rosters VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE selection_json=VALUES(selection_json),actor_id=VALUES(actor_id),request_id=VALUES(request_id),updated_at=VALUES(updated_at)',[current.id,key,JSON.stringify(input.players),actor.id,input.requestId,clock()]); // Changing participants changes the terms: every side must pick its hour again. await tx.query('DELETE FROM jarvis_war_slots WHERE proposal_id=?',[current.id]); @@ -114,14 +128,15 @@ export function createWarExchange(central,store,{authenticate=r=>identity(r,cent for(const selection of all){const party=members.find(p=>warPartyKey(p)===selection.party_key);if(!party||!await authorize({id:selection.actor_id},party.kind,party.id)){await tx.query('DELETE FROM jarvis_war_slots WHERE proposal_id=? AND party_key=?',[current.id,selection.party_key]);await audit(tx,current.id,actor,'authority-expired',{partyKey:selection.party_key});}} all=await tx.query('SELECT * FROM jarvis_war_slots WHERE proposal_id=?',[current.id]);const block=agreedWarBlock(members,rows(all));let eventId=null; if(block){ - if(resolveRoster)for(const saved of await tx.query('SELECT party_key,selection_json FROM jarvis_war_rosters WHERE proposal_id=?',[current.id])){const party=members.find(p=>warPartyKey(p)===saved.party_key);if(!party||!await resolveRoster(party,current.mode,JSON.parse(saved.selection_json)))fail('A saved roster requires review.',409);} + coalitionProposal.allies=await readWarCoalitions(tx,current.id,{authorize,requireAgreement:true}); + if(resolveRoster)for(const saved of await tx.query('SELECT party_key,selection_json FROM jarvis_war_rosters WHERE proposal_id=?',[current.id])){const party=members.find(p=>warPartyKey(p)===saved.party_key);if(!party||!await resolveRoster(party,current.mode,JSON.parse(saved.selection_json),coalitionProposal))fail('A saved roster requires review.',409);} for(const party of members){ const conflict=await tx.first("SELECT p.id FROM jarvis_war_proposals p JOIN jarvis_war_slots s ON s.proposal_id=p.id WHERE p.state='scheduled' AND p.id<>? AND s.party_key=? AND s.starts_at? LIMIT 1",[current.id,warPartyKey(party),block.endsAt,block.startsAt]); if(conflict)fail('A named party already has a war in this calendar block.',409); } const event=eventInput({kind:input.party.kind,scopeId:input.party.id,requestId:stableId(current.id,'calendar'),title:current.title,description:'War Exchange · '+members.map(p=>p.name).join(' vs ')+'\n'+current.message,...block,confirmed:true}); eventId=(await createRealmEventRecord(tx,actor,event,clock())).eventId; - if(resolveCampaign){const saved=await tx.query('SELECT party_key,selection_json FROM jarvis_war_rosters WHERE proposal_id=?',[current.id]),rosters=Object.fromEntries(saved.map(r=>[r.party_key,JSON.parse(r.selection_json)]));const proposal={id:current.id,mode:current.mode,state:'scheduled',parties:members,block,rosters};const snapshot=await resolveCampaign(proposal);if(snapshot)await prepareWarCampaign(tx,proposal,snapshot,clock());} + if(resolveCampaign){const saved=await tx.query('SELECT party_key,selection_json FROM jarvis_war_rosters WHERE proposal_id=?',[current.id]),rosters=Object.fromEntries(saved.map(r=>[r.party_key,JSON.parse(r.selection_json)]));const proposal={id:current.id,mode:current.mode,state:'scheduled',parties:members,block,rosters,allies:coalitionProposal.allies};const snapshot=await resolveCampaign(proposal);if(snapshot)await prepareWarCampaign(tx,proposal,snapshot,clock());} } await tx.query('UPDATE jarvis_war_proposals SET state=?,calendar_event_id=?,revision=revision+1,updated_at=? WHERE id=?',[block?'scheduled':'open',eventId,clock(),current.id]);await audit(tx,current.id,actor,block?'scheduled':'block-selected',{party:input.party,startsAt:input.startsAt,endsAt:input.endsAt}); } diff --git a/website/node/war-military-affiliations.mjs b/website/node/war-military-affiliations.mjs index d9e643f2..6a0e074b 100644 --- a/website/node/war-military-affiliations.mjs +++ b/website/node/war-military-affiliations.mjs @@ -15,7 +15,11 @@ export function planMilitaryAffiliations(state){ if(office.lifecycle!=='active'||!uuid(office.source?.termId)||!uuid(office.source?.keyId))continue; for(const member of office.members||[]){if(!uuid(member.uuid)||typeof member.binding!=='string')continue;const entries=memberships.get(member.uuid)||[];entries.push({office,member});memberships.set(member.uuid,entries);} } - for(const [owner,entries]of memberships)if(new Set(entries.map(e=>e.office.officeKey)).size>1)reviewOwners.push(owner); + for(const [owner,entries]of memberships){ + const emperor=entries.find(e=>e.office.officeKey==='emperor'&&e.office.leader?.uuid===owner); + if(emperor)memberships.set(owner,[emperor]); + else if(new Set(entries.map(e=>e.office.officeKey)).size>1)reviewOwners.push(owner); + } for(const [kind,records]of [['clan',state.clans],['company',state.companies]])for(const child of records){ if(child.lifecycle!=='active'||child.protected||child.hidden||!uuid(child.ownerUuid)||reviewOwners.includes(child.ownerUuid))continue; // Appointments bind an owner's existing mother, never take a client's mother diff --git a/website/node/war-native-relations.mjs b/website/node/war-native-relations.mjs index ee27268d..9923af8b 100644 --- a/website/node/war-native-relations.mjs +++ b/website/node/war-native-relations.mjs @@ -4,10 +4,12 @@ const stableId=value=>{const h=createHash('sha256').update(value).digest('hex'); export function campaignWarRelations(campaigns,now=Date.now()){ const result=[]; for(const c of campaigns){ - const phase=campaignPhase(c,now);if(c.mode!=='clan'||!['scheduled','active'].includes(phase))continue;const pairs=new Set(),roster=c.teams.flatMap(t=>t.roster.map(p=>p.uuid)).sort(); + const phase=campaignPhase(c,now);if(!['scheduled','active'].includes(phase))continue;const pairs=new Set(),roster=c.teams.flatMap(t=>t.roster.map(p=>p.uuid)).sort(); for(let i=0;ij!==i)){ + const other=opposing.id,pair=[clan,other].sort().join(':');if(clan===other||pairs.has(pair))continue;pairs.add(pair); result.push({keyId:stableId('war-campaign:'+c.id+':'+pair),campaignId:c.id,source:'war-campaign',attackerId:clan,defenderId:other,declaredAt:c.startsAt,expiresAt:c.endsAt,active:phase==='active',reserved:phase==='scheduled',roster}); + } } } if(result.length>500)throw Error('Campaign native relations exceed the supported batch.');return result; diff --git a/website/node/war-political-conquests.mjs b/website/node/war-political-conquests.mjs new file mode 100644 index 00000000..6cbc6e3d --- /dev/null +++ b/website/node/war-political-conquests.mjs @@ -0,0 +1,38 @@ +import {createHash} from 'node:crypto'; +import {setEntityParent} from './entity-relations.mjs'; +import {transferOfficeDeed} from './office-deed-transfer.mjs'; +const fail=message=>{throw Object.assign(Error(message),{status:409});}; +const id=(campaign,label)=>{const h=createHash('sha256').update(campaign+':'+label).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);}; + +// Called only by the verified victory consumer, inside consumption of its +// existing staff-parent-link instrument. No request may supply these deeds. +export async function politicalConquestAuthority(tx,campaign,state){ + const winner=campaign.teams.find(t=>t.id===campaign.winnerSideId),mandate=winner?.mandates.find(m=>m.officeKey===winner.party.id); + if(!mandate)fail('The winning political mandate is unavailable.'); + const person=await tx.first("SELECT a.id FROM site_accounts a JOIN site_game_links g ON g.user_id=a.id WHERE LOWER(g.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('official_account','system_account','memorial') FOR UPDATE",[mandate.ownerUuid.toLowerCase()]); + if(!person)fail('The winning office requires its current personal controller.'); + const losing=campaign.teams.filter(t=>t.id!==winner.id),losingClans=new Set(losing.flatMap(t=>(t.clanDeeds||[]).map(c=>c.id))); + const roots=state.clans.filter(c=>losingClans.has(c.id)&&!c.protected&&!(c.parent?.kind==='clan'&&losingClans.has(c.parent.id))).map(c=>c.id).sort(); + const imperial=campaign.provinces.find(p=>p.imperial&&p.sideId!==winner.id); + const estates=imperial?[...state.clans.map(c=>({...c,kind:'clan'})),...(state.companies||[]).map(c=>({...c,kind:'company'}))].filter(c=>c.lifecycle==='active'&&!c.protected&&!c.hidden&&c.ownerUuid===imperial.deedOwnerUuid&&(!c.parent||c.parent.kind==='politics'&&c.parent.id==='emperor')).map(c=>({kind:c.kind,id:c.id})).sort((a,b)=>(a.kind+a.id).localeCompare(b.kind+b.id)):[]; + return {winnerId:winner.id,winnerOwnerId:person.id,winnerOffice:winner.party.id,winnerUuid:mandate.ownerUuid,loserIds:losing.map(t=>t.id),clanRoots:roots,imperial:imperial?{sourceTermId:imperial.mandateTermId,previousUuid:imperial.deedOwnerUuid,estates}:null}; +} +export async function settlePoliticalConquest(tx,{campaign,authority,keyId,now}){ + const changes=[]; + for(const clan of authority.clanRoots){ + // Imperial personal estates stay under the Imperial institution after its + // succession; unrelated clients retain their complete original subtrees. + const imperialEstate=authority.imperial?.estates.some(e=>e.kind==='clan'&&e.id===clan); + const parent=imperialEstate?'emperor':authority.winnerOffice; + await setEntityParent(tx,{childKind:'clan',childId:clan,parentKind:'politics',parentId:parent,origin:'conquest',keyId,requestId:id(campaign.id,'clan:'+clan),actorId:authority.winnerOwnerId,now}); + changes.push({kind:'clan',id:clan,parent}); + } + let succession=null; + if(authority.imperial){ + succession=await transferOfficeDeed(tx,{termId:id(campaign.id,'imperial-term'),sourceTermId:authority.imperial.sourceTermId,officeKey:'emperor',winnerId:authority.winnerOwnerId,playerUuid:authority.winnerUuid,sourceId:campaign.id,method:'war',now}); + for(const estate of authority.imperial.estates){if(changes.some(c=>c.kind===estate.kind&&c.id===estate.id))continue; + await setEntityParent(tx,{childKind:estate.kind,childId:estate.id,parentKind:'politics',parentId:'emperor',origin:'conquest',keyId,requestId:id(campaign.id,estate.kind+':'+estate.id),actorId:authority.winnerOwnerId,now});changes.push({...estate,parent:'emperor'}); + } + } + return {parentChanges:changes,imperialSuccession:succession}; +} diff --git a/website/node/war-political-rosters.mjs b/website/node/war-political-rosters.mjs new file mode 100644 index 00000000..502c6f7a --- /dev/null +++ b/website/node/war-political-rosters.mjs @@ -0,0 +1,58 @@ +import {WAR_MODES,warPartyKey} from '../control-panel/public/war-exchange-policy.mjs'; +import {clanWarBranch,buildClanWarRoster} from './war-rosters.mjs'; +import {militaryClanId} from './war-military-projection.mjs'; +const worlds=new Set(['atreides','harkonnen','corrino','ordos','fremen','arrakis']); +const fail=message=>{throw Object.assign(Error(message),{status:409});}; +export function politicalWarParties(mode,parties){ + if(!['world','universal','religious'].includes(mode)||!Array.isArray(parties)||parties.length!==WAR_MODES[mode].parties||parties.some(p=>p.kind!=='politics')||new Set(parties.map(p=>p.id)).size!==parties.length)fail('Choose distinct political campaign sides.'); + if(mode==='world'&&parties.some(p=>!worlds.has(p.id)))fail('World wars require two native world offices.'); + if(mode==='universal'&&(!parties.some(p=>p.id==='emperor')||parties.some(p=>p.id!=='emperor'&&!worlds.has(p.id))))fail('Universal conflict requires the Empire and two independent world coalitions.'); + if(mode==='religious'&&(!parties.some(p=>p.id==='spacing_guild')||!parties.some(p=>p.id==='muad_dib')||parties.filter(p=>worlds.has(p.id)).length!==1))fail('War of Faith requires Guild, Church and an independent world coalition.'); + const order=mode==='religious'?['spacing_guild','muad_dib']:mode==='universal'?['emperor']:[]; + const rank=p=>order.includes(p.id)?order.indexOf(p.id):order.length; + return [...parties].sort((a,b)=>rank(a)-rank(b)); +} +function office(state,key){const o=state.offices.find(o=>o.officeKey===key);if(!o||o.lifecycle!=='active'||o.militaryReview||!o.leader?.uuid||!o.source?.termId||!o.source?.keyId)fail('A campaign office requires its current verified mandate and military roster.');return o;} +function affiliatedClans(state,key){return state.clans.filter(c=>{if(c.lifecycle!=='active'||c.protected)return false;let current=c;const seen=new Set();for(let depth=0;current&&depth<32;depth++){if(seen.has(current.id))fail('Military clan hierarchy contains a cycle.');seen.add(current.id);if(current.parent?.kind==='politics')return current.parent.id===key;current=current.parent?.kind==='clan'?state.clans.find(x=>x.id===current.parent.id):null;}if(current)fail('Military hierarchy exceeds supported depth.');return false;});} +export function politicalTeam(state,party,mode,allies=[],selection=null){ + const root=office(state,party.id),participants=[party,...allies.filter(a=>a.sideKey===warPartyKey(party)).map(a=>a.ally)]; + if(mode==='religious'&&party.id==='spacing_guild'&&!participants.some(p=>p.kind==='politics'&&p.id==='emperor'))participants.push({kind:'politics',id:'emperor'}); + const offices=[],clans=new Map(),rosterBranches=[]; + for(const participant of participants){ + if(participant.kind==='politics'){const current=office(state,participant.id);if(offices.some(o=>o.officeKey===current.officeKey))continue;offices.push(current);rosterBranches.push({id:militaryClanId(current.officeKey),ownerUuid:current.leader.uuid,members:current.members||[]});for(const clan of affiliatedClans(state,current.officeKey))clans.set(clan.id,clan);} + else if(participant.kind==='clan'){const branch=clanWarBranch(state.clans,participant.id);if(branch[0].protected)fail('Protected military clans join through their political office.');for(const clan of branch)clans.set(clan.id,clan);} + else fail('Invalid coalition participant.'); + } + const players=buildClanWarRoster([...rosterBranches,...clans.values()],WAR_MODES[mode].playersPerSide,selection); + return {root,offices,clans:[...clans.values()],team:{id:militaryClanId(party.id),name:root.name,party,officeKeys:offices.map(o=>o.officeKey),mandates:offices.map(o=>({officeKey:o.officeKey,keyId:o.source.keyId,termId:o.source.termId,ownerUuid:o.leader.uuid})),...players,clanIds:[...new Set([...offices.map(o=>militaryClanId(o.officeKey)),...clans.keys()])],clanDeeds:[...clans.values()].map(c=>({id:c.id,ownerUuid:c.ownerUuid}))}}; +} +export function buildPoliticalCampaignSnapshot(state,proposal,charters){ + politicalWarParties(proposal.mode,proposal.parties);const teams=[],provinces=[],seen=new Set(),entities=new Set(),homeServers=[]; + for(const party of proposal.parties){ + const current=politicalTeam(state,party,proposal.mode,proposal.allies||[],proposal.rosters?.[warPartyKey(party)]??null),team=current.team; + if(!team.roster.length||current.root.homeBlock?.source!=='minecraft')fail('Each political side needs a verified roster and registered in-game Home Block.'); + homeServers.push(current.root.homeServer);teams.push(team); + for(const id of team.clanIds){if(entities.has(id))fail('An organisation cannot participate on opposing sides.');entities.add(id);} + for(const record of [...current.offices,...current.clans]){ + if(proposal.mode==='world'&&record.officeKey===party.id&¤t.offices.some(o=>o.officeKey==='emperor'))continue; + if(record.homeBlock?.source!=='minecraft')continue;if(seen.has(record.homeBlock.id))fail('Coalition Home Blocks must be distinct.');seen.add(record.homeBlock.id); + const political=!!record.officeKey,key=political?record.source.keyId:charters.find(k=>k.clan_id===record.id)?.key_id; + if(!key)fail('A coalition Home Block requires its current charter.'); + provinces.push({id:record.homeBlock.id,kind:political?'protected':'clan',organisationId:record.id,name:record.name,sideId:team.id,deedKeyId:key,deedOwnerUuid:political?record.leader.uuid:record.ownerUuid,mandateTermId:political?record.source.termId:null,officeKey:record.officeKey||null,claimRevision:record.claimRevision,server:record.homeServer,homeBlock:structuredClone(record.homeBlock),imperial:record.officeKey==='emperor'}); + } + } + if(proposal.mode==='world'&&homeServers[0]===homeServers[1])fail('A world campaign requires two different home worlds.'); + if(['universal','religious'].includes(proposal.mode)&&!provinces.some(p=>p.imperial))fail('Register the Imperial final Home Block in game before agreeing this campaign.'); + // Keep the Imperial finale in the last map slot, independent of side ordering. + provinces.sort((a,b)=>Number(!!a.imperial)-Number(!!b.imperial)); + return {teams,provinces,coalitions:structuredClone(proposal.allies||[])}; +} +export function currentPoliticalCampaign(campaign,state,charters){ + const valid=new Set();for(const team of campaign.teams){ + const current=politicalTeam(state,team.party,campaign.mode,campaign.coalitions||[],null),members=new Set([...current.team.roster,...current.team.reserves].map(p=>p.uuid)); + for(const mandate of team.mandates||[]){const now=current.offices.find(o=>o.officeKey===mandate.officeKey);if(!now||now.source.keyId!==mandate.keyId||now.source.termId!==mandate.termId||now.leader.uuid!==mandate.ownerUuid)fail('A political campaign mandate changed.');} + for(const deed of team.clanDeeds||[])if(!current.clans.some(c=>c.id===deed.id&&c.ownerUuid===deed.ownerUuid))fail('A coalition clan deed changed.'); + for(const p of team.roster)if(members.has(p.uuid))valid.add(p.uuid); + for(const province of campaign.provinces.filter(p=>p.sideId===team.id)){const record=province.officeKey?current.offices.find(o=>o.officeKey===province.officeKey):current.clans.find(c=>c.id===province.organisationId);const key=province.officeKey?record?.source.keyId:charters.find(k=>k.clan_id===province.organisationId)?.key_id;if(!record||record.id!==province.organisationId||record.homeServer!==province.server||key!==province.deedKeyId||record.claimRevision!==province.claimRevision||JSON.stringify(record.homeBlock)!==JSON.stringify(province.homeBlock)||province.officeKey&&record.source.termId!==province.mandateTermId)fail('A political campaign Home Block or charter changed.');} + }return valid; +} diff --git a/website/node/war-quest-evidence.mjs b/website/node/war-quest-evidence.mjs new file mode 100644 index 00000000..2561b618 --- /dev/null +++ b/website/node/war-quest-evidence.mjs @@ -0,0 +1,24 @@ +import {createHash} from 'node:crypto'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +// Read facts from the same private campaign register used by the native bridge. +// This producer never accepts browser counters or treats calendar proposals as +// combat. Claims re-read the original capture and consumed conquest instrument. +export async function warQuestEvidence(bank,central,{minecraftUuid,startsAt,endsAt,now}){ + const totals=new Map(),proofIds=[];if(!bank)return {totals,proofIds}; + const rows=await bank.query('SELECT snapshot_json FROM jarvis_war_campaigns WHERE starts_at>=? AND starts_at500)throw Error('Campaign evidence register requires a narrower view.'); + for(const row of rows){ + const c=JSON.parse(row.snapshot_json);if(c.cancelledAt!=null)continue; + const team=c.teams.find(t=>t.roster.some(p=>p.uuid===minecraftUuid));if(!team)continue; + totals.set('pol-war-deployment',(totals.get('pol-war-deployment')||0)+1);proofIds.push('war-deployment:'+c.id+':'+team.id); + const captures=c.captures.filter(e=>e.playerUuid===minecraftUuid&&e.sideId===team.id&&e.capturedAt>=startsAt&&e.capturedAt'war-capture:'+e.eventId)); + if(c.winnerSideId!==team.id||!c.provinces.length||!c.provinces.every(p=>p.ownerSideId===team.id))continue; + const receipt=(await central.query("SELECT i.fields_json,i.manifest_json FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.action_id='war.conquest-settlement' AND i.state='applied' AND k.scope_id=? AND k.key_type='staff-parent-link' AND k.account_id=? AND k.used_at IS NOT NULL AND k.revoked_at IS NULL",['war-conquest:'+c.id,STAFF_OFFICE_ACCOUNT_ID]))[0]; + if(!receipt)continue;const source=JSON.parse(receipt.fields_json),result=JSON.parse(receipt.manifest_json).receipt; + if(source.campaignId!==c.id||source.winnerId!==team.id||source.sourceHash!==createHash('sha256').update(JSON.stringify(c)).digest('hex')||result?.winnerId!==team.id||result.sourceHash!==source.sourceHash||!Number.isSafeInteger(result.settledAt)||result.settledAt>now)continue; + totals.set('pol-war-victory',(totals.get('pol-war-victory')||0)+1);proofIds.push('war-victory:'+c.id+':'+source.sourceHash); + } + return {totals,proofIds}; +} diff --git a/website/tests/war-coalitions.test.mjs b/website/tests/war-coalitions.test.mjs new file mode 100644 index 00000000..9eeed808 --- /dev/null +++ b/website/tests/war-coalitions.test.mjs @@ -0,0 +1,24 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs'; +import {WAR_EXCHANGE_SCHEMA} from '../node/war-exchange.mjs'; +import {changeWarCoalition,readWarCoalitions} from '../node/war-coalitions.mjs'; +test('coalitions require both current authorities, reset calendar consent and rosters, and safely replay',async()=>{ + const db=new BankFixture();try{ + for(const sql of WAR_EXCHANGE_SCHEMA)await db.query(sql.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','')); + const side={kind:'politics',id:'atreides'},other={kind:'politics',id:'harkonnen'},ally={kind:'clan',id:randomUUID()},actors=[{id:randomUUID()},{id:randomUUID()}],id=randomUUID();let rights=true; + const authorize=async(a,k,i)=>rights&&(a.id===actors[0].id&&k===side.kind&&i===side.id||a.id===actors[1].id&&k===ally.kind&&i===ally.id); + await db.query("INSERT INTO jarvis_war_proposals VALUES(?,?,?,?,?,'world','War','Terms',?,'open',1,NULL,1,1)",[id,randomUUID(),actors[0].id,side.kind,side.id,JSON.stringify([side,other])]); + await db.query('INSERT INTO jarvis_war_slots VALUES(?,?,?,?,?,?,?)',[id,'politics:atreides',3600000,7200000,actors[0].id,randomUUID(),1]); + await db.query('INSERT INTO jarvis_war_rosters VALUES(?,?,?,?,?,?)',[id,'politics:atreides','[]',actors[0].id,randomUUID(),1]); + const input={party:side,side,ally,accept:true,revision:1,requestId:randomUUID()},change=(actor,input)=>db.transaction(async tx=>changeWarCoalition(tx,{proposal:await tx.first('SELECT * FROM jarvis_war_proposals WHERE id=?',[id]),actor,input,authorize,choices:[side,other,ally],now:2})); + assert.equal((await change(actors[0],input)).accepted,false); + assert.equal((await db.first('SELECT COUNT(*) n FROM jarvis_war_slots')).n,0);assert.equal((await db.first('SELECT COUNT(*) n FROM jarvis_war_rosters')).n,0); + assert.equal((await change(actors[0],input)).replayed,true);assert.equal((await db.first('SELECT revision FROM jarvis_war_proposals')).revision,2); + await assert.rejects(change(actors[0],{...input,accept:false}),/reference conflict/); + await assert.rejects(readWarCoalitions(db,id,{authorize,requireAgreement:true}),/both organisations/); + const consent={...input,party:ally,revision:2,requestId:randomUUID()};assert.equal((await change(actors[1],consent)).accepted,true);assert.equal((await readWarCoalitions(db,id,{authorize,requireAgreement:true}))[0].accepted,true); + rights=false;await assert.rejects(readWarCoalitions(db,id,{authorize,requireAgreement:true}),/both organisations/); + }finally{db.close();} +}); diff --git a/website/tests/war-political-conquests.test.mjs b/website/tests/war-political-conquests.test.mjs new file mode 100644 index 00000000..54b876c7 --- /dev/null +++ b/website/tests/war-political-conquests.test.mjs @@ -0,0 +1,31 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {fixture} from './rebellion-fixture.mjs'; +import {createClanWarConquests} from '../node/war-conquests.mjs'; +import {politicalConquestAuthority,settlePoliticalConquest} from '../node/war-political-conquests.mjs'; +import {entityParent} from '../node/entity-relations.mjs'; +async function rig(){ + const f=await fixture(),incumbentUuid=(await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.incumbent.id])).minecraft_uuid,teams=[{id:randomUUID(),party:{kind:'politics',id:'atreides'},mandates:[{officeKey:'atreides',ownerUuid:f.mc}],clanDeeds:[]},{id:randomUUID(),party:{kind:'politics',id:'emperor'},clanDeeds:[{id:f.defender}]},{id:randomUUID(),party:{kind:'politics',id:'harkonnen'},clanDeeds:[]}]; + const client=randomUUID();await f.db.query("INSERT INTO site_clans VALUES(?,?,?,'kaladam',1)",[client,'Nested client',f.people.Other.id]);await f.db.query('INSERT INTO site_clan_deeds VALUES(?,?,1,0)',[client,f.defender]); + const campaign={id:randomUUID(),mode:'universal',winnerSideId:teams[0].id,teams,provinces:[{id:f.home,imperial:true,sideId:teams[1].id,ownerSideId:teams[0].id,mandateTermId:f.term,deedOwnerUuid:incumbentUuid}],captures:[{sideId:teams[0].id}]}; + const state={clans:[{id:f.defender,lifecycle:'active',ownerUuid:incumbentUuid,parent:{kind:'politics',id:'emperor'}},{id:client,lifecycle:'active',ownerUuid:randomUUID(),parent:{kind:'clan',id:f.defender}}],companies:[]}; + const settle=createClanWarConquests(f.db,f.keys,{readWinningCampaign:async()=>campaign,verifySnapshot:tx=>politicalConquestAuthority(tx,campaign,state),settlePolitical:settlePoliticalConquest,clock:f.now}); + return {...f,client,campaign,settle}; +} +test('Imperial defeat atomically transfers the term and preserves original owners and nested clients under the institution',async()=>{ + const f=await rig();try{ + const old=await f.db.first('SELECT * FROM site_clan_deeds WHERE clan_id=?',[f.client]),result=await f.settle(f.campaign.id); + assert.equal(result.state,'applied');assert.ok(result.imperialSuccession.termId);assert.equal((await entityParent(f.db,'clan',f.defender)).parent_id,'emperor');assert.equal((await entityParent(f.db,'clan',f.defender)).relation_origin,'conquest');assert.deepEqual(await f.db.first('SELECT * FROM site_clan_deeds WHERE clan_id=?',[f.client]),old); + assert.equal((await f.db.first('SELECT owner_id FROM site_clans WHERE id=?',[f.defender])).owner_id,f.incumbent.id); + const term=await f.db.first('SELECT * FROM political_office_terms WHERE id=?',[result.imperialSuccession.termId]);assert.equal(term.user_id,f.winner.id);assert.equal(term.player_uuid,f.mc);assert.equal((await f.db.first('SELECT outcome FROM political_office_terms WHERE id=?',[f.term])).outcome,'superseded');assert.equal((await f.settle(f.campaign.id)).replayed,true); + }finally{f.db.close();} +}); +test('a failure during Imperial succession rolls back every conquest write and leaves its original key available for retry',async()=>{ + const f=await rig();try{ + f.db.sqlite.exec("CREATE TRIGGER fail_succession BEFORE INSERT ON political_office_events BEGIN SELECT RAISE(ABORT,'succession failure'); END;"); + await assert.rejects(f.settle(f.campaign.id),/succession failure/);assert.equal(await entityParent(f.db,'clan',f.defender),null);assert.equal((await f.db.first('SELECT outcome FROM political_office_terms WHERE id=?',[f.term])).outcome,'winner'); + const key=await f.db.first('SELECT id,used_at FROM organisation_keys WHERE scope_id=?',['war-conquest:'+f.campaign.id]);assert.equal(key.used_at,null); + f.db.sqlite.exec('DROP TRIGGER fail_succession');assert.equal((await f.settle(f.campaign.id)).keyId,key.id); + }finally{f.db.close();} +}); diff --git a/website/tests/war-political-rosters.test.mjs b/website/tests/war-political-rosters.test.mjs new file mode 100644 index 00000000..e69b1991 --- /dev/null +++ b/website/tests/war-political-rosters.test.mjs @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {buildPoliticalCampaignSnapshot,currentPoliticalCampaign,politicalWarParties} from '../node/war-political-rosters.mjs'; +import {createWarCampaign,captureWarProvince,imperialProvinceLocked} from '../node/war-campaign-model.mjs'; +import {campaignWarRelations} from '../node/war-native-relations.mjs'; +const party=id=>({kind:'politics',id}); +export function politicalFixture(mode='universal'){ + const offices=['emperor','atreides','harkonnen','spacing_guild','muad_dib','ordos'].map((officeKey,i)=>{const uuid=randomUUID(),home=randomUUID();return {id:randomUUID(),officeKey,name:officeKey,lifecycle:'active',leader:{uuid},source:{keyId:randomUUID(),termId:randomUUID()},members:[{uuid,name:officeKey}],homeServer:['kaitain','caladan','giedi-prime','arrakis','arrakis','sigma-draconis-iv'][i],claimRevision:1,homeBlock:{id:home,source:'minecraft',worldUuid:randomUUID(),position:{x:16*i,y:64,z:0}}};}); + const member=randomUUID(),clan={id:randomUUID(),name:'Mother',ownerUuid:member,lifecycle:'active',members:[{uuid:member}],parent:{kind:'politics',id:'atreides'}},client={id:randomUUID(),name:'Client',lifecycle:'active',ownerUuid:randomUUID(),members:[],parent:{kind:'clan',id:clan.id}}; + const state={offices,clans:[clan,client],companies:[]},proposal={mode,parties:(mode==='world'?['atreides','harkonnen']:mode==='religious'?['spacing_guild','muad_dib','ordos']:['emperor','atreides','harkonnen']).map(party)},charters=[]; + return {state,proposal,charters,offices,clan,client,snapshot:()=>buildPoliticalCampaignSnapshot(state,proposal,charters)}; +} +test('political snapshots include current military members and nested clans without changing their deeds',()=>{ + const f=politicalFixture(),before=JSON.stringify(f.state),snapshot=f.snapshot(); + assert.equal(snapshot.teams.length,3);assert.equal(snapshot.provinces.at(-1).officeKey,'emperor');assert.equal(snapshot.teams[1].roster.length,2);assert.ok(snapshot.teams[1].clanIds.includes(f.client.id));assert.equal(JSON.stringify(f.state),before); + const campaign=createWarCampaign({...snapshot,id:randomUUID(),...f.proposal,startsAt:3600000,endsAt:7200000}); + assert.equal(currentPoliticalCampaign(campaign,f.state,f.charters).size,4); + f.clan.members=[];assert.equal(currentPoliticalCampaign(campaign,f.state,f.charters).size,3); + f.offices[1].source.termId=randomUUID();assert.throws(()=>currentPoliticalCampaign(campaign,f.state,f.charters),/mandate changed/); +}); +test('all three native pairs and their client branches are projected; finale unlocks only after a challenger owns the rest',()=>{ + const f=politicalFixture(),campaign=createWarCampaign({...f.snapshot(),id:randomUUID(),...f.proposal,startsAt:3600000,endsAt:7200000}); + const relations=campaignWarRelations([campaign],3600001);for(let i=0;i<3;i++)for(let j=i+1;j<3;j++)assert.ok(relations.some(r=>[r.attackerId,r.defenderId].includes(campaign.teams[i].id)&&[r.attackerId,r.defenderId].includes(campaign.teams[j].id))); + const target=campaign.provinces.at(-1);assert.equal(imperialProvinceLocked(campaign,target),true); + let current=campaign;for(const p of campaign.provinces.filter(p=>!p.imperial&&p.sideId!==campaign.teams[1].id))current=captureWarProvince(current,{eventId:randomUUID(),playerUuid:campaign.teams[1].roster[0].uuid,provinceId:p.id,server:p.server,worldUuid:p.homeBlock.worldUuid,chunkX:Math.floor(p.homeBlock.position.x/16),chunkZ:0,claimRevision:1,expectedRevision:current.revision},3600002).campaign; + assert.equal(imperialProvinceLocked(current,target),false); +}); +test('religious Guild side automatically includes the Emperor; political allies keep their own original clan branches',()=>{ + const f=politicalFixture('religious');f.proposal.allies=[{sideKey:'politics:spacing_guild',ally:party('atreides'),accepted:true}]; + const snapshot=f.snapshot();assert.deepEqual(snapshot.teams[0].officeKeys,['spacing_guild','atreides','emperor']);assert.ok(snapshot.teams[0].clanIds.includes(f.client.id)); + assert.equal(snapshot.provinces.filter(p=>p.imperial).length,1); + f.proposal.allies.push({sideKey:'politics:muad_dib',ally:party('atreides'),accepted:true});assert.throws(()=>f.snapshot(),/opposing sides/); +}); +test('missing homes, overlapping offices and changed charters cannot silently form a campaign',()=>{ + const f=politicalFixture('world');delete f.offices[1].homeBlock;assert.throws(()=>f.snapshot(),/Home Block/); + assert.throws(()=>politicalWarParties('world',[party('emperor'),party('atreides')]),/native world/); + assert.throws(()=>politicalWarParties('religious',[party('emperor'),party('atreides'),party('harkonnen')]),/Faith/); +}); +test('Imperial intervention replaces one world province and cannot intervene in clan wars',()=>{ + const f=politicalFixture('world');f.proposal.allies=[{sideKey:'politics:atreides',ally:party('emperor'),accepted:true}]; + const snapshot=f.snapshot();assert.equal(snapshot.provinces.length,2);assert.equal(snapshot.provinces.some(p=>p.officeKey==='atreides'),false);assert.equal(snapshot.provinces.at(-1).officeKey,'emperor');assert.equal(snapshot.provinces.at(-1).sideId,snapshot.teams[0].id); + assert.deepEqual(politicalWarParties('universal',[party('harkonnen'),party('atreides'),party('emperor')]).map(p=>p.id),['emperor','harkonnen','atreides']); +}); diff --git a/website/tests/war-quest-evidence.test.mjs b/website/tests/war-quest-evidence.test.mjs new file mode 100644 index 00000000..cd280e09 --- /dev/null +++ b/website/tests/war-quest-evidence.test.mjs @@ -0,0 +1,24 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID,createHash} from 'node:crypto'; +import {systemCharacterFixture} from './system-character-fixture.mjs'; +import {initializePOLProgression,ensurePOLProgressionPolicy,ensureWarQuestPolicy} from '../node/progression-pol.mjs'; +import {initializePOLActivityEvents,createPOLActivityEvents} from '../node/pol-activity-events.mjs'; +import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs'; +import {warQuestEvidence} from '../node/war-quest-evidence.mjs'; +test('campaign evidence credits the existing POL engine once; forged game metrics and stale victory sources cannot claim',async()=>{ + const f=await systemCharacterFixture();try{ + await f.characters.provision(f.people.Owner,'thufir_hawat');await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock:()=>2000});await ensureWarQuestPolicy(f.db,f.keys,{clock:()=>2000});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true; + const uuid=randomUUID(),team=randomUUID(),campaign={id:randomUUID(),startsAt:3000,endsAt:3603000,teams:[{id:team,roster:[{uuid}]}],provinces:[{ownerSideId:team}],captures:[],winnerSideId:null}; + await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,f.people.Member.id]); + let time=4000,receipt=null;const bank={query:async()=>[{snapshot_json:JSON.stringify(campaign)}]},central={query:async()=>receipt?[receipt]:[]},runtime=createPOLProgressionRuntime(f.db,f.keys,{clock:()=>time,bank}); + await runtime.collect(f.people.Member);const first=(await runtime.quests.list(f.people.Member)).quests.find(q=>q.id==='POL-WAR-01');assert.equal(first.canClaim,true);assert.equal(first.xp,150); + const input={definitionId:first.id,revision:first.revision,requestId:randomUUID()};await runtime.quests.claim(f.people.Member,input);assert.equal((await runtime.quests.claim(f.people.Member,input)).replayed,true); + const events=createPOLActivityEvents(f.db,f.keys,{clock:()=>time,authorizeProducer:async()=>true});await assert.rejects(events.record({}, {eventId:randomUUID(),accountId:f.people.Member.id,minecraftUuid:uuid,seasonId:'S01',metric:'pol-war-victory',quantity:1,occurredAt:time,reference:randomUUID()}),/Registered quest/); + const evidence=()=>warQuestEvidence(bank,central,{minecraftUuid:uuid,startsAt:2000,endsAt:100000,now:time});assert.equal((await evidence()).totals.has('pol-war-capture'),false); + campaign.winnerSideId=team;campaign.captures.push({eventId:randomUUID(),playerUuid:uuid,sideId:team,capturedAt:3500});assert.equal((await evidence()).totals.get('pol-war-capture'),1);assert.equal((await evidence()).totals.has('pol-war-victory'),false); + const sourceHash=createHash('sha256').update(JSON.stringify(campaign)).digest('hex');receipt={fields_json:JSON.stringify({campaignId:campaign.id,winnerId:team,sourceHash}),manifest_json:JSON.stringify({receipt:{winnerId:team,sourceHash,settledAt:3800}})}; + assert.equal((await evidence()).totals.get('pol-war-victory'),1);campaign.captures[0].playerUuid=randomUUID();assert.equal((await evidence()).totals.has('pol-war-victory'),false); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_quest_claims')).n,1); + }finally{f.db.close();} +});