Spaces:
Running
Running
Download algospaced-ui/tests/storeInventory.test.mjs from iamfebin/algospaced-dsa: direct link, hf CLI and curl.
- Browser
- Download file 51.3 kB
-
https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/tests/storeInventory.test.mjs
- Command line
-
hf download hf://spaces/iamfebin/algospaced-dsa/algospaced-ui/tests/storeInventory.test.mjs
-
curl -L -o storeInventory.test.mjs https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/tests/storeInventory.test.mjs
51.3 kB
import test from 'node:test';
import assert from 'node:assert/strict';
// ============================================================================
// Mock Browser Environment for Node.js Native Test Runner
// ============================================================================
class LocalStorageMock {
constructor() {
this.store = {};
}
getItem(key) {
return this.store[key] !== undefined ? this.store[key] : null;
}
setItem(key, val) {
this.store[key] = String(val);
}
removeItem(key) {
delete this.store[key];
}
clear() {
this.store = {};
}
}
const mockStorage = new LocalStorageMock();
globalThis.localStorage = mockStorage;
globalThis.window = {
addEventListener: () => {},
removeEventListener: () => {},
location: { reload: () => {} },
dispatchEvent: () => true
};
// ============================================================================
// Authoritative Domain Catalog Specification (from PROJECT.md / Survey Report)
// ============================================================================
export const STORE_CATALOG = [
// 1. Study Consumables
{
id: 'consumable_streak_freeze',
name: 'Elixir of Frozen Time',
category: 'consumable',
price: 150,
lore: 'A crystalline phial filled with the enchanted sands of Chronos, arresting the relentless march of time when darkness falls.',
icon: 'ShieldAlert',
effect_type: 'streak_freeze',
effect_payload: { freeze_charges: 1 }
},
{
id: 'consumable_hint_scroll',
name: "Archivist's Hint Scroll",
category: 'consumable',
price: 75,
lore: 'An illuminated vellum scroll penned by royal archivists, unravelling algorithmic intuition and pattern landmarks.',
icon: 'Scroll',
effect_type: 'hint_scroll',
effect_payload: { hint_tokens: 1 }
},
{
id: 'consumable_focus_draught',
name: 'Potion of Keen Insight',
category: 'consumable',
price: 100,
lore: 'A sparkling azure potion that heightens mental acuity and doubles gold earned on your next 3 completed review cards.',
icon: 'Sparkles',
effect_type: 'focus_boost',
effect_payload: { multiplier: 2, reviews_remaining: 3 }
},
{
id: 'consumable_campfire_stew',
name: "Hearty Wayfarer's Stew",
category: 'consumable',
price: 50,
lore: 'A steaming bowl of herbal root stew prepared over the campfire coals, dispelling mental fatigue and restoring composure.',
icon: 'Flame',
effect_type: 'focus_boost',
effect_payload: { fatigue_reset: true }
},
// 2. Desktop Cosmetics
{
id: 'cosmetic_crt_scanlines',
name: 'Arcade CRT Phosphor Shader',
category: 'cosmetic',
price: 200,
lore: 'A retro cathode-ray raster filter with nostalgic scanlines, curved CRT edge vignette, and vintage phosphor bloom.',
icon: 'Tv',
effect_type: 'crt_theme',
effect_payload: { overlay_class: 'crt-scanlines-active' }
},
{
id: 'cosmetic_theme_amber',
name: 'Amber Campfire Theme',
category: 'cosmetic',
price: 250,
lore: 'A cozy UI palette featuring warm ember golds, toasted parchment backgrounds, and rustic brass window borders.',
icon: 'Flame',
effect_type: 'palette_theme',
effect_payload: { theme_id: 'amber' }
},
{
id: 'cosmetic_theme_cyber',
name: 'Synthwave Spire Theme',
category: 'cosmetic',
price: 300,
lore: 'Electric neon magenta and cyan hues inspired by the luminous power conduits pulsing beneath the ancient tower.',
icon: 'Cpu',
effect_type: 'palette_theme',
effect_payload: { theme_id: 'cyber' }
},
{
id: 'cosmetic_wallpaper_sanctuary',
name: 'Sanctuary of the Elixir',
category: 'cosmetic',
price: 350,
lore: 'A high-resolution landscape of the distant Ancient Tower glowing beneath the celestial northern aurora.',
icon: 'Image',
effect_type: 'wallpaper',
effect_payload: { wallpaper_url: '/wallpapers/sanctuary_spire.webp' }
},
// 3. Companion Gifts
{
id: 'gift_starflower_tea',
name: 'Soothing Starflower Tea',
category: 'companion_gift',
price: 80,
lore: 'Delicate white alpine blossoms harvested from mountain ridges, brewed into a soothing remedy that cools high fevers.',
icon: 'Flower2',
effect_type: 'aurelia_gift',
effect_payload: { bond_points: 15, emotion: 'smiling_warmly' }
},
{
id: 'gift_silk_shawl',
name: 'Embroidered Silver Shawl',
category: 'companion_gift',
price: 150,
lore: 'A lightweight yet luxuriously warm shawl woven from palace silk and lined with silver thread to fend off freezing winds.',
icon: 'Shirt',
effect_type: 'aurelia_gift',
effect_payload: { bond_points: 30, emotion: 'smiling_warmly' }
},
{
id: 'gift_music_box',
name: 'Celestial Music Box',
category: 'companion_gift',
price: 300,
lore: 'A miniature brass music box that softly plays the lullaby of her childhood palace gardens.',
icon: 'Music',
effect_type: 'aurelia_gift',
effect_payload: { bond_points: 60, emotion: 'excited_expression' }
},
{
id: 'gift_elixir_pendant',
name: 'Glimmer of the Sanctuary',
category: 'companion_gift',
price: 500,
lore: 'A carved crystalline teardrop imbued with starlight that brings radiant hope for her cure.',
icon: 'Gem',
effect_type: 'aurelia_gift',
effect_payload: { bond_points: 100, emotion: 'excited_expression' }
}
];
// ============================================================================
// Opaque-Box Domain Helpers & Pure Reducer Models
// ============================================================================
const GOLD_STORAGE_PREFIX = 'algospaced_player_gold_';
const INVENTORY_STORAGE_PREFIX = 'algospaced_player_inventory_';
const COMPANION_STORAGE_PREFIX = 'algospaced_companion_state_';
function getStorageKeys(userId = 'guest') {
return {
goldKey: `${GOLD_STORAGE_PREFIX}${userId}`,
inventoryKey: `${INVENTORY_STORAGE_PREFIX}${userId}`,
companionKey: `${COMPANION_STORAGE_PREFIX}${userId}`
};
}
function loadPlayerGold(userId = 'guest') {
const { goldKey } = getStorageKeys(userId);
const raw = mockStorage.getItem(goldKey);
if (!raw) return { gold: 0, lifetime_earned: 0, updated_at: new Date().toISOString() };
try {
return JSON.parse(raw);
} catch {
return { gold: 0, lifetime_earned: 0, updated_at: new Date().toISOString() };
}
}
function savePlayerGold(userId = 'guest', data) {
const { goldKey } = getStorageKeys(userId);
mockStorage.setItem(goldKey, JSON.stringify(data));
}
function loadPlayerInventory(userId = 'guest') {
const { inventoryKey } = getStorageKeys(userId);
const raw = mockStorage.getItem(inventoryKey);
if (!raw) return [];
try {
return JSON.parse(raw);
} catch {
return [];
}
}
function savePlayerInventory(userId = 'guest', items) {
const { inventoryKey } = getStorageKeys(userId);
mockStorage.setItem(inventoryKey, JSON.stringify(items));
}
// Earning functions
export function calculateReviewReward(rating) {
switch (rating) {
case 1: return 5; // Again
case 2: return 15; // Hard
case 3: return 25; // Good
case 4: return 35; // Easy
default: return 0;
}
}
export function calculateChallengeReward(isPassed) {
return isPassed ? 100 : 0;
}
export function awardGold(userId, amount) {
if (amount <= 0) return loadPlayerGold(userId);
const current = loadPlayerGold(userId);
const updated = {
gold: current.gold + amount,
lifetime_earned: current.lifetime_earned + amount,
updated_at: new Date().toISOString()
};
savePlayerGold(userId, updated);
return updated;
}
// Atomic Purchase Execution
export function executePurchase(userId, itemId, quantity = 1) {
if (quantity <= 0 || !Number.isInteger(quantity)) {
throw new Error('Purchase quantity must be a positive integer.');
}
const catalogItem = STORE_CATALOG.find(i => i.id === itemId);
if (!catalogItem) {
throw new Error(`Item ${itemId} not found in store catalog.`);
}
const totalPrice = catalogItem.price * quantity;
const currentGoldData = loadPlayerGold(userId);
if (currentGoldData.gold < totalPrice) {
throw new Error(`Insufficient gold balance to purchase item. Required: ${totalPrice}, Available: ${currentGoldData.gold}`);
}
// Deduct gold
const updatedGold = {
...currentGoldData,
gold: currentGoldData.gold - totalPrice,
updated_at: new Date().toISOString()
};
// Credit inventory
const inventory = loadPlayerInventory(userId);
const existingIdx = inventory.findIndex(item => item.item_id === itemId);
const now = new Date().toISOString();
let updatedInventoryItem;
if (existingIdx >= 0) {
inventory[existingIdx].quantity += quantity;
inventory[existingIdx].updated_at = now;
updatedInventoryItem = inventory[existingIdx];
} else {
updatedInventoryItem = {
item_id: itemId,
quantity,
is_equipped: false,
acquired_at: now,
updated_at: now
};
inventory.push(updatedInventoryItem);
}
savePlayerGold(userId, updatedGold);
savePlayerInventory(userId, inventory);
return {
success: true,
item: catalogItem,
new_balance: updatedGold.gold,
inventory_item: updatedInventoryItem
};
}
// Inventory Consumption & Usage
export function consumeInventoryItem(userId, itemId) {
const inventory = loadPlayerInventory(userId);
const existingIdx = inventory.findIndex(item => item.item_id === itemId);
if (existingIdx === -1 || inventory[existingIdx].quantity <= 0) {
throw new Error(`Item ${itemId} is not available in inventory.`);
}
const catalogItem = STORE_CATALOG.find(i => i.id === itemId);
if (!catalogItem) {
throw new Error(`Catalog item ${itemId} not recognized.`);
}
inventory[existingIdx].quantity -= 1;
const remaining = inventory[existingIdx].quantity;
if (remaining === 0) {
inventory.splice(existingIdx, 1);
} else {
inventory[existingIdx].updated_at = new Date().toISOString();
}
savePlayerInventory(userId, inventory);
return {
success: true,
effect_applied: catalogItem.effect_type,
remaining_quantity: remaining,
details: catalogItem.effect_payload
};
}
// Cosmetic Equipping
export function equipCosmeticItem(userId, itemId, isEquipped = true) {
const inventory = loadPlayerInventory(userId);
const item = inventory.find(i => i.item_id === itemId);
if (!item) {
throw new Error(`Cosmetic item ${itemId} is not owned in inventory.`);
}
const catalogItem = STORE_CATALOG.find(i => i.id === itemId);
if (!catalogItem || catalogItem.category !== 'cosmetic') {
throw new Error(`Item ${itemId} is not a valid cosmetic.`);
}
// If equipping, unequip other cosmetics of the same effect type
if (isEquipped) {
for (const inv of inventory) {
const otherCat = STORE_CATALOG.find(i => i.id === inv.item_id);
if (otherCat && otherCat.effect_type === catalogItem.effect_type && inv.item_id !== itemId) {
inv.is_equipped = false;
}
}
}
item.is_equipped = isEquipped;
item.updated_at = new Date().toISOString();
savePlayerInventory(userId, inventory);
return {
success: true,
item_id: itemId,
is_equipped: isEquipped,
effect_type: catalogItem.effect_type,
payload: catalogItem.effect_payload
};
}
// Princess Aurelia Companion Gifting Logic
export function calculateBondTier(bondPoints) {
if (bondPoints >= 100) return 'Soulbound Confidante';
if (bondPoints >= 40) return 'Trusted Ally';
return 'Acquaintance';
}
export function presentGiftToAurelia(userId, giftItemId, companionState = { bondPoints: 0, transcript: [] }) {
const catalogItem = STORE_CATALOG.find(i => i.id === giftItemId);
if (!catalogItem || catalogItem.category !== 'companion_gift') {
throw new Error(`Item ${giftItemId} is not a valid companion gift.`);
}
// Consume from inventory
const consumeRes = consumeInventoryItem(userId, giftItemId);
const bondPointsAdded = catalogItem.effect_payload.bond_points || 15;
const newBondPoints = (companionState.bondPoints || 0) + bondPointsAdded;
const newBondTier = calculateBondTier(newBondPoints);
const dialogues = {
gift_starflower_tea: "Aurelia cradles the warm steaming cup in both hands, breathing in the herbal aroma... 'Thank you, my friend. The starflower warmth eases the tightness in my chest and banishes the mountain chill.'",
gift_silk_shawl: "Aurelia softly drapes the delicate silver-stitched shawl around her shoulders... 'It is so gentle and warm. Wrapped in this, I feel shielded and safe on the trail.'",
gift_music_box: "Aurelia winds the small brass key with glistening eyes as the delicate chimes ring out... 'This melody... my mother used to hum this in the royal rose gardens. You have returned a piece of my home to me.'",
gift_elixir_pendant: "The crystal teardrop pulses with a soft celestial glow against her palm... 'A fragment of the Sanctuary itself! Feeling its radiance, I know in my heart we will reach the Tower and find the Elixir in time.'"
};
const appreciationDialogue = dialogues[giftItemId] || "Aurelia smiles warmly and accepts your gift with heartfelt gratitude.";
return {
success: true,
appreciationDialogue,
bondPointsAdded,
newBondPoints,
newBondTier,
activeEmotion: catalogItem.effect_payload.emotion || 'smiling_warmly',
remainingQuantity: consumeRes.remaining_quantity
};
}
// SRS Streak Protection Simulation
export function evaluateStreakProtection(streakData, currentDaysDelta) {
const freezeCount = streakData.streak_freeze_count || 0;
if (currentDaysDelta === 0 || currentDaysDelta === 1) {
// Consecutive or same-day practice: freeze untouched, streak maintained
return {
current_streak: streakData.current_streak,
streak_freeze_count: freezeCount,
streak_freeze_consumed: false,
streak_preserved: true
};
}
if (currentDaysDelta === 2 && freezeCount > 0) {
// Missed exactly 1 day with active freeze: consume 1 charge, preserve streak
return {
current_streak: streakData.current_streak,
streak_freeze_count: freezeCount - 1,
streak_freeze_consumed: true,
streak_preserved: true
};
}
// Missed more than 1 day or missed 1 day with 0 freezes: streak breaks to 0
return {
current_streak: 0,
streak_freeze_count: freezeCount,
streak_freeze_consumed: false,
streak_preserved: false
};
}
// ============================================================================
// TIER 1: FEATURE COVERAGE (F1 to F14 IN ISOLATION, >= 5 TEST CASES EACH)
// ============================================================================
// --- F1: Persistent Currency Engine ---
test('F1.1: Brand new user initializes with 0 gold and 0 lifetime earned', () => {
mockStorage.clear();
const currency = loadPlayerGold('usr-fresh');
assert.strictEqual(currency.gold, 0);
assert.strictEqual(currency.lifetime_earned, 0);
});
test('F1.2: Awarding gold increments both current balance and lifetime earned', () => {
mockStorage.clear();
const updated = awardGold('usr-f1-2', 50);
assert.strictEqual(updated.gold, 50);
assert.strictEqual(updated.lifetime_earned, 50);
});
test('F1.3: Subsequent awards increment balance cumulatively', () => {
mockStorage.clear();
awardGold('usr-f1-3', 25);
const updated = awardGold('usr-f1-3', 35);
assert.strictEqual(updated.gold, 60);
assert.strictEqual(updated.lifetime_earned, 60);
});
test('F1.4: Gold balance persists across simulated reload via localStorage', () => {
mockStorage.clear();
awardGold('usr-f1-4', 150);
// Reload simulation
const loaded = loadPlayerGold('usr-f1-4');
assert.strictEqual(loaded.gold, 150);
});
test('F1.5: Currency balances are strictly isolated across multiple user IDs', () => {
mockStorage.clear();
awardGold('guest', 100);
awardGold('auth-user-99', 500);
const guest = loadPlayerGold('guest');
const authUser = loadPlayerGold('auth-user-99');
assert.strictEqual(guest.gold, 100);
assert.strictEqual(authUser.gold, 500);
});
// --- F2: Review Card Earning Hook ---
test('F2.1: Rating 1 (Again) grants exactly +5g reward', () => {
assert.strictEqual(calculateReviewReward(1), 5);
});
test('F2.2: Rating 2 (Hard) grants exactly +15g reward', () => {
assert.strictEqual(calculateReviewReward(2), 15);
});
test('F2.3: Rating 3 (Good) grants exactly +25g reward', () => {
assert.strictEqual(calculateReviewReward(3), 25);
});
test('F2.4: Rating 4 (Easy) grants exactly +35g reward', () => {
assert.strictEqual(calculateReviewReward(4), 35);
});
test('F2.5: Completing a sequence of reviews accumulates correct cumulative gold', () => {
mockStorage.clear();
const ratings = [3, 4, 2, 1]; // +25, +35, +15, +5 = +80g
for (const r of ratings) {
awardGold('usr-f2-5', calculateReviewReward(r));
}
const result = loadPlayerGold('usr-f2-5');
assert.strictEqual(result.gold, 80);
});
// --- F3: Coding Problem Earning Hook ---
test('F3.1: Passing a Python coding challenge awards exactly +100g', () => {
assert.strictEqual(calculateChallengeReward(true), 100);
});
test('F3.2: Failing a coding challenge awards 0g', () => {
assert.strictEqual(calculateChallengeReward(false), 0);
});
test('F3.3: Passing challenge credits player balance directly', () => {
mockStorage.clear();
const reward = calculateChallengeReward(true);
const updated = awardGold('usr-f3-3', reward);
assert.strictEqual(updated.gold, 100);
});
test('F3.4: Repeat solves accumulate distinct rewards when valid', () => {
mockStorage.clear();
awardGold('usr-f3-4', calculateChallengeReward(true));
awardGold('usr-f3-4', calculateChallengeReward(true));
const final = loadPlayerGold('usr-f3-4');
assert.strictEqual(final.gold, 200);
});
test('F3.5: Zero reward does not modify current gold or lifetime timestamp', () => {
mockStorage.clear();
awardGold('usr-f3-5', 50);
const initial = loadPlayerGold('usr-f3-5');
const attempted = awardGold('usr-f3-5', calculateChallengeReward(false));
assert.strictEqual(attempted.gold, 50);
assert.strictEqual(attempted.updated_at, initial.updated_at);
});
// --- F4: Atomic Transaction Safety ---
test('F4.1: Purchasing with sufficient funds deducts price and adds item to inventory', () => {
mockStorage.clear();
awardGold('usr-f4-1', 200);
const res = executePurchase('usr-f4-1', 'consumable_streak_freeze', 1);
assert.strictEqual(res.success, true);
assert.strictEqual(res.new_balance, 50); // 200 - 150
assert.strictEqual(res.inventory_item.item_id, 'consumable_streak_freeze');
assert.strictEqual(res.inventory_item.quantity, 1);
});
test('F4.2: Purchasing with insufficient funds throws informative error', () => {
mockStorage.clear();
awardGold('usr-f4-2', 100);
assert.throws(() => {
executePurchase('usr-f4-2', 'consumable_streak_freeze', 1); // costs 150
}, /Insufficient gold balance/);
});
test('F4.3: Failed transaction leaves gold balance completely intact', () => {
mockStorage.clear();
awardGold('usr-f4-3', 100);
try {
executePurchase('usr-f4-3', 'consumable_streak_freeze', 1);
} catch {
// expected
}
const gold = loadPlayerGold('usr-f4-3');
assert.strictEqual(gold.gold, 100);
});
test('F4.4: Failed transaction leaves player inventory completely untouched', () => {
mockStorage.clear();
awardGold('usr-f4-4', 70);
try {
executePurchase('usr-f4-4', 'consumable_hint_scroll', 1); // costs 75
} catch {
// expected
}
const inv = loadPlayerInventory('usr-f4-4');
assert.strictEqual(inv.length, 0);
});
test('F4.5: Attempting purchase of non-existent catalog ID throws error without state mutation', () => {
mockStorage.clear();
awardGold('usr-f4-5', 500);
assert.throws(() => {
executePurchase('usr-f4-5', 'non_existent_item_id', 1);
}, /not found in store catalog/);
assert.strictEqual(loadPlayerGold('usr-f4-5').gold, 500);
});
// --- F5: Store Catalog Definition ---
test('F5.1: Catalog contains exactly 12 items as specified', () => {
assert.strictEqual(STORE_CATALOG.length, 12);
});
test('F5.2: All three mandatory categories are present in equal distribution', () => {
const consumables = STORE_CATALOG.filter(i => i.category === 'consumable');
const cosmetics = STORE_CATALOG.filter(i => i.category === 'cosmetic');
const gifts = STORE_CATALOG.filter(i => i.category === 'companion_gift');
assert.strictEqual(consumables.length, 4);
assert.strictEqual(cosmetics.length, 4);
assert.strictEqual(gifts.length, 4);
});
test('F5.3: All catalog items have positive integer prices', () => {
for (const item of STORE_CATALOG) {
assert.strictEqual(Number.isInteger(item.price), true, `${item.id} price must be integer`);
assert.strictEqual(item.price > 0, true, `${item.id} price must be positive`);
}
});
test('F5.4: All catalog item IDs are unique and follow naming conventions', () => {
const ids = new Set();
for (const item of STORE_CATALOG) {
assert.strictEqual(ids.has(item.id), false, `Duplicate ID: ${item.id}`);
ids.add(item.id);
}
});
test('F5.5: Every item contains required lore, icon, and effect metadata', () => {
for (const item of STORE_CATALOG) {
assert.strictEqual(typeof item.lore, 'string');
assert.strictEqual(item.lore.length > 10, true);
assert.strictEqual(typeof item.icon, 'string');
assert.strictEqual(typeof item.effect_type, 'string');
assert.strictEqual(typeof item.effect_payload, 'object');
}
});
// --- F6: Player Inventory Data Model ---
test('F6.1: Purchasing multiple units of the same item increments quantity stack', () => {
mockStorage.clear();
awardGold('usr-f6-1', 300);
executePurchase('usr-f6-1', 'consumable_hint_scroll', 1); // 75g
executePurchase('usr-f6-1', 'consumable_hint_scroll', 1); // 75g
const inv = loadPlayerInventory('usr-f6-1');
assert.strictEqual(inv.length, 1);
assert.strictEqual(inv[0].quantity, 2);
});
test('F6.2: Consuming an item decrements its quantity stack', () => {
mockStorage.clear();
awardGold('usr-f6-2', 200);
executePurchase('usr-f6-2', 'consumable_hint_scroll', 2);
const consumeRes = consumeInventoryItem('usr-f6-2', 'consumable_hint_scroll');
assert.strictEqual(consumeRes.success, true);
assert.strictEqual(consumeRes.remaining_quantity, 1);
const inv = loadPlayerInventory('usr-f6-2');
assert.strictEqual(inv[0].quantity, 1);
});
test('F6.3: Consuming the last item in stack removes it from inventory array', () => {
mockStorage.clear();
awardGold('usr-f6-3', 100);
executePurchase('usr-f6-3', 'consumable_hint_scroll', 1);
const consumeRes = consumeInventoryItem('usr-f6-3', 'consumable_hint_scroll');
assert.strictEqual(consumeRes.remaining_quantity, 0);
const inv = loadPlayerInventory('usr-f6-3');
assert.strictEqual(inv.length, 0);
});
test('F6.4: Items initialize with is_equipped = false by default', () => {
mockStorage.clear();
awardGold('usr-f6-4', 200);
executePurchase('usr-f6-4', 'cosmetic_crt_scanlines', 1);
const inv = loadPlayerInventory('usr-f6-4');
assert.strictEqual(inv[0].is_equipped, false);
});
test('F6.5: Inventory persists accurately to localStorage and reloads intact', () => {
mockStorage.clear();
awardGold('usr-f6-5', 500);
executePurchase('usr-f6-5', 'consumable_streak_freeze', 1);
executePurchase('usr-f6-5', 'gift_starflower_tea', 1);
// Reload simulation
const loaded = loadPlayerInventory('usr-f6-5');
assert.strictEqual(loaded.length, 2);
assert.strictEqual(loaded.find(i => i.item_id === 'consumable_streak_freeze')?.quantity, 1);
assert.strictEqual(loaded.find(i => i.item_id === 'gift_starflower_tea')?.quantity, 1);
});
// --- F7: Desktop Window OS Integration ---
test('F7.1: Window ID "store" is defined in expected window registry set', () => {
const VALID_WINDOW_IDS = [
'queue', 'journey', 'terminal', 'computer', 'sync', 'github',
'python', 'mysql', 'settings', 'createProblem', 'editProblem',
'companion', 'cardManager', 'store'
];
assert.strictEqual(VALID_WINDOW_IDS.includes('store'), true);
});
test('F7.2: Initial store window state specifies correct title and dimensions', () => {
const STORE_WINDOW_CONFIG = {
id: 'store',
isOpen: false,
isMinimized: false,
isMaximized: false,
position: { x: 120, y: 80 },
size: { width: 850, height: 600 },
title: "Merchant's Emporium"
};
assert.strictEqual(STORE_WINDOW_CONFIG.id, 'store');
assert.strictEqual(STORE_WINDOW_CONFIG.size.width >= 800, true);
assert.strictEqual(STORE_WINDOW_CONFIG.size.height >= 500, true);
});
test('F7.3: Desktop shortcut icon entry includes store with Material / Lucide icon', () => {
const DESKTOP_SHORTCUT = {
id: 'store',
title: "Merchant's Emporium",
icon: 'Store',
windowId: 'store'
};
assert.strictEqual(DESKTOP_SHORTCUT.windowId, 'store');
});
test('F7.4: Desktop Taskbar items include store entry with short title', () => {
const TASKBAR_ENTRY = {
windowId: 'store',
title: "Merchant's Emporium",
shortTitle: 'Store',
icon: 'Store'
};
assert.strictEqual(TASKBAR_ENTRY.shortTitle, 'Store');
});
test('F7.5: Start menu registry includes store launcher button', () => {
const START_MENU_ENTRY = {
id: 'store',
label: "Merchant's Emporium",
description: 'Consumables, cosmetics & companion gifts',
category: 'apps'
};
assert.strictEqual(START_MENU_ENTRY.id, 'store');
});
// --- F8: Storefront Desktop Application UI ---
test('F8.1: Category filtering filters catalog items accurately', () => {
function filterCatalogByCategory(catalog, cat) {
if (cat === 'all') return catalog;
return catalog.filter(i => i.category === cat);
}
assert.strictEqual(filterCatalogByCategory(STORE_CATALOG, 'consumable').length, 4);
assert.strictEqual(filterCatalogByCategory(STORE_CATALOG, 'cosmetic').length, 4);
assert.strictEqual(filterCatalogByCategory(STORE_CATALOG, 'companion_gift').length, 4);
assert.strictEqual(filterCatalogByCategory(STORE_CATALOG, 'all').length, 12);
});
test('F8.2: Purchase affordance returns disabled when player gold is below item price', () => {
function canAfford(playerGold, itemPrice) {
return playerGold >= itemPrice;
}
assert.strictEqual(canAfford(50, 150), false);
assert.strictEqual(canAfford(150, 150), true);
assert.strictEqual(canAfford(200, 150), true);
});
test('F8.3: Item card formatting produces readable gold price format', () => {
function formatGoldPrice(price) {
return `${price} Gold`;
}
assert.strictEqual(formatGoldPrice(150), '150 Gold');
});
test('F8.4: Category tabs have valid default active state of "all" or "consumable"', () => {
const tabs = ['all', 'consumable', 'cosmetic', 'companion_gift'];
assert.strictEqual(tabs.includes('consumable'), true);
});
test('F8.5: Selected item details modal displays lore description and system effect', () => {
const item = STORE_CATALOG[0];
assert.strictEqual(item.name, 'Elixir of Frozen Time');
assert.strictEqual(item.effect_type, 'streak_freeze');
});
// --- F9: Player Inventory Vault UI ---
test('F9.1: Inventory Vault resolves item catalog metadata for each owned item', () => {
mockStorage.clear();
awardGold('usr-f9-1', 200);
executePurchase('usr-f9-1', 'consumable_streak_freeze', 1);
const inventory = loadPlayerInventory('usr-f9-1');
const enriched = inventory.map(inv => {
const catalog = STORE_CATALOG.find(c => c.id === inv.item_id);
return { ...inv, catalog };
});
assert.strictEqual(enriched[0].catalog.name, 'Elixir of Frozen Time');
assert.strictEqual(enriched[0].catalog.category, 'consumable');
});
test('F9.2: Vault determines correct action button type by item category', () => {
function getActionType(category) {
switch (category) {
case 'consumable': return 'Consume';
case 'cosmetic': return 'Equip';
case 'companion_gift': return 'Gift';
default: return 'Inspect';
}
}
assert.strictEqual(getActionType('consumable'), 'Consume');
assert.strictEqual(getActionType('cosmetic'), 'Equip');
assert.strictEqual(getActionType('companion_gift'), 'Gift');
});
test('F9.3: Vault displays stack badge when quantity is greater than 1', () => {
function formatQuantityBadge(quantity) {
return quantity > 1 ? `x${quantity}` : '';
}
assert.strictEqual(formatQuantityBadge(1), '');
assert.strictEqual(formatQuantityBadge(5), 'x5');
});
test('F9.4: Empty inventory vault renders empty state message', () => {
function getEmptyVaultMessage(items) {
return items.length === 0 ? 'Your satchel is empty. Visit the Emporium to acquire items!' : null;
}
assert.strictEqual(getEmptyVaultMessage([]), 'Your satchel is empty. Visit the Emporium to acquire items!');
assert.strictEqual(getEmptyVaultMessage([{ item_id: 'x' }]), null);
});
test('F9.5: Filtering inventory by category filters vault items accurately', () => {
const userItems = [
{ item_id: 'consumable_streak_freeze', quantity: 1 },
{ item_id: 'cosmetic_crt_scanlines', quantity: 1 }
];
const consumablesOnly = userItems.filter(item => {
const cat = STORE_CATALOG.find(c => c.id === item.item_id);
return cat?.category === 'consumable';
});
assert.strictEqual(consumablesOnly.length, 1);
assert.strictEqual(consumablesOnly[0].item_id, 'consumable_streak_freeze');
});
// --- F10: Live Gold Counter Widget ---
test('F10.1: Live gold counter formats integer values cleanly', () => {
function formatWidgetGold(amount) {
return `${amount}g`;
}
assert.strictEqual(formatWidgetGold(0), '0g');
assert.strictEqual(formatWidgetGold(1250), '1250g');
});
test('F10.2: Widget reacts to balance updates after purchase', () => {
mockStorage.clear();
awardGold('usr-f10-2', 200);
executePurchase('usr-f10-2', 'consumable_hint_scroll', 1); // -75g
const current = loadPlayerGold('usr-f10-2');
assert.strictEqual(current.gold, 125);
});
test('F10.3: Widget prevents negative gold values from being rendered', () => {
function sanitizeWidgetGold(gold) {
return Math.max(0, gold || 0);
}
assert.strictEqual(sanitizeWidgetGold(-50), 0);
assert.strictEqual(sanitizeWidgetGold(100), 100);
});
test('F10.4: Widget displays gold tooltip indicating current and lifetime stats', () => {
function getGoldTooltip(currency) {
return `Gold: ${currency.gold} (Lifetime: ${currency.lifetime_earned})`;
}
const tooltip = getGoldTooltip({ gold: 150, lifetime_earned: 450 });
assert.strictEqual(tooltip, 'Gold: 150 (Lifetime: 450)');
});
test('F10.5: Gadget renders coin icon alongside currency value', () => {
const gadgetConfig = { showGold: true, goldIcon: 'Coins' };
assert.strictEqual(gadgetConfig.showGold, true);
assert.strictEqual(gadgetConfig.goldIcon, 'Coins');
});
// --- F11: Princess Aurelia Companion Gifting ---
test('F11.1: Gifting Soothing Starflower Tea adds +15 bond points and smiling_warmly emotion', () => {
mockStorage.clear();
awardGold('usr-f11-1', 100);
executePurchase('usr-f11-1', 'gift_starflower_tea', 1);
const res = presentGiftToAurelia('usr-f11-1', 'gift_starflower_tea', { bondPoints: 0 });
assert.strictEqual(res.bondPointsAdded, 15);
assert.strictEqual(res.newBondPoints, 15);
assert.strictEqual(res.activeEmotion, 'smiling_warmly');
});
test('F11.2: Gifting Embroidered Silver Shawl adds +30 bond points and smiling_warmly emotion', () => {
mockStorage.clear();
awardGold('usr-f11-2', 200);
executePurchase('usr-f11-2', 'gift_silk_shawl', 1);
const res = presentGiftToAurelia('usr-f11-2', 'gift_silk_shawl', { bondPoints: 0 });
assert.strictEqual(res.bondPointsAdded, 30);
assert.strictEqual(res.newBondPoints, 30);
assert.strictEqual(res.activeEmotion, 'smiling_warmly');
});
test('F11.3: Gifting Celestial Music Box adds +60 bond points and excited_expression emotion', () => {
mockStorage.clear();
awardGold('usr-f11-3', 350);
executePurchase('usr-f11-3', 'gift_music_box', 1);
const res = presentGiftToAurelia('usr-f11-3', 'gift_music_box', { bondPoints: 10 });
assert.strictEqual(res.bondPointsAdded, 60);
assert.strictEqual(res.newBondPoints, 70);
assert.strictEqual(res.activeEmotion, 'excited_expression');
});
test('F11.4: Gifting Glimmer of the Sanctuary Pendant elevates bond tier directly to Soulbound Confidante', () => {
mockStorage.clear();
awardGold('usr-f11-4', 600);
executePurchase('usr-f11-4', 'gift_elixir_pendant', 1);
const res = presentGiftToAurelia('usr-f11-4', 'gift_elixir_pendant', { bondPoints: 0 });
assert.strictEqual(res.bondPointsAdded, 100);
assert.strictEqual(res.newBondTier, 'Soulbound Confidante');
assert.strictEqual(res.activeEmotion, 'excited_expression');
});
test('F11.5: Gifting item consumes exactly 1 unit from inventory', () => {
mockStorage.clear();
awardGold('usr-f11-5', 200);
executePurchase('usr-f11-5', 'gift_starflower_tea', 2);
presentGiftToAurelia('usr-f11-5', 'gift_starflower_tea', { bondPoints: 0 });
const inv = loadPlayerInventory('usr-f11-5');
assert.strictEqual(inv[0].quantity, 1);
});
// --- F12: Desktop Cosmetics Activation ---
test('F12.1: Equipping CRT scanlines cosmetic sets is_equipped to true', () => {
mockStorage.clear();
awardGold('usr-f12-1', 250);
executePurchase('usr-f12-1', 'cosmetic_crt_scanlines', 1);
const res = equipCosmeticItem('usr-f12-1', 'cosmetic_crt_scanlines', true);
assert.strictEqual(res.is_equipped, true);
assert.strictEqual(res.payload.overlay_class, 'crt-scanlines-active');
});
test('F12.2: Equipping Amber Campfire theme updates theme payload to amber', () => {
mockStorage.clear();
awardGold('usr-f12-2', 300);
executePurchase('usr-f12-2', 'cosmetic_theme_amber', 1);
const res = equipCosmeticItem('usr-f12-2', 'cosmetic_theme_amber', true);
assert.strictEqual(res.payload.theme_id, 'amber');
});
test('F12.3: Equipping another theme automatically unequips the currently equipped theme', () => {
mockStorage.clear();
awardGold('usr-f12-3', 600);
executePurchase('usr-f12-3', 'cosmetic_theme_amber', 1);
executePurchase('usr-f12-3', 'cosmetic_theme_cyber', 1);
equipCosmeticItem('usr-f12-3', 'cosmetic_theme_amber', true);
equipCosmeticItem('usr-f12-3', 'cosmetic_theme_cyber', true);
const inv = loadPlayerInventory('usr-f12-3');
const amber = inv.find(i => i.item_id === 'cosmetic_theme_amber');
const cyber = inv.find(i => i.item_id === 'cosmetic_theme_cyber');
assert.strictEqual(amber.is_equipped, false);
assert.strictEqual(cyber.is_equipped, true);
});
test('F12.4: Equipping Sanctuary wallpaper outputs correct wallpaper URL', () => {
mockStorage.clear();
awardGold('usr-f12-4', 400);
executePurchase('usr-f12-4', 'cosmetic_wallpaper_sanctuary', 1);
const res = equipCosmeticItem('usr-f12-4', 'cosmetic_wallpaper_sanctuary', true);
assert.strictEqual(res.payload.wallpaper_url, '/wallpapers/sanctuary_spire.webp');
});
test('F12.5: Unequipping cosmetic sets is_equipped back to false', () => {
mockStorage.clear();
awardGold('usr-f12-5', 250);
executePurchase('usr-f12-5', 'cosmetic_crt_scanlines', 1);
equipCosmeticItem('usr-f12-5', 'cosmetic_crt_scanlines', true);
const unequipped = equipCosmeticItem('usr-f12-5', 'cosmetic_crt_scanlines', false);
assert.strictEqual(unequipped.is_equipped, false);
});
// --- F13: Streak Freeze Consumable Effect ---
test('F13.1: Consuming Elixir of Frozen Time outputs streak_freeze effect payload', () => {
mockStorage.clear();
awardGold('usr-f13-1', 200);
executePurchase('usr-f13-1', 'consumable_streak_freeze', 1);
const res = consumeInventoryItem('usr-f13-1', 'consumable_streak_freeze');
assert.strictEqual(res.effect_applied, 'streak_freeze');
assert.strictEqual(res.details.freeze_charges, 1);
});
test('F13.2: Streak protection intercepts missed day (delta == 2) and consumes 1 charge', () => {
const streak = { current_streak: 5, streak_freeze_count: 1 };
const res = evaluateStreakProtection(streak, 2);
assert.strictEqual(res.streak_preserved, true);
assert.strictEqual(res.current_streak, 5);
assert.strictEqual(res.streak_freeze_count, 0);
assert.strictEqual(res.streak_freeze_consumed, true);
});
test('F13.3: Consecutive day practice (delta == 1) preserves streak without consuming freeze', () => {
const streak = { current_streak: 5, streak_freeze_count: 1 };
const res = evaluateStreakProtection(streak, 1);
assert.strictEqual(res.streak_preserved, true);
assert.strictEqual(res.current_streak, 5);
assert.strictEqual(res.streak_freeze_count, 1);
assert.strictEqual(res.streak_freeze_consumed, false);
});
test('F13.4: Missed day without active freeze (delta == 2, count == 0) resets streak to 0', () => {
const streak = { current_streak: 5, streak_freeze_count: 0 };
const res = evaluateStreakProtection(streak, 2);
assert.strictEqual(res.streak_preserved, false);
assert.strictEqual(res.current_streak, 0);
});
test('F13.5: Missing multiple days (delta >= 3) resets streak to 0 even if freeze count > 0', () => {
const streak = { current_streak: 5, streak_freeze_count: 1 };
const res = evaluateStreakProtection(streak, 3);
assert.strictEqual(res.streak_preserved, false);
assert.strictEqual(res.current_streak, 0);
});
// --- F14: Comprehensive Automated Testing & Verification ---
test('F14.1: Test isolation guarantees zero leakage across tests', () => {
mockStorage.clear();
assert.strictEqual(loadPlayerGold('any-user').gold, 0);
assert.strictEqual(loadPlayerInventory('any-user').length, 0);
});
test('F14.2: Expected output values match documented formulas from PROJECT.md', () => {
assert.strictEqual(calculateReviewReward(1), 5);
assert.strictEqual(calculateReviewReward(2), 15);
assert.strictEqual(calculateReviewReward(3), 25);
assert.strictEqual(calculateReviewReward(4), 35);
assert.strictEqual(calculateChallengeReward(true), 100);
});
test('F14.3: Bond tier thresholds match specified ranges', () => {
assert.strictEqual(calculateBondTier(0), 'Acquaintance');
assert.strictEqual(calculateBondTier(39), 'Acquaintance');
assert.strictEqual(calculateBondTier(40), 'Trusted Ally');
assert.strictEqual(calculateBondTier(99), 'Trusted Ally');
assert.strictEqual(calculateBondTier(100), 'Soulbound Confidante');
});
test('F14.4: Error handling throws descriptive standard Error instances', () => {
mockStorage.clear();
assert.throws(() => {
executePurchase('usr-err', 'consumable_streak_freeze', 1);
}, Error);
});
test('F14.5: Deterministic execution operates with zero asynchronous race conditions', () => {
mockStorage.clear();
for (let i = 0; i < 10; i++) {
awardGold('perf-user', 10);
}
assert.strictEqual(loadPlayerGold('perf-user').gold, 100);
});
// ============================================================================
// TIER 2: BOUNDARY & CORNER CASES (>= 5 TEST CASES COVERING SYSTEM EDGES)
// ============================================================================
test('T2.1: Exact balance boundary (balance == price) purchases item leaving exactly 0g', () => {
mockStorage.clear();
awardGold('usr-t2-1', 150); // Exact cost of Elixir
const res = executePurchase('usr-t2-1', 'consumable_streak_freeze', 1);
assert.strictEqual(res.success, true);
assert.strictEqual(res.new_balance, 0);
assert.strictEqual(loadPlayerGold('usr-t2-1').gold, 0);
});
test('T2.2: Off-by-one insufficient funds edge (balance == price - 1) is rejected', () => {
mockStorage.clear();
awardGold('usr-t2-2', 149); // 1g short
assert.throws(() => {
executePurchase('usr-t2-2', 'consumable_streak_freeze', 1);
}, /Insufficient gold balance/);
assert.strictEqual(loadPlayerGold('usr-t2-2').gold, 149);
});
test('T2.3: Zero balance user attempting purchase of cheapest item (50g) is rejected', () => {
mockStorage.clear();
assert.strictEqual(loadPlayerGold('usr-t2-3').gold, 0);
assert.throws(() => {
executePurchase('usr-t2-3', 'consumable_campfire_stew', 1);
}, /Insufficient gold balance/);
});
test('T2.4: Negative or zero purchase quantity input is rejected', () => {
mockStorage.clear();
awardGold('usr-t2-4', 500);
assert.throws(() => {
executePurchase('usr-t2-4', 'consumable_hint_scroll', 0);
}, /positive integer/);
assert.throws(() => {
executePurchase('usr-t2-4', 'consumable_hint_scroll', -2);
}, /positive integer/);
assert.throws(() => {
executePurchase('usr-t2-4', 'consumable_hint_scroll', 1.5);
}, /positive integer/);
});
test('T2.5: Extreme balance boundary handles large numbers without numeric corruption', () => {
mockStorage.clear();
awardGold('usr-t2-5', 1000000);
const res = executePurchase('usr-t2-5', 'consumable_hint_scroll', 10);
assert.strictEqual(res.new_balance, 1000000 - 750);
assert.strictEqual(res.inventory_item.quantity, 10);
});
test('T2.6: Streak freeze delta boundary handles same-day delta == 0 correctly', () => {
const streak = { current_streak: 10, streak_freeze_count: 2 };
const res = evaluateStreakProtection(streak, 0);
assert.strictEqual(res.streak_preserved, true);
assert.strictEqual(res.streak_freeze_count, 2);
assert.strictEqual(res.streak_freeze_consumed, false);
});
test('T2.7: Consuming unowned item throws descriptive error', () => {
mockStorage.clear();
assert.throws(() => {
consumeInventoryItem('usr-t2-7', 'consumable_streak_freeze');
}, /not available in inventory/);
});
test('T2.8: Equipping unowned cosmetic throws descriptive error', () => {
mockStorage.clear();
assert.throws(() => {
equipCosmeticItem('usr-t2-8', 'cosmetic_crt_scanlines', true);
}, /not owned in inventory/);
});
test('T2.9: Gifting unowned gift item to Aurelia is rejected without bond point change', () => {
mockStorage.clear();
assert.throws(() => {
presentGiftToAurelia('usr-t2-9', 'gift_silk_shawl', { bondPoints: 10 });
}, /not available in inventory/);
});
test('T2.10: Multiple items purchased with exact balance for both leaves exactly 0g', () => {
mockStorage.clear();
awardGold('usr-t2-10', 125); // 75g (hint) + 50g (stew) = 125g
executePurchase('usr-t2-10', 'consumable_hint_scroll', 1);
executePurchase('usr-t2-10', 'consumable_campfire_stew', 1);
assert.strictEqual(loadPlayerGold('usr-t2-10').gold, 0);
});
// ============================================================================
// TIER 3: CROSS-FEATURE COMBINATIONS (PAIRWISE INTERACTIONS)
// ============================================================================
test('T3.1: Earn -> Buy -> Equip -> Verify Cosmetic OS Effect', () => {
mockStorage.clear();
const userId = 'usr-t3-1';
// 1. Earn gold from reviews (+25g x 4) and challenge (+100g) = 200g
awardGold(userId, calculateReviewReward(3) * 4); // 100g
awardGold(userId, calculateChallengeReward(true)); // 100g
assert.strictEqual(loadPlayerGold(userId).gold, 200);
// 2. Buy CRT scanlines cosmetic (200g)
const purchase = executePurchase(userId, 'cosmetic_crt_scanlines', 1);
assert.strictEqual(purchase.success, true);
assert.strictEqual(loadPlayerGold(userId).gold, 0);
// 3. Equip CRT scanlines from inventory
const equipRes = equipCosmeticItem(userId, 'cosmetic_crt_scanlines', true);
assert.strictEqual(equipRes.is_equipped, true);
assert.strictEqual(equipRes.payload.overlay_class, 'crt-scanlines-active');
// 4. Verify equipped state in inventory
const inv = loadPlayerInventory(userId);
assert.strictEqual(inv[0].is_equipped, true);
});
test('T3.2: Earn -> Buy -> Gift -> Verify Aurelia Bond & Emotional Gratitude', () => {
mockStorage.clear();
const userId = 'usr-t3-2';
// 1. Earn 100g from coding challenge
awardGold(userId, calculateChallengeReward(true));
// 2. Buy Starflower Tea (80g)
executePurchase(userId, 'gift_starflower_tea', 1);
assert.strictEqual(loadPlayerGold(userId).gold, 20);
// 3. Present gift to Princess Aurelia
const companionInitial = { bondPoints: 20, transcript: [] };
const giftRes = presentGiftToAurelia(userId, 'gift_starflower_tea', companionInitial);
// 4. Verify bond increase and emotional reaction
assert.strictEqual(giftRes.bondPointsAdded, 15);
assert.strictEqual(giftRes.newBondPoints, 35);
assert.strictEqual(giftRes.activeEmotion, 'smiling_warmly');
assert.strictEqual(giftRes.appreciationDialogue.includes('starflower warmth'), true);
// 5. Verify inventory depleted
const inv = loadPlayerInventory(userId);
assert.strictEqual(inv.length, 0);
});
test('T3.3: Earn -> Buy Streak Freeze -> Consume -> Miss Day -> Verify Streak Shield Protection', () => {
mockStorage.clear();
const userId = 'usr-t3-3';
// 1. Earn 150g from reviews (5 x 30g average -> 6 x 25g = 150g)
awardGold(userId, 150);
// 2. Buy Elixir of Frozen Time (150g)
executePurchase(userId, 'consumable_streak_freeze', 1);
// 3. Consume item to activate streak shield
const consumeRes = consumeInventoryItem(userId, 'consumable_streak_freeze');
assert.strictEqual(consumeRes.effect_applied, 'streak_freeze');
// 4. Arm active streak state with 1 freeze charge
let streakState = { current_streak: 7, streak_freeze_count: 1 };
// 5. User misses 1 day (delta == 2)
const evalRes = evaluateStreakProtection(streakState, 2);
assert.strictEqual(evalRes.streak_preserved, true);
assert.strictEqual(evalRes.current_streak, 7);
assert.strictEqual(evalRes.streak_freeze_count, 0);
assert.strictEqual(evalRes.streak_freeze_consumed, true);
});
test('T3.4: Multi-Category Purchases in Sequence (Consumable + Cosmetic + Gift)', () => {
mockStorage.clear();
const userId = 'usr-t3-4';
// Earn 500g
awardGold(userId, 500);
// Buy Consumable (75g Hint Scroll)
executePurchase(userId, 'consumable_hint_scroll', 1);
// Buy Cosmetic (200g CRT Shader)
executePurchase(userId, 'cosmetic_crt_scanlines', 1);
// Buy Companion Gift (80g Starflower Tea)
executePurchase(userId, 'gift_starflower_tea', 1);
// Total spent: 75 + 200 + 80 = 355g. Remaining: 145g
assert.strictEqual(loadPlayerGold(userId).gold, 145);
const inv = loadPlayerInventory(userId);
assert.strictEqual(inv.length, 3);
assert.strictEqual(inv.map(i => i.item_id).sort().join(','), 'consumable_hint_scroll,cosmetic_crt_scanlines,gift_starflower_tea');
});
test('T3.5: Dual-Mode Persistence & Guest Reload Simulation', () => {
mockStorage.clear();
// Guest earns gold and buys items
awardGold('guest', 150);
executePurchase('guest', 'consumable_hint_scroll', 1);
// Simulate complete page reload by re-reading localStorage
const reloadedGold = loadPlayerGold('guest');
const reloadedInv = loadPlayerInventory('guest');
assert.strictEqual(reloadedGold.gold, 75);
assert.strictEqual(reloadedInv.length, 1);
assert.strictEqual(reloadedInv[0].item_id, 'consumable_hint_scroll');
});
// ============================================================================
// TIER 4: REAL-WORLD SCENARIOS (LEARNER JOURNEYS)
// ============================================================================
test('T4.1: Scenario 1 — "The Novice Wayfarer\'s First Day"', () => {
mockStorage.clear();
const userId = 'guest-novice';
// 1. Learner starts with 0g, 0 items, 0 streak
assert.strictEqual(loadPlayerGold(userId).gold, 0);
assert.strictEqual(loadPlayerInventory(userId).length, 0);
// 2. Learner completes 1 Easy (+35g), 1 Good (+25g), and 1 Hard (+15g) review = 75g
awardGold(userId, calculateReviewReward(4));
awardGold(userId, calculateReviewReward(3));
awardGold(userId, calculateReviewReward(2));
assert.strictEqual(loadPlayerGold(userId).gold, 75);
// 3. Learner attempts to buy Elixir of Frozen Time (150g) -> Rejected
assert.throws(() => {
executePurchase(userId, 'consumable_streak_freeze', 1);
}, /Insufficient gold balance/);
assert.strictEqual(loadPlayerGold(userId).gold, 75); // Balance intact
// 4. Learner buys affordable Archivist's Hint Scroll (75g) -> Succeeded
const purchase = executePurchase(userId, 'consumable_hint_scroll', 1);
assert.strictEqual(purchase.success, true);
assert.strictEqual(purchase.new_balance, 0);
// 5. Inspect Inventory Vault
const vault = loadPlayerInventory(userId);
assert.strictEqual(vault.length, 1);
assert.strictEqual(vault[0].item_id, 'consumable_hint_scroll');
assert.strictEqual(vault[0].quantity, 1);
});
test('T4.2: Scenario 2 — "The Guardian\'s Devotion"', () => {
mockStorage.clear();
const userId = 'usr-devoted-guardian';
// 1. Learner solves Python Challenge (+100g) and 3 Good reviews (+75g) = 175g
awardGold(userId, calculateChallengeReward(true));
for (let i = 0; i < 3; i++) {
awardGold(userId, calculateReviewReward(3));
}
assert.strictEqual(loadPlayerGold(userId).gold, 175);
// 2. Buys Embroidered Silver Shawl (150g)
executePurchase(userId, 'gift_silk_shawl', 1);
assert.strictEqual(loadPlayerGold(userId).gold, 25);
// 3. Presents Shawl to Princess Aurelia
const companionState = { bondPoints: 15, transcript: [] };
const giftResult = presentGiftToAurelia(userId, 'gift_silk_shawl', companionState);
// 4. Verify Princess appreciation and bond points advance to 45 (Trusted Ally)
assert.strictEqual(giftResult.bondPointsAdded, 30);
assert.strictEqual(giftResult.newBondPoints, 45);
assert.strictEqual(giftResult.newBondTier, 'Trusted Ally');
assert.strictEqual(giftResult.activeEmotion, 'smiling_warmly');
assert.strictEqual(giftResult.appreciationDialogue.includes('shielded and safe'), true);
// 5. Shawl is completely consumed from inventory
assert.strictEqual(loadPlayerInventory(userId).length, 0);
});
test('T4.3: Scenario 3 — "The Spire Architect\'s Complete Journey"', () => {
mockStorage.clear();
const userId = 'usr-spire-architect';
// 1. Intensive study session: 5 Good reviews (+125g) + Python challenge (+100g) = 225g
for (let i = 0; i < 5; i++) {
awardGold(userId, calculateReviewReward(3));
}
awardGold(userId, calculateChallengeReward(true));
assert.strictEqual(loadPlayerGold(userId).gold, 225);
// 2. Buy Elixir of Frozen Time (150g) -> Balance 75g
executePurchase(userId, 'consumable_streak_freeze', 1);
assert.strictEqual(loadPlayerGold(userId).gold, 75);
// 3. Consume Elixir to arm streak protection
consumeInventoryItem(userId, 'consumable_streak_freeze');
assert.strictEqual(loadPlayerInventory(userId).length, 0);
// 4. Attempt to buy Amber Campfire Theme (250g) with 75g -> Rejected
assert.throws(() => {
executePurchase(userId, 'cosmetic_theme_amber', 1);
}, /Insufficient gold balance/);
// 5. Complete 5 Easy reviews (5 x 35 = 175g) -> 75 + 175 = 250g
for (let i = 0; i < 5; i++) {
awardGold(userId, calculateReviewReward(4));
}
assert.strictEqual(loadPlayerGold(userId).gold, 250);
// 6. Buy Amber Campfire Theme (250g) -> Succeeded!
executePurchase(userId, 'cosmetic_theme_amber', 1);
assert.strictEqual(loadPlayerGold(userId).gold, 0);
// 7. Equip theme
const equipRes = equipCosmeticItem(userId, 'cosmetic_theme_amber', true);
assert.strictEqual(equipRes.is_equipped, true);
assert.strictEqual(equipRes.payload.theme_id, 'amber');
});
import test from 'node:test';
import assert from 'node:assert/strict';
// ============================================================================
// Mock Browser Environment for Node.js Native Test Runner
// ============================================================================
class LocalStorageMock {
constructor() {
this.store = {};
}
getItem(key) {
return this.store[key] !== undefined ? this.store[key] : null;
}
setItem(key, val) {
this.store[key] = String(val);
}
removeItem(key) {
delete this.store[key];
}
clear() {
this.store = {};
}
}
const mockStorage = new LocalStorageMock();
globalThis.localStorage = mockStorage;
globalThis.window = {
addEventListener: () => {},
removeEventListener: () => {},
location: { reload: () => {} },
dispatchEvent: () => true
};
// ============================================================================
// Authoritative Domain Catalog Specification (from PROJECT.md / Survey Report)
// ============================================================================
export const STORE_CATALOG = [
// 1. Study Consumables
{
id: 'consumable_streak_freeze',
name: 'Elixir of Frozen Time',
category: 'consumable',
price: 150,
lore: 'A crystalline phial filled with the enchanted sands of Chronos, arresting the relentless march of time when darkness falls.',
icon: 'ShieldAlert',
effect_type: 'streak_freeze',
effect_payload: { freeze_charges: 1 }
},
{
id: 'consumable_hint_scroll',
name: "Archivist's Hint Scroll",
category: 'consumable',
price: 75,
lore: 'An illuminated vellum scroll penned by royal archivists, unravelling algorithmic intuition and pattern landmarks.',
icon: 'Scroll',
effect_type: 'hint_scroll',
effect_payload: { hint_tokens: 1 }
},
{
id: 'consumable_focus_draught',
name: 'Potion of Keen Insight',
category: 'consumable',
price: 100,
lore: 'A sparkling azure potion that heightens mental acuity and doubles gold earned on your next 3 completed review cards.',
icon: 'Sparkles',
effect_type: 'focus_boost',
effect_payload: { multiplier: 2, reviews_remaining: 3 }
},
{
id: 'consumable_campfire_stew',
name: "Hearty Wayfarer's Stew",
category: 'consumable',
price: 50,
lore: 'A steaming bowl of herbal root stew prepared over the campfire coals, dispelling mental fatigue and restoring composure.',
icon: 'Flame',
effect_type: 'focus_boost',
effect_payload: { fatigue_reset: true }
},
// 2. Desktop Cosmetics
{
id: 'cosmetic_crt_scanlines',
name: 'Arcade CRT Phosphor Shader',
category: 'cosmetic',
price: 200,
lore: 'A retro cathode-ray raster filter with nostalgic scanlines, curved CRT edge vignette, and vintage phosphor bloom.',
icon: 'Tv',
effect_type: 'crt_theme',
effect_payload: { overlay_class: 'crt-scanlines-active' }
},
{
id: 'cosmetic_theme_amber',
name: 'Amber Campfire Theme',
category: 'cosmetic',
price: 250,
lore: 'A cozy UI palette featuring warm ember golds, toasted parchment backgrounds, and rustic brass window borders.',
icon: 'Flame',
effect_type: 'palette_theme',
effect_payload: { theme_id: 'amber' }
},