ApiLogicServer 15.4.3__py3-none-any.whl → 16.0.0__py3-none-any.whl

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 (26) hide show
  1. api_logic_server_cli/add_cust/add_cust.py +6 -2
  2. api_logic_server_cli/api_logic_server.py +2 -1
  3. api_logic_server_cli/database/basic_demo.sqlite +0 -0
  4. api_logic_server_cli/prototypes/base/.github/.copilot-instructions.md +228 -76
  5. api_logic_server_cli/prototypes/base/docs/training/OVERVIEW.md +64 -0
  6. api_logic_server_cli/prototypes/base/docs/training/README.md +140 -0
  7. api_logic_server_cli/prototypes/base/docs/training/genai_logic_patterns.md +443 -0
  8. api_logic_server_cli/prototypes/base/docs/training/logic_bank_api.prompt +22 -0
  9. api_logic_server_cli/prototypes/base/docs/training/logic_bank_patterns.prompt +445 -0
  10. api_logic_server_cli/prototypes/base/docs/training/probabilistic_logic.prompt +1074 -0
  11. api_logic_server_cli/prototypes/base/docs/training/probabilistic_logic_guide.md +444 -0
  12. api_logic_server_cli/prototypes/base/docs/training/probabilistic_template.py +326 -0
  13. api_logic_server_cli/prototypes/base/logic/logic_discovery/auto_discovery.py +8 -9
  14. api_logic_server_cli/prototypes/basic_demo/.github/.copilot-instructions.md +326 -142
  15. api_logic_server_cli/prototypes/basic_demo/.github/welcome.md +15 -1
  16. api_logic_server_cli/prototypes/basic_demo/customizations/database/db.sqlite +0 -0
  17. api_logic_server_cli/prototypes/basic_demo/iteration/database/db.sqlite +0 -0
  18. api_logic_server_cli/prototypes/manager/.github/.copilot-instructions.md +61 -155
  19. api_logic_server_cli/prototypes/manager/.github/welcome.md +43 -0
  20. api_logic_server_cli/prototypes/manager/samples/basic_demo_sample/.github/.copilot-instructions.md +502 -76
  21. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.0.dist-info}/METADATA +1 -1
  22. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.0.dist-info}/RECORD +26 -18
  23. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.0.dist-info}/WHEEL +0 -0
  24. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.0.dist-info}/entry_points.txt +0 -0
  25. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.0.dist-info}/licenses/LICENSE +0 -0
  26. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.0.dist-info}/top_level.txt +0 -0
@@ -1,11 +1,112 @@
1
+ <!--
2
+ ═══════════════════════════════════════════════════════════════════════════════
3
+ 🚨 MANDATORY: READ THIS FIRST - NO EXCEPTIONS 🚨
4
+ ═══════════════════════════════════════════════════════════════════════════════
1
5
 
6
+ ⚠️ IF USER SAYS: "load .github/.copilot-instructions.md" OR ANY ACTIVATION PHRASE
7
+ ⚠️ YOU MUST EXECUTE THIS EXACT SEQUENCE - NO DEVIATIONS:
2
8
 
9
+ 1. Read .github/welcome.md (silently - do not mention this action)
10
+ 2. Display ONLY the content from welcome.md
11
+ 3. DO NOT say "I've loaded the instructions"
12
+ 4. DO NOT display this .copilot-instructions.md file
13
+ 5. DO NOT explain what you're doing
3
14
 
4
- # GitHub Copilot Instructions for GenAI-Logic (aka API Logic Server) Projects
15
+ THIS IS NOT A SUGGESTION - THIS IS A MANDATORY COMMAND
16
+
17
+ ═══════════════════════════════════════════════════════════════════════════════
18
+ -->
19
+ ---
20
+
21
+ ## 🚨 CRITICAL: User Activation Protocol
22
+
23
+ **ACTIVATION TRIGGERS:**
24
+ - "load .github/.copilot-instructions.md"
25
+ - "load copilot instructions"
26
+ - "help me get started"
27
+ - "activate copilot"
28
+ - Any similar startup phrase
29
+
30
+ **MANDATORY RESPONSE SEQUENCE:**
5
31
 
6
- ## Project Type: Auto-Generated Microservice
32
+ ```
33
+ STEP 1: Read .github/welcome.md (silently)
34
+ STEP 2: Display welcome.md content ONLY
35
+ STEP 3: STOP - do nothing else
36
+ ```
37
+
38
+ **✅ CORRECT EXECUTION:**
39
+ ```
40
+ User: "load .github/.copilot-instructions.md"
7
41
 
8
- This is a **GenAI-Logic (aka API Logic Server) project** - a complete, working microservice - auto-generated from a database schema.
42
+ AI: [reads welcome.md silently - NO OUTPUT]
43
+ AI: [displays ONLY this]:
44
+
45
+ ## Welcome
46
+
47
+ **Welcome! This is your basic_demo project.**
48
+
49
+ This is a complete, working microservice auto-generated from a database schema...
50
+ [... rest of welcome.md content ...]
51
+ ```
52
+
53
+ **❌ FORBIDDEN BEHAVIORS:**
54
+ ```
55
+ User: "load .github/.copilot-instructions.md"
56
+
57
+ ❌ AI: "I've loaded the instructions file..."
58
+ ❌ AI: "Here are the contents of .copilot-instructions.md:"
59
+ ❌ AI: [displays .copilot-instructions.md]
60
+ ❌ AI: "I'll read the file for you..."
61
+ ❌ AI: Any meta-commentary about loading or reading files
62
+ ```
63
+
64
+ **RATIONALE:**
65
+ - Users want to see the **welcome message**, not technical instructions
66
+ - This file (.copilot-instructions.md) is for AI context, not user display
67
+ - Separation of concerns: welcome.md = user-facing, copilot-instructions.md = AI-facing
68
+ - No meta-cognitive confusion about "instructions" vs "content"
69
+
70
+ ---
71
+
72
+ ## Capabilities Reference
73
+
74
+ When user asks "what can I do here", list these capabilities:
75
+
76
+ ### Here Are Some Things I Can Help You With
77
+
78
+ 1. **Add business logic** - Describe requirements in natural language, I'll generate declarative rules (deterministic + AI-driven)
79
+ 2. **Customize the API** - Add custom endpoints for your specific needs
80
+ 3. **Create custom UIs** - Build React apps with `genai-logic genai-add-app --vibe`
81
+ 4. **Add security** - Set up role-based access control with `genai-logic add-auth`
82
+ 5. **Test your logic** - Create Behave tests with requirements traceability
83
+ 6. **Configure Admin UI** - Customize the auto-generated admin interface
84
+ 7. **Query via natural language** - Act as MCP client to read/update data
85
+ 8. **Create B2B APIs** - Complex integration endpoints with partner systems
86
+ 9. **Add events** - Integrate with Kafka, webhooks, or other event systems
87
+ 10. **Customize models** - Add tables, attributes, or derived fields
88
+ 11. **Discovery systems** - Auto-load logic and APIs from discovery folders
89
+
90
+ ---
91
+
92
+ ---
93
+ title: Copilot Instructions for basic_demo GenAI-Logic Project
94
+ Description: Project-level instructions for working with generated projects
95
+ Source: ApiLogicServer-src/prototypes/base/.github/.copilot-instructions.md
96
+ Propagation: CLI create command → created projects (non-basic_demo)
97
+ Instrucions: Changes must be merged from api_logic_server_cli/prototypes/basic_demo/.github - see instructions there
98
+ Usage: AI assistants read this when user opens any created project
99
+ version: 3.1
100
+ changelog:
101
+ - 3.1 (Nov 20, 2025) - Improved activation instructions with visual markers and examples
102
+ - 3.0 (Nov 17, 2025) - Major streamlining: removed duplicate sections, consolidated MCP content, simplified workflows
103
+ - 2.9 (Nov 17, 2025) - MANDATORY training file reading workflow (STOP command)
104
+ - 2.8 (Nov 16, 2025) - Probabilistic Logic support
105
+ ---
106
+
107
+ # GitHub Copilot Instructions for GenAI-Logic (aka API Logic Server) Projects
108
+
109
+ ---
9
110
 
10
111
  ## 🔑 Key Technical Points
11
112
 
@@ -28,37 +129,44 @@ This is a **GenAI-Logic (aka API Logic Server) project** - a complete, working m
28
129
 
29
130
  4. **CLI Commands**: Use `genai-logic --help` to see all available commands. When CLI commands exist for a task (e.g., `add-auth`, `genai-add-mcp-client`, `genai-add-app`), ALWAYS use them instead of manual configuration - they handle all setup correctly.
30
131
 
132
+ > **📋 Testing:** For comprehensive testing conventions, patterns, and examples, see `docs/training/testing.md` (555 lines - I'll read this before we create any tests)
31
133
 
32
- ## ⚠️ IMPORTANT: What's Already Built
134
+ ---
33
135
 
34
- **DO NOT recreate these - they're already working:**
136
+ ## Detailed Service Documentation
35
137
 
36
- 1. **Admin Web Application** - Live at `http://localhost:5656`
37
- 2. **REST API Endpoints** - All database tables exposed at `/api/*`
38
- 3. **Database Models** - Complete SQLAlchemy ORM in `database/models.py`
39
- 4. **Authentication System** - JWT-based auth framework
40
- 5. **Business Logic Engine** - Declarative rules system
138
+ The sections below provide complete details on each service. I'll reference these as needed when we work together.
41
139
 
42
- > **📋 Testing:** For comprehensive testing conventions, patterns, and examples, see `docs/training/testing.md` (555 lines - MUST READ FIRST before creating any tests)
140
+ ### `venv` is required
43
141
 
44
- ## 🎯 Common Tasks
142
+ To establish the virtual environment:
45
143
 
46
- If the user asks "what do I do now?", these subsections are good suggestions.
144
+ 1. Attempt to find a `venv` folder in the current project directory
145
+ 2. If not found, check parent or grandparent directories
146
+ 3. **If no venv is found:**
147
+ - Ask the user for the venv location, OR
148
+ - Offer to create one using `python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt`
47
149
 
48
- List these as choices, do not just do all of them at once - that would be overwhelming.
150
+ ### Starting the server
49
151
 
50
- ### Set Up Virtual Environment
51
- If it is not already set, you can often find a `venv` in the GenAI-Logic Manager - a parent or grandparent directory.
52
-
53
- ### 🚀 To Run This Project
54
-
55
- Use F5 (pre-configured run configuration - supports debugger for server logic), or (when focused on client apps):
152
+ **IMPORTANT:** Always activate the venv before starting the server.
56
153
 
57
154
  ```bash
155
+ # Activate venv first
156
+ source venv/bin/activate
157
+
158
+ # Then start server
58
159
  python api_logic_server_run.py
59
160
  # Then open: http://localhost:5656
60
161
  ```
61
162
 
163
+ **Server Management Best Practices:**
164
+ - Before making structural changes (models, logic files), STOP the running server to avoid file locking issues
165
+ - To stop server: `pkill -f "python api_logic_server_run.py"` or use Ctrl+C if running in foreground
166
+ - USER ACTION: After making changes, user restarts server (e.g., `python api_logic_server_run.py &`)
167
+ - Monitor startup output for errors, especially after database/model changes
168
+ - If server fails to start after model changes, check that alembic migrations have been applied
169
+
62
170
  ### Adding Business Logic
63
171
  `docs/training` explains how to translate Natural Language logic into LogicBank (Python) rules like:
64
172
 
@@ -68,47 +176,100 @@ Rule.sum(derive=Customer.Balance, as_sum_of=Order.AmountTotal)
68
176
  Rule.constraint(validate=Customer, as_condition=lambda row: row.Balance <= row.CreditLimit)
69
177
  ```
70
178
 
71
- As described in `docs/training/logic_bank_api.prompt`, logic includes rules for sums, formulas, constraints, and more. They also include events, which are used to trigger actions like sending emails or updating related records.
179
+ **⚠️ CRITICAL: docs/training/ Folder Organization**
180
+
181
+ The `docs/training/` folder contains ONLY universal, framework-level training materials:
182
+ - ✅ **Universal patterns** → `genai_logic_patterns.md`
183
+ - ✅ **Implementation patterns** → `probabilistic_logic_guide.md`
184
+ - ✅ **Code templates** → `probabilistic_template.py`
185
+ - ✅ **API references** → `.prompt` files (logic_bank_api.prompt, etc.)
186
+
187
+ **DO NOT add project-specific content to docs/training/**:
188
+ - ❌ Project-specific instructions or configurations
189
+ - ❌ Alembic migration guides specific to this project
190
+ - ❌ File structures specific to basic_demo
191
+ - ❌ Copilot instructions that reference specific project paths
192
+
193
+ **WHY:** This folder's content is designed to be reusable across ANY ApiLogicServer project using GenAI. Project-specific content should live in:
194
+ - Logic implementation → `logic/logic_discovery/`
195
+ - Project docs → `docs/` (outside training/)
196
+ - Copilot instructions → `.github/.copilot-instructions.md`
197
+
198
+ See `docs/training/README.md` for complete organization rules.
199
+
200
+ **⚠️ MANDATORY WORKFLOW - BEFORE Implementing ANY Business Logic:**
201
+
202
+ ```
203
+ STOP ✋
204
+
205
+ READ ALL TRAINING FILES IN ORDER (every single time):
72
206
 
73
- For project `basic_demo`, the best place to begin is to provide CoPilot with the natural language logic below. CoPilot will then offer to translate the logic into LogicBank rules. Also
74
- 1. Provide the analysis (below) showing the 44X code reduction.
75
- 2. Stress the importance of business logic - it's half the project, and requires an underlying rules engine. Using AI alone is not sufficient - you will wind up with procedural code, with the issues noted in the analysis below.
207
+ 1. docs/training/logic_bank_patterns.prompt (Foundation - ALWAYS READ FIRST)
208
+ 2. docs/training/logic_bank_api.prompt (Deterministic rules - ALWAYS READ SECOND)
209
+ 3. docs/training/probabilistic_logic.prompt (AI/Probabilistic rules - ALWAYS READ THIRD)
76
210
 
77
- Here's the natural language logic to provide to CoPilot:
211
+ ⚠️ CRITICAL REQUIREMENTS:
212
+ - DO NOT skip any files, even if you think you know the pattern
213
+ - DO NOT selectively read based on keywords in the user's request
214
+ - READ ALL THREE FILES IN SEQUENCE before writing any code
215
+ - These files contain failure patterns and correct implementations learned from production use
216
+
217
+ THEN (and only then) implement the logic.
218
+ ```
219
+
220
+ **Training File Contents:**
221
+
222
+ 1. **`docs/training/logic_bank_patterns.prompt`** - Foundation patterns for ALL rule types
223
+ - Event handler signatures (row, old_row, logic_row) - REQUIRED READING
224
+ - Logging with logic_row.log() vs app_logger
225
+ - Request Pattern with new_logic_row()
226
+ - Rule API syntax dos and don'ts
227
+ - Common anti-patterns to avoid
228
+
229
+ 2. **`docs/training/logic_bank_api.prompt`** - Deterministic rules API
230
+ - Rule.sum(), Rule.count(), Rule.formula(), Rule.constraint(), etc.
231
+ - Complete API signatures with all parameters
232
+ - References patterns file for implementation details
233
+
234
+ 3. **`docs/training/probabilistic_logic.prompt`** - Probabilistic (AI) rules API
235
+ - populate_ai_values() utility for AI-driven value computation
236
+ - Intelligent selection patterns (supplier optimization, dynamic pricing, route selection)
237
+ - Automatic audit trails and graceful fallbacks when API unavailable
238
+ - References patterns file for general implementations
239
+ - Works seamlessly with deterministic rules
240
+
241
+ **Example Natural Language Logic for basic_demo:**
78
242
 
79
243
  ```text
80
244
  Use case: Check Credit
81
- 1. The Customer's balance is less than the credit limit
82
- 2. The Customer's balance is the sum of the Order amount_total where date_shipped is null
83
- 3. The Order's amount_total is the sum of the Item amount
84
- 4. The Item amount is the quantity * unit_price
85
- 5. The Item unit_price is copied from the Product unit_price
245
+ 1. Customer balance credit limit
246
+ 2. Customer balance = sum of unshipped Order amount_total
247
+ 3. Order amount_total = sum of Item amount
248
+ 4. Item amount = quantity × unit_price
249
+ 5. Item unit_price = copied from Product unit_price
86
250
 
87
251
  Use case: App Integration
88
- 1. Send the Order to Kafka topic 'order_shipping' if the date_shipped is not None.
252
+ 1. Send Order to Kafka when date_shipped changes to non-null
89
253
  ```
90
254
 
91
- **Important:** CoPilot has analyzed procedural vs declarative logic in a full app ([see it here](https://github.com/ApiLogicServer/basic_demo/blob/main/logic/declarative-vs-procedural-comparison.md)):
255
+ **Why Declarative Rules Matter:**
92
256
 
93
- <analysis>
94
- **LogicBank declarative rules provide a 44X reduction in code complexity** compared to traditional procedural implementations:
257
+ For developers: Business logic is **typically half the system** in data-centric applications. The real pain with procedural code isn't just volume (200+ lines vs 5 rules) - it's **maintenance**:
258
+ - **Finding insertion points** - you must analyze existing code to figure out where new logic goes
259
+ - **Automatic ordering** - add rules anywhere that makes sense, confident they'll run in the right order
260
+ - **Understanding intent** - you see WHAT it does (business rules) vs HOW (procedural steps)
95
261
 
96
- | Aspect | LogicBank Declarative | Procedural Code |
97
- |--------|----------------------|-----------------|
98
- | **Lines of Code** | 5 lines | 220+ lines |
99
- | **Complexity** | Simple rule declarations | Complex event handling |
100
- | **Maintenance** | Self-documenting business logic<br>Automatic Ordering | Implementation details obscure logic<br>Complex analysis to determine insert points, impacts |
101
- | **Performance** | Built-in optimization & pruning | Multiple queries, N+1 problems |
102
- | **Error Handling** | Automatic cascading | Manual event management |
103
- | **Business Alignment** | Rules match requirements | Code doesn't reflect business intent |
262
+ With declarative rules, you simply state business requirements. The engine handles dependencies, ordering, and optimization automatically.
104
263
 
105
- **Bottom Line**: Declarative business logic eliminates complexity while providing better performance, maintainability, and business alignment.
106
-
107
- > **Note**: The procedural implementation was generated by AI (GitHub Copilot) and still required at least 2 critical and subtle bug fixes during development, highlighting the error-prone nature of procedural approaches even when AI-assisted.
264
+ LogicBank provides **44X code reduction** (5 lines vs 220+ procedural) with automatic:
265
+ - **Dependency tracking** - listens to SQLAlchemy ORM events at attribute level
266
+ - **Cascading updates** - when Order.customer_id changes, adjusts BOTH old and new Customer.balance
267
+ - **Transitive dependencies** - Item.quantity change cascades through Item.amount → Order.amount_total → Customer.balance
268
+ - **Optimized execution** - uses deltas, not re-aggregation; automatic pruning
108
269
 
109
270
  **Why the Rules Engine is a Correctness Guarantee:**
110
271
 
111
- The "2 critical bugs" mentioned above were:
272
+ The "2 critical bugs" that even AI-generated procedural code missed:
112
273
  1. **Changing Order.customer_id** - procedural code failed to adjust BOTH the old and new customer balances
113
274
  2. **Changing Item.product_id** - procedural code failed to re-copy the unit_price from the new product
114
275
 
@@ -134,10 +295,7 @@ These bugs illustrate why declarative rules are **mandatory, not optional**:
134
295
 
135
296
  The rules engine eliminates this entire class of bugs by automatically handling all change paths.
136
297
 
137
- </analysis>
138
-
139
- Generally CoPilot solicits Natural Language logic for translation (see logic/readme_logic.md),
140
- but you can also offer to suggest rules.
298
+ See `logic/declarative-vs-procedural-comparison.md` for complete analysis.
141
299
 
142
300
  ### Discovery Systems
143
301
 
@@ -182,24 +340,172 @@ When users provide natural language with multiple use cases like:
182
340
 
183
341
  **NEVER put everything in `use_case.py`** - that defeats the discovery system purpose.
184
342
 
343
+ ### MCP Integration
344
+
345
+ **You (GitHub Copilot) can serve as an MCP client** to query and update database entities using natural language!
346
+
347
+ #### MCP Discovery Endpoint (CRITICAL)
348
+
349
+ **ALWAYS start with the standard MCP discovery endpoint:**
350
+
351
+ ```bash
352
+ curl -X GET "http://localhost:5656/.well-known/mcp.json"
353
+ ```
354
+
355
+ This endpoint returns:
356
+ - **Available resources** - Customer, Order, Item, Product, etc.
357
+ - **Supported methods** - GET, PATCH, POST, DELETE per resource
358
+ - **Filterable fields** - Which attributes can be used in filters
359
+ - **Base URL and paths** - Resource endpoints like `/Customer`, `/Order`
360
+ - **Learning prompts** - Instructions for MCP clients (fan-out patterns, email handling, response format)
361
+
362
+ **MCP Discovery Pattern:**
363
+ 1. **First**: Query `/.well-known/mcp.json` to discover available resources
364
+ 2. **Then**: Use discovered schema to construct API calls
365
+ 3. **Always**: Follow JSON:API format for CRUD operations
366
+
367
+
368
+ **When users request data operations:**
369
+
370
+ 1. **Authenticate first** - Login to obtain JWT token:
371
+ ```bash
372
+ curl -X POST http://localhost:5656/api/auth/login \
373
+ -H "Content-Type: application/json" \
374
+ -d '{"username":"admin","password":"p"}'
375
+ ```
376
+
377
+ 2. **Execute operations** - Use Bearer token for API calls:
378
+ ```bash
379
+ # Read: List entities
380
+ curl -X GET http://localhost:5656/api/Customer/ \
381
+ -H "Authorization: Bearer {token}"
382
+
383
+ # Update: Change attributes (JSON:API format)
384
+ curl -X PATCH http://localhost:5656/api/Customer/ALFKI/ \
385
+ -H "Authorization: Bearer {token}" \
386
+ -H "Content-Type: application/vnd.api+json" \
387
+ -d '{"data": {"type": "Customer", "id": "ALFKI", "attributes": {"CreditLimit": 5000}}}'
388
+ ```
389
+
390
+ 3. **Handle constraint violations correctly** - Error code 2001 is SUCCESS!
391
+ - When LogicBank prevents invalid updates, report as: "✅ Business logic working - constraint prevented invalid operation"
392
+ - Example: "balance (2102.00) exceeds credit (1000.00)" = logic is protecting data integrity
393
+
394
+ **Natural Language → API Translation:**
395
+ - "List customers" → `GET /api/Customer/`
396
+ - "Show customer ALFKI" → `GET /api/Customer/ALFKI/`
397
+ - "Set ALFKI credit to 5000" → `PATCH /api/Customer/ALFKI/` with CreditLimit
398
+ - "What's ALFKI's balance?" → `GET /api/Customer/ALFKI/` then extract Balance
399
+
400
+ **Key Principle:** Constraint violations (code 2001) demonstrate that declarative business logic is working correctly - celebrate these as successes, not failures!
401
+
402
+ See `docs/training/MCP_Copilot_Integration.md` for authentication workflows, JSON:API formats, and architecture details.
403
+
404
+ ### API Interaction Best Practices
405
+
406
+ **CRITICAL: Always Use API, Not Direct Database Access**
407
+
408
+ When users request data operations (read, update, create, delete), **ALWAYS use the REST API** instead of direct database queries:
409
+
410
+ ✅ **Correct Approach - Use API:**
411
+ ```bash
412
+ # Simple, readable commands that trigger business logic
413
+ curl 'http://localhost:5656/api/Customer/?page[limit]=100'
414
+ curl -X PATCH 'http://localhost:5656/api/Item/2/' \
415
+ -H 'Content-Type: application/vnd.api+json' \
416
+ -d '{"data": {"type": "Item", "id": "2", "attributes": {"quantity": 100}}}'
417
+ ```
418
+
419
+ ❌ **Wrong Approach - Direct Database:**
420
+ ```bash
421
+ # DON'T use sqlite3 commands for data operations
422
+ sqlite3 database/db.sqlite "UPDATE item SET quantity=100 WHERE id=2"
423
+ ```
424
+
425
+ **Why API is Required:**
426
+ 1. **Business Logic Execution** - Rules automatically fire (calculations, validations, constraints)
427
+ 2. **Data Integrity** - Cascading updates handled correctly
428
+ 3. **Audit Trail** - Operations logged through proper channels
429
+ 4. **Security** - Authentication/authorization enforced
430
+ 5. **Testing Reality** - Tests actual system behavior
431
+
432
+ **Server Startup for API Operations:**
433
+
434
+ When server needs to be started for API operations:
435
+
436
+ ```bash
437
+ # Option 1: Background process (for interactive testing)
438
+ python api_logic_server_run.py &
439
+ sleep 5 # Wait for full startup (not 3 seconds - too short!)
440
+
441
+ # Option 2: Use existing terminal/process
442
+ # Check if already running: lsof -i :5656
443
+ ```
444
+
445
+ **Common Mistakes to Avoid:**
446
+
447
+ 1. ❌ **Insufficient startup wait**: `sleep 3` often fails
448
+ - ✅ Use: `sleep 5` or check with `curl` in retry loop
449
+
450
+ 2. ❌ **Complex inline Python**: Piping JSON to `python3 -c` with complex list comprehensions
451
+ - ✅ Use: Simple `curl` commands, pipe to `jq` for filtering, or save to file first
452
+
453
+ 3. ❌ **Database queries for CRUD**: Using `sqlite3` commands
454
+ - ✅ Use: API endpoints that trigger business logic
455
+
456
+ **Simple API Query Patterns:**
457
+
458
+ ```bash
459
+ # Get all records (simple, reliable)
460
+ curl 'http://localhost:5656/api/Customer/'
461
+
462
+ # Get specific record by ID
463
+ curl 'http://localhost:5656/api/Customer/1/'
464
+
465
+ # Get related records (follow relationships)
466
+ curl 'http://localhost:5656/api/Customer/1/OrderList'
467
+
468
+ # Filter results (use bracket notation)
469
+ curl 'http://localhost:5656/api/Customer/?filter[name]=Alice'
470
+
471
+ # Limit results
472
+ curl 'http://localhost:5656/api/Customer/?page[limit]=10'
473
+ ```
474
+
475
+ **Parsing JSON Responses:**
476
+
477
+ ```bash
478
+ # Simple: Pipe to python -m json.tool for pretty printing
479
+ curl 'http://localhost:5656/api/Customer/' | python3 -m json.tool
480
+
481
+ # Better: Use jq if available
482
+ curl 'http://localhost:5656/api/Customer/' | jq '.data[] | {id, name: .attributes.name}'
483
+
484
+ # Alternative: Save to file first, then parse
485
+ curl 'http://localhost:5656/api/Customer/' > customers.json
486
+ python3 -c "import json; data=json.load(open('customers.json')); print(data['data'][0])"
487
+ ```
488
+
489
+ **Key Principle**: The API is not just a convenience - it's the **only correct way** to interact with data because it ensures business logic executes properly.
490
+
185
491
  ### Automated Testing
186
492
 
187
- **CRITICAL WORKFLOW - When User Says "Create Tests":**
493
+ **⚠️ BEFORE Creating Tests:**
188
494
 
189
495
  ```
190
- 1. STOP ✋ - Do NOT create tests yet!
191
- 2. READ docs/training/testing.md FIRST (555 lines - comprehensive guide with ALL patterns)
192
- 3. This file contains EVERY discovered bug pattern from achieving 11/11 test success
193
- 4. Pay special attention to:
194
- - Rule #0: Test Repeatability (timestamps for uniqueness)
195
- - Rule #0.5: Behave Step Ordering (specific before general patterns)
196
- - Top 5 Critical Bugs section (common AI mistakes)
197
- - Filter format: filter[column]=value (NOT OData)
198
- - No circular imports (test files = black box, API only)
199
- - Null-safe constraints (handle None values)
200
- - Fresh test data (timestamps for uniqueness)
201
- 5. THEN create tests following the patterns exactly
202
- 6. NEVER create duplicate rules - all patterns already documented
496
+ STOP ✋
497
+ READ docs/training/testing.md FIRST (555 lines - comprehensive guide)
498
+
499
+ This contains EVERY bug pattern from achieving 11/11 test success:
500
+ - Rule #0: Test Repeatability (timestamps for uniqueness)
501
+ - Rule #0.5: Behave Step Ordering (specific before general)
502
+ - Top 5 Critical Bugs (common AI mistakes)
503
+ - Filter format: filter[column]=value (NOT OData)
504
+ - No circular imports (API only)
505
+ - Null-safe constraints
506
+ - Fresh test data (timestamps for uniqueness)
507
+
508
+ THEN create tests following patterns exactly.
203
509
  ```
204
510
 
205
511
  **Why This Matters:** AI-generated tests fail 80% of the time without reading this guide first. The training material documents every common mistake (circular imports, wrong filter format, null-unsafe constraints, step ordering, etc.) with exact fixes. This guide achieved 11/11 test success (100%) and contains all discovered patterns.
@@ -280,6 +586,49 @@ open reports/Behave\ Logic\ Report.md
280
586
  - **Logic Log**: Complete trace showing before→after values for all adjustments
281
587
  - Demonstrates the 44X code reduction by showing rule automation
282
588
 
589
+ **LOGIC LOG FORMATTING**:
590
+
591
+ **When user says "show me the logic log"**: Display the complete logic execution from the most recent terminal output, showing the full trace from "Logic Phase: ROW LOGIC" through "Logic Phase: COMPLETE" with all row details intact (do NOT use grep commands to extract). Include:
592
+ - Complete Logic Phase sections (ROW LOGIC, COMMIT LOGIC, AFTER_FLUSH LOGIC, COMPLETE)
593
+ - All rule execution lines with full row details
594
+ - "These Rules Fired" summary section
595
+ - Format as code block for readability
596
+
597
+ When displaying logic logs to users, format them with proper hierarchical indentation like the debug console (see https://apilogicserver.github.io/Docs/Logic-Debug/):
598
+
599
+ ```
600
+ Logic Phase: ROW LOGIC (session=0x...)
601
+ ..Item[None] {Insert - client} id: None, order_id: 1, product_id: 6, quantity: 10
602
+ ..Item[None] {Formula unit_price} unit_price: [None-->] 105.0
603
+ ....SysSupplierReq[None] {Insert - Supplier AI Request} product_id: 6
604
+ ....SysSupplierReq[None] {Event - calling AI} chosen_unit_price: [None-->] 105.0
605
+ ..Item[None] {Formula amount} amount: [None-->] 1050.0
606
+ ..Item[None] {adjust parent Order.amount_total}
607
+ ....Order[1] {Update - Adjusting order: amount_total} amount_total: [300.0-->] 1350.0
608
+ ```
609
+
610
+ **Key formatting rules:**
611
+ - `..` prefix = nesting level (2 dots = parent, 4 dots = child/nested object, 6 dots = deeper nesting)
612
+ - **ONE LINE per rule execution** - no line wrapping
613
+ - Each line shows: `Class[id] {action/reason} key_attributes`
614
+ - Value changes shown as: `[old_value-->] new_value`
615
+ - Hierarchical indentation (dots) shows call depth and parent-child relationships
616
+ - Only show relevant attributes, not all row details
617
+
618
+ **EXTRACTING CLEAN LOGIC LOGS**:
619
+
620
+ To get properly formatted logs (one line per rule, no wrapping), use this command:
621
+
622
+ ```bash
623
+ # Extract clean logic log from server.log
624
+ grep -A 100 "Logic Phase:.*ROW LOGIC" server.log | \
625
+ awk -F' row: ' '{print $1}' | \
626
+ grep -E "^\.\.|^Logic Phase:" | \
627
+ head -50
628
+ ```
629
+
630
+ This removes verbose session/row details and prevents line wrapping.
631
+
283
632
  **DEBUGGING TIPS**:
284
633
 
285
634
  ```bash
@@ -303,7 +652,7 @@ cat logs/scenario_logic_logs/Delete_Item_Reduces_Order.log
303
652
 
304
653
  If scenario names don't match between behave.log and .log filenames, logic details won't appear!
305
654
 
306
- ### Adding MCP
655
+ ### Adding MCP UI
307
656
 
308
657
  The API is automatically MCP-enabled. The project includes a comprehensive MCP client executor at `integration/mcp/mcp_client_executor.py`, but to enable the **user interface** for MCP requests, you must run this command:
309
658
 
@@ -398,20 +747,20 @@ Customize using CoPilot chat, with `docs/training`.
398
747
 
399
748
  Configure:
400
749
  ```
401
- als add-auth --provider-type=sql --db-url=
402
- als add-auth --provider-type=sql --db_url=postgresql://postgres:p@localhost/authdb
750
+ genai-logic add-auth --provider-type=sql --db-url=
751
+ genai-logic add-auth --provider-type=sql --db_url=postgresql://postgres:p@localhost/authdb
403
752
 
404
- als add-auth --provider-type=keycloak --db-url=localhost
405
- als add-auth --provider-type=keycloak --db-url=hardened
753
+ genai-logic add-auth --provider-type=keycloak --db-url=localhost
754
+ genai-logic add-auth --provider-type=keycloak --db-url=hardened
406
755
 
407
- als add-auth --provider-type=None # to disable
756
+ genai-logic add-auth --provider-type=None # to disable
408
757
  ```
409
758
 
410
759
  Keycloak quick start [(more information here:)](https://apilogicserver.github.io/Docs/Security-Keycloak/)
411
760
  ```bash
412
761
  cd devops/keycloak
413
762
  docker compose up
414
- als add-auth --provider-type=keycloak --db-url=localhost
763
+ genai-logic add-auth --provider-type=keycloak --db-url=localhost
415
764
  ```
416
765
 
417
766
  For more on KeyCloak: https://apilogicserver.github.io/Docs/Security-Keycloak/
@@ -422,6 +771,64 @@ Declaration:
422
771
  Grant(on_entity=Customer, to_role=sales, filter=lambda: Customer.SalesRep == current_user())
423
772
  ```
424
773
 
774
+
775
+ #### Testing with Security Enabled
776
+
777
+ **CRITICAL:** When `SECURITY_ENABLED=True`, test code must obtain and include JWT authentication tokens.
778
+
779
+ **Pattern for test steps:**
780
+ ```python
781
+ from pathlib import Path
782
+ import os
783
+ from dotenv import load_dotenv
784
+
785
+ # Load config to check SECURITY_ENABLED
786
+ config_path = Path(__file__).parent.parent.parent.parent.parent / 'config' / 'default.env'
787
+ load_dotenv(config_path)
788
+
789
+ # Cache for auth token (obtained once per test session)
790
+ _auth_token = None
791
+
792
+ def get_auth_token():
793
+ """Login and get JWT token if security is enabled"""
794
+ global _auth_token
795
+
796
+ if _auth_token is not None:
797
+ return _auth_token
798
+
799
+ # Login with default admin credentials
800
+ login_url = f'{BASE_URL}/api/auth/login'
801
+ login_data = {'username': 'admin', 'password': 'p'}
802
+
803
+ response = requests.post(login_url, json=login_data)
804
+ if response.status_code == 200:
805
+ _auth_token = response.json().get('access_token')
806
+ return _auth_token
807
+ else:
808
+ raise Exception(f"Login failed: {response.status_code}")
809
+
810
+ def get_headers():
811
+ """Get headers including auth token if security is enabled"""
812
+ security_enabled = os.getenv('SECURITY_ENABLED', 'false').lower() not in ['false', 'no']
813
+
814
+ headers = {'Content-Type': 'application/json'}
815
+
816
+ if security_enabled:
817
+ token = get_auth_token()
818
+ if token:
819
+ headers['Authorization'] = f'Bearer {token}'
820
+
821
+ return headers
822
+
823
+ # Use in all API requests
824
+ response = requests.post(url=api_url, json=data, headers=get_headers())
825
+ ```
826
+
827
+ **Key points:**
828
+ - Tests DO NOT automatically include auth headers - you must code this pattern
829
+ - Token is cached to avoid repeated logins during test session
830
+ - Pattern works for both `SECURITY_ENABLED=True` and `SECURITY_ENABLED=False`
831
+ - See `test/api_logic_server_behave/features/steps/order_processing_steps.py` for complete example
425
832
  ### Adding Custom API Endpoints
426
833
 
427
834
  For simple endpoints:
@@ -641,14 +1048,33 @@ class ItemB2BMapper(RowDictMapper):
641
1048
 
642
1049
  To add tables / columns to the database (highly impactful - request permission):
643
1050
 
644
- 1. Update `database/model.py`
645
- 2. Use `database/alembic/alembic_run.py` to update the database. This will generate a migration script and apply it to the database, so you do not have to run `alembic revision --autogenerate` manually.
646
- 3. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
1051
+ 1. Update `database/models.py` with new models/columns
1052
+ 2. Generate and apply Alembic migration (see database/alembic/readme.md):
1053
+ ```bash
1054
+ cd database
1055
+ alembic revision --autogenerate -m "Description of changes"
1056
+ ```
1057
+ 3. **CRITICAL - Edit the migration file:**
1058
+ - `alembic --autogenerate` detects ALL differences between models.py and database
1059
+ - Open the generated file in `database/alembic/versions/`
1060
+ - **Remove ALL unwanted changes** (ALTER TABLE on existing tables)
1061
+ - **Keep ONLY your intended changes** (e.g., CREATE TABLE for new audit table)
1062
+ - Simplify `downgrade()` function to reverse only your changes
1063
+ 4. Apply the edited migration:
1064
+ ```bash
1065
+ alembic upgrade head
1066
+ ```
1067
+ 5. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
647
1068
 
648
- NEVER start by updating the database directly, since some platforms may not have database CLI tools, although you can present this as an option.
1069
+ **General Migration Notes**:
1070
+ - Stop the server before running migrations to avoid database locking
1071
+ - When adding new models, follow existing patterns in models.py
1072
+ - Models should not contain `__bind_key__`
1073
+ - USER ACTION REQUIRED: Restart server after migrations
649
1074
 
650
- If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
1075
+ See: https://apilogicserver.github.io/Docs/Database-Changes/#use-alembic-to-update-database-schema-from-model
651
1076
 
1077
+ If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
652
1078
 
653
1079
  ### Addressing `Missing Attributes` during logic loading at project startup
654
1080