constitution update

This commit is contained in:
2026-01-13 15:29:42 +03:00
parent ae1d630ad6
commit b2529973eb
4 changed files with 152 additions and 157 deletions

View File

@@ -1,8 +1,3 @@
Here is the revised **System Standard**, adapted for a Polyglot environment (Python Backend + Svelte Frontend) and removing the requirement for explicit assertion generation.
This protocol standardizes the "Semantic Bridge" between the two languages using unified Anchor logic while respecting the native documentation standards (Comments for Python, JSDoc for JavaScript/Svelte).
***
# SYSTEM STANDARD: POLYGLOT CODE GENERATION PROTOCOL (GRACE-Poly)
@@ -100,57 +95,121 @@ Defines high-level dependencies.
---
## IV. CONTRACTS (Design by Contract)
Contracts define *what* the code does before *how* it does it.
## IV. CONTRACTS (Design by Contract & Semantic Control)
### 1. Python Contract Style
Uses comment blocks inside the anchor.
Contracts are the **Source of Truth** and the **Control Vector** for the code. They must be written with high **semantic density** to ensure the LLM fully "understands" the function's role within the larger Graph without needing to read the implementation body.
### 1. The Anatomy of a Semantic Contract
Every contract must answer three questions for the AI Agent:
1. **Intent:** *Why* does this exist? (Vector alignment)
2. **Boundaries:** *What* are the constraints? (Pre/Post/Invariants)
3. **Dynamics:** *How* does it change the system state? (Side Effects/Graph)
#### Standard Tags Taxonomy:
* `@PURPOSE`: (**Mandatory**) A concise, high-entropy summary of functionality.
* `@PRE`: (**Mandatory**) Conditions required *before* execution. Defines the valid input space.
* `@POST`: (**Mandatory**) Conditions guaranteed *after* execution. Defines the valid output space.
* `@PARAM`: Input definitions with strict typing.
* `@RETURN`: Output definition.
* `@THROW`: Explicit failure modes.
* `@SIDE_EFFECT`: (**Critical**) Explicitly lists external state mutations (DB writes, UI updates, events). Vital for "Mental Modeling".
* `@INVARIANT`: (**Optional**) Local rules that hold true throughout the function execution.
* `@ALGORITHM`: (**Optional**) For complex logic, briefly describes the strategy (e.g., "Two-pointer approach", "Retry with exponential backoff").
* `@RELATION`: (**Graph**) Edges to other nodes (`CALLS`, `DISPATCHES`, `DEPENDS_ON`).
---
### 2. Python Contract Style (`.py`)
Uses structured comment blocks inside the anchor. Focuses on type hints and logic flow guards.
```python
# [DEF:calculate_total:Function]
# @PURPOSE: Calculates cart total including tax.
# @PRE: items list is not empty.
# @POST: returns non-negative Decimal.
# @PARAM: items (List[Item]) - Cart items.
# @RETURN: Decimal - Final total.
def calculate_total(items: List[Item]) -> Decimal:
# Logic implementation that respects @PRE
if not items:
return Decimal(0)
# ... calculation ...
# [DEF:process_order_batch:Function]
# @PURPOSE: Orchestrates the validation and processing of a batch of orders.
# Ensures atomic processing per order (failure of one does not stop others).
#
# @PRE: batch_id must be a valid UUID string.
# @PRE: orders list must not be empty.
# @POST: Returns a dict mapping order_ids to their processing status (Success/Failed).
# @INVARIANT: The length of the returned dict must equal the length of input orders.
#
# @PARAM: batch_id (str) - The unique identifier for the batch trace.
# @PARAM: orders (List[OrderDTO]) - List of immutable order objects.
# @RETURN: Dict[str, OrderStatus] - Result map.
#
# @SIDE_EFFECT: Writes audit logs to DB.
# @SIDE_EFFECT: Publishes 'ORDER_PROCESSED' event to MessageBus.
#
# @RELATION: CALLS -> InventoryService.reserve_items
# @RELATION: CALLS -> PaymentGateway.authorize
# @RELATION: WRITES_TO -> Database.AuditLog
def process_order_batch(batch_id: str, orders: List[OrderDTO]) -> Dict[str, OrderStatus]:
# 1. Structural Guard Logic (Handling @PRE)
if not orders:
return {}
# Logic ensuring @POST
return total
# [/DEF:calculate_total:Function]
# 2. Implementation with @INVARIANT in mind
results = {}
for order in orders:
# ... logic ...
pass
# 3. Completion (Logic naturally satisfies @POST)
return results
# [/DEF:process_order_batch:Function]
```
### 2. Svelte/JS Contract Style (JSDoc)
Uses JSDoc blocks inside the anchor. Standard JSDoc tags are used where possible; custom GRACE tags are added for strictness.
### 3. Svelte/JS Contract Style (JSDoc++)
Uses enhanced JSDoc. Since JS is less strict than Python, the contract acts as a strict typing and behavioral guard.
```javascript
// [DEF:updateUserProfile:Function]
// [DEF:handleUserLogin:Function]
/**
* @purpose Updates user data in the store and backend.
* @pre User must be authenticated (session token exists).
* @post UserStore is updated with new data.
* @param {Object} profileData - The new profile fields.
* @purpose Authenticates the user and synchronizes the local UI state.
* Handles the complete lifecycle from form submission to redirection.
*
* @pre LoginForm must be valid (validated by UI constraints).
* @pre Network must be available (optimistic check).
* @post SessionStore contains a valid JWT token.
* @post User is redirected to the Dashboard.
*
* @param {LoginCredentials} credentials - Email and password object.
* @returns {Promise<void>}
* @throws {AuthError} If session is invalid.
* @throws {NetworkError} If API is unreachable.
* @throws {AuthError} If credentials are invalid (401).
*
* @side_effect Updates global $session store.
* @side_effect Clears any existing error toasts.
*
* @algorithm 1. Set loading state -> 2. API Call -> 3. Decode Token -> 4. Update Store -> 5. Redirect.
*/
// @RELATION: CALLS -> api.user.update
async function updateUserProfile(profileData) {
// Logic implementation
if (!session.token) throw new AuthError();
// ...
// @RELATION: CALLS -> api.auth.login
// @RELATION: MODIFIES_STATE_OF -> stores.session
// @RELATION: DISPATCHES -> 'toast:success'
async function handleUserLogin(credentials) {
// 1. Guard Clause (@PRE)
if (!isValid(credentials)) return;
try {
// ... logic ...
} catch (e) {
// Error handling (@THROW)
}
}
// [/DEF:updateUserProfile:Function]
// [/DEF:handleUserLogin:Function]
```
---
### 4. Semantic Rules for Contracts
1. **Completeness:** A developer (or Agent) must be able to write the function body *solely* by reading the Contract, without guessing.
2. **No Implementation Leakage:** Describe *what* happens, not *how* (unless using `@ALGORITHM` for complexity reasons). E.g., say "Persists user" instead of "Inserts into users table via SQL".
3. **Active Voice:** Use active verbs (`Calculates`, `Updates`, `Enforces`) to stronger vector alignment.
4. **Graph Connectivity:** The `@RELATION` tags must explicitly link to other `[DEF:...]` IDs existing in the codebase. This builds the navigation graph for RAG.
---
## V. LOGGING STANDARD (BELIEF STATE)
Logs delineate the agent's internal state.