diff --git a/network/server-control/QUALITY-PROGRESSION-321.md b/network/server-control/QUALITY-PROGRESSION-321.md new file mode 100644 index 00000000..e9c2ea7d --- /dev/null +++ b/network/server-control/QUALITY-PROGRESSION-321.md @@ -0,0 +1,50 @@ +# Quality progression: version 1 foundation (321) + +This is the first bounded slice of native321/public112194 (sources97/98/99/100/103/104). **It is not activated or deployed.** There is no new HTTP route, activity collector, database writer, game listener, scheduled job or unlock grant. The parent remains open. + +## Current implementation verified on 6 November 2026 + +All five live planet backends contain `DuneQuests-1.0.1.jar`, SHA256 `33397373d8fd6c8a9e13a50a42256b56820d24e73cf33f4d2a0cc5b2509cd9fe`. The existing engine records worm encounters, not validated active-play minutes. The live gameplay schema has 182 quest-event rows and no quality-progress or clan-membership-history tables. Do not turn those old outcomes, online time, movement packets or survival duration into invented eligible activity. + +The existing kit Sales arc remains authoritative. Its claim ledger currently has zero rows; its logic unlocks the *next* quality after a stage claim. The website has one explicit grant for each of the five qualities, all belonging to the existing unimatrix999 override. They remain untouched. Two current website clan memberships have nonzero join timestamps and linked identities. Current membership is not evidence for an earlier faction tenure or a missing historical membership period. + +## Versioned policy + +`quality-policy-v1.json` records the approved cumulative defaults: + +| Quality | Eligible hours | Active days | Varied quests | Weekly contracts | Story chapters | +| --- | ---: | ---: | ---: | ---: | ---: | +| Common | 0 | 0 | 0 | 0 | 0 | +| Uncommon | 28 | 14 | 10 | 2 | 1 | +| Rare | 90 | 45 | 35 | 6 | 3 | +| Very Rare | 180 | 90 | 75 | 12 | 5 | +| Legendary | 360 | 180 | 150 | 24 | 8 | + +Every gate is required. The personal and per-group eligible-minute caps are120/day; an active day needs30minutes. A group contributor needs168hours of verified membership. Record at most one clan and one faction per actor per UTC day, one group quest completion/day and one group weekly contract/week. Group progress belongs to its original group. Missed days do not reset progress. Paid supporter benefits and faction designs remain cosmetic; faction kit stats remain vanilla. Legendary+ is not a sixth quest tier and the cancelled paid-power proposal is not revived. + +New-policy calendar buckets are UTC dates and ISO weeks starting Monday00:00UTC. This explicit boundary does not alter any existing Sales-arc calendar or weekly office-election logic. + +The version is recorded on6November2026. **Its effective date is unset.** A historical schedule date does not activate it. A future activation must record an effective UTC timestamp, this immutable policy hash, audited producer/consumer versions and a reviewed migration baseline. No pre-effective receipt or inferred activity may be backfilled. + +Canonical JSON SHA256 is `de796ee906904330581da5ef0444228abfc4cc144d9f661af5d6e6dca61b0c7c`. The loader rejects changes to v1; revised balance defaults require a separately reviewed policy version. Returned snapshots are copies. + +## Read-only planning primitives + +`quality_policy.py` provides integer/identity checks, exact UTC/ISO-week boundaries, daily-cap planning, a seven-day tenure check and a projection showing **each remaining gate**. It accepts already-authoritative totals; it does not establish that a player was active. A zero/unknown membership timestamp earns no tenure credit. Projection responses explicitly report `active:false` and `wouldQualify`, rather than claiming a persisted unlock. + +The legacy preservation planner takes a verified canonical Java/Floodgate UUID and verified legacy evidence. Its result is the union of the existing Sales-arc tier, explicit grants and already-earned qualities, with an empty revocation list and zero activity backfill. Stage0 retains Common and Uncommon; four claimed stages already retain all five qualities. Unavailable evidence, malformed claims, duplicate/gapped sequences or unknown qualities stop migration planning for review; they do not fall back to a smaller grant set. Unlinked account grants stay at their original source until their mapping is verified. No username guess or caller-selected account establishes authority. + +## Required remaining implementation + +1. Add trusted game event producers for meaningful, varied objectives and anti-AFK eligibility. The existing worm timer is insufficient. Actor UUID, objective completion and elapsed eligible activity must be server-derived, with no browser counters, artificial completion controls or arbitrary reward amounts. +2. Add durable, immutable, replay-safe receipts and transactional per-subject/day totals. A unique actor/day/group-scope fence must enforce the one-clan/one-faction rule across retries, servers and membership changes. The helpers in this slice do **not** implement that ledger or concurrency control. +3. Read current authorised membership and verified tenure, including a real faction-history source. Freeze ownership on receipt and keep already-earned group progress with the original group. Never invent join dates or silently transfer group quality. +4. Implement varied quest families, weekly resets and sequential story receipts. Provide normal two-hour-session and solo alternatives without forced spending/PvP wins or rare-drop luck. +5. Reconcile House Tailor's five-quality storage and native consumer compatibility (312), then review an additive migration preserving paid snapshots, current Sales-arc authority and explicit owner overrides. Reconcile any partial/unknown sources before activation. +6. Wire private read projections and UI gates only after the authoritative ledger is verified. Show remaining requirements separately; XP alone is not an unlock. Complete actual Java/Bedrock, anti-AFK, replay/concurrency, transfer and membership-change acceptance before closing321. + +## Checks and rollback + +From this directory: `python3 -m unittest -v test_quality_policy`. Twelve tests pass, including every gate one below its boundary, calendar horizon,120-minute caps,30-minute active-day threshold, UTC Sunday/Monday/year/leap-day boundaries,168-hour tenure, canonical identities, owner overrides at zero new progress, exact legacy stage mapping, corrupt/unavailable evidence, policy mutation and immutable version checks. Fixtures contain synthetic UUIDs and make no production calls. + +This source-only slice changes no live database, policy activation, inventory, receipt, unlock, membership, game service, CP response or website asset. Reverting the added policy/planner/tests/document removes the slice; no player-data rollback is needed. diff --git a/network/server-control/quality-policy-v1.json b/network/server-control/quality-policy-v1.json new file mode 100644 index 00000000..73eb18a2 --- /dev/null +++ b/network/server-control/quality-policy-v1.json @@ -0,0 +1,41 @@ +{ + "policyKey": "quality-journey", + "version": 1, + "recordedOn": "2026-11-06", + "timeZone": "UTC", + "weekStartsOn": "Monday", + "personal": {"dailyEligibleMinutesCap": 120, "activeDayMinimumMinutes": 30}, + "group": { + "dailyEligibleMinutesCap": 120, + "activeDayMinimumMinutes": 30, + "minimumMembershipHours": 168, + "clansPerActorPerDay": 1, + "factionsPerActorPerDay": 1, + "questCompletionsPerDay": 1, + "weeklyContractsPerWeek": 1 + }, + "objectiveFamilies": ["exploration", "delivery-logistics", "crafting", "ecology-water", "spice-recovery", "community-aid"], + "tiers": [ + {"quality": "common", "eligibleMinutes": 0, "activeDays": 0, "quests": 0, "weeklyContracts": 0, "storyChapters": 0}, + {"quality": "uncommon", "eligibleMinutes": 1680, "activeDays": 14, "quests": 10, "weeklyContracts": 2, "storyChapters": 1}, + {"quality": "rare", "eligibleMinutes": 5400, "activeDays": 45, "quests": 35, "weeklyContracts": 6, "storyChapters": 3}, + {"quality": "very_rare", "eligibleMinutes": 10800, "activeDays": 90, "quests": 75, "weeklyContracts": 12, "storyChapters": 5}, + {"quality": "legendary", "eligibleMinutes": 21600, "activeDays": 180, "quests": 150, "weeklyContracts": 24, "storyChapters": 8} + ], + "migration": { + "unlockStrategy": "union-only", + "retainLegacySalesArc": true, + "retainExplicitOverrides": true, + "retainUnlinkedAccountGrantsInPlace": true, + "inferHistoricalActivity": false, + "requireSeparateActivationRecord": true + }, + "scope": { + "factionBenefits": "cosmetic-only-vanilla", + "paidSupporterBenefits": "cosmetic-only", + "legendaryPlusQuestTier": false, + "missedDaysResetProgress": false, + "requireSpending": false, + "requirePvpWins": false + } +} diff --git a/network/server-control/quality_policy.py b/network/server-control/quality_policy.py new file mode 100644 index 00000000..4c236684 --- /dev/null +++ b/network/server-control/quality_policy.py @@ -0,0 +1,128 @@ +"""Inactive quality-policy and migration planning primitives. + +No route, writer, unlock grant or gameplay integration. Totals and legacy evidence +must come from authoritative stores, never from a browser or movement timer. +""" +import copy +import hashlib +import json +import re +import uuid +from datetime import datetime, timedelta, timezone +from functools import lru_cache +from pathlib import Path + +POLICY_FILE = Path(__file__).with_name('quality-policy-v1.json') +PINNED_V1_SHA256 = 'de796ee906904330581da5ef0444228abfc4cc144d9f661af5d6e6dca61b0c7c' +METRICS = ('eligibleMinutes', 'activeDays', 'quests', 'weeklyContracts', 'storyChapters') +QUALITIES = ('common', 'uncommon', 'rare', 'very_rare', 'legendary') +MAX_EXACT = 9007199254740991 +MAX_TIMESTAMP = 253402300799999 +EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) + + +def integer(value, maximum=MAX_EXACT): + if type(value) is not int or not 0 <= value <= maximum: + raise ValueError('A bounded non-negative integer is required') + return value + + +@lru_cache(maxsize=1) +def _policy(): + policy = json.loads(POLICY_FILE.read_text(encoding='utf-8')) + encoded = json.dumps(policy, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + digest = hashlib.sha256(encoded).hexdigest() + if digest != PINNED_V1_SHA256: + raise ValueError('Quality policy v1 changed; record and review a new version') + return policy + + +def policy_snapshot(): + return {'policy': copy.deepcopy(_policy()), 'sha256': PINNED_V1_SHA256, 'active': False} + + +def canonical_player(value): + if not isinstance(value, str) or not re.fullmatch(r'[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}', value): + raise ValueError('A verified canonical Minecraft UUID is required') + if uuid.UUID(value).int == 0: + raise ValueError('An actual verified Minecraft identity is required') + return value + + +def utc_day(timestamp): + return (EPOCH + timedelta(milliseconds=integer(timestamp, MAX_TIMESTAMP))).date().isoformat() + + +def utc_week(timestamp): + day = (EPOCH + timedelta(milliseconds=integer(timestamp, MAX_TIMESTAMP))).date() + year, week, _ = day.isocalendar() + return '%04d-W%02d' % (year, week) + + +def daily_credit(current_minutes, eligible_minutes, scope='personal'): + """Plan credit from already verified eligible activity; this does not verify activity.""" + if scope not in ('personal', 'group'): + raise ValueError('Unknown progression scope') + rule = _policy()[scope] + current = integer(current_minutes, rule['dailyEligibleMinutesCap']) + requested = integer(eligible_minutes) + credited = min(requested, rule['dailyEligibleMinutesCap'] - current) + total = current + credited + return {'creditedMinutes': credited, 'totalMinutes': total, + 'activeDay': total >= rule['activeDayMinimumMinutes']} + + +def membership_eligible(joined_at, event_at): + """Unknown history earns no group credit. Never infer tenure from a current roster.""" + event_at = integer(event_at, MAX_TIMESTAMP) + if joined_at is None: + return False + joined_at = integer(joined_at, MAX_TIMESTAMP) + if joined_at == 0 or joined_at > event_at: + return False + return event_at - joined_at >= _policy()['group']['minimumMembershipHours'] * 3600000 + + +def known_qualities(values): + if not isinstance(values, (list, tuple, set, frozenset)): + raise ValueError('Verified unlock evidence is unavailable; do not migrate') + if any(not isinstance(value, str) or value not in QUALITIES for value in values): + raise ValueError('Unknown legacy quality; review before migration') + return set(values) + + +def evaluate_totals(totals, retained=()): + """Read-only gate projection, not evidence validation or a persisted unlock decision.""" + if not isinstance(totals, dict) or set(totals) != set(METRICS): + raise ValueError('All authoritative progression totals are required') + totals = {name: integer(totals[name]) for name in METRICS} + retained = known_qualities(retained) + rows = [] + for tier in _policy()['tiers']: + remaining = {name: max(0, tier[name] - totals[name]) for name in METRICS} + rows.append({'quality': tier['quality'], 'retained': tier['quality'] in retained, + 'wouldQualify': not any(remaining.values()), 'remaining': remaining}) + return {'policyVersion': 1, 'policySha256': PINNED_V1_SHA256, 'active': False, 'tiers': rows} + + +def plan_legacy_unlocks(player_uuid, claimed_stages, explicit_qualities, already_earned=()): + """Preserve the existing Sales arc and explicit grants; never writes or revokes. + + Existing arc stage0 unlocks the *next* tier (Uncommon), not just Common. + An account grant without a verified current UUID stays at its original source. + Missing sources or corrupt claim sequences stop planning, rather than replacing + them with a smaller set of unlocks. + """ + player_uuid = canonical_player(player_uuid) + if not isinstance(claimed_stages, (list, tuple)) or any(type(i) is not int for i in claimed_stages): + raise ValueError('Verified Sales arc claims are required') + if list(claimed_stages) != list(range(len(claimed_stages))) or len(claimed_stages) > 5: + raise ValueError('Corrupt Sales arc sequence; retain the existing authority for review') + explicit = known_qualities(explicit_qualities) + earned = known_qualities(already_earned) + arc = set(QUALITIES[:min(5, len(claimed_stages) + 1)]) + preserve = arc | explicit | earned + return {'playerUuid': player_uuid, 'policyVersion': 1, 'policySha256': PINNED_V1_SHA256, + 'mode': 'dry-run-union-only', 'active': False, + 'preserveQualities': [quality for quality in QUALITIES if quality in preserve], + 'revokeQualities': [], 'activityBackfillMinutes': 0} diff --git a/network/server-control/test_quality_policy.py b/network/server-control/test_quality_policy.py new file mode 100644 index 00000000..57641252 --- /dev/null +++ b/network/server-control/test_quality_policy.py @@ -0,0 +1,154 @@ +import json +import tempfile +import unittest +from datetime import datetime, timezone +from pathlib import Path +import quality_policy as policy + +JAVA = 'a1111111-b111-4111-8111-c11111111111' +BEDROCK = '00000000-0000-0000-0009-000000000001' + + +def millis(value): + delta = datetime.fromisoformat(value).replace(tzinfo=timezone.utc) - policy.EPOCH + return (delta.days * 86400 + delta.seconds) * 1000 + delta.microseconds // 1000 + + +class QualityPolicyTest(unittest.TestCase): + def totals(self, value=0): + return dict.fromkeys(policy.METRICS, value) + + def test_recorded_defaults_are_inactive_and_preserve_legacy_authority(self): + snapshot = policy.policy_snapshot() + self.assertFalse(snapshot['active']) + self.assertEqual(snapshot['policy']['version'], 1) + self.assertEqual(snapshot['policy']['migration']['unlockStrategy'], 'union-only') + self.assertTrue(snapshot['policy']['migration']['retainLegacySalesArc']) + self.assertFalse(snapshot['policy']['migration']['inferHistoricalActivity']) + self.assertFalse(snapshot['policy']['scope']['legendaryPlusQuestTier']) + self.assertEqual([row['quality'] for row in snapshot['policy']['tiers']], list(policy.QUALITIES)) + + def test_all_five_milestone_gates_are_required_at_each_boundary(self): + for tier in policy.policy_snapshot()['policy']['tiers'][1:]: + totals = {key: tier[key] for key in policy.METRICS} + row = next(r for r in policy.evaluate_totals(totals)['tiers'] if r['quality'] == tier['quality']) + self.assertTrue(row['wouldQualify']) + for metric in policy.METRICS: + with self.subTest(quality=tier['quality'], metric=metric): + below = {**totals, metric: totals[metric] - 1} + row = next(r for r in policy.evaluate_totals(below)['tiers'] if r['quality'] == tier['quality']) + self.assertFalse(row['wouldQualify']) + self.assertEqual(row['remaining'][metric], 1) + + def test_large_group_or_quest_total_cannot_bypass_the_calendar_horizon(self): + totals = self.totals(1000000) + totals['activeDays'] = 179 + row = policy.evaluate_totals(totals)['tiers'][-1] + self.assertFalse(row['wouldQualify']) + self.assertEqual(row['remaining']['activeDays'], 1) + self.assertEqual(policy.daily_credit(119, 1000000, 'group')['creditedMinutes'], 1) + + def test_personal_and_group_daily_caps_and_active_day_boundary(self): + for scope in ['personal', 'group']: + with self.subTest(scope=scope): + self.assertEqual(policy.daily_credit(0, 240, scope), {'creditedMinutes': 120, 'totalMinutes': 120, 'activeDay': True}) + self.assertEqual(policy.daily_credit(120, 100, scope)['creditedMinutes'], 0) + self.assertFalse(policy.daily_credit(0, 29, scope)['activeDay']) + self.assertTrue(policy.daily_credit(29, 1, scope)['activeDay']) + self.assertEqual(policy.daily_credit(119, 5, scope)['totalMinutes'], 120) + + def test_malformed_counters_and_corrupt_over_cap_state_are_rejected(self): + for value in [True, False, -1, 1.5, '30', None, 9007199254740992]: + with self.subTest(value=value): + with self.assertRaises(ValueError): + policy.daily_credit(0, value) + with self.assertRaises(ValueError): + policy.evaluate_totals({**self.totals(), 'quests': value}) + with self.assertRaises(ValueError): + policy.daily_credit(121, 0) + with self.assertRaises(ValueError): + policy.daily_credit(0, 1, 'other') + with self.assertRaises(ValueError): + policy.evaluate_totals({'eligibleMinutes': 300}) + with self.assertRaises(ValueError): + policy.evaluate_totals({**self.totals(), 'clientOverride': True}) + + def test_utc_day_iso_week_and_year_boundaries(self): + sunday = millis('2026-11-08T23:59:59.999') + monday = sunday + 1 + self.assertEqual(policy.utc_day(sunday), '2026-11-08') + self.assertEqual(policy.utc_day(monday), '2026-11-09') + self.assertEqual(policy.utc_week(sunday), '2026-W45') + self.assertEqual(policy.utc_week(monday), '2026-W46') + self.assertEqual(policy.utc_week(millis('2027-01-01T12:00:00')), '2026-W53') + self.assertEqual(policy.utc_day(millis('2028-02-29T12:00:00')), '2028-02-29') + self.assertEqual(policy.utc_day(policy.MAX_TIMESTAMP), '9999-12-31') + for invalid in [-1, True, policy.MAX_TIMESTAMP + 1]: + with self.assertRaises(ValueError): + policy.utc_week(invalid) + + def test_membership_requires_verified_seven_day_tenure(self): + joined = millis('2026-11-01T00:00:00') + eligible = joined + 7 * 86400000 + self.assertFalse(policy.membership_eligible(joined, eligible - 1)) + self.assertTrue(policy.membership_eligible(joined, eligible)) + self.assertFalse(policy.membership_eligible(joined, joined - 1)) + self.assertFalse(policy.membership_eligible(None, eligible)) + self.assertFalse(policy.membership_eligible(0, eligible)) + with self.assertRaises(ValueError): + policy.membership_eligible(True, eligible) + + def test_existing_owner_override_survives_zero_new_progress(self): + plan = policy.plan_legacy_unlocks(JAVA, [], list(policy.QUALITIES)) + self.assertEqual(plan['preserveQualities'], list(policy.QUALITIES)) + self.assertEqual(plan['revokeQualities'], []) + self.assertEqual(plan['activityBackfillMinutes'], 0) + projection = policy.evaluate_totals(self.totals(), plan['preserveQualities']) + self.assertTrue(all(row['retained'] for row in projection['tiers'])) + self.assertFalse(projection['tiers'][-1]['wouldQualify']) + self.assertFalse(plan['active']) + + def test_sales_arc_claim_unlocks_the_next_tier_and_never_revokes(self): + for count in range(6): + with self.subTest(claims=count): + plan = policy.plan_legacy_unlocks(JAVA, list(range(count)), []) + self.assertEqual(plan['preserveQualities'], list(policy.QUALITIES[:min(5, count + 1)])) + self.assertEqual(plan['revokeQualities'], []) + earned = policy.plan_legacy_unlocks(JAVA, [], [], ['legendary']) + self.assertEqual(earned['preserveQualities'], ['common', 'legendary']) + + def test_unknown_evidence_and_corrupt_claim_sequences_stop_migration(self): + for claims in [None, [True], [1], [0, 2], [0, 0], list(range(6)), '0']: + with self.subTest(claims=claims), self.assertRaises(ValueError): + policy.plan_legacy_unlocks(JAVA, claims, []) + for grants in [None, ['legendary_plus'], ['administrator'], ['rare', 1]]: + with self.subTest(grants=grants), self.assertRaises(ValueError): + policy.plan_legacy_unlocks(JAVA, [], grants) + + def test_java_and_floodgate_identities_are_not_guessed_from_names(self): + for player in [JAVA, BEDROCK]: + self.assertEqual(policy.plan_legacy_unlocks(player, [], [])['playerUuid'], player) + for player in [None, 'mr_blueray', '.Player', JAVA.upper(), JAVA.replace('-', ''), '00000000-0000-0000-0000-000000000000']: + with self.subTest(player=player), self.assertRaises(ValueError): + policy.plan_legacy_unlocks(player, [], []) + + def test_public_snapshot_cannot_mutate_policy_and_v1_edits_are_rejected(self): + snapshot = policy.policy_snapshot() + snapshot['policy']['tiers'][-1]['eligibleMinutes'] = 0 + self.assertEqual(policy.policy_snapshot()['policy']['tiers'][-1]['eligibleMinutes'], 21600) + original = policy.POLICY_FILE + try: + with tempfile.TemporaryDirectory(prefix='quality-policy-qa-') as folder: + changed = Path(folder) / 'changed.json' + changed.write_text(json.dumps(snapshot['policy'])) + policy.POLICY_FILE = changed + policy._policy.cache_clear() + with self.assertRaises(ValueError): + policy.policy_snapshot() + finally: + policy.POLICY_FILE = original + policy._policy.cache_clear() + + +if __name__ == '__main__': + unittest.main()