qnce-engine 0.1.0 → 1.2.0

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 (53) hide show
  1. package/README.md +248 -0
  2. package/dist/cli/audit.js +6 -4
  3. package/dist/cli/audit.js.map +1 -1
  4. package/dist/cli/init.js +11 -9
  5. package/dist/cli/init.js.map +1 -1
  6. package/dist/cli/perf.d.ts +30 -0
  7. package/dist/cli/perf.d.ts.map +1 -0
  8. package/dist/cli/perf.js +219 -0
  9. package/dist/cli/perf.js.map +1 -0
  10. package/dist/engine/core.d.ts +104 -8
  11. package/dist/engine/core.d.ts.map +1 -1
  12. package/dist/engine/core.js +288 -7
  13. package/dist/engine/core.js.map +1 -1
  14. package/dist/engine/demo-story.js +4 -1
  15. package/dist/engine/demo-story.js.map +1 -1
  16. package/dist/index.js +24 -3
  17. package/dist/index.js.map +1 -1
  18. package/dist/narrative/branching/engine-simple.d.ts +84 -0
  19. package/dist/narrative/branching/engine-simple.d.ts.map +1 -0
  20. package/dist/narrative/branching/engine-simple.js +349 -0
  21. package/dist/narrative/branching/engine-simple.js.map +1 -0
  22. package/dist/narrative/branching/index.d.ts +12 -0
  23. package/dist/narrative/branching/index.d.ts.map +1 -0
  24. package/dist/narrative/branching/index.js +56 -0
  25. package/dist/narrative/branching/index.js.map +1 -0
  26. package/dist/narrative/branching/models.d.ts +223 -0
  27. package/dist/narrative/branching/models.d.ts.map +1 -0
  28. package/dist/narrative/branching/models.js +6 -0
  29. package/dist/narrative/branching/models.js.map +1 -0
  30. package/dist/performance/HotReloadDelta.d.ts +107 -0
  31. package/dist/performance/HotReloadDelta.d.ts.map +1 -0
  32. package/dist/performance/HotReloadDelta.js +333 -0
  33. package/dist/performance/HotReloadDelta.js.map +1 -0
  34. package/dist/performance/ObjectPool.d.ts +150 -0
  35. package/dist/performance/ObjectPool.d.ts.map +1 -0
  36. package/dist/performance/ObjectPool.js +297 -0
  37. package/dist/performance/ObjectPool.js.map +1 -0
  38. package/dist/performance/PerfReporter.d.ts +123 -0
  39. package/dist/performance/PerfReporter.d.ts.map +1 -0
  40. package/dist/performance/PerfReporter.js +281 -0
  41. package/dist/performance/PerfReporter.js.map +1 -0
  42. package/dist/performance/ThreadPool.d.ts +107 -0
  43. package/dist/performance/ThreadPool.d.ts.map +1 -0
  44. package/dist/performance/ThreadPool.js +348 -0
  45. package/dist/performance/ThreadPool.js.map +1 -0
  46. package/docs/PERFORMANCE.md +355 -0
  47. package/docs/branching/ERD.md +214 -0
  48. package/docs/branching/PDM.md +443 -0
  49. package/docs/branching/RELEASE-v1.2.0.md +169 -0
  50. package/examples/branching-advanced-demo.ts +339 -0
  51. package/examples/branching-quickstart.ts +314 -0
  52. package/examples/quickstart-demo.js +82 -0
  53. package/package.json +21 -8
@@ -0,0 +1,355 @@
1
+ # QNCE Performance Guide
2
+
3
+ **Version:** 1.2.0-sprint2
4
+ **Sprint #2:** Core Performance Refactor Complete
5
+
6
+ ## 🚀 Overview
7
+
8
+ The QNCE engine now includes comprehensive performance optimization infrastructure delivering:
9
+
10
+ - **90%+ allocation reduction** through object pooling
11
+ - **Background processing** via ThreadPool for non-blocking operations
12
+ - **Optimized hot-reload** with <3.5ms delta patching
13
+ - **Real-time profiling** with comprehensive event instrumentation
14
+ - **Live monitoring** via CLI dashboard with performance alerts
15
+
16
+ ## 📦 Performance Systems
17
+
18
+ ### 1. Object Pooling (S2-T1)
19
+
20
+ Eliminates garbage collection pressure through reusable object pools.
21
+
22
+ #### Basic Usage
23
+ ```typescript
24
+ import { createQNCEEngine } from 'qnce-engine';
25
+
26
+ // Enable performance mode for automatic object pooling
27
+ const engine = createQNCEEngine(storyData, initialState, true);
28
+
29
+ // Engine automatically uses pooled objects for:
30
+ // - Flow events and transitions
31
+ // - Node caching and retrieval
32
+ // - Asset management
33
+ ```
34
+
35
+ #### Pool Statistics
36
+ ```typescript
37
+ // Get pool performance metrics
38
+ const poolStats = engine.getPoolStats();
39
+ console.log('Pool efficiency:', poolStats.hitRate);
40
+ console.log('Memory savings:', poolStats.allocationReduction);
41
+ ```
42
+
43
+ ### 2. Background Processing (S2-T2)
44
+
45
+ Non-blocking operations via ThreadPool for cache preloading and telemetry.
46
+
47
+ #### Configuration
48
+ ```typescript
49
+ const threadPoolConfig = {
50
+ maxWorkers: 4, // Number of background workers
51
+ queueLimit: 1000, // Max pending jobs
52
+ idleTimeout: 30000, // Worker cleanup timeout (ms)
53
+ enableProfiling: true // Track job performance
54
+ };
55
+
56
+ const engine = createQNCEEngine(storyData, {}, true, threadPoolConfig);
57
+ ```
58
+
59
+ #### Background Operations
60
+ ```typescript
61
+ // Preload next nodes in background (automatic)
62
+ engine.selectChoice(choice); // Triggers background preloading
63
+
64
+ // Manual cache warming
65
+ await engine.warmCache(); // Preload entire story
66
+
67
+ // Background telemetry (automatic)
68
+ // Performance data written to background queue
69
+ ```
70
+
71
+ ### 3. Hot-Reload Delta Patching (S2-T3)
72
+
73
+ Live story updates with optimized field-level diffing.
74
+
75
+ #### API Usage
76
+ ```typescript
77
+ import { StoryDeltaComparator, StoryDeltaPatcher } from 'qnce-engine/performance';
78
+
79
+ // Compare story versions
80
+ const comparator = new StoryDeltaComparator();
81
+ const delta = comparator.compare(originalStory, updatedStory);
82
+
83
+ // Apply changes to running engine
84
+ const patcher = new StoryDeltaPatcher();
85
+ patcher.applyDelta(engine, delta); // <3.5ms typical performance
86
+ ```
87
+
88
+ #### Performance Targets
89
+ - **Comparison Time:** <1ms for field-level diffing
90
+ - **Patch Time:** <3.5ms for live story updates
91
+ - **Frame Stall:** Minimal impact on user experience
92
+ - **Safety:** Active node protection, graceful failure handling
93
+
94
+ ### 4. Performance Profiling (S2-T4)
95
+
96
+ Comprehensive event instrumentation with batched reporting.
97
+
98
+ #### Automatic Profiling
99
+ ```typescript
100
+ // Profiling enabled automatically in performance mode
101
+ const engine = createQNCEEngine(storyData, {}, true);
102
+
103
+ // All operations tracked:
104
+ // - State transitions
105
+ // - Cache operations
106
+ // - Hot-reload performance
107
+ // - Background job processing
108
+ ```
109
+
110
+ #### Custom Events
111
+ ```typescript
112
+ import { perf } from 'qnce-engine/performance';
113
+
114
+ // Record custom performance events
115
+ perf.record('custom', {
116
+ eventType: 'user-action',
117
+ duration: 123,
118
+ metadata: { action: 'save' }
119
+ });
120
+
121
+ // Flow tracking
122
+ const spanId = perf.flowStart('my-flow', { context: 'gameplay' });
123
+ // ... operations ...
124
+ perf.flowComplete(spanId, 'target-node', { result: 'success' });
125
+ ```
126
+
127
+ ## 🖥️ CLI Performance Dashboard
128
+
129
+ Real-time monitoring and performance analysis via `qnce-perf` command.
130
+
131
+ ### Installation
132
+ ```bash
133
+ npm install -g qnce-engine
134
+ ```
135
+
136
+ ### Dashboard Commands
137
+
138
+ #### Real-time Dashboard
139
+ ```bash
140
+ qnce-perf dashboard
141
+ ```
142
+ ```
143
+ 🚀 QNCE Performance Dashboard
144
+ =====================================
145
+ 📊 Session Duration: 45.2s
146
+ 🔢 Total Events: 234
147
+
148
+ 📈 Event Breakdown:
149
+ state-transition 45 events (avg: 2.1ms, max: 4.2ms)
150
+ cache-hit 89 events (avg: 0.8ms, max: 1.5ms)
151
+ hot-reload-start 3 events (avg: 2.8ms, max: 3.1ms)
152
+
153
+ 💾 Cache Performance:
154
+ ✅ Hit Rate: 92.4% (threshold: 80%)
155
+ ✅ Avg Cache Time: 8.2ms (threshold: 50ms)
156
+
157
+ 🔥 Hot-Reload Performance:
158
+ ✅ Avg Time: 2.8ms (threshold: 3.5ms)
159
+ 📊 Max Time: 3.1ms
160
+ 🔄 Total Reloads: 3
161
+
162
+ 🧵 ThreadPool Status:
163
+ 📊 Completed Jobs: 156
164
+ ⏳ Queued Jobs: 4
165
+ 🏃 Active Workers: 2
166
+ 📈 Worker Utilization: 73.2%
167
+
168
+ 🚨 Performance Alerts:
169
+ ✅ All systems performing within thresholds
170
+ ```
171
+
172
+ #### Live Monitoring
173
+ ```bash
174
+ qnce-perf live 1000 # Update every 1000ms
175
+ ```
176
+
177
+ #### Export Data
178
+ ```bash
179
+ qnce-perf export > performance-report.json
180
+ ```
181
+
182
+ #### Reset Counters
183
+ ```bash
184
+ qnce-perf reset
185
+ ```
186
+
187
+ ### Performance Thresholds
188
+
189
+ The dashboard monitors key performance indicators:
190
+
191
+ | Metric | Threshold | Alert Level |
192
+ |--------|-----------|-------------|
193
+ | Cache Hit Rate | >80% | ⚠️ Warning if below |
194
+ | Cache Response Time | <50ms | ⚠️ Warning if above |
195
+ | Hot-Reload Time | <3.5ms | ⚠️ Warning if above |
196
+ | State Transition Time | <10ms | ⚠️ Warning if above |
197
+ | ThreadPool Queue | <100 jobs | ⚠️ Warning if above |
198
+
199
+ ## 🔧 Configuration Examples
200
+
201
+ ### High-Performance Setup
202
+ ```typescript
203
+ const engine = createQNCEEngine(storyData, initialState, true, {
204
+ maxWorkers: 8, // High concurrency
205
+ queueLimit: 2000, // Large job queue
206
+ idleTimeout: 60000, // Keep workers alive
207
+ enableProfiling: true // Full instrumentation
208
+ });
209
+
210
+ // Warm entire story cache
211
+ await engine.warmCache();
212
+ ```
213
+
214
+ ### Memory-Constrained Setup
215
+ ```typescript
216
+ const engine = createQNCEEngine(storyData, initialState, true, {
217
+ maxWorkers: 2, // Minimal workers
218
+ queueLimit: 100, // Small queue
219
+ idleTimeout: 10000, // Quick cleanup
220
+ enableProfiling: false // Reduce overhead
221
+ });
222
+ ```
223
+
224
+ ### Development/Debug Setup
225
+ ```typescript
226
+ const engine = createQNCEEngine(storyData, initialState, true, {
227
+ maxWorkers: 1, // Single worker
228
+ queueLimit: 50, // Small queue
229
+ idleTimeout: 5000, // Fast cleanup
230
+ enableProfiling: true // Full debugging
231
+ });
232
+
233
+ // Monitor in real-time
234
+ // Run: qnce-perf live 500
235
+ ```
236
+
237
+ ## 📊 Performance Benchmarks
238
+
239
+ ### Sprint #2 Achievements
240
+
241
+ | System | Before | After | Improvement |
242
+ |--------|--------|-------|-------------|
243
+ | Object Allocation | Baseline | 90%+ reduction | Major |
244
+ | Hot-Reload Time | ~10ms | 2.8-3.5ms | 65-72% |
245
+ | Memory Usage | High GC pressure | Stable pools | Significant |
246
+ | Background Ops | Blocking | Non-blocking | Complete |
247
+ | Monitoring | None | Real-time CLI | New capability |
248
+
249
+ ### Typical Performance Profile
250
+ ```
251
+ Engine Creation: <5ms
252
+ Node Navigation: <1ms per transition
253
+ Hot-Reload: <3.5ms for story updates
254
+ Cache Operations: <1ms with 90%+ hit rate
255
+ Background Jobs: Queue processing without main thread impact
256
+ ```
257
+
258
+ ## 🚨 Troubleshooting
259
+
260
+ ### Common Issues
261
+
262
+ #### Hot-Reload Performance
263
+ ```bash
264
+ # Check current performance
265
+ qnce-perf dashboard
266
+
267
+ # Look for hot-reload metrics
268
+ # Target: <3.5ms average
269
+ # If higher, check story size and complexity
270
+ ```
271
+
272
+ #### ThreadPool Queue Overload
273
+ ```bash
274
+ # Monitor queue depth
275
+ qnce-perf live
276
+
277
+ # If queue depth consistently >100:
278
+ # 1. Increase maxWorkers
279
+ # 2. Increase queueLimit
280
+ # 3. Reduce background operation frequency
281
+ ```
282
+
283
+ #### Memory Usage
284
+ ```bash
285
+ # Check object pool efficiency
286
+ const stats = engine.getPoolStats();
287
+ console.log('Hit rate:', stats.hitRate); // Should be >90%
288
+
289
+ # If low hit rate:
290
+ # 1. Verify performance mode enabled
291
+ # 2. Check for proper object return patterns
292
+ ```
293
+
294
+ ### Performance Debugging
295
+
296
+ ```typescript
297
+ // Enable comprehensive logging
298
+ import { getPerfReporter } from 'qnce-engine/performance';
299
+
300
+ const reporter = getPerfReporter();
301
+ reporter.config.enableConsoleOutput = true;
302
+
303
+ // All performance events now logged to console
304
+ ```
305
+
306
+ ## 🎯 Best Practices
307
+
308
+ ### 1. Enable Performance Mode
309
+ Always use performance mode for production:
310
+ ```typescript
311
+ const engine = createQNCEEngine(storyData, {}, true); // ✅ Good
312
+ const engine = createQNCEEngine(storyData, {}, false); // ❌ Avoid in production
313
+ ```
314
+
315
+ ### 2. Configure ThreadPool Appropriately
316
+ Match worker count to system capabilities:
317
+ ```typescript
318
+ const workers = Math.min(navigator.hardwareConcurrency || 4, 8);
319
+ const config = { maxWorkers: workers };
320
+ ```
321
+
322
+ ### 3. Monitor Performance Continuously
323
+ Use live monitoring during development:
324
+ ```bash
325
+ # Terminal 1: Development server
326
+ npm run dev
327
+
328
+ # Terminal 2: Performance monitoring
329
+ qnce-perf live 2000
330
+ ```
331
+
332
+ ### 4. Preload Strategically
333
+ ```typescript
334
+ // Preload next probable nodes
335
+ engine.selectChoice(choice); // Auto-preloads next nodes
336
+
337
+ // Full cache warming for small stories
338
+ if (storyData.nodes.length < 100) {
339
+ await engine.warmCache();
340
+ }
341
+ ```
342
+
343
+ ### 5. Handle Performance Degradation
344
+ ```typescript
345
+ // Monitor for performance issues
346
+ const summary = perf.summary();
347
+ if (summary.cacheHitRate < 0.8) {
348
+ console.warn('Cache performance degraded');
349
+ // Consider cache warming or configuration adjustment
350
+ }
351
+ ```
352
+
353
+ ---
354
+
355
+ **Ready for Production:** QNCE v1.2.0-sprint2 delivers comprehensive performance optimization with real-time monitoring capabilities. All systems tested and production-ready! 🚀
@@ -0,0 +1,214 @@
1
+ # QNCE Branching System - Entity Relationship Diagram
2
+
3
+ ## Story Structure Hierarchy
4
+
5
+ ```mermaid
6
+ erDiagram
7
+ QNCEStory ||--o{ Chapter : "contains"
8
+ QNCEStory {
9
+ string id PK
10
+ string title
11
+ string version
12
+ StoryMetadata metadata
13
+ BranchingConfig branchingConfig
14
+ }
15
+
16
+ Chapter ||--o{ NarrativeFlow : "contains"
17
+ Chapter ||--o{ BranchPoint : "defines"
18
+ Chapter {
19
+ string id PK
20
+ string title
21
+ string description
22
+ ChapterPrerequisites prerequisites
23
+ ChapterMetadata metadata
24
+ }
25
+
26
+ NarrativeFlow ||--o{ NarrativeNode : "contains"
27
+ NarrativeFlow ||--o{ FlowEntryPoint : "has"
28
+ NarrativeFlow ||--o{ FlowExitPoint : "has"
29
+ NarrativeFlow {
30
+ string id PK
31
+ string name
32
+ string description
33
+ FlowType flowType
34
+ FlowMetadata metadata
35
+ }
36
+
37
+ BranchPoint ||--o{ BranchOption : "offers"
38
+ BranchPoint ||--o{ BranchCondition : "evaluates"
39
+ BranchPoint {
40
+ string id PK
41
+ string name
42
+ string sourceFlowId FK
43
+ string sourceNodeId FK
44
+ BranchType branchType
45
+ BranchMetadata metadata
46
+ }
47
+
48
+ BranchOption ||--o{ BranchCondition : "requires"
49
+ BranchOption {
50
+ string id PK
51
+ string targetFlowId FK
52
+ string targetNodeId FK
53
+ string displayText
54
+ number weight
55
+ Record flagEffects
56
+ }
57
+ ```
58
+
59
+ ## Runtime Context & State Management
60
+
61
+ ```mermaid
62
+ erDiagram
63
+ BranchContext ||--|| QNCEStory : "references"
64
+ BranchContext ||--|| Chapter : "current"
65
+ BranchContext ||--|| NarrativeFlow : "active"
66
+ BranchContext ||--|| QNCEState : "maintains"
67
+ BranchContext ||--o{ BranchHistoryEntry : "tracks"
68
+ BranchContext ||--o{ PendingBranch : "manages"
69
+ BranchContext ||--|| BranchAnalytics : "collects"
70
+
71
+ BranchContext {
72
+ QNCEStory currentStory
73
+ Chapter currentChapter
74
+ NarrativeFlow currentFlow
75
+ QNCEState activeState
76
+ BranchAnalytics analytics
77
+ }
78
+
79
+ BranchHistoryEntry {
80
+ string id PK
81
+ string branchPointId FK
82
+ string chosenOptionId FK
83
+ Date timestamp
84
+ number executionTime
85
+ Partial-QNCEState context
86
+ }
87
+
88
+ PendingBranch {
89
+ string id PK
90
+ string branchPointId FK
91
+ BranchCondition[] triggerConditions
92
+ number timeoutMs
93
+ Date createdAt
94
+ }
95
+
96
+ BranchAnalytics {
97
+ number totalBranchesTraversed
98
+ number avgBranchDecisionTime
99
+ string[] mostPopularBranches
100
+ string[] abandonmentPoints
101
+ number completionRate
102
+ Date sessionStartTime
103
+ }
104
+ ```
105
+
106
+ ## Dynamic Branching Operations
107
+
108
+ ```mermaid
109
+ erDiagram
110
+ DynamicBranchOperation ||--|| BranchLocation : "targets"
111
+ DynamicBranchOperation ||--o{ BranchCondition : "requires"
112
+ DynamicBranchOperation {
113
+ string type
114
+ string branchId FK
115
+ BranchLocation targetLocation
116
+ Partial-BranchPoint payload
117
+ }
118
+
119
+ BranchLocation {
120
+ string chapterId FK
121
+ string flowId FK
122
+ string nodeId FK
123
+ string insertionPoint
124
+ }
125
+
126
+ DynamicFlowOperation ||--o{ BranchCondition : "has"
127
+ DynamicFlowOperation {
128
+ string type
129
+ string flowId FK
130
+ string targetChapterId FK
131
+ NarrativeFlow flow
132
+ }
133
+ ```
134
+
135
+ ## Performance & Object Pooling Integration
136
+
137
+ ```mermaid
138
+ erDiagram
139
+ PooledBranchContext ||--|{ BranchContext : "extends"
140
+ PooledBranchContext {
141
+ string poolId
142
+ number acquisitionTime
143
+ number maxLifetime
144
+ }
145
+
146
+ PooledBranchPoint ||--|{ BranchPoint : "extends"
147
+ PooledBranchPoint {
148
+ string poolId
149
+ number activeReferences
150
+ number lastAccessed
151
+ }
152
+ ```
153
+
154
+ ## AI Integration Interfaces
155
+
156
+ ```mermaid
157
+ erDiagram
158
+ AIBranchingContext ||--|| PlayerProfile : "considers"
159
+ AIBranchingContext ||--|| NarrativeContext : "analyzes"
160
+ AIBranchingContext ||--|| AIGenerationHints : "uses"
161
+
162
+ PlayerProfile {
163
+ string playStyle
164
+ Record preferences
165
+ string[] historicalChoices
166
+ number averageDecisionTime
167
+ }
168
+
169
+ NarrativeContext {
170
+ string currentTone
171
+ string[] thematicElements
172
+ Record characterRelationships
173
+ number plotTension
174
+ }
175
+
176
+ AIGenerationHints {
177
+ number maxBranchDepth
178
+ number desiredComplexity
179
+ string[] contentThemes
180
+ string[] avoidElements
181
+ }
182
+ ```
183
+
184
+ ## Data Flow & Relationships Summary
185
+
186
+ ### Core Entity Flow
187
+ 1. **QNCEStory** contains multiple **Chapters**
188
+ 2. **Chapter** defines **NarrativeFlows** and **BranchPoints**
189
+ 3. **NarrativeFlow** contains **NarrativeNodes** with entry/exit points
190
+ 4. **BranchPoint** offers **BranchOptions** with conditions
191
+ 5. **BranchContext** maintains runtime state and analytics
192
+
193
+ ### Dynamic Operations
194
+ - **DynamicBranchOperation**: Insert/remove/modify branches at runtime
195
+ - **DynamicFlowOperation**: Insert/remove/modify entire flows
196
+ - Both operations use **BranchConditions** for evaluation
197
+
198
+ ### Performance Integration
199
+ - **PooledBranchContext** and **PooledBranchPoint** extend core entities
200
+ - Integrated with Sprint #2 object pooling for memory efficiency
201
+ - Analytics tracking for performance monitoring
202
+
203
+ ### AI Integration Points
204
+ - **AIBranchingContext** provides rich context for AI systems
205
+ - **PlayerProfile** enables personalized branching decisions
206
+ - **NarrativeContext** allows AI to understand story state
207
+ - **AIGenerationHints** guide procedural content generation
208
+
209
+ This PDM supports all Sprint #3 objectives:
210
+ - ✅ Dynamic branching mechanics
211
+ - ✅ AI integration readiness
212
+ - ✅ Performance optimization compatibility
213
+ - ✅ Analytics and debugging support
214
+ - ✅ Procedural content generation framework