Merge commit 'afa1feb' into feat/golden-path-finish-web-20261205

This commit is contained in:
unimatrixgit 2026-12-05 19:23:09 +01:00
commit 96c3f601bc
18 changed files with 768 additions and 25 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 623 B

View file

@ -0,0 +1,487 @@
// The Search for Leto II. DATA ONLY: not registered in any branch list until the owner approves
// (see docs/SEARCH-FOR-LETO-II.md, section "Activation"). amountMinor is DM in minor units (100 = 1 DM) and needs an
// owner-approved funded reward config; itemReward ids are cosmetic template keys, delivered by a claim path that does not exist yet.
const rows=[
{
"id": "POL-LETO-WHISPER",
"title": "A Whisper at Vaerkring",
"objective": "Find Ishaq the Fedaykin runner in the Guild lobby and hear why the twins' guardians are asking questions.",
"metric": "leto-contact-runner",
"target": 1,
"requires": [],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 150,
"amountMinor": 15000,
"npcRole": "leto_runner",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "lobby",
"dimension": "NORMAL",
"world": "Vaerkring"
}
},
"dialogue": {
"version": 1,
"introduction": "Word moves faster than water in the Guild lobby. A runner of the Fedaykin is looking for someone who can walk the worlds without drawing a Navigator's eye.",
"context": "Find Ishaq the Fedaykin runner in the Guild lobby and hear why the twins' guardians are asking questions.",
"turnIn": "Stilgar's people have lost the trail of Leto, son of Muad'Dib. Start where the trail began: Sietch Tabr."
},
"itemReward": "leto/sietch-map-roll"
},
{
"id": "POL-LETO-TABR",
"title": "Home of the Twins",
"objective": "Reach Sietch Tabr in Arrakduin and speak with the Sietch Steward.",
"metric": "leto-contact-steward",
"target": 1,
"requires": [
"POL-LETO-WHISPER"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 200,
"amountMinor": 15000,
"npcRole": "leto_steward",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "arrakis",
"dimension": "NORMAL",
"world": "Arrakduin"
}
},
"dialogue": {
"version": 1,
"introduction": "Sietch Tabr is where Leto and Ghanima were born and raised among the Fremen. The Steward says the boy walked out of the sietch and has not been seen.",
"context": "Reach Sietch Tabr in Arrakduin and speak with the Sietch Steward.",
"turnIn": "The Steward gives you a water ring: proof that Tabr vouches for you."
},
"itemReward": "leto/tabr-water-ring"
},
{
"id": "POL-LETO-WATER",
"title": "The Price of Water",
"objective": "Gather 12 water bottles on Arrakis and deliver them to the Keeper of the Water Basin; the sietch owes a water debt to whoever helps it.",
"metric": "leto-gather-water",
"target": 12,
"requires": [
"POL-LETO-TABR"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 250,
"amountMinor": 20000,
"npcRole": "leto_waterkeeper",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "arrakis",
"dimension": "NORMAL",
"world": "Arrakduin"
}
},
"dialogue": {
"version": 1,
"introduction": "No Fremen speaks freely until water is settled. The Keeper counts every drop in the basin.",
"context": "Gather 12 water bottles on Arrakis and deliver them to the Keeper of the Water Basin; the sietch owes a water debt to whoever helps it.",
"turnIn": "The debt is paid. The Keeper points you to the old rumours of Jacurutu, the forbidden sietch."
},
"itemReward": null
},
{
"id": "POL-LETO-JACURUTU",
"title": "Where the Worms Sleep",
"objective": "Harvest 16 raw spice in the open sand and bring it to the Ecologist; the spice trance is needed to read what the desert remembers.",
"metric": "leto-gather-spice",
"target": 16,
"requires": [
"POL-LETO-WATER"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 300,
"amountMinor": 25000,
"npcRole": "leto_ecologist",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "arrakis",
"dimension": "NORMAL",
"world": "Arrakduin"
}
},
"dialogue": {
"version": 1,
"introduction": "Chani's old laboratory still studies the sand. The Ecologist believes the boy's tracks end near a sandtrout nursery.",
"context": "Harvest 16 raw spice in the open sand and bring it to the Ecologist; the spice trance is needed to read what the desert remembers.",
"turnIn": "The Ecologist presses a sandtrout token into your hand: living proof the sand-trail is real."
},
"itemReward": "leto/sandtrout-token"
},
{
"id": "POL-LETO-CALADAN",
"title": "The Sea Remembers",
"objective": "Travel to Caladan and find the House Archivist. Atreides records may name where a hidden heir would go.",
"metric": "leto-contact-archivist",
"target": 1,
"requires": [
"POL-LETO-JACURUTU"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 350,
"amountMinor": 25000,
"npcRole": "leto_archivist",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "caladan",
"dimension": "NORMAL",
"world": "Kaladam"
}
},
"dialogue": {
"version": 1,
"introduction": "On Caladan the Atreides line is written in stone and salt. The Archivist keeps what the sea has not taken.",
"context": "Travel to Caladan and find the House Archivist. Atreides records may name where a hidden heir would go.",
"turnIn": "Records confirm Leto had Atreides contacts beyond Arrakis. The thread leads to the Harkonnen pits."
},
"itemReward": null
},
{
"id": "POL-LETO-KELP",
"title": "Salt and Rope",
"objective": "Gather 32 kelp on Caladan; the Archivist trades records for honest work.",
"metric": "leto-gather-kelp",
"target": 32,
"requires": [
"POL-LETO-CALADAN"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 350,
"amountMinor": 25000,
"npcRole": "leto_archivist",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "caladan",
"dimension": "NORMAL",
"world": "Kaladam"
}
},
"dialogue": {
"version": 1,
"introduction": "The Archivist will not part with the sealed ledger until a fisher's debt is cleared.",
"context": "Gather 32 kelp on Caladan; the Archivist trades records for honest work.",
"turnIn": "The ledger is yours: it names a man who survived the pits of Giedi Prime."
},
"itemReward": null
},
{
"id": "POL-LETO-PITS",
"title": "Chains of Giedi Prime",
"objective": "Slip into Giedi Prime and find the Pit Informer. A former pit slave knows the Harkonnen cells.",
"metric": "leto-contact-informer",
"target": 1,
"requires": [
"POL-LETO-KELP"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 450,
"amountMinor": 30000,
"npcRole": "leto_informer",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "giedi-prime",
"dimension": "NORMAL",
"world": "Giedermark"
}
},
"dialogue": {
"version": 1,
"introduction": "Giedi Prime remembers its slaves. The Informer speaks only to those who show the ledger's mark.",
"context": "Slip into Giedi Prime and find the Pit Informer. A former pit slave knows the Harkonnen cells.",
"turnIn": "The Informer confirms Tleilaxu agents passed through, carrying something that smells of spice and iron."
},
"itemReward": "leto/spice-vision-vial"
},
{
"id": "POL-LETO-FURNACE",
"title": "Out of the Furnace",
"objective": "Enter Giedermark's Nether and obtain 6 ancient debris. The Informer needs it to bribe a Harkonnen quartermaster.",
"metric": "leto-gather-debris",
"target": 6,
"requires": [
"POL-LETO-PITS"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 500,
"amountMinor": 35000,
"npcRole": "leto_informer",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "giedi-prime",
"dimension": "NETHER",
"world": "Giedermark Nether"
}
},
"dialogue": {
"version": 1,
"introduction": "The Harkonnen deep forges burn hotter than any desert. The quartermaster wants metal that cannot be traced.",
"context": "Enter Giedermark's Nether and obtain 6 ancient debris. The Informer needs it to bribe a Harkonnen quartermaster.",
"turnIn": "The quartermaster hands over a travel pass for the Imperial court."
},
"itemReward": "leto/tabr-fedaykin-knife"
},
{
"id": "POL-LETO-COURT",
"title": "Veils at Kaitain",
"objective": "Travel to Kaitain and find the Court Archivist at the Imperial palace. Someone at court sold the twins' movements.",
"metric": "leto-contact-courtier",
"target": 1,
"requires": [
"POL-LETO-FURNACE"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 500,
"amountMinor": 30000,
"npcRole": "leto_courtier",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "kaitain",
"dimension": "NORMAL",
"world": "Kaiterhof"
}
},
"dialogue": {
"version": 1,
"introduction": "The Corrino court wears its secrets in silk. The Archivist remembers who bribed whom.",
"context": "Travel to Kaitain and find the Court Archivist at the Imperial palace. Someone at court sold the twins' movements.",
"turnIn": "The Archivist names the intermediary: a Guild fixer working for the Tleilaxu."
},
"itemReward": "leto/tabr-stillsuit-cowl"
},
{
"id": "POL-LETO-IRON",
"title": "Imperial Ledgers",
"objective": "Smelt 16 iron ingots on Kaitain to pay for a bribe on your own account.",
"metric": "leto-gather-iron",
"target": 16,
"requires": [
"POL-LETO-COURT"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 550,
"amountMinor": 30000,
"npcRole": "leto_courtier",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "kaitain",
"dimension": "NORMAL",
"world": "Kaiterhof"
}
},
"dialogue": {
"version": 1,
"introduction": "Nothing at court is free, not even silence.",
"context": "Smelt 16 iron ingots on Kaitain to pay for a bribe on your own account.",
"turnIn": "The fixer's last known meeting place is on Ordos."
},
"itemReward": null
},
{
"id": "POL-LETO-ORDOS",
"title": "Cold Hands on Ordos",
"objective": "Reach Sigmadraken IV and obtain 2 diamonds to buy the fixer's ledger.",
"metric": "leto-gather-diamond",
"target": 2,
"requires": [
"POL-LETO-IRON"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 600,
"amountMinor": 35000,
"npcRole": "leto_tleilaxu_ghola",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "sigma-draconis-iv",
"dimension": "NORMAL",
"world": "Sigmadraken IV"
}
},
"dialogue": {
"version": 1,
"introduction": "The fixer is a Tleilaxu go-between; Ordos is cold and quiet, and information is the only currency here.",
"context": "Reach Sigmadraken IV and obtain 2 diamonds to buy the fixer's ledger.",
"turnIn": "The fixer gives you a name and a Guild heighliner schedule."
},
"itemReward": null
},
{
"id": "POL-LETO-GUILD",
"title": "A Navigator's Price",
"objective": "Descend to the End of Sigmadraken IV and find the Guild Navigator's agent. The Guild knows every ship that left Arrakis.",
"metric": "leto-contact-navigator",
"target": 1,
"requires": [
"POL-LETO-ORDOS"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 700,
"amountMinor": 40000,
"npcRole": "leto_navigator",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "sigma-draconis-iv",
"dimension": "END",
"world": "Sigmadraken IV End"
}
},
"dialogue": {
"version": 1,
"introduction": "A Guild Navigator folds space and sees every course. The price of his word is high, and the Guild keeps neutral appearances.",
"context": "Descend to the End of Sigmadraken IV and find the Guild Navigator's agent. The Guild knows every ship that left Arrakis.",
"turnIn": "He gives you one coordinate: the dune sea south of Sietch Tabr."
},
"itemReward": "leto/jacurutu-sand-compass"
},
{
"id": "POL-LETO-RETURN",
"title": "The Sea That Walks",
"objective": "Return to Sietch Tabr and tell the Steward what you learned along the Golden Path.",
"metric": "leto-contact-finale",
"target": 1,
"requires": [
"POL-LETO-GUILD"
],
"requiresAny": [],
"branch": "leto-search",
"season": "S01",
"revision": 1,
"optional": false,
"verifiedOnly": true,
"xpType": "pol",
"issuer": "stilgar",
"issuerName": "Sietch Tabr",
"xp": 1500,
"amountMinor": 75000,
"npcRole": "leto_stilgar",
"executionRequirements": {
"website": false,
"minecraft": {
"server": "arrakis",
"dimension": "NORMAL",
"world": "Arrakduin"
}
},
"dialogue": {
"version": 1,
"introduction": "Everything has led back to the sand. The trail of Leto II leads to the old sietch, and the boy already knows you are coming.",
"context": "Return to Sietch Tabr and tell the Steward what you learned along the Golden Path.",
"turnIn": "You have found the trace of a boy who will become more than a man. The Search is over, but the Golden Path is long."
},
"itemReward": "leto/golden-path-seal"
}
];
export const LETO_QUESTS=Object.freeze(rows.map(q=>Object.freeze({...q,requires:Object.freeze(q.requires),requiresAny:Object.freeze([]),executionRequirements:Object.freeze({website:false,minecraft:Object.freeze(q.executionRequirements.minecraft)}),dialogue:Object.freeze(q.dialogue)})));
export const LETO_BRANCH=Object.freeze({id:'leto-search',office:null,title:'The Search for Leto II',issuer:'stilgar',issuerName:'Sietch Tabr',theme:'Thirteen steps, eight worlds, one boy · Reputation XP',xpType:'pol',quests:LETO_QUESTS,decisions:[]});
export const LETO_CATEGORY=Object.freeze({"id": "golden-path", "title": "The Golden Path", "tagline": "Seek the son of Muad'Dib across every world.", "accent": "#e0b04a", "icon": "quests/golden-path", "branches": ["leto-search"]});

View file

@ -1,4 +1,5 @@
import {polQuestDialogue,polQuestContact} from './cp-v2-pol-dialogue.mjs';
import {LETO_BRANCH,LETO_QUESTS} from './cp-v2-leto-quests.mjs';
import {FAITH_QUEST_BRANCHES} from './cp-v2-faith-quests.mjs';
import {ELYTRA_BRANCH} from './cp-v2-elytra-quests.mjs';
import {WAR_QUEST_BRANCH} from './cp-v2-war-quests.mjs';
@ -1109,9 +1110,10 @@ export const POL_QUEST_BRANCHES=freeze([
BOUNTY_BRANCH,
SPICE_UPGRADE_BRANCH,
ELYTRA_BRANCH,
WAR_QUEST_BRANCH
WAR_QUEST_BRANCH,
LETO_BRANCH
]);
const gameplayMetrics=new Set(['pol-verified-report','pol-counterintelligence','pol-evidence-dossier','pol-covert-intelligence','pol-beneficiary-investigation','pol-diplomatic-dispatch','pol-diplomatic-agreement','pol-imperial-intelligence','pol-trade-intelligence','pol-confidential-diplomacy','pol-political-intelligence','pol-confidential-agreement','pol-smuggler-introduction','pol-sabotage','pol-water-supply','pol-procurement','pol-strategic-procurement','pol-settled-acquisition','pol-spice-transport','pol-sietch-service','pol-verified-route','pol-verified-manifest','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']);
const withDialogue=d=>Object.freeze({...d,npcRole:polQuestContact(d),dialogue:polQuestDialogue(d)});
export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b.quests.map((q,index)=>withDialogue({...q,issuer:q.issuer||b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:q.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','fremen-husbandry','bounty-jobs','spice-upgrading'].includes(q.branch)})}))));
export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b===LETO_BRANCH?LETO_QUESTS:b.quests.map((q,index)=>withDialogue({...q,issuer:q.issuer||b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:q.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','fremen-husbandry','bounty-jobs','spice-upgrading'].includes(q.branch)})}))));
export function polBranch(id){return POL_QUEST_BRANCHES.find(b=>b.id===id||b.office===id)||null;}

View file

@ -4,6 +4,8 @@ export const POL_SUPPLY_TASKS=Object.freeze([
{id:'POL-FREMEN-01',kind:'supply_water',metric:'pol-water-supply',item:'jerboa_water_vial',quantity:6,label:'Water Vials',server:'arrakis',role:'stilgar',contact:'Stilgar',faction:'fremen'},
{id:'POL-FREMEN-03',kind:'supply_sietch',metric:'pol-sietch-service',item:'farmers_bucket',quantity:1,label:"Farmer’s Bucket",server:'arrakis',role:'stilgar',contact:'Stilgar',faction:'fremen'},
{id:'POL-COMPANY-01',kind:'supply_company',metric:'pol-procurement',item:'spice',quantity:8,label:'raw Spice',server:'sigma-draconis-iv',role:'roma_atani',contact:'Roma Atani'},
{id:'POL-ORDOS-02',faction:'ordos',kind:'supply_ordos',metric:'pol-strategic-procurement',item:'refined_spice',quantity:4,label:'Refined Spice',server:'sigma-draconis-iv',role:'roma_atani',contact:'Roma Atani'}
{id:'POL-ORDOS-02',faction:'ordos',kind:'supply_ordos',metric:'pol-strategic-procurement',item:'refined_spice',quantity:4,label:'Refined Spice',server:'sigma-draconis-iv',role:'roma_atani',contact:'Roma Atani'},
{id:'POL-LETO-WATER',kind:'leto_gather_water',metric:'leto-gather-water',item:'bottled_water',quantity:12,label:'Water Bottles',server:'arrakis',role:'leto_waterkeeper',contact:'Keeper of the Water Basin'},
{id:'POL-LETO-JACURUTU',kind:'leto_gather_spice',metric:'leto-gather-spice',item:'spice',quantity:16,label:'raw Spice',server:'arrakis',role:'leto_ecologist',contact:'Sietch Ecologist'}
].map(Object.freeze));
export const polSupplyTask=id=>POL_SUPPLY_TASKS.find(t=>t.id===id)||null;

View file

@ -1,5 +1,6 @@
// Themed story-arc categories over the quest branches. Presentation only: quest ids, rewards,
// prerequisites and progress are never changed. Mirrors DuneRealmsGUI/src/main/resources/quest-categories.json.
import {LETO_CATEGORY} from './cp-v2-leto-quests.mjs';
export const QUEST_CATEGORIES=Object.freeze([
{
"id": "arrival",
@ -146,7 +147,8 @@ export const QUEST_CATEGORIES=Object.freeze([
"branches": [
"war-service"
]
}
},
LETO_CATEGORY
].map(c=>Object.freeze({...c,branches:Object.freeze([...c.branches])})));
export const OTHER_CATEGORY=Object.freeze({id:'other',title:'Other Work',tagline:'Quests outside the main story arcs.',accent:'#8f7a5a',icon:'quests/other',branches:Object.freeze([])});
const byBranch=new Map(QUEST_CATEGORIES.flatMap(c=>c.branches.map(b=>[b,c])));

File diff suppressed because one or more lines are too long

View file

@ -10,6 +10,7 @@ import {SMUGGLER_DELIVERY_METRIC,smugglerDeliveryReference} from './smuggler-del
import {bountyEvent,bountyReference,hasAcceptedBountyReceipt} from './bounty-quest-evidence.mjs';
import {POL_SUPPLY_TASKS} from '../control-panel/public/cp-v2/cp-v2-pol-supply-policy.mjs';
import {verifiedSupplyRequest} from './pol-supply-evidence.mjs';
import {letoObservation} from './leto-quest-evidence.mjs';
// Only fixed native observations cross this boundary. No supplied account,
// metric, progress, quantity or reward can be interpreted as quest authority.
@ -40,9 +41,13 @@ export function createGameQuestEventsAPI(db,keys,settings,{clock=Date.now,events
if(!input||Array.isArray(input)||Object.keys(input).sort().join(',')!=='eventId,kind,occurredAt,server,uuid')return json({message:'Invalid starter receipt fields'},400);
try{return json(await starter.record(input));}catch{return json({message:'The physical starter receipt could not be verified. It remains queued.'},409);}
}
const supply=POL_SUPPLY_TASKS.find(t=>t.kind===input?.kind),isFlight=Object.hasOwn(flight,input?.kind||''),isHusbandry=Object.hasOwn(husbandry,input?.kind||''),isFauna=Object.hasOwn(fauna,input?.kind||'')||isHusbandry,isDelivery=input?.kind==='smuggler_delivery',isBounty=['bounty_accept','bounty_complete'].includes(input?.kind),isPOL=isFlight||isFauna||isDelivery||isBounty||!!supply||input?.kind==='smuggler_introduction';
const isLeto=typeof input?.kind==='string'&&input.kind.startsWith('leto_');
const leto=isLeto?letoObservation(input):null;
if(isLeto&&(!leto||!validUuid(input.eventId)||!validUuid(input.uuid)||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>clock()+30000))return json({message:'Invalid Golden Path observation.'},400);
if(isLeto&&!db.letoQuestEnabled)return json({message:'The Golden Path is unavailable.'},503);
const supply=POL_SUPPLY_TASKS.find(t=>t.kind===input?.kind),isFlight=Object.hasOwn(flight,input?.kind||''),isHusbandry=Object.hasOwn(husbandry,input?.kind||''),isFauna=Object.hasOwn(fauna,input?.kind||'')||isHusbandry,isDelivery=input?.kind==='smuggler_delivery',isBounty=['bounty_accept','bounty_complete'].includes(input?.kind),isPOL=isLeto||isFlight||isFauna||isDelivery||isBounty||!!supply||input?.kind==='smuggler_introduction';
const fields=['eventId','uuid','kind','server','occurredAt',...(input?.kind==='house_mentor_intro'?['npcRole']:isFlight?['quantity','dimension',...(input.kind==='flight_elytra_acquired'?['source']:[])]:isDelivery?['commodity','amount','distance','opposed','source','destination',...(input.startedAt!==undefined?['startedAt']:[])]:isBounty?['source']:input?.kind==='spice_harvest'||isHusbandry?['quantity']:[])];
if(!input||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(f=>!Object.hasOwn(input,f))||!validUuid(input.eventId)||!validUuid(input.uuid)||!Object.hasOwn(metrics,input.kind)||!servers.has(input.server)||!isFlight&&!supply&&input.kind!=='citizen_introduction'&&input.kind!=='house_mentor_intro'&&!(input.kind==='smuggler_introduction'&&input.server==='lobby')&&(input.server==='lobby'||input.kind!=='equipment_use'&&input.server!=='arrakis')||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>clock()+30000)return json({message:'Invalid observation fields'},400);
if(!isLeto&&(!input||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(f=>!Object.hasOwn(input,f))||!validUuid(input.eventId)||!validUuid(input.uuid)||!Object.hasOwn(metrics,input.kind)||!servers.has(input.server)||!isFlight&&!supply&&input.kind!=='citizen_introduction'&&input.kind!=='house_mentor_intro'&&!(input.kind==='smuggler_introduction'&&input.server==='lobby')&&(input.server==='lobby'||input.kind!=='equipment_use'&&input.server!=='arrakis')||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>clock()+30000))return json({message:'Invalid observation fields'},400);
if(input.kind==='house_mentor_intro'&&(input.server!=='lobby'||!Object.values(HOUSE_MENTOR_CONTACTS).includes(input.npcRole)))return json({message:'Meet your matching House Mentat in the Guild lobby.'},400);
if(isFlight&&(!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>64||!['NORMAL','NETHER','THE_END'].includes(input.dimension)||flight[input.kind]&&(flight[input.kind][0]!==input.server||flight[input.kind][1]!==input.dimension)||input.kind==='flight_elytra_acquired'&&(!['end','exchange'].includes(input.source)||input.source==='end'&&input.dimension!=='THE_END')))return json({message:'Invalid flight objective location'},400);
if(input.kind==='flight_merged'&&(input.quantity!==1||input.dimension!=='NORMAL'||input.server==='lobby'))return json({message:'A single completed physical armour merge on a shared-profile planet is required.'},400);
@ -51,7 +56,7 @@ export function createGameQuestEventsAPI(db,keys,settings,{clock=Date.now,events
if(isHusbandry&&(!Number.isSafeInteger(input.quantity)||input.quantity<1||(turnin?input.quantity!==turnin.units:input.quantity>(['husbandry_leather','husbandry_collect_egg','husbandry_collect_hide','husbandry_hide_paste','husbandry_spice_paste','husbandry_spice_bread','husbandry_spice_cake'].includes(input.kind)?64:1))))return json({message:'Invalid husbandry observation quantity'},400);
if(!events)return json({message:'Quest evidence is unavailable'},503);
let deliveryReference=null;if(isDelivery){if(!db.smugglerContractsEnabled)return json({message:'Smuggling contract evidence is unavailable'},503);try{deliveryReference=smugglerDeliveryReference(input);}catch{return json({message:'Invalid native smuggling contract receipt'},400);}}
if(supply&&input.server!==supply.server)return json({message:'Wrong supply mission world'},400);
if(supply&&(input.server!==supply.server||isLeto&&input.quantity!==supply.quantity))return json({message:'Wrong supply mission world'},400);
if(isBounty&&!db.bountyQuestsEnabled)return json({message:'Bounty job evidence is unavailable'},503);
if(isBounty&&(!validUuid(input.source)||bountyEvent(input.kind,input.source.toLowerCase())!==input.eventId.toLowerCase()))return json({message:'Invalid native bounty receipt'},400);
try{
@ -64,7 +69,11 @@ export function createGameQuestEventsAPI(db,keys,settings,{clock=Date.now,events
if(supply&&(!db.polSupplyEnabled||!await verifiedSupplyRequest(db,users[0].id,seasons[0].season_id,supply,input.eventId)))return json({message:'No verified supply mission instruction.'},409);
if(turnin&&!await verifiedMeatTurninRequest(db,users[0].id,seasons[0].season_id,turnin,input.eventId))return json({message:'No verified meat turn-in instruction.'},409);
if(input.kind==='bounty_complete'&&!await hasAcceptedBountyReceipt(db,users[0].id,input.uuid,seasons[0].season_id,input.source.toLowerCase()))return json({message:'The matching accepted native bounty receipt is pending.'},409);
const evidence={eventId:input.eventId,accountId:users[0].id,minecraftUuid:input.uuid,seasonId:seasons[0].season_id,metric:metrics[input.kind],quantity:isFlight||isHusbandry||input.kind==='spice_harvest'?input.quantity:1,occurredAt:input.occurredAt,reference:input.kind==='house_mentor_intro'?'native:lobby:house_mentor_intro:'+input.npcRole+':'+input.eventId:deliveryReference||(isBounty?bountyReference(input.kind,input.source):'native:'+input.server+':'+input.kind+':'+input.eventId)};
if(leto?.metric.startsWith('leto-contact-')){
const prior=await db.query('SELECT key_id FROM jarvis_pol_activity_events WHERE event_id=? AND account_id=? AND minecraft_uuid=? AND season_id=? AND metric=?',[input.eventId,users[0].id,input.uuid,seasons[0].season_id,leto.metric]);
if(prior.length===1)return json({ok:true,eventId:input.eventId,keyId:prior[0].key_id,replayed:true});
}
const evidence={eventId:input.eventId,accountId:users[0].id,minecraftUuid:input.uuid,seasonId:seasons[0].season_id,metric:leto?.metric??metrics[input.kind],quantity:leto?.quantity??(isFlight||isHusbandry||input.kind==='spice_harvest'?input.quantity:1),occurredAt:input.occurredAt,reference:input.kind==='house_mentor_intro'?'native:lobby:house_mentor_intro:'+input.npcRole+':'+input.eventId:deliveryReference||(isBounty?bountyReference(input.kind,input.source):'native:'+input.server+':'+input.kind+':'+input.eventId)};
if(isPOL&&(!db.polActivityEventsEnabled||!polEvents))return json({message:'Reputation quest evidence is unavailable'},503);
const result=await (isPOL?polEvents:events).record(producer,evidence);
if(isPOL)await createPOLProgressionRuntime(db,keys,{clock}).collect({id:users[0].id});

View file

@ -1,3 +1,4 @@
import {letoContact,letoRewards} from './leto-quest-evidence.mjs';
import {housePrologueState,HOUSE_MENTOR_CONTACTS} from './house-prologue.mjs';
import {gameAuthorized,validUuid,json} from './game-link.mjs';
import {questChannel} from '../control-panel/public/cp-v2/cp-v2-quest-channels.mjs';
@ -27,6 +28,14 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null,starter=
let input;
try{const chunks=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096){await reader.cancel();return json({message:'Quest request too large.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));}
catch{return json({message:'Invalid quest action.'},400);}finally{reader.releaseLock();}
if(input?.action==='read_leto_rewards'){
if(!db.letoQuestEnabled)return json({message:'The Golden Path is unavailable.'},503);
if(Array.isArray(input)||Object.keys(input).length!==2||!validUuid(input.uuid))return json({message:'A player UUID is required.'},400);
try{
const player=await resolve(input.uuid);if(!player)return json({message:'Link an active personal Minecraft account first.'},403);
return json({ok:true,uuid:input.uuid.toLowerCase(),items:await letoRewards(db,player.id)});
}catch{return json({message:'The Golden Path rewards remain available for retry.'},503);}
}
if(input?.action==='login_settle'){
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['action','uuid'].includes(k))||!validUuid(input.uuid))return json({message:'A player UUID is required.'},400);
try{
@ -54,7 +63,7 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null,starter=
if(input.action==='read_refits'||workshop){if(!refits||input.kind!=='pol')return json({message:'The organisation workshop is unavailable.'},503);return json(workshop?await refits.prepare(actor,input):await refits.list(actor));}
await runtime.collect?.(actor);
const journal=await runtime.quests.list(actor);
if(input.action==='read'){let npcFaction=null,npcContact=null,housePrologue=null;if(input.npcRole!==undefined){if(typeof input.npcRole!=='string'||! /^[a-z_]{1,32}$/.test(input.npcRole)||input.kind==='personal'&&!Object.values(HOUSE_MENTOR_CONTACTS).includes(input.npcRole))return json({message:'Invalid quest contact.'},400);try{const rows=await db.query('SELECT faction FROM site_character_choices WHERE user_id=? AND minecraft_uuid=?',[user.id,input.uuid.toLowerCase()]);if(rows.length===1)npcFaction=rows[0].faction;}catch{/* Missing faction never authorises a faction NPC. */}try{const contact=await createSystemCharacters(db,null,{authorizeOperator:async()=>false}).inspect(input.npcRole);if(contact?.capabilities.includes('quest.issue'))npcContact={key:input.npcRole,name:contact.name,role:contact.characterRole,avatar:systemPortrait(contact.username)};}catch{/* Invalid or revoked system character is not presented as an issuer. */}if(input.kind==='personal')housePrologue=await housePrologueState(db,keys,actor,input.uuid);if(input.npcRole==='imperial_attendant')npcContact={key:input.npcRole,name:'Imperial attendant',role:'Imperial audience · representation',avatar:systemPortrait('imperial_attendant')};}const quests=input.npcRole&&(dossiers||cargo)&&input.kind==='pol'?await Promise.all(journal.quests.map(async q=>{if(!["active","completed"].includes(q.state)){const initial=q.canStart&&input.npcRole==="edric"?await cargo?.initialContact?.(actor,q.id,input.uuid):null;return initial?{...q,cargo:initial}:q;}const current=await dossiers?.presentation(actor,q,input.npcRole),shipment=await cargo?.presentation(actor,q,input.uuid);return current||shipment?{...q,...(current?{dossier:current}:{}),...(shipment?{cargo:shipment}:{})}:q;})):journal.quests;return json({ok:true,...journal,quests,branches:journal.branches||(input.kind==='personal'?personalBranches:[]),kind:input.kind,npcFaction,npcContact,housePrologue,npcSummary:input.npcRole?((r)=>r?{level:r.level,xp:r.xp,nextXP:r.nextXP,percent:r.percent}:null)(xpReport(journal)):null});}
if(input.action==='read'){let npcFaction=null,npcContact=null,housePrologue=null;if(input.npcRole!==undefined){if(typeof input.npcRole!=='string'||! /^[a-z_]{1,32}$/.test(input.npcRole)||input.kind==='personal'&&!Object.values(HOUSE_MENTOR_CONTACTS).includes(input.npcRole))return json({message:'Invalid quest contact.'},400);try{const rows=await db.query('SELECT faction FROM site_character_choices WHERE user_id=? AND minecraft_uuid=?',[user.id,input.uuid.toLowerCase()]);if(rows.length===1)npcFaction=rows[0].faction;}catch{/* Missing faction never authorises a faction NPC. */}try{const contact=await createSystemCharacters(db,null,{authorizeOperator:async()=>false}).inspect(input.npcRole);if(contact?.capabilities.includes('quest.issue'))npcContact={key:input.npcRole,name:contact.name,role:contact.characterRole,avatar:systemPortrait(contact.username)};}catch{/* Invalid or revoked system character is not presented as an issuer. */}if(input.kind==='personal')housePrologue=await housePrologueState(db,keys,actor,input.uuid);if(db.letoQuestEnabled&&input.kind==='pol')npcContact??=letoContact(input.npcRole);if(input.npcRole==='imperial_attendant')npcContact={key:input.npcRole,name:'Imperial attendant',role:'Imperial audience · representation',avatar:systemPortrait('imperial_attendant')};}const quests=input.npcRole&&(dossiers||cargo)&&input.kind==='pol'?await Promise.all(journal.quests.map(async q=>{if(!["active","completed"].includes(q.state)){const initial=q.canStart&&input.npcRole==="edric"?await cargo?.initialContact?.(actor,q.id,input.uuid):null;return initial?{...q,cargo:initial}:q;}const current=await dossiers?.presentation(actor,q,input.npcRole),shipment=await cargo?.presentation(actor,q,input.uuid);return current||shipment?{...q,...(current?{dossier:current}:{}),...(shipment?{cargo:shipment}:{})}:q;})):journal.quests;return json({ok:true,...journal,quests,branches:journal.branches||(input.kind==='personal'?personalBranches:[]),kind:input.kind,npcFaction,npcContact,housePrologue,npcSummary:input.npcRole?((r)=>r?{level:r.level,xp:r.xp,nextXP:r.nextXP,percent:r.percent}:null)(xpReport(journal)):null});}
const quest=journal.quests?.find(q=>q.id===input.definitionId);
if(!quest)return json({message:'This quest is not in the current mission journal.'},409);
if(cargoPartner){if(!cargo?.partner||input.kind!=='pol')return json({message:'Cooperative cargo assignments are unavailable.'},503);return json(await cargo.partner(actor,input,quest));}

View file

@ -0,0 +1,45 @@
import {starterIdentity} from './starter-kit-native-design.mjs';
import { LETO_QUESTS } from '../control-panel/public/cp-v2/cp-v2-leto-quests.mjs';
const common = ['eventId', 'uuid', 'kind', 'server', 'occurredAt', 'dimension'];
const observations = new Map(LETO_QUESTS.map(quest => {
const {server, dimension} = quest.executionRequirements.minecraft;
return [quest.metric.replaceAll('-', '_'), Object.freeze({
metric: quest.metric,
server,
dimension: dimension === 'END' ? 'THE_END' : dimension,
target: quest.target,
role: quest.metric.startsWith('leto-contact-') ? quest.npcRole : null,
})];
}));
export function letoObservation(input) {
if (!input || Array.isArray(input)) return null;
const policy = observations.get(input.kind);
if (!policy || input.server !== policy.server || input.dimension !== policy.dimension) return null;
const fields = [...common, policy.role ? 'npcRole' : 'quantity'];
if (Object.keys(input).length !== fields.length || fields.some(field => !Object.hasOwn(input, field))) return null;
if (policy.role) return input.npcRole === policy.role ? {metric: policy.metric, quantity: 1} : null;
if (!Number.isSafeInteger(input.quantity) || input.quantity < 1 || input.quantity > policy.target) return null;
return {metric: policy.metric, quantity: input.quantity};
}
const contacts=Object.freeze({
leto_runner:'Ishaq the Runner',leto_steward:'Sietch Steward',leto_waterkeeper:'Keeper of the Water Basin',
leto_ecologist:'Sietch Ecologist',leto_archivist:'Atreides Archivist',leto_informer:'Pit Informer',
leto_courtier:'Court Archivist',leto_tleilaxu_ghola:'Tleilaxu Go-Between',
leto_navigator:"Guild Navigator's Agent",leto_stilgar:'Sietch Steward of the Hall of Rites'
});
export function letoContact(key){
return Object.hasOwn(contacts,key)?{key,name:contacts[key],role:'The Golden Path'}:null;
}
const rewardByQuest=new Map(LETO_QUESTS.filter(quest=>quest.itemReward).map(quest=>[quest.id,quest.itemReward]));
/** Only a consumed, linked Reputation quest claim entitles the player to a reward item. */
export async function letoRewards(db,accountId){
const quests=[...rewardByQuest.keys()];
const rows=await db.query("SELECT s.definition_id,s.key_id,k.scope_id FROM jarvis_pol_quest_states s JOIN jarvis_pol_quest_claims c ON c.key_id=s.key_id AND c.account_id=s.account_id JOIN organisation_keys k ON k.id=s.key_id AND k.account_id=s.account_id WHERE s.account_id=? AND s.season_id='S01' AND s.state='claimed' AND k.key_type='quest' AND k.used_at IS NOT NULL AND k.revoked_at IS NULL AND s.definition_id IN ("+quests.map(()=>'?').join(',')+") ORDER BY c.claimed_at,s.definition_id",[accountId,...quests]);
return rows.filter(row=>row.scope_id==='S01:POL_'+row.definition_id).map(row=>({receiptId:starterIdentity('golden-path-item:'+row.key_id),itemId:rewardByQuest.get(row.definition_id)}));
}

View file

@ -1,9 +1,11 @@
import {validFaithReward} from './faith-blessings.mjs';
import {createPOLQuestTreasuryPayments} from './quest-treasury-payments.mjs';
import {createGoldenPathPayments,createPOLQuestTreasuryPayments} from './quest-treasury-payments.mjs';
import {LETO_QUESTS} from '../control-panel/public/cp-v2/cp-v2-leto-quests.mjs';
import {currentMentorPolicy} from './pol-mentor-rewards.mjs';
import {createSystemCharacters} from './system-characters.mjs';
import {OFFICIAL_ACCOUNT} from './official-account.mjs';
const jobs='jarvis_pol_quest_reward_jobs';
const goldenPathRewards=new Map(LETO_QUESTS.map(q=>[q.id,q.amountMinor]));
export function createPOLFundedRewards(central,bank,keys,{clock=Date.now}={}){
async function process(keyId){return central.transaction(async tx=>{
const job=await tx.first('SELECT * FROM '+jobs+' WHERE key_id=? FOR UPDATE',[keyId]);if(!job||job.state!=='queued')return 'unchanged';
@ -15,7 +17,10 @@ export function createPOLFundedRewards(central,bank,keys,{clock=Date.now}={}){
const blessed=!!r.faith;if(blessed&&(!Number.isSafeInteger(r.faithBaseAmountMinor)||r.faithBaseAmountMinor*2!==r.amountMinor||!await validFaithReward(tx,r.faith,{accountId:row.account_id,claimedAt:Number(row.claimed_at)}))||!blessed&&Object.hasOwn(r,'faithBaseAmountMinor'))throw Error('Verified faith reward required');
if(!await tx.first('SELECT id FROM organisation_keys WHERE id=? AND revoked_at IS NULL FOR UPDATE',[issuer.keyId]))throw Error('Current issuer key required');
const actor=await tx.first("SELECT username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.id]),player=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' AND role NOT IN ('official_account','system_account','memorial') FOR UPDATE",[row.account_id]);if(!player||actor?.username!==OFFICIAL_ACCOUNT.username||actor.role!=='official_account')throw Error('Current payment identities required');
const payments=createPOLQuestTreasuryPayments(bank,{clock,blessed,authorize:async()=>{const current=await tx.first('SELECT used_at,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);return current?.used_at!=null&&current.revoked_at===null;}});
const goldenPath=goldenPathRewards.get(row.definition_id);
if(goldenPath!==undefined&&(central.letoQuestEnabled!==true||goldenPath!==r.baseAmountMinor))throw Error('The approved Golden Path payout is unavailable');
const usePayments=goldenPath===undefined?createPOLQuestTreasuryPayments:createGoldenPathPayments;
const payments=usePayments(bank,{clock,blessed,authorize:async()=>{const current=await tx.first('SELECT used_at,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[keyId]);return current?.used_at!=null&&current.revoked_at===null;}});
await payments.pay({keyId,accountId:row.account_id,amountMinor:r.amountMinor,memo:'Reputation reward '+keyId});await tx.query("UPDATE "+jobs+" SET state='paid' WHERE key_id=?",[keyId]);return 'paid';
});}
return Object.freeze({async drain(){const rows=await central.query("SELECT key_id FROM "+jobs+" WHERE state='queued' AND JSON_EXTRACT(payload_json,'$.schema')='pol-funded-reward-v1' ORDER BY created_at,key_id LIMIT 25"),results=[];for(const r of rows){try{results.push({keyId:r.key_id,state:await process(r.key_id)});}catch{results.push({keyId:r.key_id,state:'awaiting-funding-or-review'});}}return {attempted:rows.length,results};}});

View file

@ -68,11 +68,12 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
if(central.secondaryAffiliationsEnabled&&definition.id==='POL-SMUGGLERS-01')await grantSmugglerAffiliations(polStore,keys,actor,{clock});return true;
}
};
const unrestrictedDefinitions=POL_QUEST_DEFINITIONS.filter(d=>!d.faction&&(d.branch!=='bounty-jobs'||central.bountyQuestsEnabled)&&(d.branch!=='spice-upgrading'||central.spiceUpgradeEnabled)),engine=createPOLProgression(central,keys,{...adapters,definitions:unrestrictedDefinitions});
const arcAvailable=d=>d.branch!=='leto-search'||central.letoQuestEnabled===true;
const unrestrictedDefinitions=POL_QUEST_DEFINITIONS.filter(d=>arcAvailable(d)&&!d.faction&&(d.branch!=='bounty-jobs'||central.bountyQuestsEnabled)&&(d.branch!=='spice-upgrading'||central.spiceUpgradeEnabled)),engine=createPOLProgression(central,keys,{...adapters,definitions:unrestrictedDefinitions});
async function engineFor(actor,requestedDefinitionId=null){
const faction=central.faunaQuestsEnabled&&await currentFremen(central,actor.id)?'fremen':null;
if(!central.polRepeatablesEnabled&&!central.organisationResearchEnabled&&!faction)return {engine,definitions:unrestrictedDefinitions};
const definitions=[...POL_QUEST_DEFINITIONS.filter(d=>(!d.faction||d.faction===faction)&&(d.branch!=='bounty-jobs'||central.bountyQuestsEnabled)&&(d.branch!=='spice-upgrading'||central.spiceUpgradeEnabled)),...(central.polRepeatablesEnabled?await repeatableDefinitions(central,actor,{requestedDefinitionId,faction}):[]),...await currentResearchDefinitions(central,actor,{clock,requestedDefinitionId})];
const definitions=[...POL_QUEST_DEFINITIONS.filter(d=>arcAvailable(d)&&(!d.faction||d.faction===faction)&&(d.branch!=='bounty-jobs'||central.bountyQuestsEnabled)&&(d.branch!=='spice-upgrading'||central.spiceUpgradeEnabled)),...(central.polRepeatablesEnabled?await repeatableDefinitions(central,actor,{requestedDefinitionId,faction}):[]),...await currentResearchDefinitions(central,actor,{clock,requestedDefinitionId})];
const scoped={...adapters,authorizeIssuer:async(tx,d)=>{if(d.faction==='fremen'&&!await currentFremen(tx,actor.id,{lock:true}))throw Error('Current Fremen character required');return authorizeIssuer(tx,d);},definitions};
return {engine:createPOLProgression(central,keys,scoped),definitions};
}

View file

@ -46,7 +46,7 @@ export function polPolicyKeys(keys){return {
list:async id=>(await keys.list(id)).filter(k=>k.keyType==='progression-policy'&&k.scopeId.startsWith('policy:POL:')),
consume:async input=>{const own=(await keys.list(input.accountId)).find(k=>k.code===input.code&&k.keyType==='progression-policy'&&k.scopeId.startsWith('policy:POL:'));if(!own)throw Error('POL policy instrument unavailable');return keys.consume({...input,apply:(tx,c)=>input.apply(polProgressionStore(tx),c)});}
};}
export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:POL_XP_POLICY,definitions:POL_QUEST_DEFINITIONS.filter(d=>!d.faction&&!['bounty-jobs','spice-upgrading'].includes(d.branch)),rewardForDefinition:faithQuestInitialReward});
export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:POL_XP_POLICY,definitions:POL_QUEST_DEFINITIONS.filter(d=>!d.faction&&!['bounty-jobs','spice-upgrading','leto-search'].includes(d.branch)),rewardForDefinition:faithQuestInitialReward});
export const ensurePOLRepeatablePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:2},definitions:repeatablePolicyDefinitions()});
@ -60,5 +60,10 @@ export const ensureFaunaQuestPolicy=(db,keys,options={})=>ensureProgressionPolic
export const ensureBountyQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:8},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='bounty-jobs')});
export const ensureSpiceUpgradeQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:9},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='spice-upgrading')});
export const ensureLetoQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{
...options,policy:{...POL_XP_POLICY,version:11},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='leto-search'),
rewardForDefinition:d=>({schema:'pol-dm-reward-v1',amountMinor:d.amountMinor})
});
// Add the physical merge without replaying v4 or overwriting existing flight rewards.
export const ensureElytraMergePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:10},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.id==='POL-ELYTRA-MERGE')});

View file

@ -1,31 +1,36 @@
import {createHash} from 'node:crypto';
import {PostbankPayments} from './postbank-payments.mjs';
import {postPayrollIssue} from './postbank-payroll-issuer.mjs';
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
import {OFFICIAL_ACCOUNT} from './official-account.mjs';
export const QUEST_TREASURY='sys_web_treasury';
const PO_ISSUER='sys_payroll_po';
const accounts='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id';
// Private domain consumer, not a staff/browser transfer permission. Its caller
// holds the actual consumed quest instruction lock until this bank commit.
function treasuryPayments(bank,{authorize,clock=Date.now,blessed=false},kind,research=false){
function treasuryPayments(bank,{authorize,clock=Date.now,blessed=false},kind,research=false,payroll=false){
if(typeof authorize!=='function')throw TypeError('A current verified quest authorizer is required');
const sourceKey=payroll?PO_ISSUER:QUEST_TREASURY;
const payments=new PostbankPayments(bank,async()=>({}),{clock});
return Object.freeze({async pay({keyId,clanId,accountId,recipientId:researchRecipient,amountMinor,memo}){
const recipientId=research?researchRecipient:kind==='clan'?clanId:accountId;
const validRecipient=research&&kind==='office'?/^[a-z0-9:_-]{1,64}$/.test(recipientId||''):/^[a-f0-9-]{36}$/i.test(recipientId||'');
if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||!validRecipient||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>(research?(blessed?30000:15000):kind==='clan'?15000000:(blessed?2500000:1250000))||memo!==(research?'Research reward ':kind==='clan'?'Rebellion reward ':'Reputation reward ')+keyId)throw Error('Invalid bound quest reward');
const fingerprint=createHash('sha256').update(JSON.stringify([QUEST_TREASURY,keyId,recipientId,amountMinor,memo])).digest('hex');
const fingerprint=createHash('sha256').update(JSON.stringify([sourceKey,keyId,recipientId,amountMinor,memo])).digest('hex');
return bank.transaction(async tx=>{
const entity=await tx.first("SELECT id FROM pb_entities WHERE kind=? AND external_key=? FOR UPDATE",[kind,recipientId]);if(!entity)throw Error('Quest recipient bank entity unavailable');
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entity.id]);
const rows=await tx.query(accounts+' WHERE a.system_key=? OR c.entity_id=? ORDER BY a.id FOR UPDATE',[QUEST_TREASURY,entity.id]),source=rows.find(r=>r.system_key===QUEST_TREASURY);
const rows=await tx.query(accounts+' WHERE a.system_key=? OR c.entity_id=? ORDER BY a.id FOR UPDATE',[sourceKey,entity.id]),source=rows.find(r=>r.system_key===sourceKey);
if(!await authorize())throw Error('Verified quest authorization expired');
const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[keyId]);
if(prior){const target=rows.find(r=>String(r.id)===String(prior.target_id));if(prior.actor_id!==OFFICIAL_ACCOUNT.id||prior.fingerprint!==fingerprint||prior.mode!=='system'||prior.state!=='posted'||prior.memo!==memo||Number(prior.amount_minor)!==amountMinor||String(prior.source_id)!==String(source?.id)||target?.kind!==kind||target.external_key!==recipientId)throw Error('Quest payment reference conflict');return prior;}
const target=rows.find(ordinaryPaymentAccount);
if(!source||source.state!=='active'||source.type_code!=='979'||!target||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<BigInt(amountMinor))throw Error('Quest treasury or recipient is unavailable or unfunded');
if(!source||source.state!=='active'||source.type_code!=='979'||!target||!payroll&&BigInt(source.balance_minor)-BigInt(source.reserved_minor)<BigInt(amountMinor))throw Error('Quest treasury or recipient is unavailable or unfunded');
await tx.query('INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[keyId,OFFICIAL_ACCOUNT.id,source.id,target.id,fingerprint,String(amountMinor),memo,'system','queued',clock()]);
await payments.post(tx,{id:keyId,actor_id:OFFICIAL_ACCOUNT.id,amount_minor:String(amountMinor)},{...source,entity_id:null},target,false);
const order={id:keyId,actor_id:OFFICIAL_ACCOUNT.id,amount_minor:String(amountMinor)};
if(payroll)await postPayrollIssue(tx,order,source,target,{now:clock()});
else await payments.post(tx,order,{...source,entity_id:null},target,false);
return tx.first('SELECT * FROM pb_orders WHERE id=?',[keyId]);
});
}});
@ -33,4 +38,5 @@ function treasuryPayments(bank,{authorize,clock=Date.now,blessed=false},kind,res
export const createQuestTreasuryPayments=(bank,options={})=>treasuryPayments(bank,options,'clan');
export const createPOLQuestTreasuryPayments=(bank,options={})=>treasuryPayments(bank,options,'person');
export const createGoldenPathPayments=(bank,options={})=>treasuryPayments(bank,options,'person',false,true);
export const createResearchTreasuryPayments=(bank,options={})=>{if(!['clan','company','office'].includes(options.kind))throw TypeError('Research organisation required.');return treasuryPayments(bank,options,options.kind,true);};

View file

@ -14,6 +14,7 @@
{"id":"lanes","title":"Lanes and Shadows","tagline":"Guild lanes, smugglers' routes and hunted bounties.","accent":"#b07a4a","icon":"quests/lanes","branches":["guild","smugglers","bounty-jobs"]},
{"id":"contracts","title":"Contracts of the Realm","tagline":"Work for clan and company.","accent":"#c3a060","icon":"quests/contracts","branches":["clan","company"]},
{"id":"wings","title":"Wings across the Realms","tagline":"Five worlds. One elytra.","accent":"#e0c27c","icon":"quests/wings","branches":["elytra"]},
{"id":"campaign","title":"Campaign Banners","tagline":"Banners raised, ground held.","accent":"#b5653f","icon":"quests/campaign","branches":["war-service"]}
{"id":"campaign","title":"Campaign Banners","tagline":"Banners raised, ground held.","accent":"#b5653f","icon":"quests/campaign","branches":["war-service"]},
{"id":"golden-path","title":"The Golden Path","tagline":"Seek the son of Muad'Dib across every world.","accent":"#e0b04a","icon":"quests/golden-path","branches":["leto-search"]}
]
}

View file

@ -0,0 +1,169 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {categoryFor} from '../control-panel/public/cp-v2/cp-v2-quest-categories.mjs';
import {questCategoryArt} from '../control-panel/quest-category-art.mjs';
import {LETO_QUESTS,LETO_BRANCH,LETO_CATEGORY} from '../control-panel/public/cp-v2/cp-v2-leto-quests.mjs';
test('arc is structurally valid',()=>{
const ids=new Set(LETO_QUESTS.map(q=>q.id));assert.equal(ids.size,LETO_QUESTS.length);
for(const q of LETO_QUESTS){assert.ok(Number.isSafeInteger(q.target)&&q.target>0);assert.ok(q.xp>0&&q.xp<=9000);
assert.ok(Number.isSafeInteger(q.amountMinor)&&q.amountMinor>=1&&q.amountMinor<=1000000);
for(const r of q.requires)assert.ok(ids.has(r),q.id+' requires '+r);assert.equal(q.branch,LETO_BRANCH.id);}
});
test('prerequisites are acyclic and form a chain',()=>{
const by=new Map(LETO_QUESTS.map(q=>[q.id,q]));const seen=new Set();
const visit=(id,path)=>{assert.ok(!path.has(id),'cycle '+id);if(seen.has(id))return;const n=new Set(path).add(id);for(const r of by.get(id).requires)visit(r,n);seen.add(id);};
for(const q of LETO_QUESTS)visit(q.id,new Set());
});
test('every world is visited',()=>{
const worlds=new Set(LETO_QUESTS.map(q=>q.executionRequirements.minecraft.world));
for(const w of ['Vaerkring','Arrakduin','Kaladam','Giedermark','Giedermark Nether','Kaiterhof','Sigmadraken IV','Sigmadraken IV End'])assert.ok(worlds.has(w),w);
});
test('The Golden Path has its own category and serves both supplied PNGs',async()=>{
assert.deepEqual(LETO_CATEGORY.branches,[LETO_BRANCH.id]);
assert.equal(categoryFor(LETO_BRANCH.id).id,LETO_CATEGORY.id);
for(const type of ['banner','icon']){
const url='https://cp.dunerealms.com/v2/art/quests/golden-path-'+type+'.png';
const get=await questCategoryArt(new Request(url));
assert.equal(get.status,200);assert.equal(get.headers.get('Content-Type'),'image/png');
assert.equal(Buffer.from(await get.arrayBuffer()).subarray(0,8).toString('hex'),'89504e470d0a1a0a');
const head=await questCategoryArt(new Request(url,{method:'HEAD'}));
assert.equal(head.status,200);assert.equal(await head.text(),'');
}
});
import {letoObservation} from '../node/leto-quest-evidence.mjs';
test('every Golden Path observation binds a fixed producer kind, source and payload shape',()=>{
const seen=new Set();
for(const q of LETO_QUESTS){
const {server,dimension}=q.executionRequirements.minecraft;
const kind=q.metric.replaceAll('-','_'), isContact=q.metric.startsWith('leto-contact-');
assert(!seen.has(kind));seen.add(kind);
const event={eventId:'receipt',uuid:'player',kind,server,occurredAt:1,dimension:dimension==='END'?'THE_END':dimension,...(isContact?{npcRole:q.npcRole}:{quantity:q.target})};
assert.deepEqual(letoObservation(event),{metric:q.metric,quantity:isContact?1:q.target});
assert.equal(letoObservation({...event,metric:q.metric}),null);
assert.equal(letoObservation({...event,server:'invalid'}),null);
assert.equal(letoObservation({...event,dimension:'CUSTOM'}),null);
assert.equal(letoObservation({...event,...(isContact?{npcRole:'unrelated'}:{quantity:q.target+1})}),null);
}
assert.equal(seen.size,13);
});
test('all 13 chapters advance and claim in sequence from authenticated evidence',async()=>{
const {randomUUID}=await import('node:crypto');
const {systemCharacterFixture}=await import('./system-character-fixture.mjs');
const {initializePOLProgression,ensurePOLProgressionPolicy,ensureLetoQuestPolicy}=await import('../node/progression-pol.mjs');
const {initializePOLActivityEvents}=await import('../node/pol-activity-events.mjs');
const {createGameQuestEventsAPI}=await import('../node/game-quest-events.mjs');
const {createGameQuestsAPI}=await import('../node/game-quests.mjs');
const {supplyEvent,supplyRequest}=await import('../node/pol-supply-evidence.mjs');
const {createPOLProgressionRuntime}=await import('../node/progression-pol-runtime.mjs');
const f=await systemCharacterFixture();try{
const actor=f.people.Member,uuid=randomUUID(),clock=()=>2000,secret='golden-path-fixture-secret-at-least-32-characters';
await f.characters.provision(f.people.Owner,'stilgar');
await initializePOLProgression(f.db);
await ensurePOLProgressionPolicy(f.db,f.keys,{clock});
assert.equal((await f.db.first("SELECT COUNT(*) n FROM jarvis_pol_quest_config WHERE definition_id LIKE 'POL-LETO-%'")).n,0);
await ensureLetoQuestPolicy(f.db,f.keys,{clock});await ensureLetoQuestPolicy(f.db,f.keys,{clock});
assert.equal((await f.db.first("SELECT COUNT(*) n FROM jarvis_pol_quest_config WHERE definition_id LIKE 'POL-LETO-%'")).n,13);
await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true;f.db.polSupplyEnabled=true;
await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,actor.id]);
const api=createGameQuestEventsAPI(f.db,f.keys,{GAME_LINK_SECRET:secret},{clock});
const send=(input,authenticated=true)=>api(new Request('https://cp.dunerealms.com/internal/game/quest-events',{
method:'POST',headers:{...(authenticated?{authorization:'Bearer '+secret}:{}),'content-type':'application/json'},body:JSON.stringify(input)
}));
const event=q=>{const {server,dimension}=q.executionRequirements.minecraft;return{
eventId:randomUUID(),uuid,kind:q.metric.replaceAll('-','_'),server,dimension:dimension==='END'?'THE_END':dimension,occurredAt:clock(),
...(q.metric.startsWith('leto-contact-')?{npcRole:q.npcRole}:{quantity:q.target})
};};
const first=event(LETO_QUESTS[0]);
assert.equal((await send(first,false)).status,401);
assert.equal((await send(first)).status,503);
assert(!(await createPOLProgressionRuntime(f.db,f.keys,{clock}).quests.list(actor)).quests.some(q=>q.branch===LETO_BRANCH.id));
f.db.letoQuestEnabled=true;
const runtime=createPOLProgressionRuntime(f.db,f.keys,{clock});
const quests=runtime.quests;
const questApi=createGameQuestsAPI(f.db,{GAME_LINK_SECRET:secret},{pol:runtime});
const callQuest=(body,authenticated=true)=>questApi(new Request('https://cp.dunerealms.com/internal/game/quests',{
method:'POST',headers:{...(authenticated?{authorization:'Bearer '+secret}:{}),'content-type':'application/json'},body:JSON.stringify(body)
}));
const items={action:'read_leto_rewards',uuid};
assert.equal((await callQuest(items,false)).status,401);
assert.deepEqual((await (await callQuest(items)).json()).items,[]);
const runner=await (await callQuest({action:'read',uuid,kind:'pol',npcRole:'leto_runner'})).json();
assert.equal(runner.npcContact.name,'Ishaq the Runner');
for(const [index,definition] of LETO_QUESTS.entries()){
const page=await quests.list(actor);
assert.equal(page.quests.find(q=>q.id===definition.id).canStart,true,definition.id);
if(index+1<LETO_QUESTS.length)assert.equal(page.quests.find(q=>q.id===LETO_QUESTS[index+1].id).canStart,false);
const evidence=event(definition);
if(['POL-LETO-WATER','POL-LETO-JACURUTU'].includes(definition.id)){
assert.equal((await send(evidence)).status,409);
await quests.start(actor,{definitionId:definition.id});
evidence.eventId=supplyEvent(evidence.kind,supplyRequest(actor.id,'S01',definition.id));
assert.equal((await send({...evidence,quantity:evidence.quantity-1})).status,400);
}
assert.equal((await send({...evidence,dimension:'CUSTOM'})).status,400);
const accepted=await send(evidence);assert.equal(accepted.status,200,await accepted.text());
assert.equal((await (await send(evidence)).json()).replayed,true);
if(evidence.npcRole)assert.equal((await (await send({...evidence,occurredAt:clock()+1})).json()).replayed,true);
const current=(await quests.list(actor)).quests.find(q=>q.id===definition.id);
assert.equal(current.progress,definition.target);
assert.equal(current.canClaim,true,definition.id);
await quests.claim(actor,{definitionId:current.id,revision:current.revision,requestId:randomUUID()});
}
const entitled=(await (await callQuest(items)).json()).items;
assert.equal(entitled.length,8);
assert.equal(new Set(entitled.map(item=>item.receiptId)).size,8);
assert.deepEqual(new Set(entitled.map(item=>item.itemId)),new Set(LETO_QUESTS.flatMap(q=>q.itemReward?[q.itemReward]:[])));
assert.deepEqual((await (await callQuest(items)).json()).items,entitled);
assert.equal((await callQuest({...items,uuid:randomUUID()})).status,403);
const done=await quests.list(actor);
assert.equal(done.quests.filter(q=>q.branch===LETO_BRANCH.id&&q.state==='claimed').length,13);
assert.equal(done.profile.totalXP,LETO_QUESTS.reduce((total,q)=>total+q.xp,0));
assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_activity_events')).n,13);
}finally{f.db.close();}
});
test('Golden Path claims pay from P&O once, including after a lost acknowledgement',async()=>{
const {randomUUID}=await import('node:crypto');
const {systemCharacterFixture}=await import('./system-character-fixture.mjs');
const {initializePOLProgression,ensureLetoQuestPolicy}=await import('../node/progression-pol.mjs');
const {initializePOLActivityEvents,createPOLActivityEvents}=await import('../node/pol-activity-events.mjs');
const {ensurePOLMentorPolicy}=await import('../node/pol-mentor-rewards.mjs');
const {createPOLProgressionRuntime}=await import('../node/progression-pol-runtime.mjs');
const {createPOLFundedRewards}=await import('../node/pol-funded-rewards.mjs');
const {PostbankService}=await import('../node/postbank-service.mjs');
const {BANK_VERSION}=await import('../node/postbank-catalogue.mjs');
const {OFFICIAL_ACCOUNT}=await import('../node/official-account.mjs');
const {BankFixture}=await import('./postbank-fixture.mjs');
const fixture=await systemCharacterFixture(),bank=new BankFixture();
try{
const {db,keys,people}=fixture,player=people.Member,uuid=randomUUID(),clock=()=>2000;
await fixture.characters.provision(people.Owner,'stilgar');
await initializePOLProgression(db);await ensureLetoQuestPolicy(db,keys,{clock});await ensurePOLMentorPolicy(db,keys,{clock});
await initializePOLActivityEvents(db);Object.assign(db,{polActivityEventsEnabled:true,polMentorBonusEnabled:true,letoQuestEnabled:true});
await db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,player.id]);
const producer={},evidence=createPOLActivityEvents(db,keys,{clock,authorizeProducer:async actor=>actor===producer});
const chapter=LETO_QUESTS[0];
await evidence.record(producer,{accountId:player.id,minecraftUuid:uuid,eventId:randomUUID(),seasonId:'S01',metric:chapter.metric,quantity:1,occurredAt:2000,reference:randomUUID()});
const runtime=createPOLProgressionRuntime(db,keys,{clock});await runtime.collect(player);
const grant=await runtime.quests.start(player,{definitionId:chapter.id});
await runtime.quests.claim(player,{definitionId:chapter.id,requestId:randomUUID(),revision:1});
const entity={id:randomUUID(),kind:'person',key:player.id,name:'Recipient',canView:true,canActivate:true,canPay:false};
await new PostbankService(bank,async()=>({entities:[entity]})).activate(player,{entityId:entity.id,packageKey:'pb_start',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_web_treasury','979','Web Treasury',999999,0,'active',1),('sys_payroll_po','979','P&O',0,0,'active',1)");
await db.query('INSERT INTO site_accounts(id,username,role) VALUES(?,?,?)',[OFFICIAL_ACCOUNT.id,OFFICIAL_ACCOUNT.username,'official_account']);
const worker=createPOLFundedRewards(db,bank,keys,{clock});
db.letoQuestEnabled=false;
assert.equal((await worker.drain()).results[0].state,'awaiting-funding-or-review');
assert.equal((await bank.first('SELECT COUNT(*) n FROM pb_entries')).n,0);
db.letoQuestEnabled=true;
assert.equal((await worker.drain()).results[0].state,'paid');
const order=await bank.first('SELECT o.amount_minor,a.system_key FROM pb_orders o JOIN pb_accounts a ON a.id=o.source_id WHERE o.id=?',[grant.id]);
assert.deepEqual({...order},{amount_minor:16500,system_key:'sys_payroll_po'});
assert.equal((await bank.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_web_treasury'")).balance_minor,999999);
await db.query("UPDATE jarvis_pol_quest_reward_jobs SET state='queued' WHERE key_id=?",[grant.id]);
assert.equal((await worker.drain()).results[0].state,'paid');
assert.deepEqual({...await bank.first('SELECT COUNT(*) n,SUM(amount_minor) net FROM pb_entries')},{n:2,net:0});
}finally{fixture.db.close();bank.close();}
});

View file

@ -45,7 +45,7 @@ test('POL policy is independently keyed, uncapped and preserves personal policy/
await ensureProgressionPolicy(f.db,f.keys,{clock:()=>2000});await ensurePOLProgressionPolicy(f.db,f.keys,{clock:()=>2000});
assert.equal((await f.db.first('SELECT level_cap FROM jarvis_progression_seasons')).level_cap,100);
assert.equal((await f.db.first('SELECT level_cap FROM jarvis_pol_progression_seasons')).level_cap,0);
assert.equal((await f.db.query('SELECT * FROM jarvis_pol_quest_config')).length,POL_QUEST_DEFINITIONS.filter(d=>!d.faction&&!['bounty-jobs','spice-upgrading'].includes(d.branch)).length);
assert.equal((await f.db.query('SELECT * FROM jarvis_pol_quest_config')).length,POL_QUEST_DEFINITIONS.filter(d=>!d.faction&&!['bounty-jobs','spice-upgrading','leto-search'].includes(d.branch)).length);
assert.equal((await ensurePOLProgressionPolicy(f.db,f.keys)).replayed,true);
assert.equal((await f.db.query("SELECT id FROM organisation_keys WHERE key_type='progression-policy'")).length,2);
}finally{f.db.close();}

View file

@ -12,8 +12,8 @@ test('every known quest branch belongs to exactly one themed category',()=>{
const seen=new Map();
for(const c of QUEST_CATEGORIES)for(const b of c.branches){assert.ok(!seen.has(b),'branch twice: '+b);seen.set(b,c.id);}
for(const b of known)assert.notEqual(categoryFor(b),OTHER_CATEGORY,'unmapped branch '+b);
assert.equal(QUEST_CATEGORIES.length,13);
assert.equal(new Set(QUEST_CATEGORIES.map(c=>c.id)).size,13);
assert.equal(QUEST_CATEGORIES.length,14);
assert.equal(new Set(QUEST_CATEGORIES.map(c=>c.id)).size,14);
});
test('the website catalogue matches the in-game catalogue file',()=>{
const game=JSON.parse(fs.readFileSync(new URL('./fixtures/quest-categories.plugin.json',import.meta.url),'utf8')).categories;