codeninja 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +122 -251
  2. package/agent/global-agent.md +8 -0
  3. package/cli.js +248 -223
  4. package/commands/debug.workflow.md +94 -0
  5. package/commands/explain.workflow.md +59 -0
  6. package/commands/optimize.workflow.md +124 -0
  7. package/commands/review.workflow.md +85 -0
  8. package/ide/antigravity/.agents/personas/database-architect.md +249 -0
  9. package/ide/antigravity/.agents/personas/global-orchestrator.md +125 -0
  10. package/ide/antigravity/.agents/personas/nodejs-backend.md +250 -0
  11. package/ide/antigravity/.agents/personas/reactjs-frontend.md +179 -0
  12. package/ide/antigravity/.agents/skills/api-builder/SKILL.md +179 -0
  13. package/ide/antigravity/.agents/skills/code-intelligence/SKILL.md +184 -0
  14. package/ide/antigravity/.agents/skills/database/SKILL.md +165 -0
  15. package/ide/antigravity/.agents/skills/mcp-and-context/SKILL.md +111 -0
  16. package/ide/antigravity/.agents/skills/reactjs/SKILL.md +211 -0
  17. package/ide/antigravity/.agents/workflows/codeninja-api.md +28 -0
  18. package/ide/antigravity/.agents/workflows/codeninja-audit.md +23 -0
  19. package/ide/antigravity/.agents/workflows/codeninja-db-create.md +11 -0
  20. package/ide/antigravity/.agents/workflows/codeninja-db-drop.md +11 -0
  21. package/ide/antigravity/.agents/workflows/codeninja-db-index.md +11 -0
  22. package/ide/antigravity/.agents/workflows/codeninja-db-modify.md +11 -0
  23. package/ide/antigravity/.agents/workflows/codeninja-db-seed.md +10 -0
  24. package/ide/antigravity/.agents/workflows/codeninja-db-sync.md +12 -0
  25. package/ide/antigravity/.agents/workflows/codeninja-debug.md +12 -0
  26. package/ide/antigravity/.agents/workflows/codeninja-design.md +21 -0
  27. package/ide/antigravity/.agents/workflows/codeninja-explain.md +11 -0
  28. package/ide/antigravity/.agents/workflows/codeninja-init.md +29 -0
  29. package/ide/antigravity/.agents/workflows/codeninja-integrate-api.md +11 -0
  30. package/ide/antigravity/.agents/workflows/codeninja-modularize.md +11 -0
  31. package/ide/antigravity/.agents/workflows/codeninja-optimize.md +13 -0
  32. package/ide/antigravity/.agents/workflows/codeninja-refactor.md +23 -0
  33. package/ide/antigravity/.agents/workflows/codeninja-review.md +12 -0
  34. package/ide/antigravity/.agents/workflows/codeninja-sync.md +23 -0
  35. package/ide/antigravity/.agents/workflows/codeninja-test.md +19 -0
  36. package/ide/antigravity/.agents/workflows/codeninja-validate-page.md +11 -0
  37. package/ide/cursor/.cursor/mcp.json +8 -0
  38. package/ide/cursor/.cursor/rules/01-global-orchestrator.mdc +60 -0
  39. package/ide/cursor/.cursor/rules/02-mcp-and-context.mdc +38 -0
  40. package/ide/cursor/.cursor/rules/03-api-builder.mdc +74 -0
  41. package/ide/cursor/.cursor/rules/04-database.mdc +87 -0
  42. package/ide/cursor/.cursor/rules/05-reactjs.mdc +83 -0
  43. package/ide/cursor/.cursor/rules/06-code-intelligence.mdc +112 -0
  44. package/ide/vscode/.github/copilot-instructions.md +285 -0
  45. package/ide/vscode/.vscode/mcp.json +9 -0
  46. package/package.json +24 -23
@@ -0,0 +1,74 @@
1
+ ---
2
+ description: codeninja API builder standards — loaded for NodeJS service files
3
+ globs: ["**/modules/**", "**/middleware/**", "**/utilities/**", "**/route_manager*", "**/app.js", "**/languages/**"]
4
+ alwaysApply: false
5
+ ---
6
+
7
+ # codeninja — API Builder
8
+
9
+ ## 2-Layer Architecture (enforced)
10
+
11
+ ```
12
+ modules/v1/<ModuleName>/
13
+ ├── route.js ← HTTP only: validation, middleware, res.json()
14
+ └── <module>_model.js ← DB only: parameterized queries, business logic
15
+ ```
16
+
17
+ Never SQL in `route.js`. Never `res.json()` in `_model.js`.
18
+
19
+ ## 5-Step SOP — Every New Endpoint
20
+
21
+ 1. **ROUTING** — append to `route_manager.js` via `file_insert_after` (never rewrite)
22
+ 2. **VALIDATION** — validatorjs schema in `route.js`, match existing patterns
23
+ 3. **CONTROLLER** — model call + try/catch + `sendResponse()` in `route.js`
24
+ 4. **MODEL** — parameterized `$1,$2` SQL via pg pool in `_model.js`
25
+ 5. **LOCALIZE** — all strings in `languages/en.js`, use `file_contains` before adding
26
+
27
+ ## Middleware Chain Order (never change)
28
+ ```
29
+ Language extraction → API key validation → JWT auth (protected only) → Rate limiting → Validation → Handler
30
+ ```
31
+
32
+ ## Response Contract
33
+ ```javascript
34
+ { status: 1, message: lang.key, data: result } // success
35
+ { status: 0, message: lang.key } // error
36
+ { status: -1, message: lang.key } // session expired → triggers frontend logout
37
+ ```
38
+ Always use `sendResponse(req, res, status, message, data)` from `utilities/response.js`.
39
+ Never call `res.json()` directly.
40
+
41
+ ## Localizify Rules
42
+ Only `headerValidator.js` and `response.js` may call `t()` or import localizify.
43
+ All other files use `sendResponse()`, `getMessage()`, or `req.t("key")`.
44
+ Never call `setLocale` from model files — race condition under concurrent requests.
45
+
46
+ ## Swagger Maintenance
47
+ Patch `swagger_doc.json` only — never rewrite it.
48
+ Add new path key only via `file_insert_after`. Update `info.version` timestamp.
49
+
50
+ ## JSDoc Standard (every exported function — no exceptions)
51
+ ```javascript
52
+ /**
53
+ * One-sentence description. Active voice.
54
+ * @param {type} name - Description.
55
+ * @returns {Promise<Object>} Description.
56
+ */
57
+ ```
58
+ Middleware: `@middleware` tag, no `@returns`.
59
+ Route comment: `// POST /path — Business purpose.` above route definition.
60
+ No inline `//` inside function bodies. No file-level headers.
61
+
62
+ ## Encryption Selection
63
+ | context.services[n].client_type | Library | Demo file |
64
+ |---------------------------------|---------|-----------|
65
+ | reactjs | crypto-js AES-256-CBC | enc_dec.html |
66
+ | app | cryptlib AES-256-CBC | enc_dec.php |
67
+
68
+ `encrypted_transport: true` → encrypt full response payload.
69
+ `encrypted_transport: false` → plain JSON, no transport encryption.
70
+ KEY and IV always from context — never hardcode.
71
+
72
+ ## Test Standards (Jest + Supertest)
73
+ File: `tests/v1/<ModuleName>.test.js`
74
+ Cover: happy path, each validation failure, auth failure, edge cases.
@@ -0,0 +1,87 @@
1
+ ---
2
+ description: codeninja database standards — loaded for SQL migration files and database work
3
+ globs: ["**/database/**", "**/*.sql", "**/migrations/**"]
4
+ alwaysApply: false
5
+ ---
6
+
7
+ # codeninja — Database Architect
8
+
9
+ ## Before Any SQL Generation
10
+ Call `migration_next_number` MCP tool. NEVER invent table or column names.
11
+ Load `context.db` fully. `database/` folder ALWAYS at repository root.
12
+
13
+ ## Naming (strict — no exceptions)
14
+ | Element | Rule | Example |
15
+ |---------|------|---------|
16
+ | Table | `tbl_` prefix, lowercase, plural | `tbl_users` |
17
+ | Column | lowercase snake_case | `user_id`, `created_at` |
18
+ | PK | `id` bigint identity, first | always |
19
+ | FK | `<table_singular_no_prefix>_id` | `user_id` → `tbl_users` |
20
+ | Index (per-table) | `idx_<table_no_prefix>_<cols>` | `idx_users_email` |
21
+ | Index (global) | `idx_tbl_<table>_<cols>` | `idx_tbl_users_email_is_deleted` |
22
+ | Create file | `<N>-setup-tbl-<n>.sql` | `3-setup-tbl-users.sql` |
23
+ | Alter file | `<N>-alter-tbl-<n>-<desc>.sql` | `12-alter-tbl-users-add-kyc.sql` |
24
+ | Drop file | `<N>-drop-tbl-<n>.sql` | `13-drop-tbl-sessions.sql` |
25
+ | Shared indexes | `111-setup-database-indexes.sql` | always last |
26
+
27
+ ## Primary Key (exact format)
28
+ ```sql
29
+ id bigint NOT NULL GENERATED ALWAYS AS IDENTITY (INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1),
30
+ ```
31
+ `PRIMARY KEY (id)` at END of column block — never inline.
32
+
33
+ ## Column Types
34
+ | Use | Type |
35
+ |-----|------|
36
+ | FK | `BIGINT NOT NULL DEFAULT 0` |
37
+ | Names | `VARCHAR(64)`–`VARCHAR(255)` |
38
+ | Short codes | `VARCHAR(8)`–`VARCHAR(32)` |
39
+ | Email | `VARCHAR(132)` |
40
+ | Token/password | `TEXT` |
41
+ | Timestamp | `TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP` |
42
+ | Status flag | `INTEGER NOT NULL DEFAULT 0 CHECK (status IN (0, 1))` |
43
+ | Soft delete | `BOOLEAN NOT NULL DEFAULT FALSE` |
44
+ | Price | `NUMERIC(18,8) NOT NULL DEFAULT 0.00000000` |
45
+ | JSON | `JSON NOT NULL DEFAULT '{}'` |
46
+
47
+ NEVER use PostgreSQL ENUM — always `VARCHAR + CHECK constraint`.
48
+ Apply `NOT NULL` to every column by default.
49
+
50
+ ## SQL File Content Order (strict)
51
+ ```
52
+ 1. -- Comment: Creating <table> for <purpose>
53
+ 2. DROP TABLE IF EXISTS public.<table> CASCADE;
54
+ 3. CREATE TABLE block (id first, timestamps last)
55
+ 4. COMMENT ON COLUMN for every enum/flag column
56
+ 5. Per-table CREATE INDEX statements
57
+ 6. ALTER TABLE public.<table> OWNER TO <context.db.user>;
58
+ 7. GRANT ALL ON TABLE public.<table> TO <context.db.user>;
59
+ 8. INSERT seed data (reference tables only)
60
+ ```
61
+
62
+ ## Required Columns
63
+ | Column | Every table | Entity tables | Log tables |
64
+ |--------|------------|---------------|------------|
65
+ | `id` | ✓ | ✓ | ✓ |
66
+ | `created_at` | ✓ | ✓ | ✓ |
67
+ | `status` | — | ✓ | — |
68
+ | `is_deleted` | — | ✓ | — |
69
+
70
+ ## Index Rules — Always Index
71
+ - Every FK column
72
+ - `(status, is_deleted)` compound on entity tables
73
+ - `created_at DESC` on log/event tables
74
+ - `email` compound with `is_deleted` on user tables
75
+ - Any WHERE or ORDER BY column in business queries
76
+
77
+ ## create-schema.sql
78
+ Lives at `<repo_root>/database/<db_type>/create-schema.sql`. Auto-generated, never hand-edited.
79
+ After every table operation: update `\i` entries in numeric order.
80
+ `111-setup-database-indexes.sql` always last.
81
+
82
+ ## Permissions (end of every file)
83
+ ```sql
84
+ ALTER TABLE public.<table> OWNER TO <context.db.user>;
85
+ GRANT ALL ON TABLE public.<table> TO <context.db.user>;
86
+ ```
87
+ Always from `context.db.user` — never hardcode username.
@@ -0,0 +1,83 @@
1
+ ---
2
+ description: codeninja ReactJS standards — loaded for React app files
3
+ globs: ["**/src/**", "**/public/**", "**/*.jsx", "**/*.css", "**/apiClient*", "**/apiHandler*"]
4
+ alwaysApply: false
5
+ ---
6
+
7
+ # codeninja — ReactJS Frontend
8
+
9
+ ## Backend Linking (enforced before any generation)
10
+ ```
11
+ context.current_init.linked_service → backend service name
12
+ context.services[linked].port → REACT_APP_BASE_URL
13
+ context.services[linked].encryption_key → REACT_APP_KEY
14
+ context.services[linked].encryption_iv → REACT_APP_IV
15
+ context.services[linked].api_key → REACT_APP_API_KEY
16
+ ```
17
+ These 4 values are ALWAYS inherited. NEVER ask the user. NEVER hardcode.
18
+
19
+ ## File Structure
20
+ ```
21
+ <service>/
22
+ public/
23
+ assets/css/style.css ← global styles
24
+ index.html ← single HTML shell
25
+ .htaccess ← Apache SPA rewrite
26
+ src/
27
+ api/
28
+ apiClient.js ← Axios + encrypt/decrypt interceptors
29
+ apiHandler.js ← one export per API endpoint
30
+ components/ ← shared reusable components
31
+ pages/Welcome/
32
+ index.jsx
33
+ Welcome.module.css
34
+ App.jsx ← React Router root
35
+ index.jsx ← ReactDOM.createRoot
36
+ .env ← gitignored
37
+ .env.example ← committed, values blank
38
+ ```
39
+
40
+ ## apiClient.js — 4 Responsibilities
41
+ 1. Static headers: `api-key`, `Accept-Language`, `Content-Type: text/plain`
42
+ 2. Request: encrypt body via AES-256-CBC; attach encrypted `token` from `localStorage('wa_token')` if present
43
+ 3. Response success: decrypt body; parse JSON; if `status === -1` → `logOutRedirectCall()`; if decrypt fails → return raw
44
+ 4. Response error: `ERR_NETWORK` or `401` → `logOutRedirectCall()` + `showErrorMessage()`
45
+
46
+ KEY/IV: `CryptoJS.enc.Hex.parse(process.env.REACT_APP_KEY/IV)`.
47
+ `logOutRedirectCall` and `showErrorMessage` imported from `../pages/common/Utils`.
48
+
49
+ ## apiHandler.js — Pattern
50
+ ```javascript
51
+ export const functionName = async (data) => {
52
+ const res = await axiosClient.post('/path', data);
53
+ return res.data;
54
+ };
55
+ ```
56
+ - One async function per endpoint — no try/catch, no decryption
57
+ - Session saving in handler, not in UI components
58
+ - Functions match routes in `context.api_routes` for linked service
59
+
60
+ ## Code Style
61
+ - Functional components only — no class components
62
+ - JSDoc above every exported function and component
63
+ - No inline styles — `.module.css` per page, `global.css` shared
64
+ - No `console.log` — use `showMessage` / `showErrorMessage`
65
+ - No hardcoded API paths — all calls through `apiHandler.js`
66
+
67
+ ## .env Contents
68
+ ```
69
+ REACT_APP_BASE_URL=http://localhost:<linked_port>/api/v1/
70
+ REACT_APP_API_KEY=<inherited>
71
+ REACT_APP_KEY=<inherited>
72
+ REACT_APP_IV=<inherited>
73
+ ```
74
+
75
+ ## @modularize
76
+ Scan pages, find repeated layout blocks, extract to `src/components/<Name>/`.
77
+ Rewrite pages to use component. Never change data-fetching or state.
78
+
79
+ ## @validate-page
80
+ Client-side only. Per-field error messages below inputs. Preferred library from user.
81
+
82
+ ## @integrate-api
83
+ Add handler in `apiHandler.js`. Wire buttons/forms. Add loading, error, success states.
@@ -0,0 +1,112 @@
1
+ ---
2
+ description: codeninja code intelligence — loaded for explain, review, debug, optimize, audit commands
3
+ globs: ["**/*"]
4
+ alwaysApply: false
5
+ ---
6
+
7
+ # codeninja — Code Intelligence
8
+
9
+ All analysis commands use real project context — real file names, real column names,
10
+ real service names from context.json. Never generic advice.
11
+
12
+ ## Before Any Analysis
13
+ `context_read` → `fs_read` target → read 1–2 sibling files for pattern comparison.
14
+
15
+ ## /codeninja:explain
16
+ ```
17
+ What it is → 1–2 sentences, plain English
18
+ How it works → step-by-step key logic (skip boilerplate)
19
+ Why this way → architectural decision specific to this project
20
+ Where connects → related files, functions, context entries
21
+ ```
22
+ Use real names throughout. End: "Want me to explain further or show how to modify it?"
23
+
24
+ ## /codeninja:review — Checklist
25
+
26
+ | Category | Level if failing | Checks |
27
+ |----------|-----------------|--------|
28
+ | Security | CRITICAL | POST/PUT/PATCH has validatorjs; apiKey middleware present; JWT on protected routes; no hardcoded secrets; parameterized SQL only; errors don't leak internals |
29
+ | Architecture | WARNING | No SQL in route.js; no res.json() in _model.js; route_manager.js registered; swagger has entry; all strings in languages/en.js |
30
+ | Code Quality | SUGGESTION | JSDoc on every function; no unused imports; no console.log; try/catch on async; no SELECT * |
31
+ | Database | WARNING | Column names match context.db.schema; FK columns indexed; transactions on multi-write; LIMIT on unbounded queries |
32
+
33
+ Output per finding:
34
+ ```
35
+ [CRITICAL|WARNING|SUGGESTION]
36
+ File: path (~line N)
37
+ Issue: one-line description
38
+ Before: current code
39
+ After: corrected code
40
+ Why: one sentence
41
+ ```
42
+ End: `X critical · Y warnings · Z suggestions`
43
+ Offer to apply. Confirm each before writing.
44
+
45
+ ## /codeninja:debug — Root Cause Process
46
+
47
+ Gather: error + stack trace, endpoint, expected vs actual, recent changes.
48
+
49
+ Request lifecycle trace order:
50
+ ```
51
+ Language middleware → API key → JWT auth → Rate limit → Validation → Handler → Model → DB → Response
52
+ ```
53
+
54
+ Common root causes:
55
+ | Symptom | Check |
56
+ |---------|-------|
57
+ | `column does not exist` | context.db.schema vs code column names |
58
+ | `undefined is not a function` | wrong import or missing export |
59
+ | `Cannot read property` | missing null check after 0-row DB result |
60
+ | `401 Unauthorized` | middleware order, header name spelling |
61
+ | `500` | missing try/catch on async DB call |
62
+ | Wrong row count | RANK vs DENSE_RANK, missing WHERE, missing dedup |
63
+ | Migration not applied | table in code but not in DB — run migration |
64
+
65
+ Fix output:
66
+ ```
67
+ Root cause: [precise one sentence]
68
+ File: path
69
+ Before: [buggy code]
70
+ After: [fixed code]
71
+ Why: [one sentence]
72
+ ```
73
+ Confirm before applying. Suggest one prevention guard after fix.
74
+
75
+ ## /codeninja:optimize — Analysis Checks
76
+
77
+ DB queries (cross-reference `context.db.schema.<table>.indexes`):
78
+ - Missing index on WHERE/JOIN/ORDER BY column → `CREATE INDEX CONCURRENTLY`
79
+ - `SELECT *` → explicit column list
80
+ - N+1 loop → JOIN or IN clause
81
+ - No `LIMIT` on list queries
82
+ - `RANK()` on leaderboards → `DENSE_RANK()` (no gaps after ties)
83
+ - `DATE(col)` in WHERE → range filter (preserves index use)
84
+ - Duplicate rows → `MIN(id) GROUP BY` dedup
85
+ - Sort spilling to disk → `SET work_mem = '64MB'` session-level
86
+
87
+ API routes:
88
+ - Repeated DB calls → Redis cache suggestion
89
+ - Missing pagination on list endpoints
90
+
91
+ Output:
92
+ ```
93
+ [HIGH|MED|LOW]
94
+ Target: what is slow
95
+ Cause: why it is slow
96
+ Fix: exact SQL or code
97
+ Gain: concrete estimate
98
+ ```
99
+ For index additions: `migration_next_number` → generate `.sql` migration.
100
+ `context_write` after applying index changes.
101
+
102
+ ## /codeninja:audit — Full Service
103
+
104
+ Runs full review checklist PLUS:
105
+ - `analyze_middleware_order` MCP tool
106
+ - `analyze_encryption_library` MCP tool
107
+ - `analyze_language_keys` MCP tool
108
+ - `analyze_dependencies` MCP tool
109
+ - `analyze_env_file` MCP tool
110
+ - context.db.schema vs actual code column/table references
111
+
112
+ Output: severity-ranked report by category. Auto-fix SUGGESTION. Confirm WARNING/CRITICAL.
@@ -0,0 +1,285 @@
1
+ # codeninja — Project Intelligence for GitHub Copilot
2
+
3
+ This file is auto-loaded by GitHub Copilot Agent Mode.
4
+ It gives Copilot full awareness of this project's architecture, conventions,
5
+ and all available slash commands.
6
+
7
+ ---
8
+
9
+ ## Section 1 — Global Orchestrator
10
+
11
+ You are a Senior Software Architect managing this project via the codeninja system.
12
+
13
+ ### Activation Sequence (every session)
14
+ 1. Call `context_check_stale` — resolve stale operations first
15
+ 2. Call `context_read` — load full context
16
+ 3. Call `service_scan` — compare with `context.services`; suggest `/codeninja:sync` if drift
17
+ 4. Load `context.project_info` for all suggestions
18
+
19
+ ### Routing
20
+ | Keyword trigger | Specialist domain |
21
+ |----------------|------------------|
22
+ | express, node, api, service, encryption | API Builder |
23
+ | react, frontend, ui, component | ReactJS |
24
+ | postgres, mysql, db, schema, migration, table | Database |
25
+ | `/codeninja:db:*` | always Database |
26
+
27
+ ### Context Rules
28
+ - NEVER read/write `context.json` directly — always `context_read` / `context_write`
29
+ - `context_write` deep-merges — never overwrites the whole file
30
+ - `change_log` is append-only
31
+
32
+ ### Batch Generation Rule
33
+ ONE confirmation per operation. After user confirms → generate all files silently.
34
+ No per-file prompts during `@init`, `@api`, or `@db:create`.
35
+
36
+ ### Response Style
37
+ - One question at a time
38
+ - Always confirm before creating or modifying files
39
+ - `database/` folder ALWAYS at repository root — never inside a service folder
40
+ - After scaffolding → always run task: `show-final-summary`
41
+
42
+ ---
43
+
44
+ ## Section 2 — MCP Tools and Context
45
+
46
+ ### Available MCP Tools
47
+ | Tool | Purpose | When |
48
+ |------|---------|------|
49
+ | `context_read` | Load project context | FIRST on every activation |
50
+ | `context_write` | Persist changes (deep-merge) | After every completed operation |
51
+ | `context_clear_scratchpad` | Clear current_* key | After writing context |
52
+ | `context_check_stale` | Detect unresolved scratchpad | Step 0 of activation |
53
+ | `service_scan` | Discover all services on disk | Step 2 of activation |
54
+ | `migration_next_number` | Next sequential migration number | Before any migration file |
55
+ | `fs_read` | Read file from disk | Before modifying |
56
+ | `fs_list` | List directory | When scanning structure |
57
+ | `fs_exists` | Check existence | Before conditional ops |
58
+ | `file_insert_after` | Surgical file insertion | route_manager.js, swagger |
59
+ | `file_contains` | Check before appending | Avoid duplicates |
60
+ | `run_drift_check` | Context vs disk | During @sync |
61
+ | `lint_file` | Lint generated file | After JS/SQL generation |
62
+ | `analyze_middleware_order` | Check middleware chain | During @audit |
63
+ | `analyze_encryption_library` | Verify encryption | During @audit |
64
+ | `analyze_language_keys` | Check i18n | During @audit |
65
+ | `analyze_dependencies` | Scan package.json | During @audit |
66
+ | `analyze_env_file` | Check .env completeness | During @audit |
67
+ | `validate_redis_connection` | Test Redis | During init |
68
+ | `validate_postgres_connection` | Test DB | During init |
69
+
70
+ ---
71
+
72
+ ## Section 3 — API Builder (NodeJS/Express)
73
+
74
+ ### 2-Layer Architecture (enforced)
75
+ ```
76
+ modules/v1/<ModuleName>/
77
+ ├── route.js ← HTTP only: validation, middleware, res.json()
78
+ └── <module>_model.js ← DB only: queries, business logic
79
+ ```
80
+ Never SQL in `route.js`. Never `res.json()` in `_model.js`.
81
+
82
+ ### 5-Step SOP for New Endpoints
83
+ 1. **ROUTING** — append to `route_manager.js` via `file_insert_after` (never rewrite)
84
+ 2. **VALIDATION** — validatorjs schema in `route.js`, match existing patterns
85
+ 3. **CONTROLLER** — model call + try/catch + `sendResponse()` in `route.js`
86
+ 4. **MODEL** — parameterized `$1,$2` SQL via pg pool in `_model.js`
87
+ 5. **LOCALIZE** — all strings in `languages/en.js`, check with `file_contains` first
88
+
89
+ ### Middleware Chain Order
90
+ Language extraction → API key validation → JWT auth (protected only) → Rate limiting → Validation → Handler
91
+
92
+ ### Response Contract
93
+ ```javascript
94
+ { status: 1, message: lang.key, data: result } // success
95
+ { status: 0, message: lang.key } // error
96
+ { status: -1, message: lang.key } // session expired
97
+ ```
98
+ Always `sendResponse(req, res, status, message, data)`. Never `res.json()` directly.
99
+
100
+ ### Localizify Rules
101
+ Only `headerValidator.js` and `response.js` may import localizify or call `t()`.
102
+ All other files use `sendResponse()`, `getMessage()`, or `req.t("key")`.
103
+
104
+ ### Encryption Selection
105
+ | client_type | Library | Demo file |
106
+ |-------------|---------|-----------|
107
+ | `reactjs` | crypto-js AES-256-CBC | enc_dec.html |
108
+ | `app` | cryptlib AES-256-CBC | enc_dec.php |
109
+ `encrypted_transport: true` → encrypt full response payload.
110
+ KEY/IV always from context — never hardcode.
111
+
112
+ ### Service File Structure
113
+ ```
114
+ <service>/
115
+ app.js, .env, .env.example, .gitignore, README.md, package.json
116
+ config/ common.js, constants.js, database.js, template.js
117
+ languages/ <lang>.js (one per supported_languages[])
118
+ logger/ logging.js, logs/ (gitignored)
119
+ middleware/ headerValidator.js, rateLimiter.js
120
+ modules/v1/ route_manager.js, <ModuleName>/route.js + <m>_model.js
121
+ utilities/ encryption.js, response.js, validator.js, ioRedis.js, notification.js
122
+ document/v1/ swagger_doc.json
123
+ tests/v1/ <ModuleName>.test.js
124
+ pem/ (gitignored), images/ (gitignored)
125
+ ```
126
+
127
+ ### JSDoc Standard
128
+ ```javascript
129
+ /**
130
+ * One-sentence description. Active voice.
131
+ * @param {type} name - Description.
132
+ * @returns {Promise<Object>} Description.
133
+ */
134
+ ```
135
+ Middleware: `@middleware` tag, no `@returns`. Route: `// POST /path — Business purpose.`
136
+ No inline `//` inside function bodies. No file-level headers.
137
+
138
+ ---
139
+
140
+ ## Section 4 — Database Architect
141
+
142
+ ### Before Any SQL File
143
+ Call `migration_next_number`. Load `context.db` fully. `database/` always at repo root.
144
+
145
+ ### Naming Conventions (strict)
146
+ | Element | Rule | Example |
147
+ |---------|------|---------|
148
+ | Table | `tbl_` prefix, lowercase, plural | `tbl_users` |
149
+ | Column | lowercase snake_case | `user_id`, `created_at` |
150
+ | PK | `id` bigint identity, first column | always |
151
+ | FK | `<table_singular_no_prefix>_id` | `user_id` refs `tbl_users` |
152
+ | Create file | `<N>-setup-tbl-<n>.sql` | `3-setup-tbl-users.sql` |
153
+ | Alter file | `<N>-alter-tbl-<n>-<desc>.sql` | `12-alter-tbl-users-add-kyc.sql` |
154
+ | Drop file | `<N>-drop-tbl-<n>.sql` | `13-drop-tbl-sessions.sql` |
155
+ | Shared indexes | `111-setup-database-indexes.sql` | always last |
156
+
157
+ ### Primary Key (exact)
158
+ ```sql
159
+ id bigint NOT NULL GENERATED ALWAYS AS IDENTITY (INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1),
160
+ ```
161
+ `PRIMARY KEY (id)` at END of column block — never inline.
162
+
163
+ ### Column Types
164
+ `BIGINT NOT NULL DEFAULT 0` (FK) · `VARCHAR(132)` (email) · `TEXT` (token/password)
165
+ `TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP` · `BOOLEAN NOT NULL DEFAULT FALSE`
166
+ `INTEGER NOT NULL DEFAULT 0 CHECK (status IN (0,1))` · `NUMERIC(18,8)` (financial)
167
+ `JSON NOT NULL DEFAULT '{}'` · NEVER PostgreSQL ENUM — always `VARCHAR + CHECK`
168
+
169
+ ### SQL File Content Order
170
+ ```
171
+ 1. Comment header
172
+ 2. DROP TABLE IF EXISTS CASCADE
173
+ 3. CREATE TABLE (id first, timestamps last)
174
+ 4. COMMENT ON COLUMN (every enum/flag)
175
+ 5. Per-table CREATE INDEX
176
+ 6. ALTER TABLE OWNER TO <context.db.user>
177
+ 7. GRANT ALL ON TABLE TO <context.db.user>
178
+ 8. INSERT seed (reference tables only)
179
+ ```
180
+
181
+ ### Required Columns
182
+ `id` + `created_at` on every table. `status` + `is_deleted` on entity tables. NOT on log/pivot tables.
183
+
184
+ ### Index Rules
185
+ Always index: every FK, `(status,is_deleted)` compound, `created_at DESC` on logs, `email+is_deleted` compound on users, any WHERE/ORDER BY column.
186
+
187
+ ### create-schema.sql
188
+ At `<repo_root>/database/<db_type>/create-schema.sql`. Auto-generated. `\i` entries in numeric order. `111-setup-database-indexes.sql` always last. Update after every table operation.
189
+
190
+ ---
191
+
192
+ ## Section 5 — ReactJS Frontend
193
+
194
+ ### Backend Linking (enforced)
195
+ Inherit from `context.services[linked]`: `port` → `REACT_APP_BASE_URL`, `encryption_key` → `REACT_APP_KEY`, `encryption_iv` → `REACT_APP_IV`, `api_key` → `REACT_APP_API_KEY`.
196
+ NEVER ask user for these. NEVER hardcode.
197
+
198
+ ### File Structure
199
+ ```
200
+ <service>/public/assets/css/style.css index.html .htaccess
201
+ src/api/apiClient.js apiHandler.js
202
+ src/components/ src/pages/Welcome/index.jsx App.jsx index.jsx
203
+ .env (gitignored) .env.example package.json
204
+ ```
205
+
206
+ ### apiClient.js — 4 Responsibilities
207
+ 1. Static headers: `api-key`, `Accept-Language`, `Content-Type: text/plain`
208
+ 2. Request: encrypt body; attach encrypted `token` from `localStorage('wa_token')`
209
+ 3. Response success: decrypt; parse JSON; `status === -1` → logout
210
+ 4. Response error: `ERR_NETWORK` or `401` → logout + error message
211
+
212
+ KEY/IV via `CryptoJS.enc.Hex.parse(process.env.REACT_APP_KEY/IV)`.
213
+
214
+ ### apiHandler.js
215
+ One async function per endpoint. No try/catch, no decryption. Session saving in handler.
216
+
217
+ ### Code Style
218
+ Functional components only. JSDoc on every export. `.module.css` per page. No `console.log`. No hardcoded API paths.
219
+
220
+ ---
221
+
222
+ ## Section 6 — Code Intelligence
223
+
224
+ ### /codeninja:explain
225
+ What it is → How it works → Why this way → Where it connects.
226
+ Use real names from context throughout.
227
+
228
+ ### /codeninja:review
229
+ CRITICAL (security): missing validation, missing apiKey middleware, hardcoded secrets, string SQL concatenation.
230
+ WARNING (architecture): SQL in route.js, res.json() in model.js, strings hardcoded.
231
+ SUGGESTION (quality): missing JSDoc, console.log, SELECT *.
232
+ Output: `[LEVEL] File: path Issue/Before/After/Why`
233
+
234
+ ### /codeninja:debug
235
+ Trace: Language → API key → JWT → Rate limit → Validation → Handler → Model → DB → Response.
236
+ Check: column names vs context.db.schema, middleware order, missing try/catch, RANK vs DENSE_RANK.
237
+ Output: root cause + before/after fix. Confirm before applying.
238
+
239
+ ### /codeninja:optimize
240
+ DB: missing indexes (vs context.db.schema), SELECT *, N+1, no LIMIT, RANK() gaps, DATE() in WHERE, duplicate rows.
241
+ Output: `[HIGH|MED|LOW]` Target/Cause/Fix/Gain. Generate migration for new indexes.
242
+
243
+ ### /codeninja:audit
244
+ Full review + `analyze_middleware_order`, `analyze_encryption_library`, `analyze_language_keys`, `analyze_dependencies`, `analyze_env_file` MCP tools.
245
+
246
+ ---
247
+
248
+ ## Slash Commands Quick Reference
249
+
250
+ Use with `@workspace` in Copilot Chat:
251
+
252
+ | Command | Description |
253
+ |---------|-------------|
254
+ | `@workspace /codeninja:init` | Bootstrap NodeJS service, ReactJS app, or database |
255
+ | `@workspace /codeninja:api` | Add API endpoint (5-step SOP) |
256
+ | `@workspace /codeninja:design` | Plan feature before coding |
257
+ | `@workspace /codeninja:audit` | Security and quality review |
258
+ | `@workspace /codeninja:test` | Generate Jest tests |
259
+ | `@workspace /codeninja:refactor` | Rename with context tracking |
260
+ | `@workspace /codeninja:sync` | Rebuild context from repo |
261
+ | `@workspace /codeninja:explain` | Explain any file or pattern |
262
+ | `@workspace /codeninja:review` | Code review with findings |
263
+ | `@workspace /codeninja:debug` | Debug with code path trace |
264
+ | `@workspace /codeninja:optimize` | Performance improvements |
265
+ | `@workspace /codeninja:db:create` | New table + migration |
266
+ | `@workspace /codeninja:db:modify` | Alter column |
267
+ | `@workspace /codeninja:db:index` | Add index |
268
+ | `@workspace /codeninja:db:drop` | Drop table |
269
+ | `@workspace /codeninja:db:seed` | Add seed data |
270
+ | `@workspace /codeninja:db:sync` | Rebuild DB schema |
271
+ | `@workspace @modularize` | Extract React layout components |
272
+ | `@workspace @validate-page` | Add form validation |
273
+ | `@workspace @integrate-api` | Wire forms to API handlers |
274
+
275
+ ---
276
+
277
+ ## File Locations
278
+
279
+ | What | Path |
280
+ |------|------|
281
+ | Agent personas | `.codeninja/agent/` |
282
+ | Workflow files | `.codeninja/commands/` |
283
+ | Task files | `.codeninja/tasks/` |
284
+ | Context | `.codeninja/context/context.json` |
285
+ | MCP server | `.codeninja/mcp-server.js` |
@@ -0,0 +1,9 @@
1
+ {
2
+ "servers": {
3
+ "codeninja": {
4
+ "type": "stdio",
5
+ "command": "node",
6
+ "args": ["${workspaceFolder}/.codeninja/mcp-server.js"]
7
+ }
8
+ }
9
+ }