qnce-engine 0.1.0 → 1.2.1

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 (154) hide show
  1. package/README.md +959 -5
  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 +220 -0
  9. package/dist/cli/perf.js.map +1 -0
  10. package/dist/cli/play.d.ts +4 -0
  11. package/dist/cli/play.d.ts.map +1 -0
  12. package/dist/cli/play.js +259 -0
  13. package/dist/cli/play.js.map +1 -0
  14. package/dist/engine/condition.d.ts +69 -0
  15. package/dist/engine/condition.d.ts.map +1 -0
  16. package/dist/engine/condition.js +195 -0
  17. package/dist/engine/condition.js.map +1 -0
  18. package/dist/engine/core.d.ts +378 -11
  19. package/dist/engine/core.d.ts.map +1 -1
  20. package/dist/engine/core.js +1433 -13
  21. package/dist/engine/core.js.map +1 -1
  22. package/dist/engine/demo-story.d.ts.map +1 -1
  23. package/dist/engine/demo-story.js +103 -14
  24. package/dist/engine/demo-story.js.map +1 -1
  25. package/dist/engine/errors.d.ts +76 -0
  26. package/dist/engine/errors.d.ts.map +1 -0
  27. package/dist/engine/errors.js +178 -0
  28. package/dist/engine/errors.js.map +1 -0
  29. package/dist/engine/types.d.ts +445 -0
  30. package/dist/engine/types.d.ts.map +1 -0
  31. package/dist/engine/types.js +9 -0
  32. package/dist/engine/types.js.map +1 -0
  33. package/dist/engine/validation.d.ts +110 -0
  34. package/dist/engine/validation.d.ts.map +1 -0
  35. package/dist/engine/validation.js +261 -0
  36. package/dist/engine/validation.js.map +1 -0
  37. package/dist/examples/examples/autosave-undo-demo.js +248 -0
  38. package/dist/examples/examples/persistence-demo.js +63 -0
  39. package/dist/examples/src/engine/condition.js +194 -0
  40. package/dist/examples/src/engine/core.js +1382 -0
  41. package/dist/examples/src/engine/demo-story.js +200 -0
  42. package/dist/examples/src/engine/types.js +8 -0
  43. package/dist/examples/src/index.js +35 -0
  44. package/dist/examples/src/integrations/react.js +322 -0
  45. package/dist/examples/src/narrative/branching/engine-simple.js +348 -0
  46. package/dist/examples/src/narrative/branching/index.js +55 -0
  47. package/dist/examples/src/narrative/branching/models.js +5 -0
  48. package/dist/examples/src/performance/ObjectPool.js +296 -0
  49. package/dist/examples/src/performance/PerfReporter.js +280 -0
  50. package/dist/examples/src/performance/ThreadPool.js +347 -0
  51. package/dist/index.d.ts +4 -0
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +35 -3
  54. package/dist/index.js.map +1 -1
  55. package/dist/integrations/react.d.ts +200 -0
  56. package/dist/integrations/react.d.ts.map +1 -0
  57. package/dist/integrations/react.js +365 -0
  58. package/dist/integrations/react.js.map +1 -0
  59. package/dist/narrative/branching/engine-simple.d.ts +84 -0
  60. package/dist/narrative/branching/engine-simple.d.ts.map +1 -0
  61. package/dist/narrative/branching/engine-simple.js +349 -0
  62. package/dist/narrative/branching/engine-simple.js.map +1 -0
  63. package/dist/narrative/branching/engine.d.ts +1 -0
  64. package/dist/narrative/branching/engine.d.ts.map +1 -0
  65. package/dist/narrative/branching/engine.js +2 -0
  66. package/dist/narrative/branching/engine.js.map +1 -0
  67. package/dist/narrative/branching/index.d.ts +12 -0
  68. package/dist/narrative/branching/index.d.ts.map +1 -0
  69. package/dist/narrative/branching/index.js +56 -0
  70. package/dist/narrative/branching/index.js.map +1 -0
  71. package/dist/narrative/branching/models.d.ts +223 -0
  72. package/dist/narrative/branching/models.d.ts.map +1 -0
  73. package/dist/narrative/branching/models.js +6 -0
  74. package/dist/narrative/branching/models.js.map +1 -0
  75. package/dist/performance/HotReloadDelta.d.ts +124 -0
  76. package/dist/performance/HotReloadDelta.d.ts.map +1 -0
  77. package/dist/performance/HotReloadDelta.js +328 -0
  78. package/dist/performance/HotReloadDelta.js.map +1 -0
  79. package/dist/performance/ObjectPool.d.ts +150 -0
  80. package/dist/performance/ObjectPool.d.ts.map +1 -0
  81. package/dist/performance/ObjectPool.js +297 -0
  82. package/dist/performance/ObjectPool.js.map +1 -0
  83. package/dist/performance/PerfReporter.d.ts +123 -0
  84. package/dist/performance/PerfReporter.d.ts.map +1 -0
  85. package/dist/performance/PerfReporter.js +281 -0
  86. package/dist/performance/PerfReporter.js.map +1 -0
  87. package/dist/performance/ThreadPool.d.ts +107 -0
  88. package/dist/performance/ThreadPool.d.ts.map +1 -0
  89. package/dist/performance/ThreadPool.js +348 -0
  90. package/dist/performance/ThreadPool.js.map +1 -0
  91. package/dist/ui/__tests__/AutosaveIndicator.test.d.ts +2 -0
  92. package/dist/ui/__tests__/AutosaveIndicator.test.d.ts.map +1 -0
  93. package/dist/ui/__tests__/AutosaveIndicator.test.js +329 -0
  94. package/dist/ui/__tests__/AutosaveIndicator.test.js.map +1 -0
  95. package/dist/ui/__tests__/UndoRedoControls.test.d.ts +2 -0
  96. package/dist/ui/__tests__/UndoRedoControls.test.d.ts.map +1 -0
  97. package/dist/ui/__tests__/UndoRedoControls.test.js +245 -0
  98. package/dist/ui/__tests__/UndoRedoControls.test.js.map +1 -0
  99. package/dist/ui/__tests__/autosave-simple.test.d.ts +2 -0
  100. package/dist/ui/__tests__/autosave-simple.test.d.ts.map +1 -0
  101. package/dist/ui/__tests__/autosave-simple.test.js +29 -0
  102. package/dist/ui/__tests__/autosave-simple.test.js.map +1 -0
  103. package/dist/ui/__tests__/setup.d.ts +2 -0
  104. package/dist/ui/__tests__/setup.d.ts.map +1 -0
  105. package/dist/ui/__tests__/setup.js +40 -0
  106. package/dist/ui/__tests__/setup.js.map +1 -0
  107. package/dist/ui/__tests__/smoke-test.d.ts +2 -0
  108. package/dist/ui/__tests__/smoke-test.d.ts.map +1 -0
  109. package/dist/ui/__tests__/smoke-test.js +18 -0
  110. package/dist/ui/__tests__/smoke-test.js.map +1 -0
  111. package/dist/ui/__tests__/smoke-test.test.d.ts +2 -0
  112. package/dist/ui/__tests__/smoke-test.test.d.ts.map +1 -0
  113. package/dist/ui/__tests__/smoke-test.test.js +18 -0
  114. package/dist/ui/__tests__/smoke-test.test.js.map +1 -0
  115. package/dist/ui/__tests__/useKeyboardShortcuts.test.d.ts +2 -0
  116. package/dist/ui/__tests__/useKeyboardShortcuts.test.d.ts.map +1 -0
  117. package/dist/ui/__tests__/useKeyboardShortcuts.test.js +374 -0
  118. package/dist/ui/__tests__/useKeyboardShortcuts.test.js.map +1 -0
  119. package/dist/ui/components/AutosaveIndicator.d.ts +18 -0
  120. package/dist/ui/components/AutosaveIndicator.d.ts.map +1 -0
  121. package/dist/ui/components/AutosaveIndicator.js +175 -0
  122. package/dist/ui/components/AutosaveIndicator.js.map +1 -0
  123. package/dist/ui/components/UndoRedoControls.d.ts +16 -0
  124. package/dist/ui/components/UndoRedoControls.d.ts.map +1 -0
  125. package/dist/ui/components/UndoRedoControls.js +144 -0
  126. package/dist/ui/components/UndoRedoControls.js.map +1 -0
  127. package/dist/ui/hooks/useKeyboardShortcuts.d.ts +22 -0
  128. package/dist/ui/hooks/useKeyboardShortcuts.d.ts.map +1 -0
  129. package/dist/ui/hooks/useKeyboardShortcuts.js +162 -0
  130. package/dist/ui/hooks/useKeyboardShortcuts.js.map +1 -0
  131. package/dist/ui/index.d.ts +9 -0
  132. package/dist/ui/index.d.ts.map +1 -0
  133. package/dist/ui/index.js +14 -0
  134. package/dist/ui/index.js.map +1 -0
  135. package/dist/ui/types.d.ts +141 -0
  136. package/dist/ui/types.d.ts.map +1 -0
  137. package/dist/ui/types.js +51 -0
  138. package/dist/ui/types.js.map +1 -0
  139. package/docs/PERFORMANCE.md +355 -0
  140. package/docs/branching/ERD.md +214 -0
  141. package/docs/branching/PDM.md +443 -0
  142. package/docs/branching/RELEASE-v1.2.0.md +169 -0
  143. package/examples/autosave-undo-demo.ts +306 -0
  144. package/examples/branching-advanced-demo.ts +339 -0
  145. package/examples/branching-demo-simple.ts +0 -0
  146. package/examples/branching-demo.ts +0 -0
  147. package/examples/branching-quickstart.ts +314 -0
  148. package/examples/persistence-demo.ts +84 -0
  149. package/examples/quickstart-demo.js +82 -0
  150. package/examples/tsconfig.json +13 -0
  151. package/examples/ui-components-demo.tsx +320 -0
  152. package/examples/validation-demo-story.json +177 -0
  153. package/examples/validation-demo.js +163 -0
  154. package/package.json +41 -8
@@ -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
@@ -0,0 +1,443 @@
1
+ # QNCE Branching System - Platform Data Model (PDM) Specification
2
+
3
+ **Sprint #3 - Advanced Narrative & AI Integration**
4
+ **Version:** 1.0.0
5
+ **Date:** July 2, 2025
6
+ **Owner:** Body (VS Code Agent)
7
+ **Reviewers:** Brain (Copilot), ByteSower (Bull)
8
+
9
+ ## Table of Contents
10
+
11
+ 1. [Overview](#overview)
12
+ 2. [Design Principles](#design-principles)
13
+ 3. [Entity Definitions](#entity-definitions)
14
+ 4. [Data Relationships](#data-relationships)
15
+ 5. [Performance Considerations](#performance-considerations)
16
+ 6. [AI Integration Points](#ai-integration-points)
17
+ 7. [Usage Examples](#usage-examples)
18
+ 8. [Migration Guide](#migration-guide)
19
+
20
+ ## Overview
21
+
22
+ The QNCE Branching System PDM defines the data structures and relationships needed to support dynamic narrative branching, AI-driven content generation, and real-time story modification. Built on Sprint #2's performance infrastructure, this PDM enables complex, interconnected narratives with enterprise-grade performance.
23
+
24
+ ### Key Capabilities
25
+
26
+ - **Dynamic Branching**: Runtime insertion, removal, and modification of narrative paths
27
+ - **AI Integration**: Rich context for procedural dialogue and content generation
28
+ - **Performance Optimization**: Built on object pooling and profiling infrastructure
29
+ - **Analytics Support**: Comprehensive tracking of player behavior and story flow
30
+ - **Modular Design**: Clean separation of concerns for maintainable code
31
+
32
+ ## Design Principles
33
+
34
+ ### 1. Performance-First Architecture
35
+ - All entities support object pooling from Sprint #2
36
+ - Minimal memory allocations during runtime
37
+ - Efficient data structures for frequent operations
38
+ - Background processing for analytics and caching
39
+
40
+ ### 2. AI Integration Ready
41
+ - Rich context interfaces for AI systems
42
+ - Extensible generation hints and constraints
43
+ - Player profiling for personalized experiences
44
+ - Content quality tracking and feedback loops
45
+
46
+ ### 3. Developer Experience
47
+ - Clear entity hierarchies and relationships
48
+ - Type-safe interfaces with comprehensive documentation
49
+ - Debugging-friendly data structures
50
+ - Migration paths from existing story formats
51
+
52
+ ### 4. Scalability & Modularity
53
+ - Support for large, complex narratives
54
+ - Chapter-based organization for memory efficiency
55
+ - Dynamic loading and unloading of story content
56
+ - Plugin architecture for custom branching logic
57
+
58
+ ## Entity Definitions
59
+
60
+ ### Core Story Structure
61
+
62
+ #### QNCEStory
63
+ Top-level container for all narrative content with branching metadata.
64
+
65
+ ```typescript
66
+ interface QNCEStory {
67
+ id: string; // Unique story identifier
68
+ title: string; // Human-readable story title
69
+ version: string; // Semantic version (e.g., "1.2.3")
70
+ metadata: StoryMetadata; // Author, description, creation info
71
+ chapters: Chapter[]; // Ordered list of story chapters
72
+ branchingConfig: BranchingConfig; // Performance and behavior settings
73
+ }
74
+ ```
75
+
76
+ **Key Features:**
77
+ - Versioning support for iterative development
78
+ - Configurable branching behavior per story
79
+ - Metadata for discovery and organization
80
+
81
+ #### Chapter
82
+ Logical grouping of narrative flows with branching points.
83
+
84
+ ```typescript
85
+ interface Chapter {
86
+ id: string; // Unique chapter identifier
87
+ title: string; // Chapter title for navigation
88
+ description?: string; // Optional chapter summary
89
+ flows: NarrativeFlow[]; // Available narrative flows
90
+ branches: BranchPoint[]; // Dynamic branching logic
91
+ prerequisites?: ChapterPrerequisites; // Access requirements
92
+ metadata: ChapterMetadata; // Difficulty, themes, duration
93
+ }
94
+ ```
95
+
96
+ **Key Features:**
97
+ - Prerequisites for gated content progression
98
+ - Metadata for AI-driven content selection
99
+ - Flexible flow organization
100
+
101
+ #### NarrativeFlow
102
+ Sequence of connected nodes with defined entry/exit points.
103
+
104
+ ```typescript
105
+ interface NarrativeFlow {
106
+ id: string; // Unique flow identifier
107
+ name: string; // Flow name for debugging
108
+ description?: string; // Optional flow summary
109
+ nodes: NarrativeNode[]; // Ordered narrative nodes
110
+ entryPoints: FlowEntryPoint[]; // Ways to enter this flow
111
+ exitPoints: FlowExitPoint[]; // Ways to exit this flow
112
+ flowType: FlowType; // 'linear' | 'branching' | 'conditional' | 'procedural'
113
+ metadata: FlowMetadata; // Complexity, timing, AI flags
114
+ }
115
+ ```
116
+
117
+ **Key Features:**
118
+ - Multiple entry/exit points for complex branching
119
+ - Type classification for AI optimization
120
+ - Performance metadata for analytics
121
+
122
+ ### Branching Logic
123
+
124
+ #### BranchPoint
125
+ Dynamic branching logic between flows with runtime modification support.
126
+
127
+ ```typescript
128
+ interface BranchPoint {
129
+ id: string; // Unique branch identifier
130
+ name: string; // Branch name for debugging
131
+ sourceFlowId: string; // Origin flow
132
+ sourceNodeId: string; // Specific trigger node
133
+ branchOptions: BranchOption[]; // Available branch paths
134
+ branchType: BranchType; // How branching is determined
135
+ conditions?: BranchCondition[]; // Global branch conditions
136
+ metadata: BranchMetadata; // Usage analytics and preferences
137
+ }
138
+ ```
139
+
140
+ **Key Features:**
141
+ - Multiple branching strategies (choice, flag, time, procedural)
142
+ - Runtime condition evaluation
143
+ - Analytics for optimization
144
+
145
+ #### BranchOption
146
+ Individual branching path with conditions and effects.
147
+
148
+ ```typescript
149
+ interface BranchOption {
150
+ id: string; // Unique option identifier
151
+ targetFlowId: string; // Destination flow
152
+ targetNodeId?: string; // Specific entry point (optional)
153
+ displayText: string; // Player-facing text
154
+ conditions?: BranchCondition[]; // Availability conditions
155
+ flagEffects?: Record<string, unknown>; // State changes
156
+ weight: number; // For procedural selection
157
+ }
158
+ ```
159
+
160
+ ### Runtime Context
161
+
162
+ #### BranchContext
163
+ Complete runtime state for branch evaluation and tracking.
164
+
165
+ ```typescript
166
+ interface BranchContext {
167
+ currentStory: QNCEStory; // Active story
168
+ currentChapter: Chapter; // Current chapter
169
+ currentFlow: NarrativeFlow; // Active flow
170
+ activeState: QNCEState; // Engine state
171
+ branchHistory: BranchHistoryEntry[]; // Decision history
172
+ pendingBranches: PendingBranch[]; // Deferred branches
173
+ analytics: BranchAnalytics; // Performance metrics
174
+ }
175
+ ```
176
+
177
+ **Key Features:**
178
+ - Complete context for AI decision making
179
+ - History tracking for complex narrative dependencies
180
+ - Real-time analytics collection
181
+
182
+ ## Data Relationships
183
+
184
+ ### Hierarchical Structure
185
+ ```
186
+ QNCEStory
187
+ ├── Chapter (1..*)
188
+ │ ├── NarrativeFlow (1..*)
189
+ │ │ ├── NarrativeNode (1..*)
190
+ │ │ ├── FlowEntryPoint (0..*)
191
+ │ │ └── FlowExitPoint (0..*)
192
+ │ └── BranchPoint (0..*)
193
+ │ └── BranchOption (1..*)
194
+ └── BranchingConfig
195
+ ```
196
+
197
+ ### Cross-References
198
+ - **BranchPoint.sourceFlowId** → **NarrativeFlow.id**
199
+ - **BranchOption.targetFlowId** → **NarrativeFlow.id**
200
+ - **FlowEntryPoint.nodeId** → **NarrativeNode.id**
201
+ - **FlowExitPoint.nodeId** → **NarrativeNode.id**
202
+
203
+ ### Runtime Associations
204
+ - **BranchContext** maintains references to active entities
205
+ - **BranchHistory** links to **BranchPoint** and **BranchOption**
206
+ - **PendingBranch** references **BranchPoint** for deferred execution
207
+
208
+ ## Performance Considerations
209
+
210
+ ### Object Pooling Integration
211
+
212
+ All frequently-created entities support object pooling:
213
+
214
+ ```typescript
215
+ interface PooledBranchContext extends BranchContext {
216
+ poolId: string; // Pool identifier
217
+ acquisitionTime: number; // Performance tracking
218
+ maxLifetime: number; // Auto-cleanup threshold
219
+ }
220
+ ```
221
+
222
+ ### Memory Management
223
+
224
+ - **Chapter-based loading**: Only active chapters kept in memory
225
+ - **Flow caching**: LRU cache for recently accessed flows
226
+ - **Branch pruning**: Remove unused branches after timeout
227
+ - **Analytics batching**: Batch analytics writes to reduce overhead
228
+
229
+ ### Performance Targets
230
+
231
+ | Operation | Target | Measurement |
232
+ |-----------|--------|-------------|
233
+ | Branch evaluation | <5ms | 95th percentile |
234
+ | Flow transition | <10ms | Average |
235
+ | Dynamic insertion | <20ms | 95th percentile |
236
+ | Analytics update | <1ms | Average |
237
+
238
+ ## AI Integration Points
239
+
240
+ ### Content Generation Context
241
+
242
+ The PDM provides rich context for AI systems:
243
+
244
+ ```typescript
245
+ interface AIBranchingContext {
246
+ playerProfile: PlayerProfile; // Behavioral patterns
247
+ narrativeContext: NarrativeContext; // Story state
248
+ generationHints: AIGenerationHints; // Constraints
249
+ }
250
+ ```
251
+
252
+ ### Player Profiling
253
+
254
+ ```typescript
255
+ interface PlayerProfile {
256
+ playStyle: 'explorer' | 'achiever' | 'socializer' | 'killer';
257
+ preferences: Record<string, number>; // Weighted preferences
258
+ historicalChoices: string[]; // Past decisions
259
+ averageDecisionTime: number; // Behavioral metric
260
+ }
261
+ ```
262
+
263
+ ### Dynamic Content Integration
264
+
265
+ - **Procedural flows**: AI-generated narrative sequences
266
+ - **Dynamic options**: Context-aware branch generation
267
+ - **Adaptive difficulty**: AI-driven complexity adjustment
268
+ - **Content quality**: Feedback loops for improvement
269
+
270
+ ## Usage Examples
271
+
272
+ ### 1. Basic Story Structure
273
+
274
+ ```typescript
275
+ const story: QNCEStory = {
276
+ id: "cyberpunk-heist",
277
+ title: "Neon Shadows",
278
+ version: "1.0.0",
279
+ metadata: {
280
+ author: "ByteSower",
281
+ description: "A cyberpunk heist story with AI companions",
282
+ tags: ["cyberpunk", "heist", "ai"],
283
+ createDate: new Date("2025-07-01"),
284
+ lastModified: new Date("2025-07-02"),
285
+ estimatedPlaytime: 45
286
+ },
287
+ chapters: [
288
+ {
289
+ id: "chapter-1-planning",
290
+ title: "The Planning Phase",
291
+ flows: [
292
+ {
293
+ id: "flow-intro",
294
+ name: "Introduction",
295
+ nodes: [/* ... */],
296
+ entryPoints: [{ id: "start", nodeId: "intro-1", priority: 1 }],
297
+ exitPoints: [{ id: "to-team", nodeId: "intro-final" }],
298
+ flowType: "linear",
299
+ metadata: { complexity: 2, avgCompletionTime: 300000 }
300
+ }
301
+ ],
302
+ branches: [
303
+ {
304
+ id: "team-selection",
305
+ name: "Choose Your Team",
306
+ sourceFlowId: "flow-intro",
307
+ sourceNodeId: "intro-final",
308
+ branchType: "choice-driven",
309
+ branchOptions: [
310
+ {
311
+ id: "tech-specialist",
312
+ targetFlowId: "flow-tech-path",
313
+ displayText: "Recruit the tech specialist",
314
+ weight: 1.0
315
+ },
316
+ {
317
+ id: "social-engineer",
318
+ targetFlowId: "flow-social-path",
319
+ displayText: "Recruit the social engineer",
320
+ weight: 1.0
321
+ }
322
+ ],
323
+ metadata: { usageCount: 0, avgTraversalTime: 0 }
324
+ }
325
+ ],
326
+ metadata: { difficulty: "medium", themes: ["planning"] }
327
+ }
328
+ ],
329
+ branchingConfig: {
330
+ maxActiveBranches: 10,
331
+ branchCacheSize: 50,
332
+ enableDynamicInsertion: true,
333
+ enableAnalytics: true,
334
+ performanceMode: true
335
+ }
336
+ };
337
+ ```
338
+
339
+ ### 2. Dynamic Branch Insertion
340
+
341
+ ```typescript
342
+ const dynamicBranch: DynamicBranchOperation = {
343
+ type: "insert",
344
+ branchId: "emergency-exit",
345
+ targetLocation: {
346
+ chapterId: "chapter-1-planning",
347
+ flowId: "flow-tech-path",
348
+ nodeId: "tech-decision-point",
349
+ insertionPoint: "after"
350
+ },
351
+ payload: {
352
+ id: "emergency-exit",
353
+ name: "Emergency Exit Option",
354
+ sourceFlowId: "flow-tech-path",
355
+ sourceNodeId: "tech-decision-point",
356
+ branchType: "conditional",
357
+ branchOptions: [{
358
+ id: "abort-mission",
359
+ targetFlowId: "flow-abort-sequence",
360
+ displayText: "Abort the mission",
361
+ conditions: [
362
+ { type: "flag", operator: "equals", key: "danger_level", value: "high" }
363
+ ],
364
+ weight: 0.5
365
+ }]
366
+ },
367
+ conditions: [
368
+ { type: "flag", operator: "greater", key: "tension", value: 0.8 }
369
+ ]
370
+ };
371
+ ```
372
+
373
+ ### 3. AI-Driven Content Generation
374
+
375
+ ```typescript
376
+ const aiContext: AIBranchingContext = {
377
+ playerProfile: {
378
+ playStyle: "explorer",
379
+ preferences: { "dialogue": 0.8, "action": 0.3, "puzzle": 0.6 },
380
+ historicalChoices: ["investigate", "ask-questions", "explore-optional"],
381
+ averageDecisionTime: 12000
382
+ },
383
+ narrativeContext: {
384
+ currentTone: "mysterious",
385
+ thematicElements: ["betrayal", "discovery", "technology"],
386
+ characterRelationships: { "ally-1": 0.7, "mentor": 0.9 },
387
+ plotTension: 0.6
388
+ },
389
+ generationHints: {
390
+ maxBranchDepth: 3,
391
+ desiredComplexity: 7,
392
+ contentThemes: ["investigation", "character-development"],
393
+ avoidElements: ["violence", "time-pressure"]
394
+ }
395
+ };
396
+ ```
397
+
398
+ ## Migration Guide
399
+
400
+ ### From Sprint #2 Core to Sprint #3 Branching
401
+
402
+ 1. **Story Data Format**:
403
+ - Wrap existing `StoryData` in `QNCEStory` structure
404
+ - Organize nodes into `NarrativeFlow` entities
405
+ - Group flows into logical `Chapter` divisions
406
+
407
+ 2. **Choice Enhancement**:
408
+ - Convert simple choices to `BranchOption` entities
409
+ - Add conditions for complex choice logic
410
+ - Implement weight-based selection for AI
411
+
412
+ 3. **State Integration**:
413
+ - Extend `QNCEState` with branching context
414
+ - Add analytics tracking to existing workflows
415
+ - Integrate with object pooling for performance
416
+
417
+ ### Backward Compatibility
418
+
419
+ The PDM maintains compatibility with existing QNCE engines:
420
+
421
+ - **Legacy node format**: Direct mapping to `NarrativeNode`
422
+ - **Simple choices**: Automatic conversion to `BranchOption`
423
+ - **Existing state**: Seamless integration with `BranchContext`
424
+
425
+ ## Conclusion
426
+
427
+ This PDM provides a comprehensive foundation for Sprint #3's advanced narrative features while maintaining the performance optimizations from Sprint #2. The design supports:
428
+
429
+ - ✅ **Dynamic Branching**: Runtime story modification
430
+ - ✅ **AI Integration**: Rich context for content generation
431
+ - ✅ **Performance**: Built on proven optimization infrastructure
432
+ - ✅ **Analytics**: Comprehensive player behavior tracking
433
+ - ✅ **Scalability**: Support for complex, large-scale narratives
434
+
435
+ The next step is to implement the **Branching API** that operates on this PDM, providing the runtime functionality needed for the complete Sprint #3 feature set.
436
+
437
+ ---
438
+
439
+ **Next Actions:**
440
+ 1. **Brain Review**: Architectural alignment and performance considerations
441
+ 2. **ByteSower Validation**: Use case coverage and content creator workflow
442
+ 3. **Implementation**: Build the Branching API on this PDM foundation
443
+ 4. **Testing**: Comprehensive test suite for all entity relationships