Project political military counterparts and reconcile scoped temporary mother links

This commit is contained in:
Dev 2026-11-24 04:17:48 +01:00
commit 463c7e9606
14 changed files with 206 additions and 15 deletions

View file

@ -1,6 +1,6 @@
plugins { java }
group = "com.dunerealms"
version = "0.5.32"
version = "0.5.33"
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") }
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")

View file

@ -25,7 +25,11 @@ final class NativeHomes {
var plugin=Bukkit.getPluginManager().getPlugin("MedievalFactions");var loader=plugin.getClass().getClassLoader();var services=call(plugin,"getServices");var factions=call(services,"getFactionService");var claims=call(services,"getClaimService");
for(var v:rows){var row=v.getAsJsonObject();String id=row.get("id").getAsString();if(!owned.contains(id)||!"active".equals(row.get("lifecycle").getAsString())||row.get("hidden").getAsBoolean())continue;var h=home(row);Location at=location(h);Object faction=call(factions,"getFactionByFactionId",id);if(faction==null)continue;
if(h==null){if(!receipt("clan",id).isEmpty()&&call(faction,"getHome")!=null)saveFactionHome(factions,faction,plugin,null);continue;}
if(at==null)continue;int x=Math.floorDiv(at.getBlockX(),16),z=Math.floorDiv(at.getBlockZ(),16);UUID world=at.getWorld().getUID();Object claim=call(claims,"getClaim",world,x,z);
if(at==null)continue;
// A political military counterpart shares the existing office vault. Its
// native home points there without claiming the same estate a second time.
if(row.has("homeProjection")&&"shared-political".equals(row.get("homeProjection").getAsString())){Object position=construct(loader.loadClass("com.dansplugins.factionsystem.area.MfPosition"),at.getWorld().getUID(),at.getX(),at.getY(),at.getZ(),0f,0f);if(!position.equals(call(faction,"getHome")))saveFactionHome(factions,faction,plugin,position);continue;}
int x=Math.floorDiv(at.getBlockX(),16),z=Math.floorDiv(at.getBlockZ(),16);UUID world=at.getWorld().getUID();Object claim=call(claims,"getClaim",world,x,z);
var estate=chunks(row,at);
// Check the whole expansion before writing its first chunk. Never take a
// foreign native claim merely because a central projection names it.

View file

@ -47,7 +47,7 @@ final class NativeKeyWorker implements AutoCloseable {
var state=api.nativeState(server);if(closed)return;
String desired=state.get("clans").toString()+state.get("companies")+state.get("offices")+state.get("wars")+(state.has("relocations")?state.get("relocations"):"")+(state.has("review")?state.get("review"):"");
if(desired.equals(appliedState))return;
var incoming=state.getAsJsonArray("clans");if(incoming==null||incoming.size()>500||state.getAsJsonArray("wars").size()>1000)throw new IllegalStateException("Native inventory invalid");
var incoming=state.getAsJsonArray("clans");if(incoming==null||incoming.size()>512||state.getAsJsonArray("wars").size()>1000)throw new IllegalStateException("Native inventory invalid");
// A remote war bridge faction is no longer local once its last war ends.
// Only remove our own projections; unresolved central deeds stay for review.
var records=incoming.deepCopy();var present=new HashSet<String>();for(var value:records)present.add(value.getAsJsonObject().get("id").getAsString());var review=new HashSet<String>();if(state.has("review"))for(var value:state.getAsJsonArray("review")){var row=value.getAsJsonObject();if("clan".equals(row.get("kind").getAsString()))review.add(row.get("id").getAsString());}

View file

@ -1,6 +1,6 @@
name: JarvisTranslator
main: com.dunerealms.jarvis.JarvisTranslator
version: 0.5.32
version: 0.5.33
api-version: '1.21.8'
description: Shared J.A.R.V.I.S. website API and native server action translator.
softdepend: [CoreProtect, SCore, ExecutableItems, ExecutableCrafting, DuneEss, ImageFrame, DecentHolograms, MedievalFactions, Towny, WorldGuard]

View file

@ -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','entity-state',[field('operationId','Campaign or appointment UUID'),field('childKind','Clan or company'),field('childId','Existing mother UUID'),field('parentId','Military mother UUID'),field('sourceKeyId','Verified political deed UUID'),field('requestId','Operation UUID')],{webIssue:false,recordOnly:true,domainAdapter:'attachWarSupermother/endWarSupermother',executionStatus:'internal-transaction-primitives-only',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. MILCLAN issuance and automatic office lifecycle are not connected yet; 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, update province colours and retain the protected Imperial final province. 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.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, update province colours and retain the protected Imperial final province. 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:'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',[]),

View file

@ -1,4 +1,5 @@
import {createWarExchange} from '../node/war-exchange.mjs';
import {createMilitaryAffiliations} from '../node/war-military-affiliations.mjs';
import {createGameWarAPI,createClanCampaignResolver,createClanWarSettlementAdapter,createClanRosterResolver} from '../node/game-wars.mjs';
import {createGameSpiceAPI} from '../node/game-spice.mjs';
import {createSpiceQuestReceipts} from '../node/spice-quest-receipts.mjs';
@ -562,7 +563,7 @@ export async function startPanel(settings=process.env){
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';
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:[{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:'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 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:'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};
const server=createServer(async(req,res)=>{try{
req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);}

View file

@ -1,6 +1,6 @@
{
"schemaVersion": 1,
"sourceHash": "4e1bc1fc7d99312b412dc5b774bbc44b20e781e8e26189c2c97f7b03d0b104cd",
"sourceHash": "7d19ccebe940bbf13507f9ffeed10dca91b30050a6bd9341632ad23f33e1d4dc",
"actions": [
{
"id": "war.calendar-agreement",
@ -61,7 +61,7 @@
"id": "war.military-affiliation",
"label": "War Exchange · MILCLAN temporary supermother",
"version": 1,
"keyType": "entity-state",
"keyType": "staff-parent-link",
"fields": [
{
"name": "ticketId",
@ -90,7 +90,7 @@
},
{
"name": "parentId",
"label": "Military mother UUID",
"label": "Political office key",
"type": "text",
"required": true
},
@ -107,7 +107,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. MILCLAN issuance and automatic office lifecycle are not connected yet; 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 remains off until coordinated native0.5.33 rollout; no website issuance or arbitrary parent writes.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true

View file

@ -12,6 +12,7 @@ import {createRebellionQuests} from './rebellion-quests.mjs';
import {readOrganisationMotd} from './organisation-motd.mjs';
import {nativeServer,scopeNativeState,NATIVE_SERVERS} from './native-server-scope.mjs';
import {registeredClaimChunks} from './game-claim-expansion.mjs';
import {projectMilitaryClans} from './war-military-projection.mjs';
const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const bounded=(rows,max)=>{if(rows.length>max)throw Error('Native inventory exceeds supported batch');return rows;};
@ -23,10 +24,10 @@ export async function readGameNativeState(db,{clock=Date.now}={}){
const reader=boardReadStore(store,db),now=clock();
const identities=bounded(await store.query('SELECT a.id,a.username,l.minecraft_uuid,p.total_xp reputation_xp,p.level_no reputation_level FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id LEFT JOIN jarvis_pol_progression_accounts p ON p.account_id=a.id ORDER BY a.id LIMIT 5001'),5000);
const people=new Map(identities.map(p=>[p.id,{uuid:p.minecraft_uuid.toLowerCase(),name:p.username,reputation:p.reputation_level===null?null:{xp:Number(p.reputation_xp),level:Number(p.reputation_level)}}]));
const parentRows=bounded(await store.query('SELECT child_kind,child_id,parent_kind,parent_id,key_id FROM jarvis_entity_relations ORDER BY child_kind,child_id LIMIT 1001'),1000);
const parent=(kind,id)=>{const p=parentRows.find(r=>r.child_kind===kind&&r.child_id===id);return p?{kind:p.parent_kind,id:p.parent_id,keyId:p.key_id}:null;};
const parentRows=bounded(await store.query('SELECT child_kind,child_id,parent_kind,parent_id,key_id,relation_origin FROM jarvis_entity_relations ORDER BY child_kind,child_id LIMIT 1001'),1000);
const parent=(kind,id)=>{const p=parentRows.find(r=>r.child_kind===kind&&r.child_id===id);return p?{kind:p.parent_kind,id:p.parent_id,keyId:p.key_id,origin:p.relation_origin}:null;};
const clans=[],companies=[],offices=[],review=[],relocations=[];
const roster=members=>members.filter(m=>people.has(m.id)).map(m=>({...people.get(m.id),role:m.role||m.clan_role})).sort((a,b)=>a.uuid.localeCompare(b.uuid));
const roster=members=>members.filter(m=>people.has(m.id)).map(m=>({...people.get(m.id),role:m.role||m.clan_role,binding:m.binding||null})).sort((a,b)=>a.uuid.localeCompare(b.uuid));
for(const row of bounded(await store.query('SELECT c.id,c.name,c.active,i.institution_key FROM site_clans c LEFT JOIN site_clan_institutions i ON i.clan_id=c.id ORDER BY c.id LIMIT 501'),500)){
if(Number(row.active)!==1){clans.push({id:row.id,lifecycle:'archived'});continue;}
try{
@ -51,6 +52,7 @@ export async function readGameNativeState(db,{clock=Date.now}={}){
}
const deed=await readCompanyDeed(reader,row.id),p=parent('company',row.id);
const record={id:row.id,name:deed.company.name,lifecycle:'active',protected:!!row.institution_key,hidden:isClandestineInstitution('company',row.id),version:deed.version,parent:p,members:roster(deed.members),managers:deed.controllers.filter(id=>people.has(id)).map(id=>people.get(id)),source:{kind:'company-deed',id:row.id}};
record.ownerUuid=people.get(deed.company.owner_account_id)?.uuid||null;
record.fingerprint=digest(record);companies.push(record);
}catch{review.push({kind:'company',id:row.id});}
}
@ -58,6 +60,10 @@ export async function readGameNativeState(db,{clock=Date.now}={}){
const charter=await reader.first('SELECT staff_key_id FROM political_office_charters WHERE office_key=?',[office.key]);if(!charter)continue;
const owner=await currentOfficeController(reader,office.key,now);
const record={id:politicalOfficeId(office.key),officeKey:office.key,name:office.scope,protected:true,lifecycle:'active',leader:owner?people.get(owner.userId)||null:null,source:{kind:'office-deed',keyId:charter.staff_key_id,termId:owner?.termId||null}};
if(owner){
try{const resolved=await createBoardDeedResolver(reader,{clock})(reader,'politics',record.id);if(resolved.organisation.lifecycle!=='active'||resolved.source.refs?.charterKeyId!==charter.staff_key_id||resolved.source.refs?.termId!==owner.termId)throw Error('Political military deed requires review');record.members=roster(resolved.policy.members);record.source.version=resolved.source.version;}
catch{review.push({kind:'military',id:record.id});record.militaryReview=true;record.members=[];}
}else record.members=[];
record.fingerprint=digest(record);offices.push(record);
}
for(const [kind,records]of [['clan',clans],['company',companies],['protected',offices]])for(const record of records){
@ -93,6 +99,6 @@ export function createGameNativeStateAPI(db,settings,{read=()=>readGameNativeSta
if(new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'Invalid request'},400);
const raw=await request.text();if(raw.length>128)return json({message:'Invalid request'},400);
let body;try{body=JSON.parse(raw);if(!body||body.action!=='read'||Object.keys(body).some(k=>!['action','server'].includes(k))||body.server!==undefined&&!NATIVE_SERVERS.includes(body.server))return json({message:'Invalid fields'},400);}catch{return json({message:'Invalid JSON'},400);}
try{const state=await read();return json(body.server?scopeNativeState(state,body.server):state);}catch{return json({message:'Native key view is temporarily unavailable'},503);}
try{let state=await read();if(settings.MILITARY_PROJECTION_ENABLED==='true')state=projectMilitaryClans(state);return json(body.server?scopeNativeState(state,body.server):state);}catch{return json({message:'Native key view is temporarily unavailable'},503);}
};
}

View file

@ -12,6 +12,10 @@ export function scopeNativeState(state,server){
if(relevant&&w.active===true){warIds.add(w.attackerId);warIds.add(w.defenderId);}return relevant;
});
const localClans=state.clans.filter(r=>r.lifecycle==='archived'||r.homeServer===server||warIds.has(r.id));
// Include only a referenced military mother, rather than importing every
// foreign office or moving a player's original primary clan membership.
const included=new Set(localClans.map(r=>r.id));
for(const row of [...localClans])if(row.parent?.kind==='clan'&&!included.has(row.parent.id)){const mother=clans.get(row.parent.id);if(mother?.source?.kind==='military-office-deed'){localClans.push(mother);included.add(mother.id);}}
const companies=state.companies.filter(r=>r.homeServer===server);
const needed=new Set(companies.map(r=>r.id)),offices=new Set();
// A native holding nation needs its parent towns. Only referenced dependencies,

View file

@ -15,7 +15,7 @@ async function previousParent(tx,kind,id){
// validate the live MILCLAN deed and authority before calling either function.
// Attach the existing mother only; every original nested child link stays intact.
export async function attachWarSupermother(tx,{operationId,childKind,childId,parentKind,parentId,keyId,requestId,actorId,now=Date.now()}){
if(!uuid(operationId)||!['clan','company'].includes(childKind)||childKind!==parentKind)invalid('A military affiliation requires matching organisation kinds.');
if(!uuid(operationId)||!['clan','company'].includes(childKind)||childKind!==parentKind&&parentKind!=='politics')invalid('A military affiliation requires a matching mother or political office.');
await guard(tx);
const prior=await tx.first('SELECT * FROM jarvis_war_affiliations WHERE operation_id=? AND child_kind=? AND child_id=? FOR UPDATE',[operationId,childKind,childId]);
if(prior){if(prior.parent_kind!==parentKind||prior.parent_id!==parentId||prior.key_id!==keyId||prior.installed_request_id!==requestId)invalid('Military affiliation reference conflict.');return {state:prior.state,replayed:true};}

View file

@ -0,0 +1,75 @@
import {createHash} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {attachWarSupermother,endWarSupermother} from './war-affiliations.mjs';
import {readGameNativeState} from './game-native-state.mjs';
import {boardReadStore} from './board-deed-source.mjs';
const ACTION='war.military-affiliation';
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const stableId=value=>{const h=hash(value);return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);};
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const fail=message=>{throw Object.assign(Error(message),{status:409});};
export function planMilitaryAffiliations(state){
const memberships=new Map(),reviewOffices=[],reviewOwners=[],plans=[];
for(const office of state.offices){
if(office.militaryReview){reviewOffices.push(office.officeKey);continue;}
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 [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
// from another owner or replace a permanent purchase/conquest relationship.
if(child.parent&&(child.parent.kind!=='politics'||child.parent.origin!=='war'))continue;
const matches=memberships.get(child.ownerUuid);if(!matches?.length)continue;
const {office,member}=matches[0],source={officeKey:office.officeKey,officeId:office.id,charterKeyId:office.source.keyId,termId:office.source.termId,binding:member.binding,childKind:kind,childId:child.id,ownerUuid:child.ownerUuid};
const operationId=stableId(['military-affiliation',source]);plans.push({operationId,...source});
}
return {plans,reviewOffices,reviewOwners,reviewChildren:(state.review||[]).map(r=>r.kind+':'+r.id)};
}
// No browser mutation route. The existing scheduler invokes one verified,
// scoped parent-link key for an appointment or its expiry. No ownership or bank
// account is replaced and no timer is added to a Minecraft server.
export function createMilitaryAffiliations(db,keys,{clock=Date.now,readAssignments=null}={}){
if(!keys)throw TypeError('Organisation key service required');
const read=readAssignments||(async tx=>{const reader=boardReadStore(tx||db,db);reader.readSnapshot=undefined;return planMilitaryAffiliations(await readGameNativeState(reader,{clock}));});
const first=(store,sql,args=[])=>store.first?store.first(sql,args):store.prepare(sql).bind(...args).first();
const load=(store,requestId)=>first(store,'SELECT * FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[requestId,ACTION]);
const uncertain=(state,row)=>state.reviewOffices.includes(row.parent_id)||state.reviewChildren.includes(row.child_kind+':'+row.child_id);
async function execute(action,source){
const operationId=source.operationId,requestId=stableId([ACTION,action,operationId]),scopeId='military-'+action+':'+operationId,fields={action,...source},encoded=JSON.stringify(fields);
const existing=await load(db,requestId);if(existing?.fields_json!==undefined&&existing.fields_json!==encoded)fail('Military instruction reference conflict.');if(existing?.state==='applied')return {state:'applied',replayed:true};
async function verify(tx){
const current=await read(tx);
if(action==='attach'){if(!current.plans.some(p=>JSON.stringify(p)===JSON.stringify(source)))fail('Political appointment or mother deed changed.');}
else{
const row=await tx.first('SELECT * FROM jarvis_war_affiliations WHERE operation_id=? AND child_kind=? AND child_id=? FOR UPDATE',[operationId,source.childKind,source.childId]);
if(!row||row.parent_kind!=='politics'||row.parent_id!==source.officeKey||uncertain(current,row)||current.reviewOwners.includes(source.ownerUuid)||current.plans.some(p=>p.operationId===operationId))fail('Military expiry requires a current resolved deed.');
}
}
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',scopeId,authorize:async(tx,{keyId})=>{
const prior=await load(tx,requestId);if(prior){if(prior.fields_json!==encoded)fail('Military instruction changed.');if(prior.state!=='applied')await verify(tx);return;}
await verify(tx);await tx.query("INSERT INTO jarvis_generated_instructions VALUES(?,?,?,?,1,?,?,'issued',?)",[keyId,requestId,STAFF_OFFICE_ACCOUNT_ID,ACTION,encoded,JSON.stringify({schema:1,source:fields}),clock()]);
}});
const instruction=await load(db,requestId);if(instruction?.key_id!==grant.id||instruction.fields_json!==encoded)fail('Military system instrument requires review.');if(instruction.state==='applied')return {state:'applied',replayed:true};
const available=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id&&k.status==='available');if(!available?.code)fail('Military system key unavailable.');
await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',code:available.code,targetId:source.childId,requestId,apply:async(tx,{keyId,scopeId:scope})=>{
const row=await load(tx,requestId);if(scope!==scopeId||row?.key_id!==keyId||row.state!=='issued'||row.fields_json!==encoded)fail('Military system instruction changed.');await verify(tx);
const input={operationId,childKind:source.childKind,childId:source.childId,actorId:STAFF_OFFICE_ACCOUNT_ID,now:clock()};
const result=action==='attach'?await attachWarSupermother(tx,{...input,parentKind:'politics',parentId:source.officeKey,keyId,requestId}):await endWarSupermother(tx,input);
await tx.query("UPDATE jarvis_generated_instructions SET state='applied',manifest_json=? WHERE key_id=?",[JSON.stringify({schema:1,source:fields,receipt:result}),keyId]);
}});
return {state:'applied',replayed:false};
}
return {async drain(){
const desired=await read(),active=await db.query("SELECT * FROM jarvis_war_affiliations WHERE state='active' AND parent_kind='politics' ORDER BY created_at,operation_id LIMIT 1001");if(active.length>1000)fail('Military affiliation register requires review.');
let attempted=0,applied=0,failed=0;
for(const row of active){if(attempted>=25)break;if(uncertain(desired,row)||desired.plans.some(p=>p.operationId===row.operation_id))continue;
const issued=await first(db,'SELECT fields_json FROM jarvis_generated_instructions WHERE key_id=? AND action_id=?',[row.key_id,ACTION]);if(!issued)continue;const {action,...source}=JSON.parse(issued.fields_json);if(action!=='attach'||desired.reviewOwners.includes(source.ownerUuid))continue;
attempted++;try{await execute('end',source);applied++;}catch{failed++;}
}
for(const plan of desired.plans){if(attempted>=25)break;if(active.some(r=>r.operation_id===plan.operationId))continue;attempted++;try{const result=await execute('attach',plan);if(!result.replayed)applied++;}catch{failed++;}}
return {attempted,applied,failed,review:desired.reviewOffices.length+desired.reviewOwners.length};
}};
}

View file

@ -0,0 +1,35 @@
import {createHash} from 'node:crypto';
import {PUBLIC_OFFICES} from './public-government.mjs';
import {entityId,HOUSES} from './postbank-authority.mjs';
const names={emperor:['Sardaukar','SAR'],atreides:['Atreides Household Guard','ATG'],harkonnen:['Harkonnen Iron Legion','HIL'],corrino:['Corrino Royal Guard','CRG'],ordos:['Ordos Shadow Guard','OSG'],fremen:['Fedaykin','FED'],veiled_concord:['Bene Gesserit','BGS'],muad_dib:['Qizarate','QIZ'],spacing_guild:['Spacing Guild','GLD'],clan_delegate:['Landsraad','LAN'],arrakis:['Council of Naibs','NAI']};
const worlds={emperor:'kaitain',atreides:'caladan',harkonnen:'giedi-prime',corrino:'kaitain',ordos:'sigma-draconis-iv',fremen:'arrakis',muad_dib:'arrakis',arrakis:'arrakis'};
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
export function militaryClanId(key){
if(!PUBLIC_OFFICES.some(o=>o.key===key))throw TypeError('Unknown political military counterpart');
const h=createHash('sha256').update('dunerealms:milclan:'+key).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);
}
export function politicalBankReference(key){
if(key==='emperor')return {kind:'office',key:'emperor',entityId:entityId('office','emperor')};
if(Object.hasOwn(HOUSES,key))return {kind:'office',key:'leader:'+key,entityId:entityId('office','leader:'+key)};
return null; // Do not invent an account for an office with no bank source.
}
export function projectMilitaryClans(state){
const next=structuredClone(state),byOffice=new Map(),ids=new Set(next.clans.map(c=>c.id));
for(const office of next.offices){
const definition=PUBLIC_OFFICES.find(o=>o.key===office.officeKey);if(!definition||office.lifecycle!=='active'||!uuid(office.source?.keyId))continue;
if(office.militaryReview){next.review??=[];next.review.push({kind:'clan',id:militaryClanId(office.officeKey)});continue;}
const id=militaryClanId(office.officeKey);if(ids.has(id))throw Error('Military projection identity collision');ids.add(id);byOffice.set(office.officeKey,id);
const [name,tag]=names[office.officeKey],members=office.members||[];
if(members.some(m=>!uuid(m.uuid)))throw Error('Military membership requires verified game identities');
const record={id,name,tag,description:'Political military counterpart · '+office.name,lifecycle:'active',protected:true,hidden:false,version:office.source.version||1,parent:null,
// MF supports one primary faction. Keep original clan membership and use
// liege/vassal edges for the military supermother; never duplicate players.
members:[],militaryMembers:members,managers:office.leader?[office.leader]:[],ownerUuid:office.leader?.uuid||null,
homeServer:office.homeServer||worlds[office.officeKey]||null,homeBlock:office.homeBlock||null,homeProjection:'shared-political',claimRevision:office.claimRevision||0,claimedChunks:[],usedChunks:0,claimTier:office.claimTier||null,motd:office.motd,
artwork:definition.art,bank:politicalBankReference(office.officeKey),politicalOfficeId:office.id,officeKey:office.officeKey,
source:{kind:'military-office-deed',keyId:office.source.keyId,termId:office.source.termId||null,officeKey:office.officeKey}};
record.fingerprint=createHash('sha256').update(JSON.stringify(record)).digest('hex');next.clans.push(record);
}
for(const clan of next.clans)if(clan.parent?.kind==='politics'&&byOffice.has(clan.parent.id))clan.parent={...clan.parent,kind:'clan',id:byOffice.get(clan.parent.id),sourceOfficeKey:clan.parent.id};
return next;
}

View file

@ -0,0 +1,46 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {randomUUID} from 'node:crypto';
import {companyFixture} from './company-deed-fixture.mjs';
import {GENERATOR_SCHEMA} from '../node/jarvis-master-generator.mjs';
import {planMilitaryAffiliations,createMilitaryAffiliations} from '../node/war-military-affiliations.mjs';
import {entityParent,setEntityParent} from '../node/entity-relations.mjs';
function state(kind='company'){
const owner=randomUUID(),child={id:randomUUID(),ownerUuid:owner,lifecycle:'active',parent:null};
return {clans:kind==='clan'?[child]:[],companies:kind==='company'?[child]:[],offices:[{id:randomUUID(),officeKey:'emperor',lifecycle:'active',source:{keyId:randomUUID(),termId:randomUUID()},members:[{uuid:owner,binding:'appointment:'+randomUUID()}]}],review:[]};
}
test('POL appointments attach only an owned mother, retain its clients and require an unambiguous office',()=>{
const s=state('clan'),child=s.clans[0];s.clans.push({...child,id:randomUUID(),parent:{kind:'clan',id:child.id}});const before=structuredClone(s),planned=planMilitaryAffiliations(s);assert.equal(planned.plans.length,1);assert.equal(planned.plans[0].childId,child.id);assert.deepEqual(s,before);
s.offices.push({...s.offices[0],officeKey:'atreides'});assert.equal(planMilitaryAffiliations(s).plans.length,0);assert.deepEqual(planMilitaryAffiliations(s).reviewOwners,[child.ownerUuid]);
s.offices.pop();child.parent={kind:'clan',id:randomUUID(),origin:'conquest'};assert.equal(planMilitaryAffiliations(s).plans.length,0,'A previous mother/conquest is not overwritten');
});
async function rig(){
const f=await companyFixture();await f.db.query(GENERATOR_SCHEMA);f.db.sqlite.exec('CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER)');
const id=await f.create(),s=state();s.companies[0].id=id;
const runtime=createMilitaryAffiliations(f.db,f.keys,{readAssignments:async()=>planMilitaryAffiliations(s)});
return {...f,state:s,id,runtime};
}
test('one scoped system key installs an office supermother; expiry uses a second key and retains owner',async()=>{
const f=await rig();try{
const original=await f.db.first('SELECT owner_account_id FROM site_company_deeds WHERE company_id=?',[f.id]);
assert.equal((await f.runtime.drain()).applied,1);const parent=await entityParent(f.db,'company',f.id);assert.equal(parent.parent_kind,'politics');assert.equal(parent.parent_id,'emperor');
assert.equal((await f.runtime.drain()).applied,0);assert.equal((await f.db.first("SELECT COUNT(*) n FROM jarvis_generated_instructions WHERE action_id='war.military-affiliation'")).n,1);
f.state.offices[0].members=[];assert.equal((await f.runtime.drain()).applied,1);assert.equal(await entityParent(f.db,'company',f.id),null);assert.deepEqual(await f.db.first('SELECT owner_account_id FROM site_company_deeds WHERE company_id=?',[f.id]),original);
assert.equal((await f.db.first("SELECT COUNT(*) n FROM jarvis_generated_instructions WHERE action_id='war.military-affiliation' AND state='applied'")).n,2);
}finally{f.db.close();}
});
test('failed audit rolls back attachment and consumption; retry uses the same issued key',async()=>{
const f=await rig();try{
f.db.sqlite.exec("CREATE TRIGGER fail_military BEFORE INSERT ON account_audit BEGIN SELECT RAISE(ABORT,'audit failure'); END");
assert.equal((await f.runtime.drain()).failed,1);assert.equal(await entityParent(f.db,'company',f.id),null);const key=await f.db.first("SELECT id,used_at FROM organisation_keys WHERE scope_id LIKE 'military-attach:%'");assert.equal(key.used_at,null);
f.db.sqlite.exec('DROP TRIGGER fail_military');assert.equal((await f.runtime.drain()).applied,1);assert.equal((await entityParent(f.db,'company',f.id)).key_id,key.id);assert.equal((await f.db.first("SELECT COUNT(*) n FROM organisation_keys WHERE scope_id LIKE 'military-attach:%'")).n,1);
}finally{f.db.close();}
});
test('expiry never undoes a newer conquest and ambiguous POL data retains the old affiliation for review',async()=>{
const f=await rig();try{
await f.runtime.drain();const initial=await entityParent(f.db,'company',f.id);
f.state.offices[0].militaryReview=true;assert.equal((await f.runtime.drain()).applied,0);assert.deepEqual(await entityParent(f.db,'company',f.id),initial);f.state.offices[0].militaryReview=false;
await f.db.transaction(tx=>setEntityParent(tx,{childKind:'company',childId:f.id,parentKind:'politics',parentId:'atreides',origin:'conquest',keyId:randomUUID(),requestId:randomUUID(),actorId:f.people.Owner.id}));const conquest=await entityParent(f.db,'company',f.id);
f.state.offices[0].members=[];await f.runtime.drain();assert.deepEqual(await entityParent(f.db,'company',f.id),conquest);assert.equal((await f.db.first('SELECT state FROM jarvis_war_affiliations')).state,'superseded');
}finally{f.db.close();}
});

View file

@ -0,0 +1,20 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {randomUUID} from 'node:crypto';
import {projectMilitaryClans,militaryClanId,politicalBankReference} from '../node/war-military-projection.mjs';
import {scopeNativeState} from '../node/native-server-scope.mjs';
import {entityId} from '../node/postbank-authority.mjs';
const source=()=>{const owner={uuid:randomUUID(),name:'Leader'},home={id:randomUUID(),source:'minecraft',worldUuid:randomUUID(),position:{x:10,y:64,z:10}};return {clans:[{id:randomUUID(),lifecycle:'active',homeServer:'caladan',members:[owner],parent:{kind:'politics',id:'emperor'}}],companies:[],offices:[{id:randomUUID(),officeKey:'emperor',name:'Emperor',lifecycle:'active',homeServer:'kaitain',homeBlock:home,claimRevision:4,members:[{...owner,role:'officeholder'}],leader:owner,source:{keyId:randomUUID(),termId:randomUUID()}}],wars:[],review:[]};};
test('military faction reuses POL deed, roster, art, bank and exact Home Block without duplicating primary membership',()=>{
const state=source(),before=structuredClone(state),view=projectMilitaryClans(state),mil=view.clans[1];
assert.deepEqual(state,before);assert.equal(mil.name,'Sardaukar');assert.equal(mil.id,militaryClanId('emperor'));assert.equal(mil.source.keyId,state.offices[0].source.keyId);
assert.deepEqual(mil.homeBlock,state.offices[0].homeBlock);assert.equal(mil.claimRevision,4);assert.deepEqual(mil.members,[]);assert.deepEqual(mil.militaryMembers,state.offices[0].members);assert.deepEqual(mil.claimedChunks,[]);assert.equal(mil.homeProjection,'shared-political');assert.equal(mil.bank.entityId,entityId('office','emperor'));
assert.equal(view.clans[0].parent.id,mil.id);assert.deepEqual(view.clans[0].members,state.clans[0].members);assert.equal(view.clans[0].parent.sourceOfficeKey,'emperor');
});
test('world databases include local counterparts and only their referenced foreign military mother',()=>{
const view=projectMilitaryClans(source());assert.equal(scopeNativeState(view,'caladan').clans.length,2);assert.equal(scopeNativeState(view,'kaitain').clans.length,1);assert.equal(scopeNativeState(view,'arrakis').clans.length,0);
});
test('unresolved political deed retains its native identity for review and unknown banks are not invented',()=>{
const state=source();state.offices[0].militaryReview=true;const view=projectMilitaryClans(state);assert.equal(view.clans.length,1);assert.deepEqual(view.review.at(-1),{kind:'clan',id:militaryClanId('emperor')});
assert.equal(politicalBankReference('clan_delegate'),null);assert.throws(()=>militaryClanId('made-up'),/Unknown/);
});