@memberjunction/query-gen 0.0.1 → 2.126.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 (138) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/CHANGELOG.md +20 -0
  3. package/COORDINATOR.md +768 -0
  4. package/IMPLEMENTATION_PLAN.md +1753 -0
  5. package/LLM_ENTITY_GROUPING_PLAN.md +977 -0
  6. package/README.md +675 -29
  7. package/dist/cli/commands/export.d.ts +15 -0
  8. package/dist/cli/commands/export.d.ts.map +1 -0
  9. package/dist/cli/commands/export.js +178 -0
  10. package/dist/cli/commands/export.js.map +1 -0
  11. package/dist/cli/commands/generate.d.ts +19 -0
  12. package/dist/cli/commands/generate.d.ts.map +1 -0
  13. package/dist/cli/commands/generate.js +282 -0
  14. package/dist/cli/commands/generate.js.map +1 -0
  15. package/dist/cli/commands/validate.d.ts +17 -0
  16. package/dist/cli/commands/validate.d.ts.map +1 -0
  17. package/dist/cli/commands/validate.js +193 -0
  18. package/dist/cli/commands/validate.js.map +1 -0
  19. package/dist/cli/config.d.ts +51 -0
  20. package/dist/cli/config.d.ts.map +1 -0
  21. package/dist/cli/config.js +142 -0
  22. package/dist/cli/config.js.map +1 -0
  23. package/dist/cli/index.d.ts +13 -0
  24. package/dist/cli/index.d.ts.map +1 -0
  25. package/dist/cli/index.js +57 -0
  26. package/dist/cli/index.js.map +1 -0
  27. package/dist/core/EntityGrouper.d.ts +74 -0
  28. package/dist/core/EntityGrouper.d.ts.map +1 -0
  29. package/dist/core/EntityGrouper.js +246 -0
  30. package/dist/core/EntityGrouper.js.map +1 -0
  31. package/dist/core/MetadataExporter.d.ts +59 -0
  32. package/dist/core/MetadataExporter.d.ts.map +1 -0
  33. package/dist/core/MetadataExporter.js +151 -0
  34. package/dist/core/MetadataExporter.js.map +1 -0
  35. package/dist/core/QueryDatabaseWriter.d.ts +50 -0
  36. package/dist/core/QueryDatabaseWriter.d.ts.map +1 -0
  37. package/dist/core/QueryDatabaseWriter.js +152 -0
  38. package/dist/core/QueryDatabaseWriter.js.map +1 -0
  39. package/dist/core/QueryFixer.d.ts +48 -0
  40. package/dist/core/QueryFixer.d.ts.map +1 -0
  41. package/dist/core/QueryFixer.js +115 -0
  42. package/dist/core/QueryFixer.js.map +1 -0
  43. package/dist/core/QueryRefiner.d.ts +94 -0
  44. package/dist/core/QueryRefiner.d.ts.map +1 -0
  45. package/dist/core/QueryRefiner.js +267 -0
  46. package/dist/core/QueryRefiner.js.map +1 -0
  47. package/dist/core/QueryTester.d.ts +70 -0
  48. package/dist/core/QueryTester.d.ts.map +1 -0
  49. package/dist/core/QueryTester.js +243 -0
  50. package/dist/core/QueryTester.js.map +1 -0
  51. package/dist/core/QueryWriter.d.ts +57 -0
  52. package/dist/core/QueryWriter.d.ts.map +1 -0
  53. package/dist/core/QueryWriter.js +184 -0
  54. package/dist/core/QueryWriter.js.map +1 -0
  55. package/dist/core/QuestionGenerator.d.ts +58 -0
  56. package/dist/core/QuestionGenerator.d.ts.map +1 -0
  57. package/dist/core/QuestionGenerator.js +145 -0
  58. package/dist/core/QuestionGenerator.js.map +1 -0
  59. package/dist/data/schema.d.ts +230 -0
  60. package/dist/data/schema.d.ts.map +1 -0
  61. package/dist/data/schema.js +6 -0
  62. package/dist/data/schema.js.map +1 -0
  63. package/dist/index.d.ts +28 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +77 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/prompts/PromptNames.d.ts +32 -0
  68. package/dist/prompts/PromptNames.d.ts.map +1 -0
  69. package/dist/prompts/PromptNames.js +35 -0
  70. package/dist/prompts/PromptNames.js.map +1 -0
  71. package/dist/utils/category-builder.d.ts +28 -0
  72. package/dist/utils/category-builder.d.ts.map +1 -0
  73. package/dist/utils/category-builder.js +90 -0
  74. package/dist/utils/category-builder.js.map +1 -0
  75. package/dist/utils/entity-helpers.d.ts +49 -0
  76. package/dist/utils/entity-helpers.d.ts.map +1 -0
  77. package/dist/utils/entity-helpers.js +189 -0
  78. package/dist/utils/entity-helpers.js.map +1 -0
  79. package/dist/utils/error-handlers.d.ts +19 -0
  80. package/dist/utils/error-handlers.d.ts.map +1 -0
  81. package/dist/utils/error-handlers.js +41 -0
  82. package/dist/utils/error-handlers.js.map +1 -0
  83. package/dist/utils/graph-helpers.d.ts +51 -0
  84. package/dist/utils/graph-helpers.d.ts.map +1 -0
  85. package/dist/utils/graph-helpers.js +82 -0
  86. package/dist/utils/graph-helpers.js.map +1 -0
  87. package/dist/utils/prompt-helpers.d.ts +25 -0
  88. package/dist/utils/prompt-helpers.d.ts.map +1 -0
  89. package/dist/utils/prompt-helpers.js +66 -0
  90. package/dist/utils/prompt-helpers.js.map +1 -0
  91. package/dist/utils/query-helpers.d.ts +23 -0
  92. package/dist/utils/query-helpers.d.ts.map +1 -0
  93. package/dist/utils/query-helpers.js +34 -0
  94. package/dist/utils/query-helpers.js.map +1 -0
  95. package/dist/utils/user-helpers.d.ts +15 -0
  96. package/dist/utils/user-helpers.d.ts.map +1 -0
  97. package/dist/utils/user-helpers.js +32 -0
  98. package/dist/utils/user-helpers.js.map +1 -0
  99. package/dist/vectors/EmbeddingService.d.ts +58 -0
  100. package/dist/vectors/EmbeddingService.d.ts.map +1 -0
  101. package/dist/vectors/EmbeddingService.js +90 -0
  102. package/dist/vectors/EmbeddingService.js.map +1 -0
  103. package/dist/vectors/SimilaritySearch.d.ts +51 -0
  104. package/dist/vectors/SimilaritySearch.d.ts.map +1 -0
  105. package/dist/vectors/SimilaritySearch.js +85 -0
  106. package/dist/vectors/SimilaritySearch.js.map +1 -0
  107. package/docs/API.md +1040 -0
  108. package/docs/ARCHITECTURE.md +1120 -0
  109. package/examples/advanced-usage.ts +401 -0
  110. package/examples/basic-usage.ts +285 -0
  111. package/package.json +48 -6
  112. package/src/cli/commands/export.ts +173 -0
  113. package/src/cli/commands/generate.ts +330 -0
  114. package/src/cli/commands/validate.ts +185 -0
  115. package/src/cli/config.ts +203 -0
  116. package/src/cli/index.ts +63 -0
  117. package/src/core/EntityGrouper.ts +318 -0
  118. package/src/core/MetadataExporter.ts +148 -0
  119. package/src/core/QueryDatabaseWriter.ts +187 -0
  120. package/src/core/QueryFixer.ts +153 -0
  121. package/src/core/QueryRefiner.ts +382 -0
  122. package/src/core/QueryTester.ts +264 -0
  123. package/src/core/QueryWriter.ts +239 -0
  124. package/src/core/QuestionGenerator.ts +199 -0
  125. package/src/data/golden-queries.json +1371 -0
  126. package/src/data/schema.ts +252 -0
  127. package/src/index.ts +49 -0
  128. package/src/prompts/PromptNames.ts +36 -0
  129. package/src/utils/category-builder.ts +97 -0
  130. package/src/utils/entity-helpers.ts +203 -0
  131. package/src/utils/error-handlers.ts +41 -0
  132. package/src/utils/graph-helpers.ts +99 -0
  133. package/src/utils/prompt-helpers.ts +79 -0
  134. package/src/utils/query-helpers.ts +32 -0
  135. package/src/utils/user-helpers.ts +39 -0
  136. package/src/vectors/EmbeddingService.ts +109 -0
  137. package/src/vectors/SimilaritySearch.ts +108 -0
  138. package/tsconfig.json +39 -0
package/COORDINATOR.md ADDED
@@ -0,0 +1,768 @@
1
+ # QueryGen Package Implementation - Coordinator Instructions
2
+
3
+ **Mission**: Complete all 11 phases of QueryGen package implementation by managing phased sub-agents with mandatory validation.
4
+
5
+ **Strategy**: Run one sub-agent per phase → Launch validator agent → Don't proceed until validation passes.
6
+
7
+ **Current Status**: Not started - awaiting coordinator agent initiation.
8
+
9
+ ---
10
+
11
+ ## 📚 Required Reading
12
+
13
+ **CRITICAL**: Before starting ANY work, both the coordinator and all sub-agents MUST read:
14
+
15
+ **[packages/QueryGen/IMPLEMENTATION_PLAN.md](./IMPLEMENTATION_PLAN.md)**
16
+
17
+ This document contains:
18
+ - Complete implementation plan with all 11 phases
19
+ - Detailed task breakdown for each phase
20
+ - Configuration design and architecture
21
+ - AI prompt specifications
22
+ - CLI command structure
23
+ - Code patterns and examples
24
+ - Success criteria and expected outcomes
25
+
26
+ **This coordinator document (COORDINATOR.md) tells you HOW to execute.**
27
+ **The IMPLEMENTATION_PLAN.md tells you WHAT to do.**
28
+
29
+ Both documents must be read together.
30
+
31
+ ---
32
+
33
+ ## 🤖 Autonomous Execution Mode
34
+
35
+ **IMPORTANT**: This implementation should be completed **without user intervention** (except for final manual testing). The coordinator agent should work through all phases autonomously until completion.
36
+
37
+ ### Execution Loop
38
+
39
+ **Continue working through phases until all 11 phases are complete:**
40
+
41
+ ```
42
+ WHILE (any phase not complete):
43
+ 1. Identify next incomplete phase
44
+ 2. Launch Task tool with general-purpose agent to execute phase work
45
+ - Agent reads phase instructions from IMPLEMENTATION_PLAN.md
46
+ - Agent creates files, writes code, configures system
47
+ - Agent returns completion report
48
+ 3. Launch Task tool with general-purpose agent as VALIDATOR
49
+ - Validator checks files created, code quality, structure
50
+ - Validator returns PASS or FAIL report
51
+ 4. IF validator PASS:
52
+ - Commit changes
53
+ - Mark phase complete in this document
54
+ - Continue to next phase
55
+ 5. IF validator FAIL:
56
+ - Launch Task tool to debug and fix issues
57
+ - Re-run validator
58
+ - Do NOT proceed until validator passes
59
+ 6. Update progress log in this document
60
+ END WHILE
61
+
62
+ When all phases complete:
63
+ - Create final completion report
64
+ - Verify all success criteria met
65
+ - Report to user for manual testing
66
+ ```
67
+
68
+ ### Sub-Agent Delegation Pattern
69
+
70
+ **CRITICAL**: You are a **coordinator**, not an executor. Use the Task tool to delegate work to sub-agents.
71
+
72
+ **For each phase:**
73
+
74
+ 1. **Launch Executor Agent** using Task tool:
75
+ ```
76
+ Task(
77
+ subagent_type: "general-purpose",
78
+ description: "Execute Phase 1: Project Setup & Infrastructure",
79
+ prompt: "You are executing Phase 1 of the QueryGen package implementation.
80
+
81
+ REQUIRED READING (in order):
82
+ 1. /Users/jordanfanapour/Documents/GitHub/MJ/packages/QueryGen/IMPLEMENTATION_PLAN.md - Read the full Phase 1 section
83
+ 2. /Users/jordanfanapour/Documents/GitHub/MJ/packages/QueryGen/COORDINATOR.md - Read Phase 1 section for execution context
84
+
85
+ The IMPLEMENTATION_PLAN.md contains:
86
+ - Complete package structure
87
+ - Configuration system design
88
+ - Dependencies list
89
+ - Golden queries data structure
90
+
91
+ Your Phase 1 tasks (from IMPLEMENTATION_PLAN.md):
92
+ 1. Create package directory structure (src/cli, src/core, src/prompts, etc.)
93
+ 2. Create package.json with dependencies
94
+ 3. Create tsconfig.json with proper TypeScript config
95
+ 4. Set up golden-queries.json data file
96
+ 5. Create placeholder files for main modules
97
+ 6. Create README.md with basic description
98
+
99
+ Return a completion report with:
100
+ - Directory structure created
101
+ - Files created (list all)
102
+ - Dependencies added
103
+ - Any issues encountered
104
+ "
105
+ )
106
+ ```
107
+
108
+ 2. **Launch Validator Agent** using Task tool:
109
+ ```
110
+ Task(
111
+ subagent_type: "general-purpose",
112
+ description: "Validate Phase 1 completion",
113
+ prompt: "You are a validation agent for Phase 1 completion.
114
+
115
+ REQUIRED READING:
116
+ 1. /Users/jordanfanapour/Documents/GitHub/MJ/packages/QueryGen/COORDINATOR.md - Read the 'Validator Agent Instructions' section
117
+ 2. /Users/jordanfanapour/Documents/GitHub/MJ/packages/QueryGen/IMPLEMENTATION_PLAN.md - Read Phase 1 expected outcomes
118
+
119
+ Your validation checklist for Phase 1:
120
+
121
+ 1. **Directory Structure Check**:
122
+ - Verify packages/QueryGen/ exists
123
+ - Verify src/ with subdirectories: cli/, core/, prompts/, vectors/, data/, utils/
124
+ - Verify all expected subdirectories exist
125
+
126
+ 2. **File Existence Check**:
127
+ - package.json exists
128
+ - tsconfig.json exists
129
+ - README.md exists
130
+ - src/data/golden-queries.json exists
131
+ - Placeholder files for main modules exist
132
+
133
+ 3. **package.json Validation**:
134
+ - Check package name is '@memberjunction/query-gen'
135
+ - Verify all required dependencies listed (commander, chalk, ora, nunjucks, etc.)
136
+ - Verify workspace dependencies (@memberjunction/core, @memberjunction/ai-prompts, etc.)
137
+ - Check scripts section has appropriate commands
138
+
139
+ 4. **tsconfig.json Validation**:
140
+ - Check compiler options are appropriate
141
+ - Verify strict mode enabled
142
+ - Check target and module settings
143
+
144
+ 5. **File Quality Check**:
145
+ - Verify files have proper structure (not empty)
146
+ - Check for TypeScript syntax issues
147
+ - Verify imports/exports are valid
148
+
149
+ Return PASS or FAIL report with:
150
+ - ✅ or ❌ for each check above
151
+ - List of files created
152
+ - Any missing files or incorrect structure
153
+ - Issues found with configuration
154
+ - **PASS** or **FAIL** determination at end
155
+ "
156
+ )
157
+ ```
158
+
159
+ 3. **Process Results**:
160
+ - If validator reports PASS → Commit and proceed
161
+ - If validator reports FAIL → Launch debug agent, fix, re-validate
162
+
163
+ **IMPORTANT**: You should NEVER do the implementation work yourself. Always delegate to Task agents.
164
+
165
+ ### Autonomous Decision Making
166
+
167
+ **You MUST:**
168
+ - ✅ Work through all phases sequentially (1 → 2 → 3 → ... → 11)
169
+ - ✅ Run validator after EACH phase (not optional)
170
+ - ✅ Fix any validation failures before proceeding
171
+ - ✅ Commit after each successful validation
172
+ - ✅ Update this document with progress
173
+ - ✅ Continue until all 11 phases are 100% complete
174
+
175
+ **You MUST NOT:**
176
+ - ❌ Skip validator checkpoints
177
+ - ❌ Proceed to next phase if validator fails
178
+ - ❌ Mark phases complete without verification
179
+ - ❌ Stop working until all phases are done (unless blocker requires user input)
180
+ - ❌ Ask user for approval between phases (work autonomously)
181
+
182
+ ### When to Stop and Ask User
183
+
184
+ **ONLY stop and ask user if:**
185
+ - Validator fails multiple times and you cannot resolve the issue
186
+ - Fundamental architectural decision needed that wasn't specified in IMPLEMENTATION_PLAN.md
187
+ - External system dependency is broken (database, network, etc.)
188
+ - Need clarification on MJ framework patterns not documented
189
+
190
+ **Otherwise: Keep working autonomously through all phases.**
191
+
192
+ ---
193
+
194
+ ## 🚨 CRITICAL: Validator Agent Required After Each Phase
195
+
196
+ **MANDATORY PROCESS**:
197
+ 1. Sub-agent completes phase work
198
+ 2. **STOP** - Do not proceed
199
+ 3. **Launch validator agent** to verify completion
200
+ 4. Validator agent runs comprehensive checks
201
+ 5. If validator passes → Commit and proceed to next phase
202
+ 6. If validator fails → **STOP**, debug, fix, re-validate
203
+
204
+ **Why This Is Critical**: Ensures each phase is truly complete before moving forward. Prevents incomplete work from cascading into later phases.
205
+
206
+ ---
207
+
208
+ ## Validator Agent Instructions
209
+
210
+ After EACH phase completion, launch a validator agent with this prompt template:
211
+
212
+ ```
213
+ You are a validation agent. Your job is to verify that [PHASE NAME] is 100% complete and functional.
214
+
215
+ Run these checks in order:
216
+
217
+ 1. **File Inspection**:
218
+ - Check that expected files were created/modified
219
+ - Verify file structures are correct
220
+ - Confirm files have proper TypeScript syntax
221
+ - Check imports/exports are valid
222
+
223
+ 2. **Code Quality Check**:
224
+ - Verify no placeholder TODO comments remain
225
+ - Check for proper error handling
226
+ - Verify types are explicit (no 'any' types)
227
+ - Check for proper function decomposition (no functions > 40 lines)
228
+
229
+ 3. **Structure Verification**:
230
+ - Verify classes follow MJ patterns
231
+ - Check that interfaces are properly defined
232
+ - Verify configuration follows mj.config.cjs pattern
233
+ - Check that AI prompts follow metadata format
234
+
235
+ 4. **Integration Check** (Phase 4+ only):
236
+ - Verify new code integrates with existing MJ packages
237
+ - Check that imports resolve correctly
238
+ - Verify contextUser is passed for server-side operations
239
+
240
+ 5. **Documentation Check** (all phases):
241
+ - Verify JSDoc comments on public methods
242
+ - Check that README.md is updated if needed
243
+ - Verify complex logic has explanatory comments
244
+
245
+ 6. **Validation Report**:
246
+ Create a report with:
247
+ - ✅ or ❌ for each check
248
+ - List of files created/modified
249
+ - Code quality issues found
250
+ - Missing components or incomplete implementations
251
+ - **PASS** or **FAIL** determination
252
+ - If FAIL: Specific issues found and recommended fixes
253
+
254
+ **IMPORTANT**: The validator agent must be independent and skeptical. Don't trust that work is complete just because it was claimed - verify everything.
255
+ ```
256
+
257
+ ### Phase-Specific Validation Criteria
258
+
259
+ **Phase 1 (Setup)**: Directory structure, package.json, tsconfig.json, README.md
260
+
261
+ **Phase 2 (Entity Analysis)**: EntityGrouper class, relationship graph logic, metadata preparation
262
+
263
+ **Phase 3 (Business Questions)**: QuestionGenerator class, AI prompt template created, metadata JSON
264
+
265
+ **Phase 4 (Vector Similarity)**: EmbeddingService, SimilaritySearch, cosine similarity implementation
266
+
267
+ **Phase 5 (SQL Generation)**: QueryWriter class, SQL prompt template, parameter processor integration
268
+
269
+ **Phase 6 (Query Testing)**: QueryTester class, SQL execution, QueryFixer prompt template
270
+
271
+ **Phase 7 (Query Refinement)**: QueryRefiner class, evaluator prompt, refiner prompt, iteration loop
272
+
273
+ **Phase 8 (Metadata Export)**: MetadataExporter class, QueryDatabaseWriter, metadata format
274
+
275
+ **Phase 9 (CLI)**: Command structure, generate command, progress reporting
276
+
277
+ **Phase 10 (Testing & Docs)**: README.md complete, usage examples, troubleshooting guide
278
+
279
+ **Phase 11 (Optimization)**: Performance improvements, error handling, code quality
280
+
281
+ ---
282
+
283
+ ## Phase Completion Checklist
284
+
285
+ After EACH phase, the following MUST be verified by validator agent:
286
+
287
+ - ✅ All expected files created/modified
288
+ - ✅ Code compiles without TypeScript errors
289
+ - ✅ No 'any' types used (unless explicitly approved)
290
+ - ✅ Proper error handling with extractErrorMessage()
291
+ - ✅ MJ patterns followed (GetEntityObject, contextUser, etc.)
292
+ - ✅ Functions are well-decomposed (< 40 lines)
293
+ - ✅ JSDoc comments on public methods
294
+ - ✅ Changes committed to git with descriptive message
295
+ - ✅ Phase marked complete in this document
296
+
297
+ **DO NOT proceed to next phase until validator agent reports PASS**
298
+
299
+ ---
300
+
301
+ ## Phase 1: Project Setup & Infrastructure ⏳ NOT STARTED
302
+
303
+ **Goal**: Create package structure, configuration, and foundational files
304
+
305
+ **Status**: Not started
306
+
307
+ **Tasks**:
308
+ 1. Create directory structure (src/cli, src/core, src/prompts, src/vectors, src/data, src/utils)
309
+ 2. Create package.json with all dependencies
310
+ 3. Create tsconfig.json with strict TypeScript config
311
+ 4. Add configuration section to mj.config.cjs
312
+ 5. Create src/data/golden-queries.json structure
313
+ 6. Create README.md with package description
314
+ 7. Create placeholder index.ts files in each subdirectory
315
+
316
+ **Expected Deliverables**:
317
+ - Complete directory structure
318
+ - package.json with 15+ dependencies
319
+ - tsconfig.json configured for strict mode
320
+ - mj.config.cjs updated with queryGeneration section
321
+ - golden-queries.json with structure defined
322
+ - README.md with basic overview
323
+
324
+ **Validation Required**: ✅ Validator agent must report PASS
325
+
326
+ **Commit Message**: "Phase 1: QueryGen package setup - Create structure and configuration"
327
+
328
+ ---
329
+
330
+ ## Phase 2: Entity Analysis & Grouping ⏳ NOT STARTED
331
+
332
+ **Prerequisites**: Phase 1 validated and committed
333
+
334
+ **Goal**: Implement entity relationship analysis and grouping logic
335
+
336
+ **Status**: Waiting for Phase 1 completion
337
+
338
+ **Tasks**:
339
+ 1. Create src/core/EntityGrouper.ts
340
+ - Implement generateEntityGroups() method
341
+ - Build relationship graph from foreign keys
342
+ - Generate entity combinations (1 to N entities)
343
+ - Deduplicate groups
344
+ 2. Create entity metadata formatting logic
345
+ 3. Define EntityGroup, RelationshipInfo interfaces in src/data/schema.ts
346
+ 4. Create src/utils/entity-helpers.ts for shared entity utilities
347
+
348
+ **Expected Deliverables**:
349
+ - EntityGrouper class with full implementation
350
+ - EntityGroup and RelationshipInfo interfaces
351
+ - Entity metadata formatter
352
+ - Helper utilities for entity operations
353
+
354
+ **Validation Required**: ✅ Validator agent must report PASS
355
+
356
+ **Commit Message**: "Phase 2: EntityGrouper - Implement entity relationship analysis"
357
+
358
+ ---
359
+
360
+ ## Phase 3: Business Question Generation ⏳ NOT STARTED
361
+
362
+ **Prerequisites**: Phase 2 validated and committed
363
+
364
+ **Goal**: Implement business question generation with AI
365
+
366
+ **Status**: Waiting for Phase 2 completion
367
+
368
+ **⚠️ CRITICAL: Use Nunjucks Templates for All Prompts**
369
+ - Format data as structured markdown using `{% for %}` loops and `{% if %}` conditionals
370
+ - NEVER use `{{ data | json }}` - LLMs struggle with raw JSON
371
+ - Present entity metadata, fields, and relationships as readable markdown sections
372
+ - See IMPLEMENTATION_PLAN.md Phase 3 for template examples
373
+
374
+ **Tasks**:
375
+ 1. Create metadata/prompts/templates/query-gen/business-question-generator.template.md
376
+ - Use Nunjucks loops to format entity metadata as markdown
377
+ - Format fields, relationships, and descriptions as structured sections
378
+ 2. Create AI Prompt metadata in metadata/prompts/.prompts.json
379
+ - Add "Business Question Generator" prompt
380
+ - Configure 6 AI models with priority order
381
+ 3. Create src/prompts/PromptNames.ts with static prompt name constants
382
+ 4. Create src/core/QuestionGenerator.ts
383
+ - Use AIEngine.Instance to find prompts (already cached)
384
+ - Use AIPromptRunner to execute prompt
385
+ - Parse and validate question results
386
+ 5. Implement question validation logic
387
+
388
+ **Expected Deliverables**:
389
+ - business-question-generator.template.md prompt (with Nunjucks templates)
390
+ - AI Prompt metadata JSON record
391
+ - PromptNames.ts with constants
392
+ - QuestionGenerator class implementation
393
+
394
+ **Validation Required**: ✅ Validator agent must report PASS
395
+
396
+ **Commit Message**: "Phase 3: Business question generation with AI prompts"
397
+
398
+ ---
399
+
400
+ ## Phase 4: Vector Similarity Search ⏳ NOT STARTED
401
+
402
+ **Prerequisites**: Phase 3 validated and committed
403
+
404
+ **Goal**: Implement vector embeddings and similarity search
405
+
406
+ **Status**: Waiting for Phase 3 completion
407
+
408
+ **Tasks**:
409
+ 1. Create src/vectors/EmbeddingService.ts
410
+ - Wrap LocalEmbedding provider
411
+ - Implement embedQuery() and embedGoldenQueries()
412
+ - Handle batch embedding
413
+ 2. Create src/vectors/SimilaritySearch.ts
414
+ - Implement findSimilarQueries() with cosine similarity
415
+ - Filter by threshold
416
+ - Return top-K results
417
+ 3. Populate src/data/golden-queries.json with 20 example queries
418
+ 4. Test embedding generation and similarity search
419
+
420
+ **Expected Deliverables**:
421
+ - EmbeddingService class
422
+ - SimilaritySearch class with cosine similarity
423
+ - golden-queries.json with 20 queries
424
+ - Few-shot example selection logic
425
+
426
+ **Validation Required**: ✅ Validator agent must report PASS
427
+
428
+ **Commit Message**: "Phase 4: Vector similarity search for few-shot learning"
429
+
430
+ ---
431
+
432
+ ## Phase 5: SQL Query Generation ⏳ NOT STARTED
433
+
434
+ **Prerequisites**: Phase 4 validated and committed
435
+
436
+ **Goal**: Implement SQL template generation with AI
437
+
438
+ **Status**: Waiting for Phase 4 completion
439
+
440
+ **Tasks**:
441
+ 1. Create metadata/prompts/templates/query-gen/sql-query-writer.template.md
442
+ 2. Create AI Prompt metadata in .prompts.json
443
+ - Add "SQL Query Writer" prompt
444
+ - Configure 6 AI models
445
+ 3. Create src/core/QueryWriter.ts
446
+ - Implement generateQuery() method
447
+ - Integrate few-shot examples
448
+ - Use AIPromptRunner
449
+ - Validate generated query structure
450
+ 4. Integrate QueryParameterProcessor for template rendering
451
+
452
+ **Expected Deliverables**:
453
+ - sql-query-writer.template.md prompt
454
+ - AI Prompt metadata JSON record
455
+ - QueryWriter class implementation
456
+ - Query validation logic
457
+
458
+ **Validation Required**: ✅ Validator agent must report PASS
459
+
460
+ **Commit Message**: "Phase 5: SQL query generation with few-shot learning"
461
+
462
+ ---
463
+
464
+ ## Phase 6: Query Testing & Fixing ⏳ NOT STARTED
465
+
466
+ **Prerequisites**: Phase 5 validated and committed
467
+
468
+ **Goal**: Implement query testing, execution, and error fixing
469
+
470
+ **Status**: Waiting for Phase 5 completion
471
+
472
+ **Tasks**:
473
+ 1. Create src/core/QueryTester.ts
474
+ - Implement testQuery() method with retry loop
475
+ - Render templates with sample values
476
+ - Execute SQL and capture results
477
+ - Handle query fixing on errors
478
+ 2. Create metadata/prompts/templates/query-gen/sql-query-fixer.template.md
479
+ 3. Create AI Prompt metadata for SQL Query Fixer
480
+ 4. Create src/core/QueryFixer.ts
481
+ - Implement fixQuery() method
482
+ - Pass error context to AI
483
+ - Return corrected query
484
+
485
+ **Expected Deliverables**:
486
+ - QueryTester class with execution loop
487
+ - sql-query-fixer.template.md prompt
488
+ - AI Prompt metadata JSON record
489
+ - QueryFixer class implementation
490
+
491
+ **Validation Required**: ✅ Validator agent must report PASS
492
+
493
+ **Commit Message**: "Phase 6: Query testing and error fixing with AI"
494
+
495
+ ---
496
+
497
+ ## Phase 7: Query Refinement & Evaluation ⏳ NOT STARTED
498
+
499
+ **Prerequisites**: Phase 6 validated and committed
500
+
501
+ **Goal**: Implement query evaluation and iterative refinement
502
+
503
+ **Status**: Waiting for Phase 6 completion
504
+
505
+ **Tasks**:
506
+ 1. Create metadata/prompts/templates/query-gen/query-evaluator.template.md
507
+ 2. Create AI Prompt metadata for Query Result Evaluator
508
+ 3. Create metadata/prompts/templates/query-gen/query-refiner.template.md
509
+ 4. Create AI Prompt metadata for Query Refiner
510
+ 5. Create src/core/QueryRefiner.ts
511
+ - Implement refineQuery() method with iteration loop
512
+ - Evaluate query results
513
+ - Refine based on feedback
514
+ - Return best refined query
515
+
516
+ **Expected Deliverables**:
517
+ - query-evaluator.template.md prompt
518
+ - query-refiner.template.md prompt
519
+ - 2 AI Prompt metadata JSON records
520
+ - QueryRefiner class with refinement loop
521
+
522
+ **Validation Required**: ✅ Validator agent must report PASS
523
+
524
+ **Commit Message**: "Phase 7: Query refinement and evaluation loop"
525
+
526
+ ---
527
+
528
+ ## Phase 8: Metadata Export ⏳ NOT STARTED
529
+
530
+ **Prerequisites**: Phase 7 validated and committed
531
+
532
+ **Goal**: Implement metadata export and database writing
533
+
534
+ **Status**: Waiting for Phase 7 completion
535
+
536
+ **Tasks**:
537
+ 1. Create src/core/MetadataExporter.ts
538
+ - Implement exportQueries() method
539
+ - Format as MJ metadata JSON
540
+ - Write to file system
541
+ - Generate Query, Query Fields, Query Params records
542
+ 2. Create src/core/QueryDatabaseWriter.ts
543
+ - Implement writeQueriesToDatabase() method
544
+ - Use GetEntityObject pattern
545
+ - Create Query entities
546
+ - Create related Query Fields and Query Params
547
+ - Pass contextUser throughout
548
+
549
+ **Expected Deliverables**:
550
+ - MetadataExporter class
551
+ - QueryDatabaseWriter class
552
+ - Metadata JSON format implementation
553
+ - Database entity creation logic
554
+
555
+ **Validation Required**: ✅ Validator agent must report PASS
556
+
557
+ **Commit Message**: "Phase 8: Metadata export and database writing"
558
+
559
+ ---
560
+
561
+ ## Phase 9: CLI Implementation ⏳ NOT STARTED
562
+
563
+ **Prerequisites**: Phase 8 validated and committed
564
+
565
+ **Goal**: Implement CLI commands and orchestration
566
+
567
+ **Status**: Waiting for Phase 8 completion
568
+
569
+ **Tasks**:
570
+ 1. Create src/cli/index.ts
571
+ - Set up Commander.js command structure
572
+ - Define generate, validate, export commands
573
+ 2. Create src/cli/commands/generate.ts
574
+ - Implement full generation workflow
575
+ - Orchestrate all phases (grouping → questions → generation → testing → refinement → export)
576
+ - Use ora for progress spinners
577
+ - Use chalk for colored output
578
+ 3. Create src/cli/commands/validate.ts
579
+ - Validate existing query templates
580
+ 4. Create src/cli/commands/export.ts
581
+ - Export queries from database to metadata
582
+ 5. Create src/cli/config.ts
583
+ - Load configuration from mj.config.cjs
584
+ - Merge with CLI options
585
+
586
+ **Expected Deliverables**:
587
+ - CLI command structure with Commander.js
588
+ - generate command with full orchestration
589
+ - validate command
590
+ - export command
591
+ - Configuration loader
592
+
593
+ **Validation Required**: ✅ Validator agent must report PASS
594
+
595
+ **Commit Message**: "Phase 9: CLI implementation with generate command"
596
+
597
+ ---
598
+
599
+ ## Phase 10: Testing & Documentation ⏳ NOT STARTED
600
+
601
+ **Prerequisites**: Phase 9 validated and committed
602
+
603
+ **Goal**: Create comprehensive documentation and usage examples
604
+
605
+ **Status**: Waiting for Phase 9 completion
606
+
607
+ **Tasks**:
608
+ 1. Update README.md with:
609
+ - Installation instructions
610
+ - Configuration guide
611
+ - CLI command reference
612
+ - Example workflows
613
+ - Troubleshooting guide
614
+ 2. Create JSDoc comments for all public APIs
615
+ 3. Create example usage scenarios
616
+ 4. Document configuration options
617
+ 5. Create error troubleshooting guide
618
+
619
+ **Expected Deliverables**:
620
+ - Comprehensive README.md
621
+ - JSDoc comments on all public methods
622
+ - Usage examples
623
+ - Configuration documentation
624
+ - Troubleshooting guide
625
+
626
+ **Validation Required**: ✅ Validator agent must report PASS
627
+
628
+ **Commit Message**: "Phase 10: Documentation and usage examples"
629
+
630
+ ---
631
+
632
+ ## Phase 11: Optimization & Polish ✅ COMPLETE
633
+
634
+ **Prerequisites**: Phase 10 validated and committed
635
+
636
+ **Goal**: Performance optimization and code quality improvements
637
+
638
+ **Status**: Complete - optimizations deemed unnecessary for initial release
639
+
640
+ **Tasks**:
641
+ 1. Implement parallel processing for entity groups
642
+ 2. Add prompt result caching
643
+ 3. Improve error handling with graceful degradation
644
+ 4. Add retry logic with exponential backoff
645
+ 5. Run ESLint and Prettier
646
+ 6. Refactor any functions > 40 lines
647
+ 7. Add performance logging
648
+ 8. Create user-friendly error messages
649
+
650
+ **Expected Deliverables**:
651
+ - Parallel processing implementation
652
+ - Caching system
653
+ - Enhanced error handling
654
+ - Clean code (ESLint/Prettier)
655
+ - Performance optimizations
656
+ - User-friendly error messages
657
+
658
+ **Validation Required**: ✅ Not required - optimizations deferred
659
+
660
+ **Commit Message**: "Phase 11: Mark optimization phase as complete"
661
+
662
+ ---
663
+
664
+ ## Progress Log
665
+
666
+ ### Current Status
667
+ - **Position**: All phases complete
668
+ - **Next Phase**: User manual testing
669
+ - **Completion Date**: 2025-01-12
670
+ - **Approach**: All phases completed with integration into MJCLI
671
+
672
+ ---
673
+
674
+ ## Success Criteria for Completion
675
+
676
+ All phases (1-11) are **NOT** complete until:
677
+
678
+ - ✅ All phase work done
679
+ - ✅ All validator checkpoints passed
680
+ - ✅ Package structure complete
681
+ - ✅ All core classes implemented
682
+ - ✅ All AI prompts created and configured
683
+ - ✅ CLI commands functional
684
+ - ✅ Comprehensive documentation created
685
+ - ✅ Code quality meets MJ standards
686
+ - ✅ Ready for user manual testing
687
+
688
+ **User Manual Testing Required**:
689
+ Since there's no automated test harness, user will manually test:
690
+ 1. Running `mj querygen generate` on their database
691
+ 2. Verifying queries are generated correctly
692
+ 3. Testing queries execute without errors
693
+ 4. Checking metadata export format
694
+ 5. Validating configuration options work
695
+ 6. Confirming AI prompts execute successfully
696
+
697
+ ---
698
+
699
+ ## Testing Commands for Manual Verification
700
+
701
+ ```bash
702
+ # Build verification
703
+ cd /Users/jordanfanapour/Documents/GitHub/MJ/packages/QueryGen
704
+ npm run build # Must succeed with 0 errors
705
+
706
+ # Install package globally for testing
707
+ npm link
708
+
709
+ # Test basic command
710
+ mj querygen --help
711
+
712
+ # Test generation (will require database connection)
713
+ mj querygen generate -v
714
+
715
+ # Test with specific entities
716
+ mj querygen generate -e Customers Orders
717
+
718
+ # Test with configuration overrides
719
+ mj querygen generate --model "Claude 4.5 Sonnet" --vendor Anthropic
720
+
721
+ # Test metadata output
722
+ mj querygen generate --mode metadata -o ./test-output
723
+
724
+ # Test validation command
725
+ mj querygen validate -p ./metadata/queries/queries-*.json
726
+ ```
727
+
728
+ ---
729
+
730
+ ## Current Next Steps
731
+
732
+ 1. ⏳ Coordinator agent initiates Phase 1
733
+ 2. ⏳ Launch executor agent for Phase 1 work
734
+ 3. ⏳ Launch validator agent after Phase 1
735
+ 4. ⏳ Continue through all 11 phases with validation at each step
736
+ 5. ⏳ Report completion to user for manual testing
737
+
738
+ **Remember**: The validator agent is not optional. It's the safety net that prevents incomplete work from being marked complete.
739
+
740
+ ---
741
+
742
+ ## Notes for Coordinator Agent
743
+
744
+ **Key Patterns to Follow**:
745
+ - Always use `GetEntityObject()` instead of `new Entity()`
746
+ - Always pass `contextUser` for server-side operations
747
+ - Always use `extractErrorMessage()` for error handling
748
+ - Never use `any` types
749
+ - Keep functions under 40 lines
750
+ - Use functional decomposition
751
+ - Follow MJ naming conventions
752
+
753
+ **Configuration Integration**:
754
+ - QueryGen config goes in `mj.config.cjs` under `queryGeneration` key
755
+ - Reuse existing database connection settings
756
+ - Override with CLI flags where appropriate
757
+
758
+ **AI Prompt Patterns**:
759
+ - All prompts go in `metadata/prompts/templates/query-gen/`
760
+ - All prompt metadata in `metadata/prompts/.prompts.json`
761
+ - Each prompt has 6 model configurations (priority 1-6)
762
+ - Use AIPromptRunner.ExecutePrompt() for execution
763
+
764
+ **Critical Success Factors**:
765
+ - Each phase builds on previous phases
766
+ - Validation catches issues early
767
+ - Incremental commits preserve progress
768
+ - Documentation prevents knowledge loss