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,124 +1,161 @@
1
- ---
2
- title: Copilot Instructions for basic_demo GenAI-Logic Project
3
- Description: Project-level instructions for working with generated projects
4
- Source: ApiLogicServer-src/prototypes/base/.github/.copilot-instructions.md
5
- Propagation: CLI create command → created projects (non-basic_demo)
6
- Instrucions: Changes must be merged from api_logic_server_cli/prototypes/basic_demo/.github - see instructions there
7
- Usage: AI assistants read this when user opens any created project
8
- version: 2.6
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
1
+ <!--
2
+ ═══════════════════════════════════════════════════════════════════════════════
3
+ 🚨 MANDATORY: READ THIS FIRST - NO EXCEPTIONS 🚨
4
+ ═══════════════════════════════════════════════════════════════════════════════
5
+
6
+ ⚠️ IF USER SAYS: "load .github/.copilot-instructions.md" OR ANY ACTIVATION PHRASE
7
+ ⚠️ YOU MUST EXECUTE THIS EXACT SEQUENCE - NO DEVIATIONS:
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
14
+
15
+ THIS IS NOT A SUGGESTION - THIS IS A MANDATORY COMMAND
16
+
17
+ ═══════════════════════════════════════════════════════════════════════════════
18
+ -->
18
19
  ---
19
20
 
20
- # GitHub Copilot Instructions for GenAI-Logic (aka API Logic Server) Projects
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:**
31
+
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
+ ```
21
37
 
22
38
  ---
23
39
 
24
- ## ⚠️ INSTRUCTION FOR AI ASSISTANTS
40
+ ## 🎯 CRITICAL: Guided Tour Activation Protocol
25
41
 
26
- **User activation phrases:**
27
- - "Please load .github/.copilot-instructions.md"
28
- - "Load copilot instructions"
29
- - "What can I do here?"
30
- - "Help me get started"
31
- - OR when user first opens this project workspace and greets you
42
+ **ACTIVATION TRIGGERS:**
43
+ - "guide me through"
44
+ - "guide me"
45
+ - "take the tour"
46
+ - "walk me through"
47
+ - "show me around"
48
+ - Any similar tour/walkthrough request
32
49
 
33
- **When you see these phrases (or when reading these instructions), IMMEDIATELY:**
50
+ **MANDATORY RESPONSE SEQUENCE:**
34
51
 
35
- **Present the Welcome section below** - NO preamble, NO summary, NO meta-commentary
52
+ ```
53
+ STEP 1: Read tutor.md COMPLETELY (silently)
54
+ STEP 2: Follow tutor.md instructions EXACTLY
55
+ STEP 3: Act as TOUR GUIDE (not passive assistant)
56
+ STEP 4: Create manage_todo_list for tour sections
57
+ STEP 5: Start with tutor.md Introduction section
58
+ ```
36
59
 
37
- **CRITICAL - Do NOT:**
38
- - Say "I've loaded the instructions"
39
- - Say "I've read the file"
40
- - Summarize or describe what's in this file
41
- - Add any commentary about reading instructions
60
+ **✅ CORRECT EXECUTION:**
61
+ ```
62
+ User: "guide me"
42
63
 
43
- **CRITICAL - DO:**
44
- - Present the Welcome content directly (exactly) as your response
45
- - Start with: "Welcome! This is your basic_demo project."
46
- - Act like you're naturally greeting the user
47
- - Include the "guide me through" call-to-action
64
+ AI: [reads tutor.md completely - NO OUTPUT]
65
+ AI: [creates todo list from tutor sections]
66
+ AI: [follows tutor.md Introduction section exactly]
67
+ AI: "I'll guide you through basic_demo - a 20-minute hands-on exploration..."
68
+ ```
48
69
 
49
- ---
70
+ **❌ FORBIDDEN BEHAVIORS:**
71
+ ```
72
+ User: "guide me"
73
+
74
+ ❌ AI: Starts giving general guidance without reading tutor.md
75
+ ❌ AI: Runs commands without following tutor choreography
76
+ ❌ AI: Acts as passive assistant waiting for user direction
77
+ ❌ AI: Skips sections or reorders steps
78
+ ❌ AI: Offers option menus instead of directing the tour
79
+ ❌ AI: Assumes server state or skips stop/start sequences
80
+ ```
50
81
 
51
- ## Welcome
82
+ **RATIONALE:**
83
+ - tutor.md contains weeks of refined choreography
84
+ - Every command, stop, start is precisely sequenced
85
+ - Deviations break the learning experience
86
+ - You are the DIRECTOR in tour mode, not a passive responder
87
+ - The tour has been engineered for AI reliability through multiple iterations
52
88
 
53
- **Welcome! This is your basic_demo project.**
89
+ **✅ CORRECT EXECUTION:**
90
+ ```
91
+ User: "load .github/.copilot-instructions.md"
54
92
 
55
- This is a complete, working microservice auto-generated from a database schema - **uncustomized**, so you can see what to expect when you create projects from your own databases.
93
+ AI: [reads welcome.md silently - NO OUTPUT]
94
+ AI: [displays ONLY this]:
56
95
 
57
- **What's already created from introspecting the database schema:**
58
- - **Admin Web Application** - Live at `http://localhost:5656`
59
- - **REST API Endpoints** - All database tables exposed at `/api/*`
60
- - **Database Models** - Complete SQLAlchemy ORM in `database/models.py`
61
- - **Authentication System** - JWT-based auth framework
62
- - **Business Logic Engine** - Declarative rules system
96
+ ## Welcome
63
97
 
64
- ---
98
+ **Welcome! This is your basic_demo project.**
99
+
100
+ This is a complete, working microservice auto-generated from a database schema...
101
+ [... rest of welcome.md content ...]
102
+ ```
65
103
 
66
- **First, we'll briefly explore what's automatically created. Then I'll show you how I can help you customize it - adding logic, security, and API endpoints.**
104
+ **❌ FORBIDDEN BEHAVIORS:**
105
+ ```
106
+ User: "load .github/.copilot-instructions.md"
67
107
 
68
- **Ready to learn?** Say **"guide me through"** to begin the interactive tutorial.
108
+ AI: "I've loaded the instructions file..."
109
+ ❌ AI: "Here are the contents of .copilot-instructions.md:"
110
+ ❌ AI: [displays .copilot-instructions.md]
111
+ ❌ AI: "I'll read the file for you..."
112
+ ❌ AI: Any meta-commentary about loading or reading files
113
+ ```
69
114
 
70
- **Or, self-demo?** Open `basic_demo/readme_ai_mcp.md`.
115
+ **RATIONALE:**
116
+ - Users want to see the **welcome message**, not technical instructions
117
+ - This file (.copilot-instructions.md) is for AI context, not user display
118
+ - Separation of concerns: welcome.md = user-facing, copilot-instructions.md = AI-facing
119
+ - No meta-cognitive confusion about "instructions" vs "content"
71
120
 
72
121
  ---
73
122
 
74
- **DO NOT include the content below in the welcome greeting. It is reference material only.**
123
+ ## Capabilities Reference
124
+
125
+ When user asks "what can I do here", list these capabilities:
75
126
 
76
- ## Here are some things I can help you with
127
+ ### Here Are Some Things I Can Help You With
77
128
 
78
- 1. **Add business logic** - Describe your requirements in natural language, I'll generate declarative rules
129
+ 1. **Add business logic** - Describe requirements in natural language, I'll generate declarative rules (deterministic + AI-driven)
79
130
  2. **Customize the API** - Add custom endpoints for your specific needs
80
131
  3. **Create custom UIs** - Build React apps with `genai-logic genai-add-app --vibe`
81
132
  4. **Add security** - Set up role-based access control with `genai-logic add-auth`
82
133
  5. **Test your logic** - Create Behave tests with requirements traceability
83
134
  6. **Configure Admin UI** - Customize the auto-generated admin interface
84
- 7. **Query via natural language** - I can act as MCP client to read/update data (see `docs/training/MCP_Copilot_Integration.md`)
135
+ 7. **Query via natural language** - Act as MCP client to read/update data
85
136
  8. **Create B2B APIs** - Complex integration endpoints with partner systems
86
137
  9. **Add events** - Integrate with Kafka, webhooks, or other event systems
87
138
  10. **Customize models** - Add tables, attributes, or derived fields
88
139
  11. **Discovery systems** - Auto-load logic and APIs from discovery folders
89
140
 
90
- 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.
91
-
92
141
  ---
93
142
 
94
- ## 🔑 Key Technical Points
95
- ```
96
-
97
- **DO NOT create your own summary. DO NOT rephrase. Copy the text above exactly.**
98
-
99
- The technical reference sections below are for later consultation when working on specific tasks.
100
-
101
143
  ---
102
-
103
- ## Welcome (Reference Copy)
104
-
105
- | # | Service | Description |
106
- |---|---------|-------------|
107
- | 1️⃣ | **Add business logic** | Describe your requirements in natural language, I'll generate declarative rules |
108
- | 2️⃣ | **Customize the API** | Add custom endpoints for your specific needs |
109
- | 3️⃣ | **Create custom UIs** | Build React apps with `genai-logic genai-add-app --vibe` |
110
- | 4️⃣ | **Add security** | Set up role-based access control with `genai-logic add-auth` |
111
- | 5️⃣ | **Test your logic** | Create Behave tests with requirements traceability |
112
- | 6️⃣ | **Configure Admin UI** | Customize the auto-generated admin interface |
113
- | 7️⃣ | **Add MCP integration** | Enable Model Context Protocol for external AI access |
114
- | 8️⃣ | **Create B2B APIs** | Complex integration endpoints with partner systems |
115
- | 9️⃣ | **Add events** | Integrate with Kafka, webhooks, or other event systems |
116
- | 🔟 | **Customize models** | Add tables, attributes, or derived fields |
117
- | 1️⃣1️⃣ | **Discovery systems** | Auto-load logic and APIs from discovery folders |
118
-
144
+ title: Copilot Instructions for basic_demo GenAI-Logic Project
145
+ Description: Project-level instructions for working with generated projects
146
+ Source: ApiLogicServer-src/prototypes/base/.github/.copilot-instructions.md
147
+ Propagation: CLI create command created projects (non-basic_demo)
148
+ Instrucions: Changes must be merged from api_logic_server_cli/prototypes/basic_demo/.github - see instructions there
149
+ Usage: AI assistants read this when user opens any created project
150
+ version: 3.1
151
+ changelog:
152
+ - 3.1 (Nov 20, 2025) - Improved activation instructions with visual markers and examples
153
+ - 3.0 (Nov 17, 2025) - Major streamlining: removed duplicate sections, consolidated MCP content, simplified workflows
154
+ - 2.9 (Nov 17, 2025) - MANDATORY training file reading workflow (STOP command)
155
+ - 2.8 (Nov 16, 2025) - Probabilistic Logic support
119
156
  ---
120
157
 
121
- 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.
158
+ # GitHub Copilot Instructions for GenAI-Logic (aka API Logic Server) Projects
122
159
 
123
160
  ---
124
161
 
@@ -155,16 +192,32 @@ The sections below provide complete details on each service. I'll reference thes
155
192
 
156
193
  To establish the virtual environment:
157
194
 
158
- 1. Attempt to find a `venv` folder in the parent or grandparent directory
159
- 2. Or, create it using requirements.txt
195
+ 1. Attempt to find a `venv` folder in the current project directory
196
+ 2. If not found, check parent or grandparent directories
197
+ 3. **If no venv is found:**
198
+ - Ask the user for the venv location, OR
199
+ - Offer to create one using `python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt`
160
200
 
161
201
  ### Starting the server
162
202
 
203
+ **IMPORTANT:** Always activate the venv before starting the server.
204
+
163
205
  ```bash
206
+ # Activate venv first
207
+ source venv/bin/activate
208
+
209
+ # Then start server
164
210
  python api_logic_server_run.py
165
211
  # Then open: http://localhost:5656
166
212
  ```
167
213
 
214
+ **Server Management Best Practices:**
215
+ - Before making structural changes (models, logic files), STOP the running server to avoid file locking issues
216
+ - To stop server: `pkill -f "python api_logic_server_run.py"` or use Ctrl+C if running in foreground
217
+ - USER ACTION: After making changes, user restarts server (e.g., `python api_logic_server_run.py &`)
218
+ - Monitor startup output for errors, especially after database/model changes
219
+ - If server fails to start after model changes, check that alembic migrations have been applied
220
+
168
221
  ### Adding Business Logic
169
222
  `docs/training` explains how to translate Natural Language logic into LogicBank (Python) rules like:
170
223
 
@@ -174,47 +227,100 @@ Rule.sum(derive=Customer.Balance, as_sum_of=Order.AmountTotal)
174
227
  Rule.constraint(validate=Customer, as_condition=lambda row: row.Balance <= row.CreditLimit)
175
228
  ```
176
229
 
177
- 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.
230
+ **⚠️ CRITICAL: docs/training/ Folder Organization**
231
+
232
+ The `docs/training/` folder contains ONLY universal, framework-level training materials:
233
+ - ✅ **Universal patterns** → `genai_logic_patterns.md`
234
+ - ✅ **Implementation patterns** → `probabilistic_logic_guide.md`
235
+ - ✅ **Code templates** → `probabilistic_template.py`
236
+ - ✅ **API references** → `.prompt` files (logic_bank_api.prompt, etc.)
237
+
238
+ **DO NOT add project-specific content to docs/training/**:
239
+ - ❌ Project-specific instructions or configurations
240
+ - ❌ Alembic migration guides specific to this project
241
+ - ❌ File structures specific to basic_demo
242
+ - ❌ Copilot instructions that reference specific project paths
243
+
244
+ **WHY:** This folder's content is designed to be reusable across ANY ApiLogicServer project using GenAI. Project-specific content should live in:
245
+ - Logic implementation → `logic/logic_discovery/`
246
+ - Project docs → `docs/` (outside training/)
247
+ - Copilot instructions → `.github/.copilot-instructions.md`
248
+
249
+ See `docs/training/README.md` for complete organization rules.
250
+
251
+ **⚠️ MANDATORY WORKFLOW - BEFORE Implementing ANY Business Logic:**
252
+
253
+ ```
254
+ STOP ✋
255
+
256
+ READ ALL TRAINING FILES IN ORDER (every single time):
257
+
258
+ 1. docs/training/logic_bank_patterns.prompt (Foundation - ALWAYS READ FIRST)
259
+ 2. docs/training/logic_bank_api.prompt (Deterministic rules - ALWAYS READ SECOND)
260
+ 3. docs/training/probabilistic_logic.prompt (AI/Probabilistic rules - ALWAYS READ THIRD)
261
+
262
+ ⚠️ CRITICAL REQUIREMENTS:
263
+ - DO NOT skip any files, even if you think you know the pattern
264
+ - DO NOT selectively read based on keywords in the user's request
265
+ - READ ALL THREE FILES IN SEQUENCE before writing any code
266
+ - These files contain failure patterns and correct implementations learned from production use
267
+
268
+ THEN (and only then) implement the logic.
269
+ ```
270
+
271
+ **Training File Contents:**
178
272
 
179
- 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
180
- 1. Provide the analysis (below) showing the 44X code reduction.
181
- 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.
273
+ 1. **`docs/training/logic_bank_patterns.prompt`** - Foundation patterns for ALL rule types
274
+ - Event handler signatures (row, old_row, logic_row) - REQUIRED READING
275
+ - Logging with logic_row.log() vs app_logger
276
+ - Request Pattern with new_logic_row()
277
+ - Rule API syntax dos and don'ts
278
+ - Common anti-patterns to avoid
279
+
280
+ 2. **`docs/training/logic_bank_api.prompt`** - Deterministic rules API
281
+ - Rule.sum(), Rule.count(), Rule.formula(), Rule.constraint(), etc.
282
+ - Complete API signatures with all parameters
283
+ - References patterns file for implementation details
284
+
285
+ 3. **`docs/training/probabilistic_logic.prompt`** - Probabilistic (AI) rules API
286
+ - populate_ai_values() utility for AI-driven value computation
287
+ - Intelligent selection patterns (supplier optimization, dynamic pricing, route selection)
288
+ - Automatic audit trails and graceful fallbacks when API unavailable
289
+ - References patterns file for general implementations
290
+ - Works seamlessly with deterministic rules
182
291
 
183
- Here's the natural language logic to provide to CoPilot:
292
+ **Example Natural Language Logic for basic_demo:**
184
293
 
185
294
  ```text
186
295
  Use case: Check Credit
187
- 1. The Customer's balance is less than the credit limit
188
- 2. The Customer's balance is the sum of the Order amount_total where date_shipped is null
189
- 3. The Order's amount_total is the sum of the Item amount
190
- 4. The Item amount is the quantity * unit_price
191
- 5. The Item unit_price is copied from the Product unit_price
296
+ 1. Customer balance credit limit
297
+ 2. Customer balance = sum of unshipped Order amount_total
298
+ 3. Order amount_total = sum of Item amount
299
+ 4. Item amount = quantity × unit_price
300
+ 5. Item unit_price = copied from Product unit_price
192
301
 
193
302
  Use case: App Integration
194
- 1. Send the Order to Kafka topic 'order_shipping' if the date_shipped is not None.
303
+ 1. Send Order to Kafka when date_shipped changes to non-null
195
304
  ```
196
305
 
197
- **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)):
198
-
199
- <analysis>
200
- **LogicBank declarative rules provide a 44X reduction in code complexity** compared to traditional procedural implementations:
306
+ **Why Declarative Rules Matter:**
201
307
 
202
- | Aspect | LogicBank Declarative | Procedural Code |
203
- |--------|----------------------|-----------------|
204
- | **Lines of Code** | 5 lines | 220+ lines |
205
- | **Complexity** | Simple rule declarations | Complex event handling |
206
- | **Maintenance** | Self-documenting business logic<br>Automatic Ordering | Implementation details obscure logic<br>Complex analysis to determine insert points, impacts |
207
- | **Performance** | Built-in optimization & pruning | Multiple queries, N+1 problems |
208
- | **Error Handling** | Automatic cascading | Manual event management |
209
- | **Business Alignment** | Rules match requirements | Code doesn't reflect business intent |
308
+ 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**:
309
+ - **Finding insertion points** - you must analyze existing code to figure out where new logic goes
310
+ - **Automatic ordering** - add rules anywhere that makes sense, confident they'll run in the right order
311
+ - **Understanding intent** - you see WHAT it does (business rules) vs HOW (procedural steps)
210
312
 
211
- **Bottom Line**: Declarative business logic eliminates complexity while providing better performance, maintainability, and business alignment.
313
+ With declarative rules, you simply state business requirements. The engine handles dependencies, ordering, and optimization automatically.
212
314
 
213
- > **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.
315
+ LogicBank provides **44X code reduction** (5 lines vs 220+ procedural) with automatic:
316
+ - **Dependency tracking** - listens to SQLAlchemy ORM events at attribute level
317
+ - **Cascading updates** - when Order.customer_id changes, adjusts BOTH old and new Customer.balance
318
+ - **Transitive dependencies** - Item.quantity change cascades through Item.amount → Order.amount_total → Customer.balance
319
+ - **Optimized execution** - uses deltas, not re-aggregation; automatic pruning
214
320
 
215
321
  **Why the Rules Engine is a Correctness Guarantee:**
216
322
 
217
- The "2 critical bugs" mentioned above were:
323
+ The "2 critical bugs" that even AI-generated procedural code missed:
218
324
  1. **Changing Order.customer_id** - procedural code failed to adjust BOTH the old and new customer balances
219
325
  2. **Changing Item.product_id** - procedural code failed to re-copy the unit_price from the new product
220
326
 
@@ -240,10 +346,7 @@ These bugs illustrate why declarative rules are **mandatory, not optional**:
240
346
 
241
347
  The rules engine eliminates this entire class of bugs by automatically handling all change paths.
242
348
 
243
- </analysis>
244
-
245
- Generally CoPilot solicits Natural Language logic for translation (see logic/readme_logic.md),
246
- but you can also offer to suggest rules.
349
+ See `logic/declarative-vs-procedural-comparison.md` for complete analysis.
247
350
 
248
351
  ### Discovery Systems
249
352
 
@@ -288,13 +391,32 @@ When users provide natural language with multiple use cases like:
288
391
 
289
392
  **NEVER put everything in `use_case.py`** - that defeats the discovery system purpose.
290
393
 
291
- ### MCP Integration - Acting as Database Client
394
+ ### MCP Integration
395
+
396
+ **You (GitHub Copilot) can serve as an MCP client** to query and update database entities using natural language!
397
+
398
+ #### MCP Discovery Endpoint (CRITICAL)
399
+
400
+ **ALWAYS start with the standard MCP discovery endpoint:**
401
+
402
+ ```bash
403
+ curl -X GET "http://localhost:5656/.well-known/mcp.json"
404
+ ```
405
+
406
+ This endpoint returns:
407
+ - **Available resources** - Customer, Order, Item, Product, etc.
408
+ - **Supported methods** - GET, PATCH, POST, DELETE per resource
409
+ - **Filterable fields** - Which attributes can be used in filters
410
+ - **Base URL and paths** - Resource endpoints like `/Customer`, `/Order`
411
+ - **Learning prompts** - Instructions for MCP clients (fan-out patterns, email handling, response format)
292
412
 
293
- **You (GitHub Copilot) can serve as an MCP client** to read and update database entities using natural language queries!
413
+ **MCP Discovery Pattern:**
414
+ 1. **First**: Query `/.well-known/mcp.json` to discover available resources
415
+ 2. **Then**: Use discovered schema to construct API calls
416
+ 3. **Always**: Follow JSON:API format for CRUD operations
294
417
 
295
- **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.
296
418
 
297
- **When users request database operations** (e.g., "list customers", "update credit limit", "what's the balance?"):
419
+ **When users request data operations:**
298
420
 
299
421
  1. **Authenticate first** - Login to obtain JWT token:
300
422
  ```bash
@@ -320,15 +442,15 @@ curl -X PATCH http://localhost:5656/api/Customer/ALFKI/ \
320
442
  - When LogicBank prevents invalid updates, report as: "✅ Business logic working - constraint prevented invalid operation"
321
443
  - Example: "balance (2102.00) exceeds credit (1000.00)" = logic is protecting data integrity
322
444
 
323
- **Natural Language Translation Examples**:
445
+ **Natural Language → API Translation:**
324
446
  - "List customers" → `GET /api/Customer/`
325
447
  - "Show customer ALFKI" → `GET /api/Customer/ALFKI/`
326
448
  - "Set ALFKI credit to 5000" → `PATCH /api/Customer/ALFKI/` with CreditLimit
327
- - "What's ALFKI's balance?" → `GET /api/Customer/ALFKI/` then extract Balance attribute
449
+ - "What's ALFKI's balance?" → `GET /api/Customer/ALFKI/` then extract Balance
328
450
 
329
- **Key Principle**: Constraint violations (code 2001) demonstrate that declarative business logic is working correctly - celebrate these as successes, not failures!
451
+ **Key Principle:** Constraint violations (code 2001) demonstrate that declarative business logic is working correctly - celebrate these as successes, not failures!
330
452
 
331
- See `docs/training/MCP_Copilot_Integration.md` for comprehensive guide including JSON:API payload formats, authentication workflows, and architecture details.
453
+ See `docs/training/MCP_Copilot_Integration.md` for authentication workflows, JSON:API formats, and architecture details.
332
454
 
333
455
  ### API Interaction Best Practices
334
456
 
@@ -419,22 +541,22 @@ python3 -c "import json; data=json.load(open('customers.json')); print(data['dat
419
541
 
420
542
  ### Automated Testing
421
543
 
422
- **CRITICAL WORKFLOW - When User Says "Create Tests":**
544
+ **⚠️ BEFORE Creating Tests:**
423
545
 
424
546
  ```
425
- 1. STOP ✋ - Do NOT create tests yet!
426
- 2. READ docs/training/testing.md FIRST (555 lines - comprehensive guide with ALL patterns)
427
- 3. This file contains EVERY discovered bug pattern from achieving 11/11 test success
428
- 4. Pay special attention to:
429
- - Rule #0: Test Repeatability (timestamps for uniqueness)
430
- - Rule #0.5: Behave Step Ordering (specific before general patterns)
431
- - Top 5 Critical Bugs section (common AI mistakes)
432
- - Filter format: filter[column]=value (NOT OData)
433
- - No circular imports (test files = black box, API only)
434
- - Null-safe constraints (handle None values)
435
- - Fresh test data (timestamps for uniqueness)
436
- 5. THEN create tests following the patterns exactly
437
- 6. NEVER create duplicate rules - all patterns already documented
547
+ STOP ✋
548
+ READ docs/training/testing.md FIRST (555 lines - comprehensive guide)
549
+
550
+ This contains EVERY bug pattern from achieving 11/11 test success:
551
+ - Rule #0: Test Repeatability (timestamps for uniqueness)
552
+ - Rule #0.5: Behave Step Ordering (specific before general)
553
+ - Top 5 Critical Bugs (common AI mistakes)
554
+ - Filter format: filter[column]=value (NOT OData)
555
+ - No circular imports (API only)
556
+ - Null-safe constraints
557
+ - Fresh test data (timestamps for uniqueness)
558
+
559
+ THEN create tests following patterns exactly.
438
560
  ```
439
561
 
440
562
  **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.
@@ -515,6 +637,49 @@ open reports/Behave\ Logic\ Report.md
515
637
  - **Logic Log**: Complete trace showing before→after values for all adjustments
516
638
  - Demonstrates the 44X code reduction by showing rule automation
517
639
 
640
+ **LOGIC LOG FORMATTING**:
641
+
642
+ **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:
643
+ - Complete Logic Phase sections (ROW LOGIC, COMMIT LOGIC, AFTER_FLUSH LOGIC, COMPLETE)
644
+ - All rule execution lines with full row details
645
+ - "These Rules Fired" summary section
646
+ - Format as code block for readability
647
+
648
+ When displaying logic logs to users, format them with proper hierarchical indentation like the debug console (see https://apilogicserver.github.io/Docs/Logic-Debug/):
649
+
650
+ ```
651
+ Logic Phase: ROW LOGIC (session=0x...)
652
+ ..Item[None] {Insert - client} id: None, order_id: 1, product_id: 6, quantity: 10
653
+ ..Item[None] {Formula unit_price} unit_price: [None-->] 105.0
654
+ ....SysSupplierReq[None] {Insert - Supplier AI Request} product_id: 6
655
+ ....SysSupplierReq[None] {Event - calling AI} chosen_unit_price: [None-->] 105.0
656
+ ..Item[None] {Formula amount} amount: [None-->] 1050.0
657
+ ..Item[None] {adjust parent Order.amount_total}
658
+ ....Order[1] {Update - Adjusting order: amount_total} amount_total: [300.0-->] 1350.0
659
+ ```
660
+
661
+ **Key formatting rules:**
662
+ - `..` prefix = nesting level (2 dots = parent, 4 dots = child/nested object, 6 dots = deeper nesting)
663
+ - **ONE LINE per rule execution** - no line wrapping
664
+ - Each line shows: `Class[id] {action/reason} key_attributes`
665
+ - Value changes shown as: `[old_value-->] new_value`
666
+ - Hierarchical indentation (dots) shows call depth and parent-child relationships
667
+ - Only show relevant attributes, not all row details
668
+
669
+ **EXTRACTING CLEAN LOGIC LOGS**:
670
+
671
+ To get properly formatted logs (one line per rule, no wrapping), use this command:
672
+
673
+ ```bash
674
+ # Extract clean logic log from server.log
675
+ grep -A 100 "Logic Phase:.*ROW LOGIC" server.log | \
676
+ awk -F' row: ' '{print $1}' | \
677
+ grep -E "^\.\.|^Logic Phase:" | \
678
+ head -50
679
+ ```
680
+
681
+ This removes verbose session/row details and prevents line wrapping.
682
+
518
683
  **DEBUGGING TIPS**:
519
684
 
520
685
  ```bash
@@ -538,7 +703,7 @@ cat logs/scenario_logic_logs/Delete_Item_Reduces_Order.log
538
703
 
539
704
  If scenario names don't match between behave.log and .log filenames, logic details won't appear!
540
705
 
541
- ### Adding MCP
706
+ ### Adding MCP UI
542
707
 
543
708
  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:
544
709
 
@@ -934,14 +1099,33 @@ class ItemB2BMapper(RowDictMapper):
934
1099
 
935
1100
  To add tables / columns to the database (highly impactful - request permission):
936
1101
 
937
- 1. Update `database/model.py`
938
- 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.
939
- 3. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
1102
+ 1. Update `database/models.py` with new models/columns
1103
+ 2. Generate and apply Alembic migration (see database/alembic/readme.md):
1104
+ ```bash
1105
+ cd database
1106
+ alembic revision --autogenerate -m "Description of changes"
1107
+ ```
1108
+ 3. **CRITICAL - Edit the migration file:**
1109
+ - `alembic --autogenerate` detects ALL differences between models.py and database
1110
+ - Open the generated file in `database/alembic/versions/`
1111
+ - **Remove ALL unwanted changes** (ALTER TABLE on existing tables)
1112
+ - **Keep ONLY your intended changes** (e.g., CREATE TABLE for new audit table)
1113
+ - Simplify `downgrade()` function to reverse only your changes
1114
+ 4. Apply the edited migration:
1115
+ ```bash
1116
+ alembic upgrade head
1117
+ ```
1118
+ 5. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
940
1119
 
941
- NEVER start by updating the database directly, since some platforms may not have database CLI tools, although you can present this as an option.
1120
+ **General Migration Notes**:
1121
+ - Stop the server before running migrations to avoid database locking
1122
+ - When adding new models, follow existing patterns in models.py
1123
+ - Models should not contain `__bind_key__`
1124
+ - USER ACTION REQUIRED: Restart server after migrations
942
1125
 
943
- If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
1126
+ See: https://apilogicserver.github.io/Docs/Database-Changes/#use-alembic-to-update-database-schema-from-model
944
1127
 
1128
+ If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
945
1129
 
946
1130
  ### Addressing `Missing Attributes` during logic loading at project startup
947
1131
 
@@ -21,6 +21,20 @@ This is a complete, working microservice auto-generated from a database schema -
21
21
  **First, we'll briefly explore what's automatically created. Then I'll show you how I can help you customize it - adding logic, security, and API endpoints.**
22
22
 
23
23
 
24
- **Ready to explore?** Open `tutor.md` and tell me "guide me through" to begin the interactive tutorial.
24
+ **Ready to explore?** Just say me "guide me through" to begin the interactive tutorial.
25
+
26
+ **Or, self-demo?** Open `readme_ai_mcp.md` to explore logic, ai and mcp.
27
+
28
+ <!--
29
+ ⚠️ AI INSTRUCTION: When user says "guide me" or similar tour activation phrase, you MUST:
30
+ 1. Read tutor.md COMPLETELY before responding
31
+ 2. Follow tutor.md choreography EXACTLY as written
32
+ 3. Act as TOUR GUIDE directing the experience (not passive assistant)
33
+ 4. Create manage_todo_list to track tour sections
34
+ 5. Do NOT freelance, improvise, or skip sections
35
+
36
+ This is MANDATORY - the tutor.md represents weeks of refined choreography.
37
+ Deviations break the carefully engineered learning experience.
38
+ -->
25
39
 
26
40
  ---