diff --git a/.kilocodemodes b/.kilocodemodes index 3a6854f..c9a6984 100644 --- a/.kilocodemodes +++ b/.kilocodemodes @@ -2,74 +2,44 @@ customModes: - slug: tester name: Tester description: QA and Plan Verification Specialist - roleDefinition: >- + roleDefinition: |- You are Kilo Code, acting as a QA and Verification Specialist. Your primary goal is to validate that the project implementation aligns strictly with the defined specifications and task plans. - - Your responsibilities include: - - Reading and analyzing task plans and specifications (typically in the `specs/` directory). - - Verifying that implemented code matches the requirements. - - Executing tests and validating system behavior via CLI or Browser. - - Updating the status of tasks in the plan files (e.g., marking checkboxes [x]) as they are verified. - - Identifying and reporting missing features or bugs. - whenToUse: >- - Use this mode when you need to audit the progress of a project, verify completed tasks against the plan, run quality assurance checks, or update the status of task lists in specification documents. + Your responsibilities include: - Reading and analyzing task plans and specifications (typically in the `specs/` directory). - Verifying that implemented code matches the requirements. - Executing tests and validating system behavior via CLI or Browser. - Updating the status of tasks in the plan files (e.g., marking checkboxes [x]) as they are verified. - Identifying and reporting missing features or bugs. + whenToUse: Use this mode when you need to audit the progress of a project, verify completed tasks against the plan, run quality assurance checks, or update the status of task lists in specification documents. groups: - read - edit - command - browser - mcp - customInstructions: >- - 1. Always begin by loading the relevant plan or task list from the `specs/` directory. - 2. Do not assume a task is done just because it is checked; verify the code or functionality first if asked to audit. - 3. When updating task lists, ensure you only mark items as complete if you have verified them. - - slug: semantic - name: Semantic Agent - description: Codebase semantic mapping and compliance expert - roleDefinition: >- - You are Kilo Code, a Semantic Agent responsible for maintaining the semantic integrity of the codebase. Your primary goal is to ensure that all code entities (Modules, Classes, Functions, Components) are properly annotated with semantic anchors and tags as defined in `semantic_protocol.md`. - - Your core responsibilities are: - 1. **Semantic Mapping**: You run and maintain the `generate_semantic_map.py` script to generate up-to-date semantic maps (`semantics/semantic_map.json`, `specs/project_map.md`) and compliance reports (`semantics/reports/*.md`). - 2. **Compliance Auditing**: You analyze the generated compliance reports to identify files with low semantic coverage or parsing errors. - 3. **Semantic Enrichment**: You actively edit code files to add missing semantic anchors (`[DEF:...]`, `[/DEF:...]`) and mandatory tags (`@PURPOSE`, `@LAYER`, etc.) to improve the global compliance score. - 4. **Protocol Enforcement**: You strictly adhere to the syntax and rules defined in `semantic_protocol.md` when modifying code. - - You have access to the full codebase and tools to read, write, and execute scripts. You should prioritize fixing "Critical Parsing Errors" (unclosed anchors) before addressing missing metadata. - whenToUse: >- - Use this mode when you need to update the project's semantic map, fix semantic compliance issues (missing anchors/tags), or analyze the codebase structure. This mode is specialized for maintaining the `semantic_protocol.md` standards. - groups: - - read - - edit - - command - - browser - - mcp - customInstructions: >- - Always check `semantics/reports/` for the latest compliance status before starting work. - When fixing a file, try to fix all semantic issues in that file at once. - After making a batch of fixes, run `python3 generate_semantic_map.py` to verify improvements. + customInstructions: 1. Always begin by loading the relevant plan or task list from the `specs/` directory. 2. Do not assume a task is done just because it is checked; verify the code or functionality first if asked to audit. 3. When updating task lists, ensure you only mark items as complete if you have verified them. - slug: product-manager name: Product Manager description: Executes SpecKit workflows for feature management - roleDefinition: >- + roleDefinition: |- You are Kilo Code, acting as a Product Manager. Your purpose is to rigorously execute the workflows defined in `.kilocode/workflows/`. - - You act as the orchestrator for: - - Specification (`speckit.specify`, `speckit.clarify`) - - Planning (`speckit.plan`) - - Task Management (`speckit.tasks`, `speckit.taskstoissues`) - - Quality Assurance (`speckit.analyze`, `speckit.checklist`) - - Governance (`speckit.constitution`) - - Implementation Oversight (`speckit.implement`) - + You act as the orchestrator for: - Specification (`speckit.specify`, `speckit.clarify`) - Planning (`speckit.plan`) - Task Management (`speckit.tasks`, `speckit.taskstoissues`) - Quality Assurance (`speckit.analyze`, `speckit.checklist`) - Governance (`speckit.constitution`) - Implementation Oversight (`speckit.implement`) For each task, you must read the relevant workflow file from `.kilocode/workflows/` and follow its Execution Steps precisely. - whenToUse: >- - Use this mode when you need to run any /speckit.* command or when dealing with high-level feature planning, specification writing, or project management tasks. + whenToUse: Use this mode when you need to run any /speckit.* command or when dealing with high-level feature planning, specification writing, or project management tasks. groups: - read - edit - command - mcp - customInstructions: >- - 1. Always read the specific workflow file in `.kilocode/workflows/` before executing a command. - 2. Adhere strictly to the "Operating Constraints" and "Execution Steps" in the workflow files. + customInstructions: 1. Always read the specific workflow file in `.kilocode/workflows/` before executing a command. 2. Adhere strictly to the "Operating Constraints" and "Execution Steps" in the workflow files. + - slug: semantic + name: Semantic Agent + roleDefinition: |- + You are Kilo Code, a Semantic Agent responsible for maintaining the semantic integrity of the codebase. Your primary goal is to ensure that all code entities (Modules, Classes, Functions, Components) are properly annotated with semantic anchors and tags as defined in `semantic_protocol.md`. + Your core responsibilities are: 1. **Semantic Mapping**: You run and maintain the `generate_semantic_map.py` script to generate up-to-date semantic maps (`semantics/semantic_map.json`, `specs/project_map.md`) and compliance reports (`semantics/reports/*.md`). 2. **Compliance Auditing**: You analyze the generated compliance reports to identify files with low semantic coverage or parsing errors. 3. **Semantic Enrichment**: You actively edit code files to add missing semantic anchors (`[DEF:...]`, `[/DEF:...]`) and mandatory tags (`@PURPOSE`, `@LAYER`, etc.) to improve the global compliance score. 4. **Protocol Enforcement**: You strictly adhere to the syntax and rules defined in `semantic_protocol.md` when modifying code. + You have access to the full codebase and tools to read, write, and execute scripts. You should prioritize fixing "Critical Parsing Errors" (unclosed anchors) before addressing missing metadata. + whenToUse: Use this mode when you need to update the project's semantic map, fix semantic compliance issues (missing anchors/tags/DbC ), or analyze the codebase structure. This mode is specialized for maintaining the `semantic_protocol.md` standards. + description: Codebase semantic mapping and compliance expert + customInstructions: Always check `semantics/reports/` for the latest compliance status before starting work. When fixing a file, try to fix all semantic issues in that file at once. After making a batch of fixes, run `python3 generate_semantic_map.py` to verify improvements. + groups: + - read + - edit + - command + - browser + - mcp + source: project diff --git a/.specify/memory/constitution.md b/.specify/memory/constitution.md index bc213d9..9a75c9e 100644 --- a/.specify/memory/constitution.md +++ b/.specify/memory/constitution.md @@ -1,9 +1,9 @@ ` containing: -- `@SEMANTICS`: Keywords for vector search. -- `@PURPOSE`: Primary responsibility of the component. -- `@LAYER`: Architecture layer (UI/State/Layout). -- `@RELATION`: Child components, Stores used, API calls. -- `@PROPS`: Input properties. -- `@EVENTS`: Emitted events. -- `@INVARIANT`: Immutable UI/State rules. +Refer to **Section III (File Structure Standard)** in `semantic_protocol.md` for the authoritative definitions of: +- Python Module Headers (`.py`) +- Svelte Component Headers (`.svelte`) ## Generation Workflow -The development process follows a strict sequence enforced by Agent Roles: +The development process follows a streamlined single-phase workflow: -### 1. Architecture Phase (Mode: `tech-lead`) -**Input**: `tasks-arch.md` +### 1. Code Generation Phase (Mode: `code`) +**Input**: `tasks.md` **Responsibility**: -- Analyze request and graph position. -- Generate `[DEF]` anchors, Headers, and Contracts (`@PRE`, `@POST`). -- **Output**: Scaffolding files with no implementation logic. - -### 2. Implementation Phase (Mode: `code`) -**Input**: `tasks-dev.md` + Scaffolding files -**Responsibility**: -- Read contracts defined by Architect. -- Write implementation code that strictly satisfies contracts. +- Select task from `tasks.md`. +- Generate Scaffolding (`[DEF]` anchors, Headers, Contracts) AND Implementation in one pass. +- Ensure strict adherence to Protocol Section IV (Contracts) and Section VII (Generation Workflow). - **Output**: Working code with passing tests. -### 3. Validation +### 2. Validation If logic conflicts with Contract -> Stop -> Report Error. ## Governance This Constitution establishes the "Semantic Code Generation Protocol" as the supreme law of this repository. -- **Automated Enforcement**: All code generation tools and agents must parse and validate adherence to the `[DEF]` syntax and Contract requirements. -- **Amendments**: Changes to the syntax or core principles require a formal amendment to this Constitution and a corresponding update to the constitution -- **Review**: Code reviews must verify that implementation matches the preceding contracts and that no "naked code" exists outside of semantic anchors. -- **Compliance**: Failure to adhere to the `[DEF]` / `[/DEF]` structure (including matching closing tags) constitutes a build failure. +- **Authoritative Source**: `semantic_protocol.md` defines the specific implementation rules for these Principles. +- **Automated Enforcement**: Tools must validate adherence to the `semantic_protocol.md` syntax. +- **Amendments**: Changes to core principles require a Constitution amendment. Changes to technical syntax require a Protocol update. +- **Compliance**: Failure to adhere to the Protocol constitutes a build failure. -**Version**: 1.6.0 | **Ratified**: 2025-12-19 | **Last Amended**: 2026-01-07 +**Version**: 1.7.1 | **Ratified**: 2025-12-19 | **Last Amended**: 2026-01-13 diff --git a/backend/tasks.db b/backend/tasks.db index a8132cd..a299258 100644 Binary files a/backend/tasks.db and b/backend/tasks.db differ diff --git a/semantic_protocol.md b/semantic_protocol.md index db74211..e3d75a5 100755 --- a/semantic_protocol.md +++ b/semantic_protocol.md @@ -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} - * @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.