cyclecad 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/API-BUILD-MANIFEST.txt +339 -0
  2. package/API-SERVER.md +535 -0
  3. package/Architecture-Deck.pptx +0 -0
  4. package/CLAUDE.md +172 -11
  5. package/CLI-BUILD-SUMMARY.md +504 -0
  6. package/CLI-INDEX.md +356 -0
  7. package/CLI-README.md +466 -0
  8. package/COLLABORATION-INTEGRATION-GUIDE.md +325 -0
  9. package/CONNECTED_FABS_GUIDE.md +612 -0
  10. package/CONNECTED_FABS_README.md +310 -0
  11. package/DELIVERABLES.md +343 -0
  12. package/DFM-ANALYZER-INTEGRATION.md +368 -0
  13. package/DFM-QUICK-START.js +253 -0
  14. package/Dockerfile +69 -0
  15. package/IMPLEMENTATION.md +327 -0
  16. package/LICENSE +31 -0
  17. package/MARKETPLACE_QUICK_REFERENCE.txt +294 -0
  18. package/MCP-INDEX.md +264 -0
  19. package/QUICKSTART-API.md +388 -0
  20. package/QUICKSTART-CLI.md +211 -0
  21. package/QUICKSTART-MCP.md +196 -0
  22. package/README-MCP.md +208 -0
  23. package/TEST-TOKEN-ENGINE.md +319 -0
  24. package/TOKEN-ENGINE-SUMMARY.md +266 -0
  25. package/TOKENS-README.md +263 -0
  26. package/TOOLS-REFERENCE.md +254 -0
  27. package/app/index.html +168 -3
  28. package/app/js/TOKEN-INTEGRATION.md +391 -0
  29. package/app/js/agent-api.js +3 -3
  30. package/app/js/ai-copilot.js +1435 -0
  31. package/app/js/cam-pipeline.js +840 -0
  32. package/app/js/collaboration-ui.js +995 -0
  33. package/app/js/collaboration.js +1116 -0
  34. package/app/js/connected-fabs-example.js +404 -0
  35. package/app/js/connected-fabs.js +1449 -0
  36. package/app/js/dfm-analyzer.js +1760 -0
  37. package/app/js/marketplace.js +1994 -0
  38. package/app/js/material-library.js +2115 -0
  39. package/app/js/token-dashboard.js +563 -0
  40. package/app/js/token-engine.js +743 -0
  41. package/app/test-agent.html +1801 -0
  42. package/bin/cyclecad-cli.js +662 -0
  43. package/bin/cyclecad-mcp +2 -0
  44. package/bin/server.js +242 -0
  45. package/cycleCAD-Architecture.pptx +0 -0
  46. package/cycleCAD-Investor-Deck.pptx +0 -0
  47. package/demo-mcp.sh +60 -0
  48. package/docs/API-SERVER-SUMMARY.md +375 -0
  49. package/docs/API-SERVER.md +667 -0
  50. package/docs/CAM-EXAMPLES.md +344 -0
  51. package/docs/CAM-INTEGRATION.md +612 -0
  52. package/docs/CAM-QUICK-REFERENCE.md +199 -0
  53. package/docs/CLI-INTEGRATION.md +510 -0
  54. package/docs/CLI.md +872 -0
  55. package/docs/MARKETPLACE-API-SCHEMA.json +564 -0
  56. package/docs/MARKETPLACE-INTEGRATION.md +467 -0
  57. package/docs/MARKETPLACE-SETUP.html +439 -0
  58. package/docs/MCP-SERVER.md +403 -0
  59. package/examples/api-client-example.js +488 -0
  60. package/examples/api-client-example.py +359 -0
  61. package/examples/batch-manufacturing.txt +28 -0
  62. package/examples/batch-simple.txt +26 -0
  63. package/model-marketplace.html +1273 -0
  64. package/package.json +14 -3
  65. package/server/api-server.js +1120 -0
  66. package/server/mcp-server.js +1161 -0
  67. package/test-api-server.js +432 -0
  68. package/test-mcp.js +198 -0
  69. package/~$cycleCAD-Investor-Deck.pptx +0 -0
@@ -0,0 +1,319 @@
1
+ # Token Engine Testing Guide
2
+
3
+ ## Quick Start (5 minutes)
4
+
5
+ 1. Open cycleCAD in browser: `https://cyclecad.com/app/` (or local dev server)
6
+ 2. Look for **"💰 Tokens"** button in toolbar (right side, green+blue gradient)
7
+ 3. Click it → Properties panel opens "Tokens" tab
8
+ 4. You should see:
9
+ - Balance: **1,000 tokens** (FREE tier allowance)
10
+ - Tier badge: **FREE**
11
+ - Monthly usage: **0 / 1,000**
12
+ - Recent activity: empty
13
+ - "Estimate Price" and "Buy Tokens" buttons
14
+
15
+ ## Test Scenarios
16
+
17
+ ### Scenario 1: Check Balance
18
+ ```javascript
19
+ // In browser console:
20
+ window.cycleCAD.tokens.getBalance()
21
+ // Expected: 1000
22
+ ```
23
+
24
+ ### Scenario 2: Spend Tokens
25
+ ```javascript
26
+ // Simulate exporting a STEP file
27
+ window.cycleCAD.tokens.spendTokens(10, 'model.export.step', { fileSize: 2.5 });
28
+
29
+ // Check new balance
30
+ window.cycleCAD.tokens.getBalance()
31
+ // Expected: 990
32
+
33
+ // In dashboard, "Recent Activity" should now show:
34
+ // model.export.step -10 tokens Balance: 990
35
+ ```
36
+
37
+ ### Scenario 3: View Transaction History
38
+ ```javascript
39
+ window.cycleCAD.tokens.getTransactionHistory({ limit: 5 });
40
+ // Expected: Array with 1 debit entry (10 tokens spent)
41
+ ```
42
+
43
+ ### Scenario 4: Estimate Operation Cost
44
+ 1. Click **"Estimate Price"** button in dashboard
45
+ 2. Select "Export as STEP" from dropdown
46
+ 3. Change "Batch Size" to 10
47
+ 4. See: "Base: 10 tokens, Discount: 25%, Final: 7 tokens (€0.07)"
48
+ 5. Click "Close"
49
+
50
+ ### Scenario 5: Test Batch Discount
51
+ ```javascript
52
+ // Batch of 1 operation: full price
53
+ const est1 = window.cycleCAD.tokens.estimateOperation('model.export.stl', { batchSize: 1 });
54
+ console.log(est1.finalPrice); // 2 tokens
55
+
56
+ // Batch of 10: 25% discount
57
+ const est10 = window.cycleCAD.tokens.estimateOperation('model.export.stl', { batchSize: 10 });
58
+ console.log(est10.finalPrice); // Math.ceil(2 * 0.75) = 2 tokens (no discount for this cheap op)
59
+
60
+ // Batch of 100: 50% discount
61
+ const est100 = window.cycleCAD.tokens.estimateOperation('model.export.step', { batchSize: 100 });
62
+ console.log(est100.finalPrice); // Math.ceil(10 * 0.5) = 5 tokens
63
+ ```
64
+
65
+ ### Scenario 6: Test Cache Discount
66
+ ```javascript
67
+ // First export: full price
68
+ const price1 = window.cycleCAD.tokens.getPriceForOperation('model.export.step', {});
69
+ console.log(price1); // 10 tokens
70
+
71
+ // Immediate repeat: 10% of price (cache hit)
72
+ const price2 = window.cycleCAD.tokens.getPriceForOperation('model.export.step', {});
73
+ console.log(price2); // Math.ceil(10 * 0.1) = 1 token
74
+
75
+ // Wait 24h+ or manually clear cache...
76
+ // (Testing: clear the cache in localStorage and repeat for full price)
77
+ ```
78
+
79
+ ### Scenario 7: Purchase Tokens
80
+ 1. Click **"Buy Tokens"** button
81
+ 2. See dialog with presets: 1K (€10), 5K (€50), 10K (€90)
82
+ 3. Change custom amount to 2000
83
+ 4. Click "Proceed to Checkout"
84
+ 5. See alert: "Purchase initiated! Tokens: 2000, URL: [Stripe URL]" (demo mode)
85
+ 6. Click OK
86
+
87
+ ### Scenario 8: Upgrade Tier
88
+ 1. Click **"Upgrade to PRO"** button in dashboard
89
+ 2. See 3-column comparison (FREE, PRO*, ENTERPRISE)
90
+ 3. PRO shows: €49/mo, 10,000 tokens, 80% royalty
91
+ 4. Click "Upgrade" on PRO column
92
+ 5. See alert: "Upgraded to PRO tier! Refreshing dashboard..."
93
+ 6. Dashboard updates: balance now shows 10,000 tokens, tier badge is now "PRO"
94
+
95
+ ### Scenario 9: View Tier Info
96
+ ```javascript
97
+ window.cycleCAD.tokens.getTier();
98
+ // Expected (after upgrade): { tier: 'PRO', tokensPerMonth: 10000, creatorRoyalty: 0.8, ... }
99
+ ```
100
+
101
+ ### Scenario 10: Transaction History Export
102
+ 1. Click **"View full history"** link at bottom of dashboard
103
+ 2. Modal opens with table: Date | Operation | Type | Amount | Balance
104
+ 3. Shows all transactions (debit/credit) in reverse chronological order
105
+ 4. Click **"Export CSV"** button
106
+ 5. Downloads: `cyclecad-tokens-2026-03-26.csv`
107
+ 6. Open in Excel/Sheets to verify columns and data
108
+
109
+ ### Scenario 11: Create Escrow (Manufacturing)
110
+ ```javascript
111
+ // Create escrow for a CNC job
112
+ const escrow = window.cycleCAD.tokens.createEscrow(
113
+ 500, // 500 tokens held
114
+ 'job_fab_123', // Job ID
115
+ 'fab_shop_456', // Fab shop ID
116
+ { service: 'CNC milling', est_cost: '$50' }
117
+ );
118
+ console.log(escrow);
119
+ // Expected: { escrowId: 'escrow_1', amount: 500, status: 'held' }
120
+
121
+ // Check balance decreased
122
+ window.cycleCAD.tokens.getBalance();
123
+ // Expected: 990 - 500 = 490 (if on PRO tier after previous test)
124
+
125
+ // Get escrow status
126
+ window.cycleCAD.tokens.getEscrowStatus('escrow_1');
127
+
128
+ // Release escrow when job delivered
129
+ window.cycleCAD.tokens.releaseEscrow('escrow_1');
130
+ // (In real system, this credits the fab shop's account)
131
+
132
+ // Check transaction history shows escrow_hold and escrow_release
133
+ window.cycleCAD.tokens.getTransactionHistory({ limit: 10 });
134
+ ```
135
+
136
+ ### Scenario 12: Cancel Escrow
137
+ ```javascript
138
+ const escrow = window.cycleCAD.tokens.createEscrow(100, 'job2', 'fab2', {});
139
+ const balanceBefore = window.cycleCAD.tokens.getBalance();
140
+
141
+ window.cycleCAD.tokens.cancelEscrow(escrow.escrowId);
142
+
143
+ const balanceAfter = window.cycleCAD.tokens.getBalance();
144
+ // Expected: balanceAfter = balanceBefore (tokens refunded)
145
+ ```
146
+
147
+ ### Scenario 13: Test Monthly Allowance Reset
148
+ ```javascript
149
+ // Current tier
150
+ console.log(window.cycleCAD.tokens.getTier());
151
+
152
+ // Spend some tokens
153
+ window.cycleCAD.tokens.spendTokens(5, 'test');
154
+
155
+ // Check monthly usage
156
+ console.log(window.cycleCAD.tokens.getMonthlyUsage()); // 5
157
+
158
+ // (Normally this resets on month boundary automatically)
159
+ // To simulate: manually set month_start to last month in localStorage
160
+ // localStorage.setItem('cyclecad_month_start', new Date('2026-02-01').toISOString());
161
+
162
+ // Then call getBalance() which triggers refresh:
163
+ window.cycleCAD.tokens.getBalance();
164
+ // Console should show: "[Token Engine] Month reset: balance restored to [tier tokens]"
165
+ ```
166
+
167
+ ### Scenario 14: Cost Breakdown
168
+ ```javascript
169
+ // Do several operations (spend tokens on different ones)
170
+ window.cycleCAD.tokens.spendTokens(2, 'model.export.stl');
171
+ window.cycleCAD.tokens.spendTokens(10, 'model.export.step');
172
+ window.cycleCAD.tokens.spendTokens(15, 'ai.design_review');
173
+
174
+ // View breakdown
175
+ const breakdown = window.cycleCAD.tokens.getCostBreakdown();
176
+ console.table(breakdown);
177
+ // Expected columns: operation, count, totalTokens, averagePerOp, costInEuros
178
+ ```
179
+
180
+ ### Scenario 15: Usage by Operation
181
+ ```javascript
182
+ const usage = window.cycleCAD.tokens.getUsageByOperation();
183
+ console.table(usage);
184
+ // Expected: { 'model.export.stl': { count: 1, totalTokens: 2 }, ... }
185
+ ```
186
+
187
+ ### Scenario 16: Event Subscriptions
188
+ ```javascript
189
+ // Listen to token spent
190
+ window.cycleCAD.tokens.on('token-spent', (data) => {
191
+ console.log(`💸 Spent ${data.amount} tokens on ${data.operation}`);
192
+ });
193
+
194
+ // Listen to tokens added
195
+ window.cycleCAD.tokens.on('token-added', (data) => {
196
+ console.log(`💰 Added ${data.amount} tokens from ${data.source}`);
197
+ });
198
+
199
+ // Now trigger events
200
+ window.cycleCAD.tokens.spendTokens(5, 'test');
201
+ // Console: "💸 Spent 5 tokens on test"
202
+
203
+ window.cycleCAD.tokens.addTokens(100, 'bonus');
204
+ // Console: "💰 Added 100 tokens from bonus"
205
+ ```
206
+
207
+ ### Scenario 17: Export Data
208
+ ```javascript
209
+ const allData = window.cycleCAD.tokens.exportDataAsJSON();
210
+ console.log(JSON.stringify(allData, null, 2));
211
+ // Shows: balance, tier, monthStart, ledger (all transactions), escrow, cache
212
+ ```
213
+
214
+ ### Scenario 18: UI Button Updates
215
+ 1. Do a transaction (spend tokens)
216
+ 2. Watch toolbar button label change:
217
+ - After spending 10 tokens (balance 990): Label should update to "990 Tokens"
218
+ - After adding 1000 tokens: Label should show "1.99K Tokens"
219
+ 3. Click button → should open Tokens tab
220
+ 4. Check tab content updates with new balance
221
+
222
+ ### Scenario 19: Persistent Data
223
+ 1. Perform several transactions
224
+ 2. Refresh the page (F5)
225
+ 3. Check toolbar: balance should be preserved
226
+ 4. Open Tokens tab: balance, tier, activity should all be the same
227
+ 5. Open DevTools → Application → localStorage → verify keys exist:
228
+ - `cyclecad_token_balance`
229
+ - `cyclecad_token_ledger`
230
+ - `cyclecad_user_tier`
231
+
232
+ ### Scenario 20: Multiple Tier Upgrades
233
+ ```javascript
234
+ // Start: FREE
235
+ console.log(window.cycleCAD.tokens.getTier().tier); // FREE
236
+
237
+ // Upgrade to PRO
238
+ window.cycleCAD.tokens.setTier('PRO');
239
+ console.log(window.cycleCAD.tokens.getTier().tier); // PRO
240
+ // Balance reset to 10,000
241
+
242
+ // Upgrade to ENTERPRISE
243
+ window.cycleCAD.tokens.setTier('ENTERPRISE');
244
+ console.log(window.cycleCAD.tokens.getTier().tier); // ENTERPRISE
245
+ // Balance reset to 100,000
246
+
247
+ // Back to FREE
248
+ window.cycleCAD.tokens.setTier('FREE');
249
+ console.log(window.cycleCAD.tokens.getTier().tier); // FREE
250
+ // Balance reset to 1,000
251
+ ```
252
+
253
+ ## Debugging Tips
254
+
255
+ ### Check Internal State
256
+ ```javascript
257
+ // View all localStorage token data
258
+ {
259
+ balance: localStorage.getItem('cyclecad_token_balance'),
260
+ ledger_entries: JSON.parse(localStorage.getItem('cyclecad_token_ledger')).length,
261
+ tier: localStorage.getItem('cyclecad_user_tier'),
262
+ month_start: localStorage.getItem('cyclecad_month_start')
263
+ }
264
+ ```
265
+
266
+ ### Clear All Data (Hard Reset)
267
+ ```javascript
268
+ // WARNING: This deletes all token history
269
+ window.cycleCAD.tokens.clearAllData();
270
+ // Page will refresh, all token data gone, back to FREE with 1,000 tokens
271
+ ```
272
+
273
+ ### Check if Module is Loaded
274
+ ```javascript
275
+ typeof window.cycleCAD?.tokens?.getBalance;
276
+ // Expected: 'function' (if loaded)
277
+
278
+ // If undefined, check console for errors:
279
+ // "[Token Engine] $CYCLE initialized..."
280
+ ```
281
+
282
+ ### Performance Testing
283
+ ```javascript
284
+ // How fast is the API?
285
+ console.time('chargeForOperation');
286
+ window.cycleCAD.tokens.chargeForOperation('model.export.step', {});
287
+ console.timeEnd('chargeForOperation');
288
+ // Expected: < 5ms
289
+ ```
290
+
291
+ ## Troubleshooting
292
+
293
+ | Symptom | Likely Cause | Fix |
294
+ |---------|--------------|-----|
295
+ | Token button missing | Script not loaded | Hard refresh (Ctrl+Shift+R) |
296
+ | Tokens tab empty | initTokenDashboard() not called | Check browser console for errors |
297
+ | Balance not persisting | localStorage disabled | Check incognito/private mode |
298
+ | No events firing | Event listeners not attached | Check console: `window.cycleCAD.tokens.on` |
299
+ | Operations not charging | Agent API not integrated yet | Manual test: call `chargeForOperation()` |
300
+ | Math errors on escrow | Negative balance check | ensure balance ≥ amount before `createEscrow()` |
301
+
302
+ ## Success Criteria
303
+
304
+ All tests pass when:
305
+ - ✅ Token balance displays and updates in real-time
306
+ - ✅ Spending tokens decreases balance
307
+ - ✅ Adding tokens increases balance
308
+ - ✅ Operations show in Recent Activity within 1 second
309
+ - ✅ Discount calculations are correct (cache 10%, batch 25-50%)
310
+ - ✅ Tiers upgrade properly (balance resets to tier allowance)
311
+ - ✅ Escrow creates, releases, and cancels without errors
312
+ - ✅ All data persists across page reloads
313
+ - ✅ CSV export contains all transactions
314
+ - ✅ Event listeners fire on every operation
315
+
316
+ ---
317
+
318
+ **Estimated Testing Time**: 30 minutes for all 20 scenarios
319
+ **Report Issues**: Check browser console (F12) for errors, paste into GitHub issue
@@ -0,0 +1,266 @@
1
+ # $CYCLE Token Engine — Build Complete ✓
2
+
3
+ ## What Was Built
4
+
5
+ A complete per-operation billing system for cycleCAD inspired by the Claude API token model. Users earn tokens through purchases and marketplace sales, spend them on CAD operations, and see real-time balance updates.
6
+
7
+ ## Files Created
8
+
9
+ ### 1. `app/js/token-engine.js` (750 lines)
10
+ The core engine handling:
11
+ - **Balance Management**: Get/add/spend tokens with localStorage persistence
12
+ - **Operation Pricing**: 30+ operations priced from 1-1000 tokens
13
+ - **Double-Entry Ledger**: Every spend debits user, credits creator (70-90%) + platform (10-30%)
14
+ - **Tier System**: FREE (1K/mo), PRO (10K/mo, €49), ENTERPRISE (100K/mo, €299)
15
+ - **Discounts**:
16
+ - Cache: 10% for repeat operations within 24h
17
+ - Batch: 25% for 10+ operations, 50% for 100+
18
+ - **Escrow System**: Hold tokens for manufacturing jobs, release on delivery
19
+ - **Purchase Flow**: Stripe checkout placeholder + crypto payments (Polygon/USDC)
20
+ - **Event System**: Listen to token-spent, token-added, month-reset, tier-changed, escrow events
21
+ - **Transaction History**: Query with filters (type, operation, date, amount)
22
+
23
+ **API:**
24
+ ```javascript
25
+ // Core
26
+ window.cycleCAD.tokens.getBalance() // 1000
27
+ window.cycleCAD.tokens.addTokens(100, 'purchase')
28
+ window.cycleCAD.tokens.spendTokens(10, 'model.export.step')
29
+ window.cycleCAD.tokens.chargeForOperation('export.step', {}, metadata)
30
+
31
+ // Operations
32
+ window.cycleCAD.tokens.getPriceForOperation(op, params)
33
+ window.cycleCAD.tokens.estimateOperation(op, { batchSize: 10 })
34
+
35
+ // History
36
+ window.cycleCAD.tokens.getTransactionHistory({ limit: 50 })
37
+ window.cycleCAD.tokens.getMonthlyUsage()
38
+ window.cycleCAD.tokens.getUsageByOperation()
39
+ window.cycleCAD.tokens.getCostBreakdown()
40
+
41
+ // Escrow
42
+ window.cycleCAD.tokens.createEscrow(100, jobId, fabId)
43
+ window.cycleCAD.tokens.releaseEscrow(escrowId)
44
+ window.cycleCAD.tokens.cancelEscrow(escrowId)
45
+
46
+ // Tier
47
+ window.cycleCAD.tokens.setTier('PRO')
48
+ window.cycleCAD.tokens.getTier()
49
+
50
+ // Purchase
51
+ window.cycleCAD.tokens.purchaseTokens(1000, 'stripe')
52
+ window.cycleCAD.tokens.purchaseWithCrypto(10, 'USDC')
53
+ window.cycleCAD.tokens.completePurchase(sessionId, amount)
54
+
55
+ // Events
56
+ window.cycleCAD.tokens.on('token-spent', listener)
57
+ window.cycleCAD.tokens.off('token-spent', listener)
58
+ ```
59
+
60
+ ### 2. `app/js/token-dashboard.js` (600 lines)
61
+ Rich UI dashboard with:
62
+ - **Balance Card**: Shows current balance, tier badge, monthly usage progress
63
+ - **Quick Actions**: "Estimate Price" and "Buy Tokens" buttons
64
+ - **Tier Info**: Monthly allowance, creator royalty %, upgrade button
65
+ - **Recent Activity**: Last 5 transactions with type/amount/balance
66
+ - **Top Operations**: Most-used operations this month
67
+ - **4 Dialog Systems**:
68
+ 1. **Estimate Price Dialog**: Pick operation + batch size → see final cost with discounts
69
+ 2. **Purchase Dialog**: Preset packages or custom amount → Stripe checkout link
70
+ 3. **Upgrade Dialog**: Compare FREE/PRO/ENTERPRISE with features & pricing
71
+ 4. **History Modal**: Full transaction table + CSV export
72
+ - **Real-time Updates**: Dashboard refreshes on every token event
73
+
74
+ ### 3. `app/index.html` (Modified)
75
+ Integrated token engine into the UI:
76
+ - `<script src="./js/token-engine.js"></script>` in `<head>` — loads early
77
+ - `import { initTokenDashboard }` in main script
78
+ - Added **"💰 Tokens"** tab to right panel (next to Properties/Chat/Guide)
79
+ - Added **token balance indicator** button to toolbar (shows "1K Tokens", updates in real-time)
80
+ - Wired tab switching and event listeners
81
+ - Tab button has gradient background (blue → green) to stand out
82
+
83
+ ### 4. `app/js/TOKEN-INTEGRATION.md` (Comprehensive guide)
84
+ Full documentation including:
85
+ - All API examples with code snippets
86
+ - Operation pricing table (30+ operations)
87
+ - Tier system details
88
+ - Discount mechanics explained
89
+ - Double-entry ledger example
90
+ - localStorage keys reference
91
+ - Architecture diagram
92
+ - Testing commands
93
+ - Next steps for enhancements
94
+
95
+ ## UI Components
96
+
97
+ ### Right Panel (Properties)
98
+ New "💰 Tokens" tab showing:
99
+ ```
100
+ ┌─────────────────────────────────┐
101
+ │ Balance: 1,000 tokens │ ← Blue badge showing current balance
102
+ │ FREE tier │
103
+ ├─────────────────────────────────┤
104
+ │ [Estimate Price] [Buy Tokens] │ ← Quick action buttons
105
+ ├─────────────────────────────────┤
106
+ │ TIER INFO │
107
+ │ 1,000 tokens/month │
108
+ │ 70% creator royalty │
109
+ │ [Upgrade to PRO €49/mo] │
110
+ ├─────────────────────────────────┤
111
+ │ RECENT ACTIVITY │
112
+ │ export.stl -2 tokens │ ← Last 5 transactions
113
+ │ export.stl -2 tokens │
114
+ │ stripe_purchase +1,000 tokens │
115
+ ├─────────────────────────────────┤
116
+ │ TOP OPERATIONS (This Month) │
117
+ │ model.export.stl 10 tokens, 5x │
118
+ ├─────────────────────────────────┤
119
+ │ [View full history] │
120
+ └─────────────────────────────────┘
121
+ ```
122
+
123
+ ### Toolbar Token Button
124
+ Shows live balance:
125
+ - "1K Tokens" (GREEN with gradient background) — clickable to open Tokens tab
126
+ - Updates in real-time as tokens are spent/added
127
+ - Uses short format: "5M" for 5,000,000, "1K" for 1,000
128
+
129
+ ### Dialogs (Triggered by dashboard buttons)
130
+
131
+ **Estimate Price Dialog:**
132
+ ```
133
+ Estimate Operation Cost
134
+ ├─ Operation dropdown (30+ options)
135
+ ├─ Batch Size input
136
+ └─ Summary:
137
+ Base: 10 tokens
138
+ Discount: 25% (batch of 10+)
139
+ Final: 7 tokens (€0.07)
140
+ ```
141
+
142
+ **Purchase Tokens Dialog:**
143
+ ```
144
+ Purchase Tokens
145
+ ├─ Preset packages:
146
+ │ ├─ 1,000 tokens (€10)
147
+ │ ├─ 5,000 tokens (€50) ← Save €0.50
148
+ │ └─ 10,000 tokens (€90) ← Save €10
149
+ ├─ Custom amount input
150
+ └─ [Proceed to Checkout]
151
+ ```
152
+
153
+ **Upgrade Tier Dialog:**
154
+ ```
155
+ Three columns (FREE, PRO*, ENTERPRISE):
156
+ ├─ Price & tokens/month
157
+ ├─ 70%/80%/90% creator royalty
158
+ ├─ Feature list (checkmarks)
159
+ └─ [Current] [Upgrade] [Upgrade]
160
+ ```
161
+
162
+ **History Modal:**
163
+ ```
164
+ Token Transaction History
165
+ ├─ Table: Date | Operation | Type | Amount | Balance
166
+ ├─ Last 100 transactions, newest first
167
+ └─ [Export CSV]
168
+ ```
169
+
170
+ ## Key Features
171
+
172
+ 1. **Zero Upfront Cost** — FREE tier has 1,000 tokens/month, no payment required
173
+ 2. **Pay-as-you-go** — Buy tokens in €1 increments (100 tokens = €1)
174
+ 3. **Creator Economics** — 70-90% of spending goes back to part creators (double-entry ledger)
175
+ 4. **Marketplace Ready** — Escrow system holds tokens until manufacturing delivery
176
+ 5. **Smart Discounts** — Cache hits (10% repeat), batch operations (25-50% off)
177
+ 6. **Monthly Allowance** — Auto-resets on month boundary with tier tokens
178
+ 7. **Real-time Dashboard** — See balance, recent activity, usage trends instantly
179
+ 8. **Persistent Data** — All transactions stored in localStorage (survives page reload)
180
+ 9. **Event System** — Subscribe to token changes for custom integrations
181
+ 10. **Admin-Friendly** — Export transaction history as CSV for accounting
182
+
183
+ ## Operation Pricing (Sample)
184
+
185
+ | Operation | Cost | Tier Benefit |
186
+ |-----------|------|--------------|
187
+ | Export STL | 2 | FREE |
188
+ | Export STEP | 10 | PRO only |
189
+ | AI Design Review | 15 | PRO/ENTERPRISE |
190
+ | CNC Toolpath | 75 | Speed priority |
191
+ | 3D Print Slice | 20 | Queue priority |
192
+
193
+ **Total FREE Allowance:** 1,000 tokens/month = enough for ~100 STL exports or ~66 design reviews
194
+
195
+ ## localStorage Keys
196
+
197
+ - `cyclecad_token_balance` — current balance (integer)
198
+ - `cyclecad_token_ledger` — transaction array (JSON)
199
+ - `cyclecad_token_cache` — cached operations (JSON object with timestamps)
200
+ - `cyclecad_token_escrow` — active escrows (JSON object)
201
+ - `cyclecad_user_tier` — 'FREE' | 'PRO' | 'ENTERPRISE'
202
+ - `cyclecad_month_start` — month start date for auto-reset
203
+
204
+ ## Testing in Console
205
+
206
+ ```javascript
207
+ // View balance
208
+ console.log(window.cycleCAD.tokens.getBalance()); // 1000
209
+
210
+ // Spend tokens (simulated operation)
211
+ window.cycleCAD.tokens.spendTokens(10, 'model.export.step');
212
+
213
+ // View transaction history
214
+ console.log(window.cycleCAD.tokens.getTransactionHistory({ limit: 5 }));
215
+
216
+ // Get usage breakdown
217
+ console.log(window.cycleCAD.tokens.getCostBreakdown());
218
+
219
+ // Upgrade to PRO
220
+ window.cycleCAD.tokens.setTier('PRO');
221
+
222
+ // View current tier
223
+ console.log(window.cycleCAD.tokens.getTier());
224
+
225
+ // Subscribe to events
226
+ window.cycleCAD.tokens.on('token-spent', (data) => {
227
+ console.log('Just spent:', data.amount, 'on', data.operation);
228
+ });
229
+ ```
230
+
231
+ ## Integration Points (Ready for)
232
+
233
+ 1. **Agent API**: Call `chargeForOperation()` before executing operations via JSON-RPC
234
+ 2. **Export Functions**: Wrap STL/STEP/DXF export in token charge flow
235
+ 3. **AI Operations**: Charge for Gemini Vision, design review, suggestions
236
+ 4. **Marketplace**: Debit buyer, credit seller in double-entry ledger
237
+ 5. **Stripe**: Replace `purchaseTokens()` placeholder with real checkout
238
+ 6. **Analytics**: Use transaction history for usage reports
239
+
240
+ ## Files Modified Summary
241
+
242
+ | File | Changes | Lines |
243
+ |------|---------|-------|
244
+ | token-engine.js | NEW | 750 |
245
+ | token-dashboard.js | NEW | 600 |
246
+ | TOKEN-INTEGRATION.md | NEW | 350 |
247
+ | index.html | 4 edits | +60 |
248
+
249
+ **Total LOC:** ~1,700 lines of new code + documentation
250
+
251
+ ## Next Phase
252
+
253
+ When Sachin is ready to integrate with actual operations:
254
+
255
+ 1. Wrap `exportSTL()`, `exportGLTF()`, etc. with `chargeForOperation()` calls
256
+ 2. Add cost estimation prompts before expensive operations (e.g., "This will cost 75 tokens. Continue?")
257
+ 3. Connect Stripe API key for real payments
258
+ 4. Build "Tokens Earnings" dashboard for creators
259
+ 5. Add monthly billing emails
260
+ 6. Create "Cost Report" showing token spend by operation type
261
+
262
+ ---
263
+
264
+ **Status**: ✅ Complete and ready to test
265
+ **Access**: Click "💰 Tokens" button in toolbar or tab in Properties panel
266
+ **No setup required** — token-engine.js initializes automatically with FREE tier (1,000 tokens/month)