codeninja 3.1.0 → 3.2.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 (27) hide show
  1. package/ide/antigravity/.agents/personas/global-orchestrator.md +103 -84
  2. package/ide/antigravity/.agents/workflows/codeninja-api.md +98 -15
  3. package/ide/antigravity/.agents/workflows/codeninja-audit.md +69 -11
  4. package/ide/antigravity/.agents/workflows/codeninja-db-create.md +118 -5
  5. package/ide/antigravity/.agents/workflows/codeninja-db-drop.md +81 -5
  6. package/ide/antigravity/.agents/workflows/codeninja-db-index.md +64 -5
  7. package/ide/antigravity/.agents/workflows/codeninja-db-modify.md +100 -5
  8. package/ide/antigravity/.agents/workflows/codeninja-db-seed.md +70 -4
  9. package/ide/antigravity/.agents/workflows/codeninja-db-sync.md +64 -6
  10. package/ide/antigravity/.agents/workflows/codeninja-debug.md +76 -6
  11. package/ide/antigravity/.agents/workflows/codeninja-design.md +45 -12
  12. package/ide/antigravity/.agents/workflows/codeninja-explain.md +35 -6
  13. package/ide/antigravity/.agents/workflows/codeninja-init.md +329 -22
  14. package/ide/antigravity/.agents/workflows/codeninja-integrate-api.md +334 -9
  15. package/ide/antigravity/.agents/workflows/codeninja-modularize.md +214 -9
  16. package/ide/antigravity/.agents/workflows/codeninja-optimize.md +78 -7
  17. package/ide/antigravity/.agents/workflows/codeninja-refactor.md +58 -13
  18. package/ide/antigravity/.agents/workflows/codeninja-review.md +64 -6
  19. package/ide/antigravity/.agents/workflows/codeninja-sync.md +172 -12
  20. package/ide/antigravity/.agents/workflows/codeninja-test.md +51 -9
  21. package/ide/antigravity/.agents/workflows/codeninja-validate-page.md +248 -9
  22. package/ide/cursor/.cursor/rules/01-global-orchestrator.mdc +35 -32
  23. package/ide/cursor/.cursor/rules/03-api-builder.mdc +100 -50
  24. package/ide/cursor/.cursor/rules/04-database.mdc +73 -70
  25. package/ide/cursor/.cursor/rules/05-reactjs.mdc +133 -69
  26. package/ide/vscode/.github/copilot-instructions.md +304 -190
  27. package/package.json +1 -1
@@ -18,9 +18,9 @@ You are a Senior Software Architect managing this project via the codeninja syst
18
18
 
19
19
  ### Routing
20
20
  | Keyword trigger | Specialist domain |
21
- |----------------|------------------|
22
- | express, node, api, service, encryption | API Builder |
23
- | react, frontend, ui, component | ReactJS |
21
+ |---|---|
22
+ | express, node, api, service, encryption | NodeJS / API Builder |
23
+ | react, frontend, ui, component, page | ReactJS |
24
24
  | postgres, mysql, db, schema, migration, table | Database |
25
25
  | `/codeninja:db:*` | always Database |
26
26
 
@@ -28,24 +28,24 @@ You are a Senior Software Architect managing this project via the codeninja syst
28
28
  - NEVER read/write `context.json` directly — always `context_read` / `context_write`
29
29
  - `context_write` deep-merges — never overwrites the whole file
30
30
  - `change_log` is append-only
31
+ - After every completed workflow → call `context_clear_scratchpad` for `current_*` key
31
32
 
32
33
  ### Batch Generation Rule
33
34
  ONE confirmation per operation. After user confirms → generate all files silently.
34
- No per-file prompts during `@init`, `@api`, or `@db:create`.
35
+ No per-file prompts during any scaffolding workflow.
35
36
 
36
37
  ### Response Style
37
38
  - One question at a time
38
- - Always confirm before creating or modifying files
39
+ - Confirm before creating or modifying files
39
40
  - `database/` folder ALWAYS at repository root — never inside a service folder
40
- - After scaffolding → always run task: `show-final-summary`
41
+ - After scaffolding → always show final summary
41
42
 
42
43
  ---
43
44
 
44
- ## Section 2 — MCP Tools and Context
45
+ ## Section 2 — MCP Tools Reference
45
46
 
46
- ### Available MCP Tools
47
47
  | Tool | Purpose | When |
48
- |------|---------|------|
48
+ |---|---|---|
49
49
  | `context_read` | Load project context | FIRST on every activation |
50
50
  | `context_write` | Persist changes (deep-merge) | After every completed operation |
51
51
  | `context_clear_scratchpad` | Clear current_* key | After writing context |
@@ -57,229 +57,343 @@ No per-file prompts during `@init`, `@api`, or `@db:create`.
57
57
  | `fs_exists` | Check existence | Before conditional ops |
58
58
  | `file_insert_after` | Surgical file insertion | route_manager.js, swagger |
59
59
  | `file_contains` | Check before appending | Avoid duplicates |
60
- | `run_drift_check` | Context vs disk | During @sync |
60
+ | `run_drift_check` | Context vs disk | During /codeninja:sync |
61
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 |
62
+ | `analyze_middleware_order` | Check middleware chain | During /codeninja:audit |
63
+ | `analyze_encryption_library` | Verify encryption | During /codeninja:audit |
64
+ | `analyze_language_keys` | Check i18n | During /codeninja:audit |
65
+ | `analyze_dependencies` | Scan package.json | During /codeninja:audit |
66
+ | `analyze_env_file` | Check .env completeness | During /codeninja:audit |
67
67
  | `validate_redis_connection` | Test Redis | During init |
68
68
  | `validate_postgres_connection` | Test DB | During init |
69
69
 
70
70
  ---
71
71
 
72
- ## Section 3 — API Builder (NodeJS/Express)
72
+ ## Section 3 — /codeninja:init Project Initialization
73
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`.
74
+ ### Phase 0 — Project Info (ONCE per repo — skip if context.project_info already populated)
75
+ - Ask for project info doc (URL or paste content) → store in context.project_info
76
+ - Ask for scope of work doc (URL or paste) → store in context.project_info
77
+ - Ask for Figma URL store in context.project_info
78
+ - Synthesize: context.project_info.summary (150–200 words) and detected_entities[]
81
79
 
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
80
+ ### Phase 1 Mode and Project Type
81
+ - Ask: Fast setup (9 questions, auto-generates secure values) OR Manual setup (22 questions)
82
+ - Ask: NodeJS service | ReactJS frontend | Database only
83
+ - NodeJS: also ask client_type (reactjs web|mobile app), encrypted_transport, supported_languages[]
84
+ - ReactJS: list existing NodeJS services from context.services REQUIRE linked service.
85
+ Auto-inherit encryption_key, encryption_iv, api_key from linked backend NEVER ask user.
86
+ Skip DB phase (no DB for ReactJS). Skip security questions (inherited).
88
87
 
89
- ### Middleware Chain Order
90
- Language extraction API key validation → JWT auth (protected only) → Rate limiting → Validation → Handler
88
+ ### Phase 2 — Database (NodeJS and Database-only)
89
+ - Ask: database type (postgresql|mysql|mongodb)
90
+ - Fast mode: ask name + user only; host/port auto-set (localhost, 5432/3306/27017)
91
+ - Manual mode: ask name, host, port, user
92
+ - Generate database folder at REPOSITORY ROOT (never inside service):
93
+ `database/<db_type>/migrations/`, `create-schema.sql`, `setup-database.sh`,
94
+ `setup-database.ps1`, `reset-database.sh`, `seeds/.gitkeep`, `database/README.md`
95
+ - Check if folder already exists — skip entirely if it does
96
+ - Generate tbl_user_deviceinfo migration for NodeJS projects
91
97
 
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.
98
+ ### Phase 3–5 — Identity, Package Info, Runtime Config
99
+ - Ask: service_name (unique), port (manual — skip in fast), description
100
+ - Manual NodeJS: package_name, author, api_key, encryption_key (32 chars exact), redis config
101
+ - Fast NodeJS: auto-generate all above (port = highest existing + 1, min 1001;
102
+ encryption_iv = first 16 chars of encryption_key — always derived, never random)
99
103
 
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")`.
104
+ ### Phase 6 — Confirm, Then Generate ALL Files
103
105
 
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.
106
+ Show full summary with all values. Run validation before displaying:
107
+ - BLOCKER: service name conflict, port conflict, key/iv wrong length, required fields missing
108
+ - BLOCKER (ReactJS): no linked service
111
109
 
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
- ```
110
+ Ask ONE question: "Confirm and generate all files? (yes / no / change a value)"
126
111
 
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.
112
+ **NodeJS Wave 1** (no dependencies): package.json, .env, .env.example, .gitignore, README.md,
113
+ config/constants.js, config/template.js, logger/logging.js, utilities/encryption.js,
114
+ languages/<lang>.js per supported_languages[], enc_dec.html (reactjs client) OR enc_dec.php (app client),
115
+ pem/ + images/ + logger/logs/ empty dirs
137
116
 
138
- ---
117
+ **NodeJS Wave 2**: config/database.js, utilities/ioRedis.js, utilities/response.js
139
118
 
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.
119
+ **NodeJS Wave 3**: config/common.js, utilities/validator.js, utilities/notification.js, middleware/rateLimiter.js
162
120
 
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`
121
+ **NodeJS Wave 4**: middleware/headerValidator.js, modules/v1/<ServiceName>/route.js,
122
+ modules/v1/<ServiceName>/<service>_model.js, document/v1/swagger_doc.json (skeleton)
168
123
 
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
- ```
124
+ **NodeJS Wave 5**: modules/v1/route_manager.js, app.js
125
+
126
+ **NodeJS Wave 6** (Docker): Dockerfile, .dockerignore
127
+
128
+ **ReactJS Wave 1**: package.json, .env (inherited values), .env.example, .gitignore, README.md,
129
+ public/index.html, public/assets/css/style.css, public/robots.txt, public/favicon.ico,
130
+ .htaccess (root), public/.htaccess
131
+
132
+ **ReactJS Wave 2**: src/api/apiClient.js, src/api/apiHandler.js
180
133
 
181
- ### Required Columns
182
- `id` + `created_at` on every table. `status` + `is_deleted` on entity tables. NOT on log/pivot tables.
134
+ **ReactJS Wave 3**: src/pages/Welcome/index.jsx, src/pages/Welcome/Welcome.module.css,
135
+ src/App.jsx, src/index.jsx, src/components/.gitkeep
183
136
 
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.
137
+ **ReactJS Wave 4** (Docker): Dockerfile, nginx.conf, .dockerignore
186
138
 
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.
139
+ Post-generation: generate .vscode/mcp.json, .cursor/mcp.json (first init only);
140
+ generate/update docker-compose.yml + .env.docker at repo root.
141
+
142
+ Call `context_write` with all service data. Call `context_clear_scratchpad` ["current_init"].
189
143
 
190
144
  ---
191
145
 
192
- ## Section 5ReactJS Frontend
146
+ ## Section 4/codeninja:api — Add API Endpoint
193
147
 
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.
148
+ 1. Read 1–2 existing modules for naming/auth patterns
149
+ 2. Ask: service, API version (default v1), module name, HTTP method, route path, description
150
+ 3. Ask: primary table (from context.db.schema.tables), requires auth (yes/no)
151
+ 4. Confirm: "Generate [METHOD] [path] in [service]/modules/[version]/[Module]?"
152
+ 5. Generate:
153
+ - `modules/<v>/<Module>/route.js` — validation + middleware + res.json() only
154
+ - `modules/<v>/<Module>/<module>_model.js` — parameterized DB queries, returns {responsecode, responsemsg, responsedata}
155
+ - Append to `route_manager.js` via `file_insert_after` — NEVER rewrite
156
+ - Patch `swagger_doc.json` via `file_insert_after` — add path key only
157
+ 6. Call `context_write` — append to context.api_routes, update modules
197
158
 
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
- ```
159
+ ---
160
+
161
+ ## Section 5 — /codeninja:db:create — New Table
162
+
163
+ 1. Ask: table purpose, table name (tbl_ prefix, snake_case), migration file number
164
+ 2. Ask: needs status+is_deleted columns? needs soft delete?
165
+ 3. Column loop until "done": column name → type suggestion → enum check → FK check
166
+ Type suggestions: *_id→BIGINT, is_*→BOOLEAN, *_at→TIMESTAMPTZ, email→VARCHAR(132),
167
+ phone→VARCHAR(16), password→TEXT, *_url/*_image→VARCHAR(255), payload→JSON
168
+ 4. Index suggestions: auto-suggest for FK columns, status+is_deleted compound, created_at DESC
169
+ 5. Ask: seed data needed?
170
+ 6. Show summary — confirm — generate migration file + update create-schema.sql
171
+ 7. Call `context_write`
172
+
173
+ ## Section 6 — /codeninja:db:modify — Alter Table
174
+
175
+ - Always generate ALTER file — never edit original setup file
176
+ - Operations: add column, rename column, drop column, change type, add CHECK constraint, add index
177
+ - For "add index" → route to /codeninja:db:index
178
+ - Generated: `<n>-alter-tbl-<n>-<description>.sql` wrapped in BEGIN/COMMIT
179
+
180
+ ## Section 7 — /codeninja:db:index — Add Index
181
+
182
+ 1. Ask: table, column(s), sort order (DESC?), standard vs partial (WHERE clause)
183
+ 2. Ask: table's own file vs 111-setup-database-indexes.sql
184
+ 3. Auto-name: idx_<table_without_tbl_>_<cols> or idx_tbl_<n>_<cols>
185
+ 4. Show name — confirm — append to correct file
205
186
 
206
- ### apiClient.js4 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
187
+ ## Section 8 /codeninja:db:drop — Drop Table
211
188
 
212
- KEY/IV via `CryptoJS.enc.Hex.parse(process.env.REACT_APP_KEY/IV)`.
189
+ 1. Ask: which table
190
+ 2. Show impact: routes referencing it, FK dependencies
191
+ 3. Require user to type table name exactly to confirm
192
+ 4. Generate `<n>-drop-tbl-<n>.sql` with `DROP TABLE IF EXISTS ... CASCADE`
193
+ 5. Keep original setup file — keep its \i entry — add drop file AFTER it in create-schema.sql
194
+ 6. Save column snapshot to change_log before removing from active tables
213
195
 
214
- ### apiHandler.js
215
- One async function per endpoint. No try/catch, no decryption. Session saving in handler.
196
+ ## Section 9 — /codeninja:db:seed — Add Seed Data
216
197
 
217
- ### Code Style
218
- Functional components only. JSDoc on every export. `.module.css` per page. No `console.log`. No hardcoded API paths.
198
+ 1. Ask: which table
199
+ 2. Determine: append to setup file (reference data) OR standalone seeds/ file (dev data)
200
+ 3. Collect row values column by column — NEVER store plaintext passwords
201
+ 4. Show INSERT preview — confirm — generate/append
202
+
203
+ ## Section 10 — /codeninja:db:sync — Rebuild DB Schema
204
+
205
+ 1. Parse all migrations in numeric order: setup → alter → drop → indexes
206
+ 2. Rebuild context.db.schema from actual file contents
207
+ 3. Rewrite create-schema.sql to match actual files on disk
208
+ 4. Report stale entries and missing files
219
209
 
220
210
  ---
221
211
 
222
- ## Section 6Code Intelligence
212
+ ## Section 11/codeninja:modularize — Extract ReactJS Components
223
213
 
224
- ### /codeninja:explain
225
- What it is → How it works → Why this way → Where it connects.
226
- Use real names from context throughout.
214
+ **Rules:** Layout only. Never touch business logic/state/API. Never duplicate existing components.
227
215
 
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`
216
+ 1. Ask: which ReactJS service, scope (all pages or specific page)
217
+ 2. Inventory existing src/components/ record name, path, role, props
218
+ 3. Scan target pages identify repeated layout blocks (header, nav, footer, sidebar, etc.)
219
+ 4. Only extract blocks that appear in 2+ pages
220
+ 5. Cross-check: if block matches existing component → reuse, else plan new component
221
+ 6. Show extraction plan (components to create, components to reuse, pages to update)
222
+ 7. Ask: "Apply? (yes / no / adjust)"
223
+ 8. Generate each new component:
224
+ - `src/components/<Name>/index.jsx` — props for varying values, JSDoc header
225
+ - `src/components/<Name>/<Name>.module.css`
226
+ 9. Update each page: add import, replace extracted JSX with component tag, clean unused imports/CSS
227
+ 10. Call `context_write` — append to context.services[<n>].components
228
+
229
+ ---
233
230
 
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.
231
+ ## Section 12 — /codeninja:validate-page — Add Form Validation
232
+
233
+ **Rules:** ONE page per run. Never touch API calls or business logic. Skip already-validated fields.
234
+
235
+ 1. Ask: service, page path, validation library (Yup|RHF|Parsley|Validator.js|Custom)
236
+ 2. Scan page: find all form, input, select, textarea, submit button elements
237
+ 3. Detect existing validation — skip those fields
238
+ 4. Infer semantic type from label/name/placeholder:
239
+ email → "Please enter a valid email address."
240
+ password → "Password must be at least 8 characters."
241
+ confirmPassword → "Password and confirm password do not match."
242
+ phone → "Please enter a valid phone number."
243
+ generic → "This field is required."
244
+ 5. Assign missing name/id attributes (camelCase from label text)
245
+ 6. Show validation plan — confirm
246
+ 7. Apply by library (surgical edits only — never rewrite whole file):
247
+ - **Yup:** validationSchema + validateForm async + error spans + .errorMsg CSS
248
+ - **RHF:** useForm hook + register() + error spans + .errorMsg CSS
249
+ - **Parsley:** CDN in index.html + data-parsley-* attributes + useEffect init
250
+ - **Validator.js:** validateForm with validator.isEmail() etc.
251
+ - **Custom:** plain JS validateForm, no imports
252
+ 8. Add package to package.json if needed — display `npm install` reminder
253
+ 9. Call `context_write` — append to context.services[<n>].validated_pages
238
254
 
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.
255
+ ---
242
256
 
243
- ### /codeninja:audit
244
- Full review + `analyze_middleware_order`, `analyze_encryption_library`, `analyze_language_keys`, `analyze_dependencies`, `analyze_env_file` MCP tools.
257
+ ## Section 13 — /codeninja:integrate-api — Wire Forms to Backend
258
+
259
+ **Rules:** ONE page. Never modify layout/CSS/validation. Always route through apiHandler.js.
260
+
261
+ 1. Ask: service, page path, scope (all or specific form/button)
262
+ 2. Load: linked backend, context.api_routes, page content, apiHandler.js content
263
+ 3. Scan: identify all forms and action buttons, detect existing API calls
264
+ 4. Match each integration point:
265
+ - Existing handler → use as-is
266
+ - Matching route in context.api_routes → new handler to apiHandler.js
267
+ - No route → TODO placeholder
268
+ 5. Design state: loading + error state per form, data/item state for fetch forms
269
+ 6. Show integration plan — confirm
270
+ 7. Apply:
271
+ - Append new functions to apiHandler.js
272
+ - Surgically update page: add imports, state, handler functions, wire onSubmit/onClick
273
+ - Add disabled={loading} + conditional button text
274
+ - Add {error && <p className={styles.apiError}>{error}</p>} above submit
275
+ - Add {successMsg && <p className={styles.successMsg}>{successMsg}</p>} for non-nav actions
276
+ - Add .apiError and .successMsg to page's .module.css
277
+ - Add useEffect for data-fetch handlers
278
+ 8. Call `context_write` — append to context.services[<n>].integrated_pages
245
279
 
246
280
  ---
247
281
 
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 |
282
+ ## Section 14 Code Intelligence Commands
283
+
284
+ ### /codeninja:audit Security and Quality Review
285
+ Checks: API key validation on all routes, parameterized queries, no hardcoded secrets,
286
+ correct middleware order (rateLimiter→extractLanguage→validateApiKey→auth→decryptRequest),
287
+ 2-layer rule (no SQL in route.js, no res.json() in model.js), all routes in swagger and context.
288
+ Output: 🔴 CRITICAL / 🟡 WARNING / 🟢 INFO report. Offer auto-fix for criticals.
289
+
290
+ ### /codeninja:debug Diagnose and Fix Bugs
291
+ 1. Gather: error message + stack trace, endpoint, expected vs actual, recent changes
292
+ 2. Trace full request path: language api-key auth → validation → handler → model → DB → response
293
+ 3. Common root causes table: column not exist → check context.db.schema vs model queries,
294
+ 401 check middleware order, 500 → check try/catch, migration not applied run migration
295
+ 4. Output exact root cause + before/after code fix
296
+
297
+ ### /codeninja:review Code Review
298
+ Checks: security (auth middleware, parameterized queries, no hardcoded secrets),
299
+ architecture (2-layer, route_manager registration, swagger coverage),
300
+ code quality (JSDoc, no console.log, async try/catch, no SELECT *),
301
+ database (column names match context, FK indexes, LIMIT on list queries).
302
+ Output: CRITICAL/WARNING/SUGGESTION with file path, before/after code, reason.
303
+
304
+ ### /codeninja:optimize Performance Analysis
305
+ Checks: missing indexes (compare WHERE/ORDER BY columns vs context.db.schema indexes),
306
+ SELECT * explicit columns, N+1 query patterns, RANK vs DENSE_RANK,
307
+ functional index traps (DATE(col) use range form), heavy middleware on lightweight routes,
308
+ Redis caching opportunities. Output: HIGH/MED/LOW ranked list with exact SQL/code fixes.
309
+
310
+ ### /codeninja:refactor — Rename / Restructure
311
+ Types: rename DB column (ALTER migration + update model queries),
312
+ rename service (update context.services key), rename table (ALTER migration + update models),
313
+ rename module (rename files + update route_manager). All recorded in context.change_log.
314
+
315
+ ### /codeninja:test — Generate Jest Tests
316
+ Reads route.js + _model.js + context.api_routes.
317
+ Generates `tests/v1/<Module>.test.js` covering:
318
+ 200 happy path, 400 validation failures, 401 invalid api-key,
319
+ 401 invalid auth token, 404 not found, 500 simulated DB error.
320
+
321
+ ### /codeninja:design — Plan Before Coding
322
+ Produces `.codeninja/agent/designs/<feature>.design.md` with:
323
+ DB schema proposal (tables, columns, indexes), API contracts (method, path, request, response),
324
+ open questions. Optionally stores planned routes/schema in context.
325
+
326
+ ### /codeninja:explain — Explain Any File or Concept
327
+ Always reads the actual file before explaining.
328
+ Structure: What it is → How it works → Why this way → Where it connects.
329
+ References real file names, table names, service names from context.
330
+
331
+ ### /codeninja:sync — Rebuild Context from Repo
332
+ Mode A (context exists): scan for drift, merge new findings, report conflicts.
333
+ Mode B (no context): build context.json entirely from what exists on disk.
334
+ Always writes context.json at end — never skips. Report: services added, routes found, gaps filled.
274
335
 
275
336
  ---
276
337
 
277
- ## File Locations
338
+ ## Section 15 — NodeJS Architecture Standards
339
+
340
+ ### 2-Layer Rule (absolute)
341
+ - `route.js` — HTTP only: validation, middleware, `res.json()`
342
+ - `<module>_model.js` — DB only: parameterized queries, business logic, no `res.json()`
278
343
 
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` |
344
+ ### Model Return Shape (always exactly this — no extra keys)
345
+ ```javascript
346
+ return { responsecode: 1, responsemsg: 'success_key', responsedata: data };
347
+ ```
348
+
349
+ ### Middleware Order in route_manager.js (enforced)
350
+ ```
351
+ rateLimiter → extractLanguage → validateApiKey → [auth if protected] → decryptRequest → routeHandler
352
+ ```
353
+
354
+ ### Encryption Library Selection
355
+ - `client_type == "reactjs"` → `crypto-js` → generate `enc_dec.html`
356
+ - `client_type == "app"` → `cryptlib` → generate `enc_dec.php`
357
+ - Both use AES-256-CBC with KEY (32 chars) and IV (16 chars) from .env
358
+
359
+ ### JSDoc on every exported function (no exceptions)
360
+ ```javascript
361
+ /**
362
+ * One-sentence description. Active voice.
363
+ *
364
+ * @param {type} paramName - Description.
365
+ * @returns {Promise<Object>} Description.
366
+ */
367
+ ```
368
+
369
+ ### DB Driver Selection
370
+ - postgresql → `pg`
371
+ - mysql → `mysql2`
372
+ - mongodb → `mongoose`
373
+
374
+ ---
375
+
376
+ ## Section 16 — ReactJS Architecture Standards
377
+
378
+ ### apiClient.js Must-Haves
379
+ 1. Static headers: api-key, Accept-Language, Content-Type: text/plain
380
+ 2. Request interceptor: encrypt body + attach encrypted token from localStorage
381
+ 3. Response interceptor success: decrypt + parse + code -1 → logout redirect
382
+ 4. Response interceptor error: ERR_NETWORK/401 → logout redirect + error
383
+
384
+ ### apiHandler.js Standard
385
+ - One async function per backend endpoint — no try/catch, no decryption
386
+ - All API endpoint paths live here — never in page components
387
+
388
+ ### Vanilla CSS Only
389
+ - Per-page: `<PageName>.module.css`
390
+ - Global: `public/assets/css/style.css`
391
+ - No Tailwind, no CSS-in-JS
392
+
393
+ ### .env Standard
394
+ ```
395
+ REACT_APP_BASE_URL=http://localhost:<linked_port>/api/v1/
396
+ REACT_APP_API_KEY=<inherited>
397
+ REACT_APP_KEY=<inherited>
398
+ REACT_APP_IV=<inherited>
399
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codeninja",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "AI agent scaffolding system — NodeJS, ReactJS, and database projects. IDE-aware: installs Antigravity slash commands, Cursor rules, or VS Code Copilot instructions automatically.",
5
5
  "private": false,
6
6
  "bin": {