# ARCH.FullProjectSeniorCleanArchitecture — Authoritative Execution Prompt

## Role

Act as a Principal Node.js Architect, Senior Backend Engineer, Senior Dashboard
Engineer, Socket.IO Reliability Engineer, MongoDB/Mongoose Specialist, and QA Lead on
the existing KamTeswa Node.js 18 + Express 5 + MongoDB/Mongoose 8 + EJS + Socket.IO
codebase.

## Mission

Convert the active application into a **domain-first modular monolith** without changing
its approved product behavior. Cover the complete project, not only the dashboard:

- API routes, validation, controllers, services, DTOs, and OpenAPI/Postman;
- dashboard routes, validation, controllers, services, repositories, view models, EJS,
  and browser assets;
- Socket.IO events, validation, policies, DTOs, services, and registration;
- Mongoose models, repositories, constants, policies, and query builders;
- cron handlers and persisted job contracts;
- shared authentication, errors, uploads, logging, i18n, notifications, and security;
- tests, QA scripts, documentation, and generated delivery artifacts.

The objective is cleaner ownership, explicit dependencies, testable OOP boundaries, and
zero functional regression. Folder movement alone is not architecture.

## Governing Sources

Read and obey, in precedence order:

1. `AGENTS.md`;
2. `docs/FINAL_PROJECT_ARCHITECTURE_BLUEPRINT.md`;
3. `docs/MIGRATION_WAVES.md`;
4. `docs/PROJECT_STRUCTURE_HYGIENE_REPORT.md`;
5. `docs/DEAD_CODE_CANDIDATES.md`;
6. `docs/API_MODULE_GUIDE.md`;
7. `docs/DASHBOARD_MODULE_GUIDE.md`;
8. `docs/SOCKET_MODULE_GUIDE.md`;
9. `docs/LINT_FORMAT_GUIDE.md`;
10. existing route, response, validation, auth, upload, i18n, and test contracts.

When documentation and runtime disagree, inspect the active code and tests. Never guess
the business contract.

## Non-negotiable Safety Rules

1. Do not install or remove packages without explicit approval.
2. Do not modify `.env`, deployment files, certificates, secrets, or uploaded data.
3. Do not change endpoint paths, HTTP methods, middleware order, authentication buckets,
   response envelopes, field names, Socket event names, cron handler names, EJS URLs, or
   asset URLs as an architecture side effect.
4. Do not change Mongoose schema fields, indexes, hooks, model names, references, or data
   without a separately approved contract/migration phase.
5. Do not enable global RBAC as a side effect.
6. Do not redesign approved UI modules.
7. Do not bulk-move files. Move one bounded context per independently reversible wave.
8. Do not delete a file because static search finds no import. Follow the complete proof
   checklist in `docs/DEAD_CODE_CANDIDATES.md`.
9. Do not return raw Mongoose documents or sensitive data.
10. Do not replace working legacy behavior merely to make the architecture look uniform.
11. If a contract is ambiguous, mark the slice `BLOCKED` or `PARTIAL`; do not invent it.
12. Preserve all unrelated dirty-worktree changes and classify every Git-status entry.

## Target Module Shape

Use this shape only where the domain needs the corresponding layer:

```text
src/modules/<domain>/
  domain/
    <domain>.constants.js
    <domain>.policy.js
    <domain>.query.js
    <domain>.events.js
  application/
    <domain>.service.js
    <domain>.useCases.js
  infrastructure/
    <domain>.repository.js
    <domain>.model.js             # only in an approved model-move wave
  interfaces/
    api/
      <domain>.api.controller.js
      <domain>.api.validation.js
      <domain>.dto.js
      <domain>.api.routes.js
    dashboard/
      <domain>.dashboard.controller.js
      <domain>.dashboard.validation.js
      <domain>.viewModel.js
      <domain>.dashboard.routes.js
      <domain>.uploads.js
    socket/
      <domain>.socket.js
      <domain>.socket.dto.js
      <domain>.socket.policy.js
  index.js
```

EJS remains under `views/`, public assets remain under `public/`, and their domain owner
is recorded in manifests until the delivery architecture explicitly changes.

## Dependency Rules

Allowed:

```text
interface -> application service -> policy/repository -> model
interface -> DTO/viewModel
socket/cron adapter -> application service
domain -> shared contract
cross-domain caller -> target module public index
```

Forbidden:

- controller querying Mongoose directly;
- repository producing API DTOs or dashboard view models;
- model importing Express, EJS, Socket.IO, or HTTP responses;
- EJS deciding permissions or transitions from raw magic strings;
- API importing dashboard adapters or dashboard importing API adapters;
- importing another domain's private path;
- shared infrastructure importing a business implementation;
- duplicate model compilation;
- circular module imports hidden by CommonJS load order.

## OOP and Clean-code Standard

Use OOP where it creates a real boundary:

- repositories own persistence queries;
- services/use cases own orchestration;
- policies own authorization, deletion, transition, and eligibility decisions;
- query builders own reusable filter composition;
- DTO/view-model mappers own serialization;
- constants/enums own status, role, type, action, and event vocabulary;
- registrars own route/Socket wiring.

Do not create empty classes, one-method wrappers, generic BaseRepository abstractions, or
dependency-injection machinery without a concrete repeated need. Composition is preferred
over inheritance.

Replace repeated business comparisons such as `status === 'active'` only after mapping
their complete allowed values and behavior. Do not globally replace strings without
domain proof.

## Mandatory Execution Order

### Wave 0.1 — make the baseline green

Reconcile existing test/contract blockers before moving runtime ownership:

1. Auction test/fixture expectations, with the current Auction schema and indexes frozen;
2. Auction CSRF wrapper versus brittle static assertion;
3. Provider Product visibility response expectation;
4. Postman export test-order/generated-state isolation.

Fix the smallest correct layer. Do not modify `src/models/auctionModel.js`, its schema, or
its indexes in this program. Do not change a real contract merely to satisfy a stale
test. Run focused tests, then `npm test`, and restore generated artifacts.

### Wave 1 — architecture safety harness

Add package-independent tests/manifests for:

- forbidden dependency directions;
- public module-boundary imports;
- route path/method/middleware-order snapshots;
- Mongoose model-name/index/hook registration uniqueness;
- Socket event names and one-time listener registration;
- persisted cron handler resolution;
- sensitive-field DTO denylist;
- dynamic EJS allowlists;
- browser asset ownership and missing-reference detection.

Do not move implementation in this wave.

### Wave 2 — shared compatibility facades

Introduce only proven shared contracts for errors, response envelopes, logging,
localization, pagination, uploads/files, notifications, money/date helpers, and Socket
transport. Keep old paths as compatibility exports. Auth/Passport/CSRF remain untouched
until dedicated high-risk waves.

### Wave 3 onward — one bounded context per wave

Use the order in `docs/MIGRATION_WAVES.md`:

1. low-risk Reasons/Socials pilot;
2. low-risk support/catalogue domains;
3. catalogue taxonomy;
4. safe dashboard route registrars;
5. low-risk API adapters;
6. communication Socket adapters;
7. settings/content/support;
8. people/accounts;
9. Products;
10. Orders/returns;
11. Auctions/realtime;
12. Payments/wallet/settlements/shipping;
13. physical model moves only after consumer boundaries are proven;
14. EJS/assets cleanup;
15. lint/format rollout after package approval;
16. compatibility-path retirement with complete proof.

Never combine two high-risk domains in one wave.

## Per-wave Procedure

Before editing:

1. print `git status --short`;
2. classify every changed/untracked file;
3. state scope and forbidden scope;
4. inventory routes, middlewares, models, validators, DTOs, EJS/assets, Socket events,
   cron names, tests, and delivery docs for the selected domain;
5. capture current contracts and rollback strategy;
6. publish a targeted discovery report.

During editing:

1. add the public module boundary;
2. extract constants/policies/mappers/repositories only where behavior is understood;
3. preserve compatibility exports from old paths;
4. switch one consumer family at a time;
5. avoid broad formatting;
6. keep each diff reviewable and reversible;
7. update focused tests alongside the boundary.

After editing:

1. run focused tests;
2. run `node --check` on every changed JavaScript file;
3. run full `npm test`;
4. run `git diff --check`;
5. verify route/middleware snapshots;
6. verify OpenAPI/Postman for touched API endpoints only;
7. verify dashboard routes in authenticated light/dark/mobile states where applicable;
8. verify Socket listener/event behavior where applicable;
9. verify cron handler resolution where applicable;
10. restore accidental generated artifacts;
11. classify the final Git status;
12. document results and rollback.

If a gate fails, stop the wave, preserve evidence, and report `PARTIAL` or `BLOCKED`.

## Contract-specific Checks

### API

- public/authenticated registration bucket unchanged;
- validators reject unknown fields;
- thin controllers delegate to application services;
- `ApiResponse` envelope unchanged;
- DTO mapper omits passwords, hashes, OTPs, tokens, reset data, and internal state;
- Arabic and English localization preserved;
- OpenAPI/Postman updated only when a touched contract genuinely changes.

### Dashboard

- route path/method/order unchanged;
- multipart upload middleware remains before CSRF;
- auth/authorization middleware sequence unchanged;
- render locals and EJS partial contracts unchanged;
- AJAX mutations/filter fragments retain their response shape;
- Light/Dark/System, RTL, mobile, no-overflow, console, and network QA remain green.

### Socket

- event names and payload envelopes unchanged;
- listener registration remains exactly once;
- validation and actor authorization preserved;
- reconnect/disconnect behavior preserved;
- errors do not expose credentials or internal stacks.

### Models

- model name, collection, schema paths, defaults, enums, indexes, hooks, plugins,
  populate behavior, and timestamps snapshotted before any physical move;
- old model path re-exports the exact same compiled model;
- no migration or data rewrite in an architecture-only wave.

### Cron

- every persisted handler name resolves to an exported function;
- schedules and idempotency remain unchanged;
- no job executes during static verification.

## Lint and Format Policy

Do not install ESLint/Prettier in the architecture waves. First prepare the documented
configuration and ignore strategy. After explicit package approval, roll out in this
order:

1. changed files only;
2. low-risk new modules;
3. shared adapters;
4. high-risk modules;
5. full repository only after legacy debt is explicitly reconciled.

Never mix mass formatting with behavior or ownership changes.

## Deletion Proof

No deletion is allowed unless all are documented:

- no static import;
- no alias/dynamic/convention require;
- no route, EJS, asset, model-name, Socket, cron, operational-script, or package consumer;
- temporary removal passes focused/full tests and relevant runtime QA;
- rollback patch is available;
- owner/business intent is confirmed for operational files.

Otherwise classify as `KEEP`, `MANUAL_REVIEW`, or `DELETE_CANDIDATE_AFTER_PROOF`.

## Completion Gate

The full program may report `COMPLETE` only when:

- all active business ownership is domain-first or documented compatibility debt is
  explicitly accepted;
- no known route/API/dashboard/Socket/cron/model behavior regression exists;
- every active domain has an explicit public boundary;
- no unexplained circular/private cross-domain imports remain;
- all moved paths have compatibility and rollback proof;
- full `npm test` is green;
- every changed JavaScript file passes `node --check`;
- `git diff --check` is green;
- OpenAPI/Postman delivery is clean;
- authenticated browser QA is green for touched dashboard surfaces;
- Socket and cron gates are green;
- secret/generated-artifact scans are clean;
- every Git-status entry is classified;
- remaining legacy/dead-code candidates are documented honestly.

Tests passing alone do not prove completion. Folder movement alone does not prove clean
architecture. When any gate is red, use `PARTIAL` or `BLOCKED` and continue only through
the next safe wave.

## Required Final Report Per Wave

Report:

1. status;
2. scope and exclusions;
3. files inspected/created/modified/moved/deleted;
4. public module boundary and dependency changes;
5. route/API/dashboard/Socket/cron/model contracts preserved;
6. constants/policies/DTO/repository/OOP work completed;
7. compatibility exports and rollback;
8. security and sensitive-data checks;
9. focused/full tests with exact counts;
10. syntax, Git, generated-artifact, docs, and runtime QA results;
11. every Git-status file classification;
12. remaining risks/debt;
13. the exact next safe wave.
