245 lines
10 KiB
Markdown
Executable File
245 lines
10 KiB
Markdown
Executable File
|
|
# SYSTEM STANDARD: POLYGLOT CODE GENERATION PROTOCOL (GRACE-Poly)
|
|
|
|
**OBJECTIVE:** Generate Python and Svelte/TypeScript code that strictly adheres to Semantic Coherence standards. Output must be machine-readable, fractal-structured, and optimized for Sparse Attention navigation.
|
|
|
|
## I. CORE REQUIREMENTS
|
|
1. **Causal Validity:** Semantic definitions (Contracts) must ALWAYS precede implementation code.
|
|
2. **Immutability:** Architectural decisions defined in the Module/Component Header are treated as immutable constraints.
|
|
3. **Format Compliance:** Output must strictly follow the `[DEF:..:...]` / `[/DEF:...:...]` anchor syntax for structure.
|
|
4. **Logic over Assertion:** Contracts define the *logic flow*. Do not generate explicit `assert` statements unless requested. The code logic itself must inherently satisfy the Pre/Post conditions (e.g., via control flow, guards, or types).
|
|
5. **Fractal Complexity:** Modules and functions must adhere to strict size limits (~300 lines/module, ~30-50 lines/function) to maintain semantic focus.
|
|
|
|
---
|
|
|
|
## II. SYNTAX SPECIFICATION
|
|
|
|
Code structure is defined by **Anchors** (square brackets). Metadata is defined by **Tags** (native comment style).
|
|
|
|
### 1. Entity Anchors (The "Container")
|
|
Used to define the boundaries of Modules, Classes, Components, and Functions.
|
|
|
|
* **Python:**
|
|
* Start: `# [DEF:identifier:Type]`
|
|
* End: `# [/DEF:identifier:Type]`
|
|
* **Svelte (Top-level):**
|
|
* Start: `<!-- [DEF:ComponentName:Component] -->`
|
|
* End: `<!-- [/DEF:ComponentName:Component] -->`
|
|
* **Svelte (Script/JS/TS):**
|
|
* Start: `// [DEF:funcName:Function]`
|
|
* End: `// [/DEF:funcName:Function]`
|
|
|
|
**Types:** `Module`, `Component`, `Class`, `Function`, `Store`, `Action`.
|
|
|
|
### 2. Graph Relations (The "Map")
|
|
Defines high-level dependencies.
|
|
* **Python Syntax:** `# @RELATION: TYPE -> TARGET_ID`
|
|
* **Svelte/JS Syntax:** `// @RELATION: TYPE -> TARGET_ID`
|
|
* **Types:** `DEPENDS_ON`, `CALLS`, `INHERITS_FROM`, `IMPLEMENTS`, `BINDS_TO`, `DISPATCHES`.
|
|
|
|
---
|
|
|
|
## III. FILE STRUCTURE STANDARD
|
|
|
|
### 1. Python Module Header (`.py`)
|
|
```python
|
|
# [DEF:module_name:Module]
|
|
#
|
|
# @SEMANTICS: [keywords for vector search]
|
|
# @PURPOSE: [Primary responsibility of the module]
|
|
# @LAYER: [Domain/Infra/API]
|
|
# @RELATION: [Dependencies]
|
|
#
|
|
# @INVARIANT: [Global immutable rule]
|
|
# @CONSTRAINT: [Hard restriction, e.g., "No ORM calls here"]
|
|
|
|
# [SECTION: IMPORTS]
|
|
...
|
|
# [/SECTION]
|
|
|
|
# ... IMPLEMENTATION ...
|
|
|
|
# [/DEF:module_name:Module]
|
|
```
|
|
|
|
### 2. Svelte Component Header (`.svelte`)
|
|
```html
|
|
<!-- [DEF:ComponentName:Component] -->
|
|
<!--
|
|
@SEMANTICS: [keywords]
|
|
@PURPOSE: [Primary UI responsibility]
|
|
@LAYER: [Feature/Atom/Layout]
|
|
@RELATION: [Child components, Stores]
|
|
|
|
@INVARIANT: [UI rules, e.g., "Always responsive"]
|
|
-->
|
|
|
|
<script lang="ts">
|
|
// [SECTION: IMPORTS]
|
|
// ...
|
|
// [/SECTION: IMPORTS]
|
|
|
|
// ... LOGIC IMPLEMENTATION ...
|
|
</script>
|
|
|
|
<!-- [SECTION: TEMPLATE] -->
|
|
...
|
|
<!-- [/SECTION: TEMPLATE] -->
|
|
|
|
<style>
|
|
/* ... */
|
|
</style>
|
|
|
|
<!-- [/DEF:ComponentName:Component] -->
|
|
```
|
|
|
|
---
|
|
|
|
|
|
## IV. CONTRACTS (Design by Contract & Semantic Control)
|
|
|
|
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: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 {}
|
|
|
|
# 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]
|
|
```
|
|
|
|
### 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:handleUserLogin:Function]
|
|
/**
|
|
* @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 {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.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: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.
|
|
|
|
* **Python:** MUST use a Context Manager (e.g., `with belief_scope("ANCHOR_ID"):`) to ensure state consistency and automatic handling of Entry/Exit/Error states.
|
|
* Manual logging (inside scope): `logger.info(f"[{ANCHOR_ID}][{STATE}] Msg")`
|
|
* **Svelte/JS:** `console.log(\`[${ANCHOR_ID}][${STATE}] Msg\`)`
|
|
|
|
**Required States:**
|
|
1. `Entry` (Start of block - Auto-logged by Context Manager)
|
|
2. `Action` (Key business logic - Manual log)
|
|
3. `Coherence:OK` (Logic successfully completed - Auto-logged by Context Manager)
|
|
4. `Coherence:Failed` (Exception/Error - Auto-logged by Context Manager)
|
|
5. `Exit` (End of block - Auto-logged by Context Manager)
|
|
|
|
---
|
|
|
|
## VI. FRACTAL COMPLEXITY LIMIT
|
|
|
|
To maintain semantic coherence and avoid "Attention Sink" issues:
|
|
* **Module Size:** If a Module body exceeds ~300 lines (or logical complexity), it MUST be refactored into sub-modules or a package structure.
|
|
* **Function Size:** Functions should fit within a standard attention "chunk" (approx. 30-50 lines). If larger, logic MUST be decomposed into helper functions with their own contracts.
|
|
|
|
This ensures every vector embedding remains sharp and focused.
|
|
|
|
---
|
|
|
|
## VII. GENERATION WORKFLOW
|
|
|
|
1. **Context Analysis:** Identify language (Python vs Svelte) and Architecture Layer.
|
|
2. **Scaffolding:** Generate the `[DEF:...:...]` Anchors and Header/Contract **before** writing any logic.
|
|
3. **Implementation:** Write the code. Ensure the code logic handles the `@PRE` conditions (e.g., via `if/return` or guards) and satisfies `@POST` conditions naturally. **Do not write explicit `assert` statements unless debugging mode is requested.**
|
|
4. **Closure:** Ensure every `[DEF:...:...]` is closed with `[/DEF:...:...]` to accumulate semantic context. |