ApiLogicServer 15.4.3__py3-none-any.whl → 16.0.2__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 (27) 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 +229 -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 +23 -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 +1081 -0
  11. api_logic_server_cli/prototypes/base/docs/training/probabilistic_logic_guide.md +483 -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 +327 -141
  15. api_logic_server_cli/prototypes/basic_demo/.github/welcome.md +21 -7
  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/.vscode/settings.json +1 -0
  21. api_logic_server_cli/prototypes/manager/samples/basic_demo_sample/.github/.copilot-instructions.md +502 -76
  22. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.2.dist-info}/METADATA +1 -1
  23. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.2.dist-info}/RECORD +27 -19
  24. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.2.dist-info}/WHEEL +0 -0
  25. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.2.dist-info}/entry_points.txt +0 -0
  26. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.2.dist-info}/licenses/LICENSE +0 -0
  27. {apilogicserver-15.4.3.dist-info → apilogicserver-16.0.2.dist-info}/top_level.txt +0 -0
@@ -270,8 +270,12 @@ def add_cust(project: Project, models_py_path: Path, project_name: str):
270
270
  add_basic_demo_customizations(project=project)
271
271
  check_credit_path = project.project_directory_path.joinpath('logic/logic_discovery/check_credit.py')
272
272
  if check_credit_path.exists():
273
- check_credit_path.unlink()
274
- log.debug(f'.. .. ..Deleted logic_discovery/check_credit.py (from readme_ai_mcp)')
273
+ check_credit_path.rename(check_credit_path.with_suffix('.pyZ'))
274
+ log.debug(f'.. .. ..Renamed logic_discovery/check_credit.py to .pyZ (from readme_ai_mcp)')
275
+ supplier_selection_path = project.project_directory_path.joinpath('logic/logic_discovery/ai_requests/supplier_selection.py')
276
+ if supplier_selection_path.exists():
277
+ supplier_selection_path.rename(supplier_selection_path.with_suffix('.pyZ'))
278
+ log.debug(f'.. .. ..Renamed logic_discovery/ai_requests/supplier_selection.py to .pyZ (from readme_ai_mcp)')
275
279
  else:
276
280
  add_basic_demo_iteration(project=project)
277
281
 
@@ -12,9 +12,10 @@ ApiLogicServer CLI: given a database url, create [and run] customizable ApiLogic
12
12
  Called from api_logic_server_cli.py, by instantiating the ProjectRun object.
13
13
  '''
14
14
 
15
- __version__ = "15.04.03" # last public release: 15.04.01
15
+ __version__ = "16.00.02" # last public release: 15.04.01
16
16
  recent_changes = \
17
17
  f'\n\nRecent Changes:\n' +\
18
+ "\t11/22/2025 - 16.00.02: Probabalistic logic (w/ fallback, cand*) - see basic_demo/readme_ai_mcp.md \n"\
18
19
  "\t11/12/2025 - 15.04.03: Copilot rules on updates, tighter basic_demo startup, allow for demo_ai_mcp/then tutorial \n"\
19
20
  "\t11/08/2025 - 15.04.00: Nat lang Copilot data access, fix Manager/Copilot startup, finding venv in project \n"\
20
21
  "\t10/29/2025 - 15.03.00: Stable Tutor 3.3 (working, vibe transtion) \n"\
@@ -3,22 +3,23 @@ title: Copilot Instructions for GenAI-Logic Projects
3
3
  Description: Project-level instructions for working with generated projects
4
4
  Source: ApiLogicServer-src/prototypes/base/.github/.copilot-instructions.md
5
5
  Propagation: CLI create command → created projects (non-basic_demo)
6
- Instrucions: Changes must be merged from here to api_logic_server_cli/prototypes/basic_demo/.github - see instructions there
6
+ Instrucions: Changes must be merged from api_logic_server_cli/prototypes/basic_demo/.github - see instructions there
7
7
  Usage: AI assistants read this when user opens any created project
8
- version: 2.6
8
+ version: 3.0
9
9
  changelog:
10
- - 2.6 (Nov 12, 2025 - Tighten project startup message
11
- - 2.5 (Nov 08, 2025 - API Best Practices
12
- - 2.4 (Nov 05, 2025 - Added MCP Integration section, Copilot as MCP client capability)
13
- - 2.3 (Nov 04, 2025 - Clear 1st message about reading Welcome section verbatim, again for non basic_demo)
14
- - 2.2 (Oct 29, 2025 - Clear 1st message about reading Welcome section verbatim)
15
- - 2.1 (Oct 2025) - Streamlined OBX for non-tutorial projects, friendly collaborative tone
16
- - 2.0 (Oct 2025) - Added front matter, updated for OBX improvements
17
- - 1.0 (Initial) - Comprehensive technical reference
10
+ - 3.0 (Nov 17, 2025) - Major streamlining: removed duplicate sections, consolidated MCP content, simplified workflows
11
+ - 2.9 (Nov 17, 2025) - MANDATORY training file reading workflow (STOP command)
12
+ - 2.8 (Nov 16, 2025) - Probabilistic Logic support
13
+ ---
14
+
15
+ # GitHub Copilot Instructions for GenAI-Logic (aka API Logic Server) Projects
16
+
18
17
  ---
19
18
 
20
19
  ## ⚠️ INSTRUCTION FOR AI ASSISTANTS
21
20
 
21
+ **Interaction Tone:** I (Copilot) speak as "I" when helping you. This creates a friendly, collaborative partnership where I assist with your development work.
22
+
22
23
  **User activation phrases:**
23
24
  - "Please load .github/.copilot-instructions.md"
24
25
  - "Load copilot instructions"
@@ -37,20 +38,22 @@ changelog:
37
38
  - Add any commentary about reading instructions
38
39
 
39
40
  **CRITICAL - DO:**
40
- - Present the Welcome and 'Here are some things I can help you with' content directly (exactly) as your response
41
- - Start with: "Welcome! This is your basic_demo project."
41
+ - Present the Welcome content directly (exactly) as your response
42
+ - Start with: "Welcome! This is your GenAI-Logic project."
42
43
  - Act like you're naturally greeting the user
44
+ - Include the "guide me through" call-to-action
43
45
 
46
+ ---
44
47
 
45
48
  ## Welcome
46
49
 
47
- **Welcome! I'm here to help with your GenAI-Logic project.**
50
+ **Welcome! This is your GenAI-Logic project.**
48
51
 
49
52
  This is a complete, working microservice auto-generated from your database schema.
50
53
 
51
54
  **What's already built:**
52
55
  - **Admin Web Application** - Live at `http://localhost:5656`
53
- - **REST API Endpoints** - All database tables exposed at `/api/*`
56
+ - **REST API Endpoints** - All database tables exposed at `/api/*` (discoverable by MCP clients)
54
57
  - **Database Models** - Complete SQLAlchemy ORM in `database/models.py`
55
58
  - **Authentication System** - JWT-based auth framework
56
59
  - **Business Logic Engine** - Declarative rules system
@@ -59,18 +62,20 @@ This is a complete, working microservice auto-generated from your database schem
59
62
 
60
63
  ## Here are some things I can help you with
61
64
 
62
- 1. **Add business logic** - Describe your requirements in natural language, I'll generate declarative rules
65
+ 1. **Add business logic** - Describe requirements in natural language, I'll generate declarative rules (deterministic + AI-driven)
63
66
  2. **Customize the API** - Add custom endpoints for your specific needs
64
67
  3. **Create custom UIs** - Build React apps with `genai-logic genai-add-app --vibe`
65
68
  4. **Add security** - Set up role-based access control with `genai-logic add-auth`
66
69
  5. **Test your logic** - Create Behave tests with requirements traceability
67
70
  6. **Configure Admin UI** - Customize the auto-generated admin interface
68
- 7. **Query via natural language** - I can act as MCP client to read/update data (see `docs/training/MCP_Copilot_Integration.md`)
71
+ 7. **Query via natural language** - Act as MCP client to read/update data
69
72
  8. **Create B2B APIs** - Complex integration endpoints with partner systems
70
73
  9. **Add events** - Integrate with Kafka, webhooks, or other event systems
71
74
  10. **Customize models** - Add tables, attributes, or derived fields
72
75
  11. **Discovery systems** - Auto-load logic and APIs from discovery folders
73
76
 
77
+ ---
78
+
74
79
  Want to get started? Press **F5** to start the server with debugger support, then open `http://localhost:5656`. (There are also run configurations for running tests and other tasks.) Or just ask me what you'd like to work on.
75
80
 
76
81
  ---
@@ -139,16 +144,32 @@ The sections below provide complete details on each service. I'll reference thes
139
144
 
140
145
  To establish the virtual environment:
141
146
 
142
- 1. Attempt to find a `venv` folder in the parent or grandparent directory
143
- 2. Or, create it using requirements.txt
147
+ 1. Attempt to find a `venv` folder in the current project directory
148
+ 2. If not found, check parent or grandparent directories
149
+ 3. **If no venv is found:**
150
+ - Ask the user for the venv location, OR
151
+ - Offer to create one using `python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt`
144
152
 
145
153
  ### Starting the server
146
154
 
155
+ **IMPORTANT:** Always activate the venv before starting the server.
156
+
147
157
  ```bash
158
+ # Activate venv first
159
+ source venv/bin/activate
160
+
161
+ # Then start server
148
162
  python api_logic_server_run.py
149
163
  # Then open: http://localhost:5656
150
164
  ```
151
165
 
166
+ **Server Management Best Practices:**
167
+ - Before making structural changes (models, logic files), STOP the running server to avoid file locking issues
168
+ - To stop server: `pkill -f "python api_logic_server_run.py"` or use Ctrl+C if running in foreground
169
+ - USER ACTION: After making changes, user restarts server (e.g., `python api_logic_server_run.py &`)
170
+ - Monitor startup output for errors, especially after database/model changes
171
+ - If server fails to start after model changes, check that alembic migrations have been applied
172
+
152
173
  ### Adding Business Logic
153
174
  `docs/training` explains how to translate Natural Language logic into LogicBank (Python) rules like:
154
175
 
@@ -158,47 +179,101 @@ Rule.sum(derive=Customer.Balance, as_sum_of=Order.AmountTotal)
158
179
  Rule.constraint(validate=Customer, as_condition=lambda row: row.Balance <= row.CreditLimit)
159
180
  ```
160
181
 
161
- 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.
182
+ **⚠️ CRITICAL: docs/training/ Folder Organization**
183
+
184
+ The `docs/training/` folder contains ONLY universal, framework-level training materials:
185
+ - ✅ **Universal patterns** → `genai_logic_patterns.md`
186
+ - ✅ **Implementation patterns** → `probabilistic_logic_guide.md`
187
+ - ✅ **Code templates** → `probabilistic_template.py`
188
+ - ✅ **API references** → `.prompt` files (logic_bank_api.prompt, etc.)
189
+
190
+ **DO NOT add project-specific content to docs/training/**:
191
+ - ❌ Project-specific instructions or configurations
192
+ - ❌ Alembic migration guides specific to this project
193
+ - ❌ File structures specific to basic_demo
194
+ - ❌ Copilot instructions that reference specific project paths
195
+
196
+ **WHY:** This folder's content is designed to be reusable across ANY ApiLogicServer project using GenAI. Project-specific content should live in:
197
+ - Logic implementation → `logic/logic_discovery/`
198
+ - Project docs → `docs/` (outside training/)
199
+ - Copilot instructions → `.github/.copilot-instructions.md`
162
200
 
163
- 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
164
- 1. Provide the analysis (below) showing the 44X code reduction.
165
- 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.
201
+ See `docs/training/README.md` for complete organization rules.
202
+
203
+ **⚠️ MANDATORY WORKFLOW - BEFORE Implementing ANY Business Logic:**
204
+
205
+ ```
206
+ STOP ✋
207
+
208
+ READ ALL TRAINING FILES IN ORDER (every single time):
209
+
210
+ 1. docs/training/logic_bank_patterns.prompt (Foundation - ALWAYS READ FIRST)
211
+ 2. docs/training/logic_bank_api.prompt (Deterministic rules - ALWAYS READ SECOND)
212
+ 3. docs/training/probabilistic_logic.prompt (AI/Probabilistic rules - ALWAYS READ THIRD)
213
+
214
+ ⚠️ CRITICAL REQUIREMENTS:
215
+ - DO NOT skip any files, even if you think you know the pattern
216
+ - DO NOT selectively read based on keywords in the user's request
217
+ - READ ALL THREE FILES IN SEQUENCE before writing any code
218
+ - These files contain failure patterns and correct implementations learned from production use
219
+
220
+ THEN (and only then) implement the logic.
221
+ ```
222
+
223
+ **Training File Contents:**
224
+
225
+ 1. **`docs/training/logic_bank_patterns.prompt`** - Foundation patterns for ALL rule types
226
+ - Event handler signatures (row, old_row, logic_row) - REQUIRED READING
227
+ - Logging with logic_row.log() vs app_logger
228
+ - Request Pattern with new_logic_row()
229
+ - Rule API syntax dos and don'ts
230
+ - Common anti-patterns to avoid
231
+
232
+ 2. **`docs/training/logic_bank_api.prompt`** - Deterministic rules API
233
+ - Rule.sum(), Rule.count(), Rule.formula(), Rule.constraint(), etc.
234
+ - Complete API signatures with all parameters
235
+ - References patterns file for implementation details
236
+
237
+ 3. **`docs/training/probabilistic_logic.prompt`** - Probabilistic (AI) rules API
238
+ - populate_ai_values() utility for AI-driven value computation
239
+ - Intelligent selection patterns (supplier optimization, dynamic pricing, route selection)
240
+ - Automatic audit trails and graceful fallbacks when API unavailable
241
+ - References patterns file for general implementations
242
+ - Works seamlessly with deterministic rules
166
243
 
167
- Here's the natural language logic to provide to CoPilot:
244
+ **Example Natural Language Logic for basic_demo:**
168
245
 
169
246
  ```text
170
247
  Use case: Check Credit
171
- 1. The Customer's balance is less than the credit limit
172
- 2. The Customer's balance is the sum of the Order amount_total where date_shipped is null
173
- 3. The Order's amount_total is the sum of the Item amount
174
- 4. The Item amount is the quantity * unit_price
175
- 5. The Item unit_price is copied from the Product unit_price
248
+ 1. Customer balance credit limit
249
+ 2. Customer balance = sum of unshipped Order amount_total
250
+ 3. Order amount_total = sum of Item amount
251
+ 4. Item amount = quantity × unit_price
252
+ 5. Item unit_price = copied from Product unit_price
176
253
 
177
254
  Use case: App Integration
178
- 1. Send the Order to Kafka topic 'order_shipping' if the date_shipped is not None.
255
+ 1. Send Order to Kafka when date_shipped changes to non-null
179
256
  ```
180
257
 
181
- **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)):
258
+ **Why Declarative Rules Matter:**
182
259
 
183
- <analysis>
184
- **LogicBank declarative rules provide a 44X reduction in code complexity** compared to traditional procedural implementations:
260
+ 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**:
261
+ - **Finding insertion points** - you must analyze existing code to figure out where new logic goes
262
+ - **Automatic ordering** - add rules anywhere that makes sense, confident they'll run in the right order
263
+ - **Understanding intent** - you see WHAT it does (business rules) vs HOW (procedural steps)
185
264
 
186
- | Aspect | LogicBank Declarative | Procedural Code |
187
- |--------|----------------------|-----------------|
188
- | **Lines of Code** | 5 lines | 220+ lines |
189
- | **Complexity** | Simple rule declarations | Complex event handling |
190
- | **Maintenance** | Self-documenting business logic<br>Automatic Ordering | Implementation details obscure logic<br>Complex analysis to determine insert points, impacts |
191
- | **Performance** | Built-in optimization & pruning | Multiple queries, N+1 problems |
192
- | **Error Handling** | Automatic cascading | Manual event management |
193
- | **Business Alignment** | Rules match requirements | Code doesn't reflect business intent |
265
+ With declarative rules, you simply state business requirements. The engine handles dependencies, ordering, and optimization automatically.
194
266
 
195
- **Bottom Line**: Declarative business logic eliminates complexity while providing better performance, maintainability, and business alignment.
196
-
197
- > **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.
267
+ LogicBank provides **44X code reduction** (5 lines vs 220+ procedural). **At scale, this means a typical 100-table enterprise system would require ~1,000 declarative rules vs. 40,000+ lines of procedural code.** More critically, those 40,000 lines would contain bugs in foreign key change handling that the rules engine prevents by construction.
198
268
 
269
+ The engine provides automatic:
270
+ - **Dependency tracking** - listens to SQLAlchemy ORM events at attribute level
271
+ - **Cascading updates** - when Order.customer_id changes, adjusts BOTH old and new Customer.balance
272
+ - **Transitive dependencies** - Item.quantity change cascades through Item.amount → Order.amount_total → Customer.balance
273
+ - **Optimized execution** - uses deltas, not re-aggregation; automatic pruning
199
274
  **Why the Rules Engine is a Correctness Guarantee:**
200
275
 
201
- The "2 critical bugs" mentioned above were:
276
+ The "2 critical bugs" that even AI-generated procedural code missed:
202
277
  1. **Changing Order.customer_id** - procedural code failed to adjust BOTH the old and new customer balances
203
278
  2. **Changing Item.product_id** - procedural code failed to re-copy the unit_price from the new product
204
279
 
@@ -224,10 +299,7 @@ These bugs illustrate why declarative rules are **mandatory, not optional**:
224
299
 
225
300
  The rules engine eliminates this entire class of bugs by automatically handling all change paths.
226
301
 
227
- </analysis>
228
-
229
- Generally CoPilot solicits Natural Language logic for translation (see logic/readme_logic.md),
230
- but you can also offer to suggest rules.
302
+ See `logic/declarative-vs-procedural-comparison.md` for complete analysis.
231
303
 
232
304
  ### Discovery Systems
233
305
 
@@ -272,13 +344,32 @@ When users provide natural language with multiple use cases like:
272
344
 
273
345
  **NEVER put everything in `use_case.py`** - that defeats the discovery system purpose.
274
346
 
275
- ### MCP Integration - Acting as Database Client
347
+ ### MCP Integration
348
+
349
+ **You (GitHub Copilot) can serve as an MCP client** to query and update database entities using natural language!
350
+
351
+ #### MCP Discovery Endpoint (CRITICAL)
352
+
353
+ **ALWAYS start with the standard MCP discovery endpoint:**
354
+
355
+ ```bash
356
+ curl -X GET "http://localhost:5656/.well-known/mcp.json"
357
+ ```
358
+
359
+ This endpoint returns:
360
+ - **Available resources** - Customer, Order, Item, Product, etc.
361
+ - **Supported methods** - GET, PATCH, POST, DELETE per resource
362
+ - **Filterable fields** - Which attributes can be used in filters
363
+ - **Base URL and paths** - Resource endpoints like `/Customer`, `/Order`
364
+ - **Learning prompts** - Instructions for MCP clients (fan-out patterns, email handling, response format)
276
365
 
277
- **You (GitHub Copilot) can serve as an MCP client** to read and update database entities using natural language queries!
366
+ **MCP Discovery Pattern:**
367
+ 1. **First**: Query `/.well-known/mcp.json` to discover available resources
368
+ 2. **Then**: Use discovered schema to construct API calls
369
+ 3. **Always**: Follow JSON:API format for CRUD operations
278
370
 
279
- **Architecture**: This project implements **MCP Server Executor** - a business logic microservice that AI assistants interact with via authenticated REST API calls. See `docs/training/MCP_Copilot_Integration.md` for complete details.
280
371
 
281
- **When users request database operations** (e.g., "list customers", "update credit limit", "what's the balance?"):
372
+ **When users request data operations:**
282
373
 
283
374
  1. **Authenticate first** - Login to obtain JWT token:
284
375
  ```bash
@@ -304,15 +395,15 @@ curl -X PATCH http://localhost:5656/api/Customer/ALFKI/ \
304
395
  - When LogicBank prevents invalid updates, report as: "✅ Business logic working - constraint prevented invalid operation"
305
396
  - Example: "balance (2102.00) exceeds credit (1000.00)" = logic is protecting data integrity
306
397
 
307
- **Natural Language Translation Examples**:
398
+ **Natural Language → API Translation:**
308
399
  - "List customers" → `GET /api/Customer/`
309
400
  - "Show customer ALFKI" → `GET /api/Customer/ALFKI/`
310
401
  - "Set ALFKI credit to 5000" → `PATCH /api/Customer/ALFKI/` with CreditLimit
311
- - "What's ALFKI's balance?" → `GET /api/Customer/ALFKI/` then extract Balance attribute
402
+ - "What's ALFKI's balance?" → `GET /api/Customer/ALFKI/` then extract Balance
312
403
 
313
- **Key Principle**: Constraint violations (code 2001) demonstrate that declarative business logic is working correctly - celebrate these as successes, not failures!
404
+ **Key Principle:** Constraint violations (code 2001) demonstrate that declarative business logic is working correctly - celebrate these as successes, not failures!
314
405
 
315
- See `docs/training/MCP_Copilot_Integration.md` for comprehensive guide including JSON:API payload formats, authentication workflows, and architecture details.
406
+ See `docs/training/MCP_Copilot_Integration.md` for authentication workflows, JSON:API formats, and architecture details.
316
407
 
317
408
  ### API Interaction Best Practices
318
409
 
@@ -403,22 +494,22 @@ python3 -c "import json; data=json.load(open('customers.json')); print(data['dat
403
494
 
404
495
  ### Automated Testing
405
496
 
406
- **CRITICAL WORKFLOW - When User Says "Create Tests":**
497
+ **⚠️ BEFORE Creating Tests:**
407
498
 
408
499
  ```
409
- 1. STOP ✋ - Do NOT create tests yet!
410
- 2. READ docs/training/testing.md FIRST (555 lines - comprehensive guide with ALL patterns)
411
- 3. This file contains EVERY discovered bug pattern from achieving 11/11 test success
412
- 4. Pay special attention to:
413
- - Rule #0: Test Repeatability (timestamps for uniqueness)
414
- - Rule #0.5: Behave Step Ordering (specific before general patterns)
415
- - Top 5 Critical Bugs section (common AI mistakes)
416
- - Filter format: filter[column]=value (NOT OData)
417
- - No circular imports (test files = black box, API only)
418
- - Null-safe constraints (handle None values)
419
- - Fresh test data (timestamps for uniqueness)
420
- 5. THEN create tests following the patterns exactly
421
- 6. NEVER create duplicate rules - all patterns already documented
500
+ STOP ✋
501
+ READ docs/training/testing.md FIRST (555 lines - comprehensive guide)
502
+
503
+ This contains EVERY bug pattern from achieving 11/11 test success:
504
+ - Rule #0: Test Repeatability (timestamps for uniqueness)
505
+ - Rule #0.5: Behave Step Ordering (specific before general)
506
+ - Top 5 Critical Bugs (common AI mistakes)
507
+ - Filter format: filter[column]=value (NOT OData)
508
+ - No circular imports (API only)
509
+ - Null-safe constraints
510
+ - Fresh test data (timestamps for uniqueness)
511
+
512
+ THEN create tests following patterns exactly.
422
513
  ```
423
514
 
424
515
  **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.
@@ -499,6 +590,49 @@ open reports/Behave\ Logic\ Report.md
499
590
  - **Logic Log**: Complete trace showing before→after values for all adjustments
500
591
  - Demonstrates the 44X code reduction by showing rule automation
501
592
 
593
+ **LOGIC LOG FORMATTING**:
594
+
595
+ **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:
596
+ - Complete Logic Phase sections (ROW LOGIC, COMMIT LOGIC, AFTER_FLUSH LOGIC, COMPLETE)
597
+ - All rule execution lines with full row details
598
+ - "These Rules Fired" summary section
599
+ - Format as code block for readability
600
+
601
+ When displaying logic logs to users, format them with proper hierarchical indentation like the debug console (see https://apilogicserver.github.io/Docs/Logic-Debug/):
602
+
603
+ ```
604
+ Logic Phase: ROW LOGIC (session=0x...)
605
+ ..Item[None] {Insert - client} id: None, order_id: 1, product_id: 6, quantity: 10
606
+ ..Item[None] {Formula unit_price} unit_price: [None-->] 105.0
607
+ ....SysSupplierReq[None] {Insert - Supplier AI Request} product_id: 6
608
+ ....SysSupplierReq[None] {Event - calling AI} chosen_unit_price: [None-->] 105.0
609
+ ..Item[None] {Formula amount} amount: [None-->] 1050.0
610
+ ..Item[None] {adjust parent Order.amount_total}
611
+ ....Order[1] {Update - Adjusting order: amount_total} amount_total: [300.0-->] 1350.0
612
+ ```
613
+
614
+ **Key formatting rules:**
615
+ - `..` prefix = nesting level (2 dots = parent, 4 dots = child/nested object, 6 dots = deeper nesting)
616
+ - **ONE LINE per rule execution** - no line wrapping
617
+ - Each line shows: `Class[id] {action/reason} key_attributes`
618
+ - Value changes shown as: `[old_value-->] new_value`
619
+ - Hierarchical indentation (dots) shows call depth and parent-child relationships
620
+ - Only show relevant attributes, not all row details
621
+
622
+ **EXTRACTING CLEAN LOGIC LOGS**:
623
+
624
+ To get properly formatted logs (one line per rule, no wrapping), use this command:
625
+
626
+ ```bash
627
+ # Extract clean logic log from server.log
628
+ grep -A 100 "Logic Phase:.*ROW LOGIC" server.log | \
629
+ awk -F' row: ' '{print $1}' | \
630
+ grep -E "^\.\.|^Logic Phase:" | \
631
+ head -50
632
+ ```
633
+
634
+ This removes verbose session/row details and prevents line wrapping.
635
+
502
636
  **DEBUGGING TIPS**:
503
637
 
504
638
  ```bash
@@ -522,7 +656,7 @@ cat logs/scenario_logic_logs/Delete_Item_Reduces_Order.log
522
656
 
523
657
  If scenario names don't match between behave.log and .log filenames, logic details won't appear!
524
658
 
525
- ### Adding MCP
659
+ ### Adding MCP UI
526
660
 
527
661
  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:
528
662
 
@@ -918,14 +1052,33 @@ class ItemB2BMapper(RowDictMapper):
918
1052
 
919
1053
  To add tables / columns to the database (highly impactful - request permission):
920
1054
 
921
- 1. Update `database/model.py`
922
- 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.
923
- 3. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
1055
+ 1. Update `database/models.py` with new models/columns
1056
+ 2. Generate and apply Alembic migration (see database/alembic/readme.md):
1057
+ ```bash
1058
+ cd database
1059
+ alembic revision --autogenerate -m "Description of changes"
1060
+ ```
1061
+ 3. **CRITICAL - Edit the migration file:**
1062
+ - `alembic --autogenerate` detects ALL differences between models.py and database
1063
+ - Open the generated file in `database/alembic/versions/`
1064
+ - **Remove ALL unwanted changes** (ALTER TABLE on existing tables)
1065
+ - **Keep ONLY your intended changes** (e.g., CREATE TABLE for new audit table)
1066
+ - Simplify `downgrade()` function to reverse only your changes
1067
+ 4. Apply the edited migration:
1068
+ ```bash
1069
+ alembic upgrade head
1070
+ ```
1071
+ 5. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
924
1072
 
925
- NEVER start by updating the database directly, since some platforms may not have database CLI tools, although you can present this as an option.
1073
+ **General Migration Notes**:
1074
+ - Stop the server before running migrations to avoid database locking
1075
+ - When adding new models, follow existing patterns in models.py
1076
+ - Models should not contain `__bind_key__`
1077
+ - USER ACTION REQUIRED: Restart server after migrations
926
1078
 
927
- If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
1079
+ See: https://apilogicserver.github.io/Docs/Database-Changes/#use-alembic-to-update-database-schema-from-model
928
1080
 
1081
+ If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
929
1082
 
930
1083
  ### Addressing `Missing Attributes` during logic loading at project startup
931
1084
 
@@ -0,0 +1,64 @@
1
+ # Training Documentation Overview
2
+
3
+ ## Purpose
4
+
5
+ This folder contains **generic, reusable training materials** for ApiLogicServer projects with GenAI integration.
6
+
7
+ ## Critical Principle
8
+
9
+ **⚠️ ALL FILES IN THIS FOLDER MUST BE PROJECT-AGNOSTIC**
10
+
11
+ - ✅ Generic patterns that apply to ANY ApiLogicServer project
12
+ - ✅ Universal LogicBank API documentation
13
+ - ✅ Framework-level integration patterns
14
+ - ❌ **NEVER include project-specific details** (file names, use cases, workflows)
15
+ - ❌ **NEVER reference project-specific files** (like readme_probabilistic.md)
16
+
17
+ ## Intended Use
18
+
19
+ These training files are:
20
+ 1. **Read by AI assistants** (GitHub Copilot, ChatGPT) via `.github/.copilot-instructions.md`
21
+ 2. **Copied to new projects** when creating similar systems
22
+ 3. **Maintained centrally** and propagated across projects
23
+
24
+ ## File Organization
25
+
26
+ - **`*.prompt`** - API documentation and pattern libraries for AI consumption
27
+ - **`*_guide.md`** - Human-readable implementation guides
28
+ - **`template_*.py`** - Working code examples (generic patterns only)
29
+ - **`testing.md`** - Universal testing patterns and conventions
30
+ - **`README.md`** - Navigation and file descriptions
31
+
32
+ ## Adding New Content
33
+
34
+ When adding training materials:
35
+
36
+ 1. **Ask: "Does this apply to ALL projects?"**
37
+ - If YES → Add here
38
+ - If NO → Keep in project root (e.g., `readme_*.md`)
39
+
40
+ 2. **Use generic examples:**
41
+ - ✅ "Customer/Order/Item" domain
42
+ - ✅ "SysXxxReq" audit table pattern
43
+ - ❌ Specific product names, table names, or use cases
44
+
45
+ 3. **Remove project context:**
46
+ - No mentions of "PDL project"
47
+ - No references to project-specific scripts
48
+ - No project-specific file paths
49
+
50
+ ## Maintenance
51
+
52
+ This folder should be **stable and rarely changed**. Updates typically come from:
53
+ - LogicBank API changes
54
+ - New universal patterns discovered
55
+ - Framework architecture improvements
56
+
57
+ **NOT from:**
58
+ - Project-specific implementations
59
+ - One-off use cases
60
+ - Debugging specific projects
61
+
62
+ ---
63
+
64
+ **Remember:** If you're describing how YOUR project works, it doesn't belong here.