Merge pull request 'Apply scoped Mentat bonuses and pay explicitly funded Reputation claims once' (#458) from feature/dev-workload-resume-20261121 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m28s

This commit is contained in:
unimatrix 2026-11-21 11:16:12 +00:00
commit 8d1761750a
10 changed files with 153 additions and 13 deletions

View file

@ -0,0 +1,15 @@
# Scoped Mentat bonuses and funded Reputation rewards
Ticket 412. The existing POL QST claim engine owns awards. No third XP currency, alternate ledger or NPC player permission is introduced. Personal claims and the level-70 seasonal policy remain unchanged.
An ordinary consumed progression-policy key, scope policy:POL:S01:v3, records a 10% eligible Mentat XP bonus and a 10% bonus on explicitly configured DM rewards. Policy validation caps a bonus at 25%; existing custom configuration is never overwritten. A current unrevoked questmaster SID with quest.issue and quest.reward-bonus is required. Gurney/Esmar retain their issue-only scope. Integer bonuses round upward once at the final award, with safe-integer overflow rejection. Continuing-episode base growth remains separately capped by its existing policy.
The journal displays the actual bonus-inclusive XP. The claim transaction rechecks the bound issuer and policy, then writes the final award and its base/bonus basis to the existing claim/history receipt. Replay returns the original receipt and cannot add another bonus. Completed earlier claims are never rewritten or retroactively paid.
## Money is explicit and funded
No DM reward is enabled by default. An intentionally configured existing POL quest reward must use exactly {schema: 'pol-dm-reward-v1', amountMinor: N}, with positive N at most 1,000,000 minor units. No PDF reward proposal is adopted automatically. The claim records a bound pol-funded-reward-v1 receipt with recipient, definition, season, original base amount, issuer/policy keys and final bonus-inclusive amount.
The existing central scheduler drains only these queued typed POL reward jobs. It verifies the consumed unrevoked QST, current ordinary player, claim/job equality, current original issuer and policy, and pays only the matching ordinary personal bank account. The shared private treasury payment primitive debits existing sys_web_treasury funds and posts the existing balanced Postbank entries and audit. No mint, privileged player transfer, new finance ledger or personal/loser funding account is used. Bank order identity is the original QST UUID; a lost central acknowledgement reuses the posted order without charging again. Insufficient funds, frozen account, invalid proof or failed ledger/audit transaction retain the queued receipt for review.
No real-money transaction, production game event, contract or payout is generated as a test. Isolated fixtures cover bonus/replay, Personal isolation, funded double entry, concurrent retries, lost acknowledgement, missing funds, frozen recipient, revoked QST/SID, altered beneficiary and atomic audit failure.

View file

@ -30,6 +30,8 @@ export const MASTER_KEY_TEMPLATES=[
{id:'state',label:'Entity state',actions:[action('state.estate-freeze','Freeze estate from lore-death ESK','entity-state',[field('keyId','Verified lore-death ESK'),reference],{domainAdapter:'PostbankEstates.freeze',executionStatus:'bank-staff-consumer',effect:'Restrict existing personal accounts using a verified lore-death ESK; no balance changes.'}),action('state.estate-unlock','Unlock ESK estate','entity-state',[field('keyId','Existing ESK'),field('revision','Current bank effect revision','number',{min:1}),reference],{domainAdapter:'PostbankEstates.unlock',executionStatus:'bank-staff-consumer',effect:'Bank staff restore only the accounts held by the named ESK. Original death evidence remains unchanged.'}),action('state.record','Entity State Key','entity-state',[field('eventId','Unique source event ID'),field('action','State event'),field('targetUuid','Target entity UUID'),field('targetKind','Player or mob'),field('entityType','Entity type'),field('actorUuid','Killer / actor UUID','text',{required:false}),field('cause','Cause / reason'),field('scope','Server / lore scope'),field('world','World'),field('occurredAt','Event timestamp','number',{min:0}),reference],{recordOnly:true,domainAdapter:'entityStateKeys',executionStatus:'verified-service-record',artwork:'esk-key-v1.png',effect:'Record a verified death, respawn, ban or unban. Shared quest/contract/deed evidence with separate once-only consumer receipts. No Minecraft producer or ban migration in this batch.'})]},
{id:'progression',label:'Progression & XP',actions:[
action('progression.smuggler-institutions','Protected hidden smuggler institutions','staff-parent-link',[],{webIssue:false,domainAdapter:'clandestineInstitutions.provision',executionStatus:'current-owner-server-operator',effect:'Create the fixed protected clan and company under the current Esmar Tuek system identity. A verified introduction QST grants secondary quest affiliations only; never replace a player clan/company or grant PvP, bank, staff or office authority.'}),
action('progression.mentor-policy','Scoped Mentat reward bonus','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:3})],{webIssue:false,recordOnly:true,domainAdapter:'ensurePOLMentorPolicy',executionStatus:'recorded-system-policy',effect:'Record the bounded 10% eligible Mentat bonus through the existing POL award engine. Preserve Personal XP and earlier claims; no default DM reward.'}),
action('progression.pol-funded-rewards','Funded Reputation reward delivery','quest',[],{webIssue:false,recordOnly:true,domainAdapter:'createPOLFundedRewards',executionStatus:'consumed-quest-outbox-only',effect:'Pay only explicitly configured and verified claim rewards from existing website treasury funds to the bound ordinary player bank account. Original QST identity prevents duplicate ledger entries; unfunded or invalid rewards remain queued.'}),
action('progression.personal-activity','Verified Personal activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current Personal season'),field('metric','Registered Personal objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original committed evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'personalActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Read current immutable QSM evidence through the existing Personal quest engine. Preserve dedicated bank, forum, acquisition and Q0 proof readers. Missing external events remain pending; no browser counters or Minecraft producer are included.'}),
action('progression.pol-activity','Verified Reputation activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current season'),field('metric','Registered objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'polActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Bind actual committed activity to the current player, season and quest-giver SID. Reuse existing QSM evidence and POL claims; a browser cannot assert progress. PvP, mob and death objectives require original production Minecraft ESK evidence instead.'}),
action('progression.pol-repeatables','Ongoing Reputation quest policy','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:2})],{webIssue:false,recordOnly:true,domainAdapter:'ensurePOLRepeatablePolicy',executionStatus:'recorded-system-policy',effect:'Configure repeating PvP, mob, death, spice and smuggling episodes through existing QST claims. The bonus grows by 2% per completed round to a 5x cap. No default DM is minted; unverified game objectives stay pending.'}),

View file

@ -1,3 +1,5 @@
import {createPOLFundedRewards} from '../node/pol-funded-rewards.mjs';
import {ensurePOLMentorPolicy} from '../node/pol-mentor-rewards.mjs';
import {initializePersonalActivityEvents} from '../node/personal-activity-events.mjs';
import {createPersonalActivityAPI} from '../node/personal-activity-api.mjs';
import {initializeSecondaryAffiliations} from '../node/clandestine-institutions.mjs';
@ -472,9 +474,9 @@ export async function startPanel(settings=process.env){
inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));
}
const bankDatabase=await openPostbankDatabase(settings);
const db=await openDatabase(settings);await 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);db.polRepeatablesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com';
const db=await openDatabase(settings);await 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 ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=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:'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:[{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:'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':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"};
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": "79fa31642b0586f73d5d2aff7d252176dbdf6071d1cf8fea69839554153a95bd",
"sourceHash": "ece3772972a6246f3070afb310f9376b01e9d2ec446876d59deefa85ab596704",
"actions": [
{
"id": "clan.clear-protected-rosters",
@ -797,6 +797,57 @@
"webIssue": false,
"recordOnly": false
},
{
"id": "progression.mentor-policy",
"label": "Progression & XP · Scoped Mentat reward bonus",
"version": 1,
"keyType": "progression-policy",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "season",
"label": "Season",
"type": "text",
"required": true
},
{
"name": "policyVersion",
"label": "Policy version",
"type": "number",
"required": true,
"min": 3
}
],
"effect": "Record the bounded 10% eligible Mentat bonus through the existing POL award engine. Preserve Personal XP and earlier claims; no default DM reward.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "progression.pol-funded-rewards",
"label": "Progression & XP · Funded Reputation reward delivery",
"version": 1,
"keyType": "quest",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
}
],
"effect": "Pay only explicitly configured and verified claim rewards from existing website treasury funds to the bound ordinary player bank account. Original QST identity prevents duplicate ledger entries; unfunded or invalid rewards remain queued.",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "progression.personal-activity",
"label": "Progression & XP · Verified Personal activity",

View file

@ -0,0 +1,20 @@
import {createPOLQuestTreasuryPayments} from './quest-treasury-payments.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';
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';
const row=await tx.first('SELECT s.account_id,s.season_id,s.definition_id,s.state,c.reward_json,c.account_id claim_account,k.used_at,k.revoked_at,k.key_type,k.scope_id,k.account_id key_account,i.issuer_key_id,i.issuer_name FROM jarvis_pol_quest_states s JOIN jarvis_pol_quest_claims c ON c.key_id=s.key_id JOIN organisation_keys k ON k.id=s.key_id JOIN jarvis_pol_quest_issuers i ON i.quest_key_id=s.key_id WHERE s.key_id=? FOR UPDATE',[keyId]);
if(!row||row.state!=='claimed'||row.used_at==null||row.revoked_at!==null||row.key_type!=='quest'||row.key_account!==job.account_id||row.claim_account!==job.account_id||row.account_id!==job.account_id||row.season_id!==job.season_id||row.scope_id!==job.season_id+':POL_'+row.definition_id)throw Error('Consumed verified POL claim required');
const r=JSON.parse(row.reward_json);if(r.schema!=='pol-funded-reward-v1'||JSON.stringify(r)!==job.payload_json||r.definitionId!==row.definition_id||r.accountId!==row.account_id||r.seasonId!==row.season_id||r.issuerKeyId!==row.issuer_key_id||!Number.isSafeInteger(r.baseAmountMinor)||r.baseAmountMinor<1||r.baseAmountMinor>1000000)throw Error('Bound funded POL reward required');
const policy=await currentMentorPolicy(tx,{lock:true}),issuer=await createSystemCharacters(tx,keys,{authorizeOperator:async()=>false}).inspect(row.issuer_name),bps=issuer?.capabilities.includes('quest.reward-bonus')?policy?.dmBonusBps:0;
if(!policy||r.policyKeyId!==policy.keyId||!issuer?.capabilities.includes('quest.issue')||issuer.keyId!==row.issuer_key_id||r.bonusBps!==bps||r.amountMinor!==r.baseAmountMinor+Number((BigInt(r.baseAmountMinor)*BigInt(bps)+9999n)/10000n))throw Error('Current scoped reward policy and issuer 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,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

@ -0,0 +1,30 @@
import {randomUUID} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {polPolicyKeys} from './progression-pol.mjs';
export const POL_MENTOR_POLICY=Object.freeze({schema:'pol-mentor-bonus-v1',xpBonusBps:1000,dmBonusBps:1000,maximumBps:2500});
const definitionId='POL-MENTOR-BONUS',scopeId='policy:POL:S01:v3';
export async function ensurePOLMentorPolicy(db,keys,{clock=Date.now}={}){
const policyKeys=polPolicyKeys(keys),grant=await policyKeys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',scopeId,authorize:async()=>{}}),key=(await policyKeys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id);if(key.status==='used')return {replayed:true};if(!key.code||key.status!=='available')throw Error('Mentor policy instrument unavailable');
return policyKeys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',code:key.code,targetId:STAFF_OFFICE_ACCOUNT_ID,requestId:grant.id,apply:async(tx,{keyId})=>{
const prior=await tx.first('SELECT definition_id FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[definitionId]);if(prior)throw Error('Existing mentor configuration requires explicit review');
await tx.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,1,0,?,?,?)',[definitionId,JSON.stringify(POL_MENTOR_POLICY),STAFF_OFFICE_ACCOUNT_ID,clock()]);
await tx.query('INSERT INTO jarvis_progression_history(id,account_id,key_id,action,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),STAFF_OFFICE_ACCOUNT_ID,keyId,'mentor-bonus-policy',JSON.stringify(POL_MENTOR_POLICY),clock()]);
}});
}
export async function currentMentorPolicy(tx,{lock=false}={}){
const row=await tx.first("SELECT h.key_id,h.details_json,k.used_at,k.revoked_at,k.key_type,k.account_id,k.scope_id FROM jarvis_pol_progression_history h JOIN organisation_keys k ON k.id=h.key_id WHERE h.action='mentor-bonus-policy' AND k.scope_id=?"+(lock?' FOR UPDATE':''),[scopeId]);if(!row||row.used_at==null||row.revoked_at!==null||row.key_type!=='progression-policy'||row.account_id!==STAFF_OFFICE_ACCOUNT_ID)return null;
const p=JSON.parse(row.details_json);if(p.schema!=='pol-mentor-bonus-v1'||!['xpBonusBps','dmBonusBps'].every(k=>Number.isSafeInteger(p[k])&&p[k]>=0&&p[k]<=2500)||p.maximumBps!==2500)throw Error('Mentor bonus policy requires review');return {...p,keyId:row.key_id};
}
const increased=(base,bps)=>{if(!Number.isSafeInteger(base)||base<0)throw Error('Invalid base quest reward');const value=BigInt(base)+(BigInt(base)*BigInt(bps)+9999n)/10000n;if(value>BigInt(Number.MAX_SAFE_INTEGER))throw Error('Quest reward overflow');return Number(value);};
export async function mentorAward(tx,keys,{actor,definition,issuer,award,enabled}){
if(!enabled)return award;const policy=await currentMentorPolicy(tx,{lock:true});if(!policy)throw Error('Current mentor policy required');
const saved=await tx.first('SELECT issuer_key_id,issuer_name FROM jarvis_pol_quest_issuers WHERE quest_key_id=? FOR UPDATE',[award.keyId]);if(!saved||saved.issuer_key_id!==issuer.keyId||saved.issuer_name!==definition.issuer)throw Error('Current quest issuer binding required');
const eligible=issuer.capabilities.includes('quest.reward-bonus'),xp=increased(award.xp,eligible?policy.xpBonusBps:0),basis={policyKeyId:policy.keyId,issuerKeyId:issuer.keyId,baseXP:award.xp,xpBonusBps:eligible?policy.xpBonusBps:0};
let reward=award.reward;if(reward.schema==='pol-dm-reward-v1'){
if(Object.keys(reward).some(k=>!['schema','amountMinor'].includes(k))||!Number.isSafeInteger(reward.amountMinor)||reward.amountMinor<1||reward.amountMinor>1000000)throw Error('Explicit bounded POL reward required');
reward={schema:'pol-funded-reward-v1',baseAmountMinor:reward.amountMinor,amountMinor:increased(reward.amountMinor,eligible?policy.dmBonusBps:0),bonusBps:eligible?policy.dmBonusBps:0,policyKeyId:policy.keyId,issuerKeyId:issuer.keyId,definitionId:definition.id,accountId:actor.id,seasonId:definition.season};
}
return {...award,xp,reward,basis};
}
export const mentorXP=(base,bps)=>increased(base,bps);

View file

@ -1,3 +1,4 @@
import {mentorAward,currentMentorPolicy,mentorXP} from './pol-mentor-rewards.mjs';
import {grantSmugglerAffiliations,readSmugglerAffiliations} from './clandestine-institutions.mjs';
import {createPOLProgression} from './progression-pol.mjs';
import {createSystemCharacters} from './system-characters.mjs';
@ -28,6 +29,7 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
return {...activity,season};
}
const adapters={clock,authorizePlayer,authorizeIssuer,resolvePlayer,
resolveAward:async(actor,definition,tx,award)=>mentorAward(tx,keys,{actor,definition,issuer:await authorizeIssuer(tx,definition),award,enabled:central.polMentorBonusEnabled}),
authorizeObservation:async(actor,input,store)=>actor===observer||typeof verifyObservation==='function'&&await verifyObservation(actor,input,store),verifyAcquisition:async()=>false,
authorizeClaim:async(actor,definition,polStore)=>{
// An explicitly supplied authoritative adapter retains its existing contract.
@ -45,7 +47,10 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO
async claim(actor,input){return (await engineFor(actor,input.definitionId)).engine.claim(actor,input);},
async observe(actor,input){return (await engineFor({id:input.accountId})).engine.observe(actor,input);},
async list(actor){const current=await engineFor(actor),result=await current.engine.list(actor),proof=typeof verifyObservation==='function'||result.state!=='active'?null:await evidence(actor);
return {...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!d.repeatable&&q.revision===null;return {...q,xp:derived?d.xp:q.xp,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified,...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}),xpType:'pol',branches:[...POL_QUEST_BRANCHES.map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]};
const claimedIds=result.quests.filter(q=>q.state==='claimed'&&q.keyId).map(q=>q.keyId),claimedAwards=new Map((claimedIds.length?await central.query('SELECT key_id,xp FROM jarvis_pol_quest_claims WHERE account_id=? AND key_id IN ('+claimedIds.map(()=>'?').join(',')+')',[actor.id,...claimedIds]):[]).map(r=>[r.key_id,Number(r.xp)]));
const bonusPolicy=central.polMentorBonusEnabled?await currentMentorPolicy(central):null,bonusIssuers=new Map();
if(bonusPolicy){const characters=createSystemCharacters(central,keys,{authorizeOperator:async()=>false});for(const issuer of new Set(current.definitions.map(d=>d.issuer))){const identity=await characters.inspect(issuer);bonusIssuers.set(issuer,!!identity?.capabilities.includes('quest.reward-bonus'));}}
return {...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!d.repeatable&&q.revision===null,baseXP=derived?d.xp:q.xp,xp=claimedAwards.has(q.keyId)?claimedAwards.get(q.keyId):Number.isSafeInteger(baseXP)&&bonusPolicy&&bonusIssuers.get(d.issuer)?mentorXP(baseXP,bonusPolicy.xpBonusBps):baseXP;return {...q,baseXP,xp,mentorBonusXP:q.state==='claimed'?null:Number.isSafeInteger(xp)?xp-baseXP:0,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified,...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}),xpType:'pol',branches:[...POL_QUEST_BRANCHES.map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]};
}
});
async function collect(actor){

View file

@ -8,7 +8,7 @@ const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('h
const cap=season=>Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base));
const read=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;};
const deterministicId=text=>{const h=createHash('sha256').update(text).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);};
export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,authorizePlayer,authorizeObservation,verifyAcquisition,resolvePlayer,authorizeClaim=async()=>true,clock=Date.now}){
export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,authorizePlayer,authorizeObservation,verifyAcquisition,resolvePlayer,authorizeClaim=async()=>true,resolveAward=async(_actor,_d,_tx,award)=>award,clock=Date.now}){
if(![authorizePlayer,authorizeObservation,verifyAcquisition,resolvePlayer].every(f=>typeof f==='function'))throw TypeError('Verified quest adapters required');
const ids=definitions.map(d=>d.id),placeholders=ids.map(()=>'?').join(',');
const types=new Map(definitions.map(d=>[d.id,d])),metrics=new Set(definitions.map(d=>d.metric));
@ -83,9 +83,10 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au
if(!await authorizeClaim(actor,d,tx,{eligibility:e,season,state})||scopeId!==d.season+':'+d.id||!e.ready)throw Error('Quest objective is not complete');
const config=await tx.first('SELECT * FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[d.id]);
if(!config||!Number.isSafeInteger(config.xp)||config.xp<0||Number(config.revision)!==revision)throw Error('Quest reward changed or is not configured');
const xp=questAwardXP(d,config.xp),reward=config.reward_json?JSON.parse(config.reward_json):{};
const baseXP=questAwardXP(d,config.xp),baseReward=config.reward_json?JSON.parse(config.reward_json):{},award=await resolveAward(actor,d,tx,{xp:baseXP,reward:baseReward,keyId,revision,season}),{xp,reward}=award;
if(!Number.isSafeInteger(xp)||xp<0||!reward||typeof reward!=='object'||Array.isArray(reward))throw Error('Invalid verified quest award');
await tx.query('INSERT INTO jarvis_quest_claims(key_id,request_id,account_id,xp,reward_json,claimed_at) VALUES(?,?,?,?,?,?)',[keyId,requestId,actor.id,xp,JSON.stringify(reward),clock()]);
await saveXPAccount(tx,actor.id,creditXP(state,xp,{capXP:cap(season)}),season,keyId,'quest-claimed',{definitionId:d.id,xp,reason:e.reason},clock());
await saveXPAccount(tx,actor.id,creditXP(state,xp,{capXP:cap(season)}),season,keyId,'quest-claimed',{definitionId:d.id,xp,reason:e.reason,...(award.basis?{awardBasis:award.basis}:{})},clock());
await tx.query("UPDATE jarvis_quest_states SET state='claimed',completed_at=COALESCE(completed_at,?) WHERE key_id=?",[clock(),keyId]);
if(Object.keys(reward).length)await tx.query("INSERT INTO jarvis_quest_reward_jobs(key_id,account_id,season_id,payload_json,state,created_at) VALUES(?,?,?,?,'queued',?)",[keyId,actor.id,season.season_id,JSON.stringify(reward),clock()]);
}});

View file

@ -7,19 +7,20 @@ export const QUEST_TREASURY='sys_web_treasury';
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.
export function createQuestTreasuryPayments(bank,{authorize,clock=Date.now}={}){
function treasuryPayments(bank,{authorize,clock=Date.now},kind){
if(typeof authorize!=='function')throw TypeError('A current verified quest authorizer is required');
const payments=new PostbankPayments(bank,async()=>({}),{clock});
return Object.freeze({async pay({keyId,clanId,amountMinor,memo}){
if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||!/^[a-f0-9-]{36}$/i.test(clanId||'')||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>15000000||memo!=='Rebellion reward '+keyId)throw Error('Invalid bound quest reward');
const fingerprint=createHash('sha256').update(JSON.stringify([QUEST_TREASURY,keyId,clanId,amountMinor,memo])).digest('hex');
return Object.freeze({async pay({keyId,clanId,accountId,amountMinor,memo}){
const recipientId=kind==='clan'?clanId:accountId;
if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||!/^[a-f0-9-]{36}$/i.test(recipientId||'')||!Number.isSafeInteger(amountMinor)||amountMinor<1||amountMinor>(kind==='clan'?15000000:1250000)||memo!==(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');
return bank.transaction(async tx=>{
const entity=await tx.first("SELECT id FROM pb_entities WHERE kind='clan' AND external_key=? FOR UPDATE",[clanId]);if(!entity)throw Error('Winning clan bank entity unavailable');
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);
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!=='clan'||target.external_key!==clanId)throw Error('Quest payment reference conflict');return prior;}
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');
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()]);
@ -28,3 +29,6 @@ export function createQuestTreasuryPayments(bank,{authorize,clock=Date.now}={}){
});
}});
}
export const createQuestTreasuryPayments=(bank,options={})=>treasuryPayments(bank,options,'clan');
export const createPOLQuestTreasuryPayments=(bank,options={})=>treasuryPayments(bank,options,'person');

View file

@ -0,0 +1,10 @@
import {initializeProgression} from '../node/progression-schema.mjs';
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
import {systemCharacterFixture} from './system-character-fixture.mjs';import {initializePOLProgression,ensurePOLProgressionPolicy} from '../node/progression-pol.mjs';import {initializePOLActivityEvents,createPOLActivityEvents} from '../node/pol-activity-events.mjs';import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs';import {ensurePOLMentorPolicy} from '../node/pol-mentor-rewards.mjs';
import {createPOLFundedRewards} from '../node/pol-funded-rewards.mjs';import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs';
async function setup({cash=true}={}){const f=await systemCharacterFixture(),clock=()=>2000;await f.characters.provision(f.people.Owner,'thufir_hawat');await initializeProgression(f.db);await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock});await ensurePOLMentorPolicy(f.db,f.keys,{clock});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true;f.db.polMentorBonusEnabled=true;
const minecraftUuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[minecraftUuid,f.people.Member.id]);const producer={},events=createPOLActivityEvents(f.db,f.keys,{clock,authorizeProducer:async a=>a===producer}),proof=await events.record(producer,{eventId:randomUUID(),accountId:f.people.Member.id,minecraftUuid,seasonId:'S01',metric:'pol-verified-report',quantity:1,occurredAt:2000,reference:randomUUID()});if(cash)await f.db.query('UPDATE jarvis_pol_quest_config SET reward_json=? WHERE definition_id=?',[JSON.stringify({schema:'pol-dm-reward-v1',amountMinor:1000}),'POL-ATREIDES-01']);const runtime=createPOLProgressionRuntime(f.db,f.keys,{clock});await runtime.collect(f.people.Member);const grant=await runtime.quests.start(f.people.Member,{definitionId:'POL-ATREIDES-01'});await runtime.quests.claim(f.people.Member,{definitionId:'POL-ATREIDES-01',requestId:randomUUID(),revision:1});const claim={keyId:grant.id};return {...f,clock,runtime,claim,proof};}
async function bankSetup(){const f=await setup(),bank=new BankFixture(),entity={id:randomUUID(),kind:'person',key:f.people.Member.id,name:'Recipient'},authority=async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:false}],readAdmin:false,manageAdmin:false});await new PostbankService(bank,authority).activate(f.people.Member,{entityId:entity.id,packageKey:'pb_start',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const target=await bank.first("SELECT * FROM pb_accounts WHERE type_code='108'");const treasury=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','Treasury',10000,100,'active',1)");await f.db.query('INSERT INTO site_accounts(id,username,role) VALUES(?,?,?)',[OFFICIAL_ACCOUNT.id,OFFICIAL_ACCOUNT.username,'official_account']);return {...f,bank,target,treasuryId:treasury.insertId,worker:createPOLFundedRewards(f.db,bank,f.keys,{clock:f.clock})};}
test('a recorded scoped Mentat policy increases eligible XP once without a default cash award or Personal changes',async()=>{const f=await setup({cash:false});try{assert.equal((await f.db.first('SELECT total_xp FROM jarvis_pol_progression_accounts WHERE account_id=?',[f.people.Member.id])).total_xp,165);assert.equal((await f.runtime.quests.list(f.people.Member)).quests.find(q=>q.id==='POL-ATREIDES-01').xp,165);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_quest_reward_jobs')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_progression_accounts')).n,0);assert.equal((await ensurePOLMentorPolicy(f.db,f.keys,{clock:f.clock})).replayed,true);await f.runtime.quests.claim(f.people.Member,{definitionId:'POL-ATREIDES-01',requestId:randomUUID(),revision:1});assert.equal((await f.db.first('SELECT total_xp FROM jarvis_pol_progression_accounts WHERE account_id=?',[f.people.Member.id])).total_xp,165);}finally{f.db.close();}});
test('explicit funded POL reward and Mentat bonus post balanced ordinary-bank entries once and recover lost acknowledgement',async()=>{const f=await bankSetup();try{const before=(await f.bank.first('SELECT SUM(balance_minor) total FROM pb_accounts')).total;assert.equal((await f.worker.drain()).results[0].state,'paid');assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,1100);assert.deepEqual({...await f.bank.first('SELECT COUNT(*) n,SUM(amount_minor) net FROM pb_entries')},{n:2,net:0});await f.db.query("UPDATE jarvis_pol_quest_reward_jobs SET state='queued' WHERE key_id=?",[f.claim.keyId]);await Promise.all([f.worker.drain(),f.worker.drain()]);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal((await f.bank.first('SELECT SUM(balance_minor) total FROM pb_accounts')).total,before);assert.equal((await f.bank.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.treasuryId])).reserved_minor,100);}finally{f.db.close();f.bank.close();}});
test('unfunded, frozen, revoked, conflicting or interrupted POL payouts preserve money and remain queued for review',async()=>{for(const failure of ['funds','recipient','claim','issuer','payload','ledger']){const f=await bankSetup();try{if(failure==='funds')await f.bank.query('UPDATE pb_accounts SET balance_minor=1000 WHERE id=?',[f.treasuryId]);if(failure==='recipient')await f.bank.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.target.id]);if(failure==='claim')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[f.claim.keyId]);if(failure==='issuer')await f.db.query("UPDATE organisation_keys SET revoked_at=1 WHERE key_type='system-identity'");if(failure==='payload')await f.db.query('UPDATE jarvis_pol_quest_reward_jobs SET account_id=? WHERE key_id=?',[f.people.Other.id,f.claim.keyId]);if(failure==='ledger')f.bank.sqlite.exec("CREATE TRIGGER fail_pol_audit BEFORE INSERT ON pb_audit BEGIN SELECT RAISE(ABORT,'injected'); END;");assert.equal((await f.worker.drain()).results[0].state,'awaiting-funding-or-review');assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT state FROM jarvis_pol_quest_reward_jobs WHERE key_id=?',[f.claim.keyId])).state,'queued');}finally{f.db.close();f.bank.close();}}});