# AGENT.md

## Purpose

- This file defines repository-specific instructions for coding agents.
- Scope is the full repo unless a deeper `AGENT.md` overrides it.
- Use RTK to reduce token usage, avoid repeated context transfer, and preserve repository knowledge across sessions.

---

# ✅ RTK-FIRST RULES (STRICT)

Always prefer RTK commands for repository inspection, navigation, and code understanding.

## Command Rewrite Rules

Prefer:

```bash
git status        -> rtk git status
git diff          -> rtk git diff
git log           -> rtk git log
ls                -> rtk ls
tree              -> rtk ls
cat <file>        -> rtk read <file>
grep <pattern>    -> rtk grep <pattern>
rg <pattern>      -> rtk grep <pattern>
find              -> rtk find
```

Avoid raw commands for repository inspection when RTK equivalents exist.

Do not:
- use raw `cat` for large files
- use raw `grep`/`rg` across the repository
- use recursive `find` blindly
- inspect large diffs with raw `git diff`
- scan directories manually before searching

Raw commands are allowed only when:
- RTK cannot perform the operation
- executing builds/tests/runtime commands
- debugging environment/runtime issues
- working outside indexed repository scope

---

# 📂 CODE NAVIGATION WORKFLOW (MANDATORY)

Follow this order when working in the repository.

## 1. Discover Structure

```bash
rtk ls
```

## 2. Search Before Opening Files

```bash
rtk grep <symbol | class | function | DTO | service>
```

Examples:

```bash
rtk grep "InputComponent"
rtk grep "fieldControl"
rtk grep "breadcrumbItems"
```

## 3. Read Only Necessary Files

```bash
rtk read <file>
```

## 4. Large File Strategy

For files larger than ~300 lines:

```bash
rtk read <file> -l aggressive
```

## 5. Fast Context Understanding

```bash
rtk smart <file>
```

Never:
- open many files blindly
- read entire modules without searching first
- inspect unrelated folders
- load generated directories into context

---

# 🧠 DIFF INSPECTION RULES

For repository changes use:

```bash
rtk git diff
```

For large diffs:

```bash
rtk git diff -l aggressive
```

Avoid raw:

```bash
git diff
```

unless RTK diff is unavailable.

---

# 🚫 LOW-VALUE PATHS

Avoid loading:

```txt
dist/
.angular/
coverage/
node_modules/
.git/
.cache/
.tmp/
```

unless explicitly required.

---

# RTK Usage Rules

## Required RTK Usage

- Always use RTK for:
  - repository indexing
  - semantic code search
  - symbol lookup
  - dependency tracing
  - architectural context
  - change impact analysis

- Prefer RTK context retrieval over:
  - reading large files entirely
  - repeatedly scanning unchanged directories
  - re-sending full file contents
  - broad grep operations

- Retrieve only the minimal relevant context before making changes.

## Recommended RTK Workflow

1. Index repository
2. Search related symbols/files/components
3. Retrieve minimal context
4. Apply scoped changes
5. Validate impacted areas only

Example workflow:

```bash
rtk index
rtk search "InputComponent number normalization"
rtk search "fieldControl"
rtk refs "goodListConfig"
```

## Token Reduction Rules

- Never load entire large files unless required.
- Never inspect generated folders (`dist`, `.angular`, coverage, etc.).
- Prefer symbol-level retrieval over file-level retrieval.
- Reuse previously retrieved RTK context whenever possible.
- Avoid duplicate searches for the same symbols within one task.
- Use targeted searches:
  - component name
  - selector
  - signal/store name
  - config constant
  - Angular route
  - injected service
  - form control key

## Suggested RTK Queries

### Angular Components

```bash
rtk search "selector: 'field-"
rtk search "standalone: true"
rtk search "InputComponent"
```

### Forms & Controls

```bash
rtk search "fieldControl."
rtk search "ControlConfig"
rtk search "Validators.required"
```

### Stores & Signals

```bash
rtk search "breadcrumbItems"
rtk search "computed("
rtk search "signal("
```

### Tenant / Docker

```bash
rtk search "DIST_DIR"
rtk search "configuration tis"
rtk search "prebuild:tis"
```

### List Configs

```bash
rtk search "IListConfig"
rtk search "columns:"
rtk search "goodListConfig"
```

---

## Stack Context

- Frontend: Angular 20 standalone app.
- Package manager: `pnpm`.
- Deployment: Docker / Docker Compose with tenant-specific services.
- AI-assisted repository navigation: RTK.

### Current service mapping expectation

- `app_default` on host port `8090`
- `app_tis` on host port `8091`

---

## Tenant Build Rules

- `default` tenant currently builds via `ng build` and outputs to `dist/production`.
- `tis` tenant builds via `ng build --configuration tis` and outputs to `dist/tis`.
- `prebuild:tis` is tenant-scoped and should keep using scripts under `scripts/tis/*`.
- Keep Docker `DIST_DIR` aligned with actual Angular output path.
- Do not assume `default` Angular configuration is usable unless verified (it may reference missing replacements).
- Do not use Angular `fileReplacements` for static assets (`.png`, `.jpg`, etc.); use tenant public assets or prebuild copy scripts.

---

## Tenant PWA Rules

- Keep tenant manifest files under tenant public assets (e.g. `public-tis/favicon/site.webmanifest`).
- Ensure `manifest` `id`, `start_url`, and `scope` match actual deployment path:
  - root deploy: `/`
  - subpath deploy example: `/tis/`
- Keep `<link rel="manifest">` path and branding config `manifestPath` aligned.

---

## Input Component Rules

File:
- `src/app/shared/components/input/input.component.ts`

For:
- `type === 'number'`
- `type === 'price'`

Requirements:
- Normalize Persian/Arabic digits to English digits.
- Allow only digits and `.`.
- Support `fixed` precision formatting when provided.

Additional rule:
- Keep behavior for identifier fields (`mobile`, `phone`, `postalCode`, `nationalId`) string-safe.

---

## Change Policy

- Keep changes minimal and scoped to user request.
- Prefer root-cause fixes over temporary workarounds.
- Avoid unrelated refactors.
- Reuse existing patterns and naming conventions.
- Use RTK to understand existing patterns before introducing new ones.

---

## Do / Don't

### Do

- Follow existing field wrapper style in:
  - `src/app/shared/components/fields/*.component.ts`
- Reuse `app-input` and set only required props:
  - `type`
  - `label`
  - `name`
  - constraints
- Register every new field in:
  - `src/app/shared/components/fields/index.ts`
  - `src/app/shared/constants/fields/index.ts`
- Keep control keys consistent across:
  - form group
  - field component `name`
  - `fieldControl` key
- Use RTK searches before creating new abstractions.

### Don't

- Don't add one-off field patterns when an existing field component can be reused.
- Don't use invalid Angular file replacements for directories or empty paths.
- Don't change tenant output directories without updating Docker `DIST_DIR`.
- Don't scan unrelated folders/files when RTK can retrieve exact symbols.
- Don't load full files if RTK symbol extraction is sufficient.

---

## How To Create Form Fields

- Create a wrapper component in:
  - `src/app/shared/components/fields`
- Use the same pattern as existing files like:
  - `src/app/shared/components/fields/name.component.ts`
  - `src/app/shared/components/fields/unit_price.component.ts`

Minimal wrapper shape:

```ts
@Component({
  selector: 'field-example',
  template: `<app-input [label]="label" [control]="control" [name]="name" type="simple" />`,
  imports: [ReactiveFormsModule, InputComponent],
})
export class ExampleComponent {
  @Input({ required: true }) control = new FormControl<string>('');
  @Input() name = 'example';
  @Input() label = 'Example';
}
```

---

## Register New Fields

Export the component from:
- `src/app/shared/components/fields/index.ts`

Add its form control factory in:
- `src/app/shared/constants/fields/index.ts`

`fieldControl` entry shape:
- key must match form control name
- return tuple: `[defaultValue, validators]`

Example:

```ts
example: (value = '', isRequired = true): ControlConfig => [
  value,
  isRequired ? [Validators.required] : [],
],
```

---

## Using Fields In Forms

- In form group builders, use:
  - `fieldControl.<key>(initialValue, isRequired)`
- In templates, render matching wrapper component and pass matching control:
  - `<field-example [control]="form.controls.example" />`
- For numeric/price behavior:
  - use `app-input`
  - use `type="number"` or `type="price"`
  - optional `[fixed]`

---

## List Component Configs

Centralized list metadata is stored in:
- `src/app/shared/constants/list-configs/`

Never store configs inside domain modules.

### Structure

Structure by data type, not domain:
- `good-list.const.ts`
- `sku-list.const.ts`
- `category-list.const.ts`

### Requirements

Each config implements `IListConfig`:
- `pageTitle`
- `addNewCtaLabel`
- `emptyPlaceholderTitle`
- `emptyPlaceholderDescription`
- `columns`

### Usage

```ts
@Input() header: IColumn[] = goodListConfig.columns;
listConfig = goodListConfig;
```

### Rules

- Any domain needing a list config imports from:
  - `@/shared/constants/list-configs`
- No cross-domain dependencies.
- Do not duplicate configs.

---

## Breadcrumb Usage in Stores & Views

- Entity stores expose `breadcrumbItems` as a computed signal.
- Call `store.breadcrumbItems()` in view components and extend with current page:

```ts
setBreadcrumb() {
  this.breadcrumbService.setItems([
    ...this.store.breadcrumbItems(),
    { title: 'Current Page' },
  ]);
}
```

- Root page breadcrumbs are set in the store's `getData()` method once entity is loaded.

---

## Validation Checklist

### TypeScript-only changes

```bash
pnpm -s exec tsc -p tsconfig.app.json --noEmit
```

### Docker/build changes

```bash
docker compose build app_default
docker compose build app_tis
```

### Validation Strategy

- Start with targeted validation.
- Run broader checks only if needed.
- Validate only impacted tenants/features when possible.

---

## Communication Expectations

- Report exactly which files changed and why.
- Call out assumptions and discovered config mismatches.
- If validation is blocked:
  - explain why
  - provide next command
- Mention RTK searches/symbols used when relevant to implementation decisions.

---

## Preferred Investigation Order

Before editing code:

1. RTK symbol search
2. Existing implementation discovery
3. Shared abstraction verification
4. Minimal scoped change
5. Targeted validation

Avoid:
- broad exploratory reads
- repeated file dumping
- unnecessary context expansion

---

## Angular Architecture Preferences

- Prefer standalone components.
- Prefer signals/computed over legacy observable-only state when consistent with current architecture.
- Keep forms typed.
- Keep reusable UI in `shared`.
- Keep domain logic outside presentation components.
- Preserve existing tenant separation model.

---

## Performance & AI Efficiency

- Optimize for:
  - minimal token usage
  - minimal file reads
  - scoped context retrieval
  - reusable architectural understanding

Prefer:
- RTK symbol search
- targeted reads
- incremental inspection

Avoid:
- dumping full files
- repeated repository scans
- repeated searches for the same symbols
- unnecessary architectural exploration

- RTK should be the primary repository understanding tool.
