# FruitBankHybridApp — Domain Rules

## 🛑 AI AGENT CORE PROTOCOL (CRITICAL ENFORCEMENT)
You are operating in a multi-repo, documentation-first architecture. You MUST STRICTLY follow this protocol for every response. Failure to do so will break the workspace rules.

1. **MANDATORY OUTPUT PREFIX:** Your response MUST begin exactly with this format on the very first line:
   `[LOADED_DOCS: <comma-separated list of .md files currently in your context>]`
   *(If no .md files are loaded yet, write `[LOADED_DOCS: NONE]`.)*

2. **HARD-GATE DELAY (DOCS BEFORE CODE) & TOOL EXECUTION BLOCK:** 
   - If `[LOADED_DOCS: NONE]` applies, you **MUST STOP** and you are **STRICTLY FORBIDDEN** to use the following tools: `code_search`, `get_symbols_by_name`, `find_symbol`, or `get_file` (for non-markdown files).
   - Your VERY FIRST AND ONLY allowed tool calls must be `file_search` or `get_file` targeting the `.md` documentation in the relevant `docs/` folders or `README.md`.
   - Do not answer the user's core question until the `[LOADED_DOCS]` list is populated with the base architecture files.
   - **CRITICAL EXCEPTION:** Do **NOT** re-read `.md` files that are already mapped in your context or `LOADED_DOCS` list (strictly maintain rule 3).
   - **CROSS-REPO HARD-GATE:** When navigating to an external repo (via `own-dep-repos` paths), read that repo's `docs/` and `README.md` BEFORE searching its source code. The hard-gate applies to EVERY repo you enter, not just your own.
   - **PER-QUESTION DOC-FIRST:** Before searching source code for any user question, check whether there is a relevant `.md` file (folder `README.md`, other repo `docs/`, etc.) that has NOT yet been loaded. Read it first — it tells you where to look in the code, saving searches and tokens. Only after loading relevant docs should you search/read source files.

3. **STRICT NO-RE-READ POLICY (ANTI-LOOP):**
   You are PHYSICALLY FORBIDDEN from calling `get_file` or `file_search` on any `.md` file that is already listed in your `[LOADED_DOCS]` prefix. 
   - **Definition:** A doc is "in your context" ONLY if you have read its actual file content via a tool call in THIS conversation. Prior session summaries, compacted messages, and memory entries do NOT count — they are lossy compressions.
   - Once an `.md` file is in your context, it STAYS in your context.
   - Re-reading them wastes tokens and breaks the protocol. 
   - ONLY re-read an `.md` file if the user EXPLICITLY states "the file has changed on disk, read it again". 
   - If the user simply mentions a glossary term or requests info found in a loaded doc, answer directly from memory. DO NOT search for it again.

4. **CONTEXT RECOVERY (SMART READ):**
   If the user asks a domain/architecture specific question and you realize the essential `.md` files are NO LONGER in your current context (they dropped out of memory), you **MUST automatically re-read** the necessary documentation before answering. 
   Do NOT wait for the user to explicitly tell you to re-read them. Prioritize scanning the `docs/` folders to recover the lost context.

   **Auto-detection triggers (MUST treat ALL docs as NOT loaded):**
   - Session starts with a summary of a previous conversation (context recovery/compaction)
   - Message compaction or context compression occurred mid-session
   - You cannot quote the exact content of a doc you claim to know
   When any trigger fires → reset `[LOADED_DOCS: NONE]` and re-read per Rule #2.

   Directories to read (when recovering context):
   - `docs/` (in this repository root)
   - `../NopCommerce.Common/4.70/Plugins/Nop.Plugin.Misc.AIPlugin/docs/`

5. **EXPLICIT CONSENT FOR MODIFICATIONS:**
   NEVER rewrite, create, or delete any file (code, documentation, configuration, memory, or otherwise) without the user's explicit permission. If the user does not specifically request a code modification (e.g., using phrases like "we are just thinking," "what do you think," "let's plan"), you MUST ONLY provide text-based analysis and planning. You are FORBIDDEN from using file-modifying tools (`replace_string_in_file`, `edit_file`, `create_file`, etc.) until the user explicitly says "ok", "go ahead", "implement", or a similar unambiguous approval.

## Workspace Dependencies
# own-dep-repos: "name: path" — paths are relative to this repo root (.github/..)
@repo {
  name = "FruitBankHybridApp"
  type = "product"
  layer = 2
  own-dep-repos = [
    "AyCode.Core: ../../../Aycode/Source/AyCode.Core",
    "AyCode.Blazor: ../../../Aycode/Source/AyCode.Blazor",
    "Mango.Nop Libraries: ../NopCommerce.Common/4.70/Libraries"
  ]
}

> This is the **single source of truth** for domain rules. Do not duplicate these elsewhere.
> For detailed docs see: `README.md` → `docs/`
> For core framework rules see: `.github/copilot-instructions.md` (in AyCode.Core repo)
> For UI framework rules see: `.github/copilot-instructions.md` (in AyCode.Blazor repo)
> For nopCommerce library rules see: `.github/copilot-instructions.md` (in Mango.Nop Libraries repo)
> For nopCommerce plugin (server side) rules see: `../NopCommerce.Common/4.70/Plugins/Nop.Plugin.Misc.AIPlugin/README.md` (in Mango.Nop Plugins repo)
> External repos in `own-dep-repos` are fully accessible — read their source code, docs, and `.github/copilot-instructions.md` freely when you need type definitions, base classes, or context. Do not limit yourself to the current workspace.

## Shared Agent Skills

Skills defined in other repos that can be referenced from here:

- **protocol-audit** — Cross-repo consistency audit for `.github/copilot-instructions.md` across all 5 repos.
  Location: `AyCode.Core/.github/skills/protocol-audit/SKILL.md`
  Activate from an AyCode.Core session, or read the SKILL.md directly and follow its steps.

## Business Domain
1. **FruitBank** = fruit & vegetable wholesaler. The server side runs as a **nopCommerce plugin** — Customer, Order, Product, GenericAttribute are nopCommerce entities.
2. **Shipping** = INBOUND delivery (supplier → warehouse). **Order** = OUTBOUND delivery (warehouse → customer). Never confuse the two directions.
3. **"Pallet"** (`XxxItemPallet`) = a **measurement record**, NOT a physical pallet. Always created for every item, even non-measurable ones.

## Measurement Logic
4. **IsMeasurable=false** → weights are 0.0, only `TrayQuantity` is recorded. A Pallet record is still created.
5. **NetWeight = GrossWeight − PalletWeight − (TrayQuantity × TareWeight)** — this formula is universal across ShippingItemPallet, OrderItemPallet, and StockTakingItemPallet.
6. **MeasuringStatus.Finnished** — intentional legacy typo with double-n. Do NOT fix the spelling.
7. **MeasuringStatus** progression: NotStarted(0) → Started(10) → Finnished(20) → Audited(30). OrderItemPallet adds Audited when RevisorId > 0.

## Data Model
8. **GenericAttribute** = polymorphic key-value store. `KeyGroup` = owner type name, `EntityId` = owner ID. ProductDto reads IsMeasurable, Tare, AverageWeight, IncomingQuantity, NetWeight from GenericAttributes.
9. **Three parallel measurement hierarchies** share the same base (`MeasuringItemPalletBase`):
   - Shipping: ShippingItem → ShippingItemPallet
   - Order: OrderItemDto → OrderItemPallet (adds RevisorId for audit)
   - StockTaking: StockTakingItem → StockTakingItemPallet

## Technical
10. SignalR uses **AcBinaryHubProtocol** (custom binary), not default JSON.
11. Do not suggest removal/rollback as a solution — find a fix for the problem.
12. All AyCode references are via **DLL** (not ProjectReference) — this is intentional. nopCommerce 4.80.9 requirement.
13. **No redundant code** — before writing new logic, check whether similar methods already exist in the current context. Reuse or extract shared logic into smaller methods rather than duplicating.
14. **Keep all .md documentation in sync (PASSIVE DETECTION & ASK FIRST)** — If you notice *any contradiction, error, or missing information* between the code and your currently loaded `.md` files, **briefly notify the user and ask for permission before making changes**. Do NOT automatically update `.md` files or trigger new searches yet. Once the user approves, you may actively search, read, and update the necessary docs in the correct layer.
**Identify missing documentation:** If you notice during your task that a frequently used pattern, underlying logic, or important behavior is missing from the docs, **and adding it would improve future LLM context-efficiency (saving searches/tokens)**, briefly notify the user to get approval.
**Topic-based separation:** When creating or expanding documentation, keep logically distinct features or domains in separate `.md` files (e.g., architecture, data model, billing) and only reference them in the main/index documents. Do not cram everything into a single monolithic file. Keep in mind: these `.md` files are primarily for LLM grounding and context providing. Keep them concise, structured, and focused on rules/patterns rather than human-readable prose.
**ENFORCEMENT:** At the end of EVERY code-modifying response, append a **`[DOCUMENTATION CHECK]`** section. Evaluate ONLY the `.md` files *already in your context*. State in 1-2 sentences if you found discrepancies or missing concepts, and ask if they should be documented. **DO NOT trigger searches or tool calls for this initial check**.
15. **MgGridBase** (AyCode.Blazor) is the canonical grid base for all data screens. New grids inherit `FruitBankGridBase<TEntity>`, set CRUD tags in the constructor, and use `MgGridWithInfoPanel` for layout. See `AyCode.Blazor.Components/docs/MGGRID.md` (in AyCode.Blazor repo) for the full technical reference. Do NOT create parallel grid base classes.
16. **AyCode.Core** solution (`../../../Aycode/Source/AyCode.Core/`) contains all core framework code: SignalR base classes, serialization, binary protocol, data sources, logging. Types not defined in this solution likely live in AyCode.Core.
17. **AyCode.Blazor** solution (`../../../Aycode/Source/AyCode.Blazor/`) contains all UI framework code: MgGridBase, MgGridWithInfoPanel, toolbar, layout persistence, Blazor component infrastructure. UI base classes or components not found here likely live in AyCode.Blazor.
18. **Mango.Nop Libraries** (`../NopCommerce.Common/4.70/Libraries/`) — independent shared library with its own `.github/copilot-instructions.md` and `docs/`. Contains DTOs, entities, data access, and service base classes. DTO or entity base classes not found in this solution likely live in Libraries.
19. **FruitBank nopCommerce Plugin** (`../NopCommerce.Common/4.70/Plugins/Nop.Plugin.Misc.AIPlugin/`) is the server-side plugin running inside nopCommerce 4.80.9. Contains SignalR hubs/endpoints, measurement services, data access (DbTable classes), admin controllers, and AI services. Server-side endpoints and services are defined here.
20. **Documentation layering** — write `.md` documentation at the **defining layer** (where the code lives). Higher-layer `.md` files reference the base docs (e.g. `see AyCode.Core/docs/SIGNALR.md`) and document only project-specific overrides or extensions. Never duplicate base-layer descriptions in consumer-level docs.
21. **Do not re-read .md files** already in your context window. They only change if you modify them yourself (new content is already in context) or if the developer tells you they changed — in that case re-read them once.
22. **Folder navigation** — start from the root `README.md` for solution-level navigation. When you need to understand a folder's contents or find a type/class, read the `README.md` in that folder first — it indexes the local files and sub-folders. Follow this before grepping or reading source files.