codeninja 2.0.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 (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 +144 -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 +111 -0
  18. package/ide/antigravity/.agents/workflows/codeninja-audit.md +81 -0
  19. package/ide/antigravity/.agents/workflows/codeninja-db-create.md +124 -0
  20. package/ide/antigravity/.agents/workflows/codeninja-db-drop.md +87 -0
  21. package/ide/antigravity/.agents/workflows/codeninja-db-index.md +70 -0
  22. package/ide/antigravity/.agents/workflows/codeninja-db-modify.md +106 -0
  23. package/ide/antigravity/.agents/workflows/codeninja-db-seed.md +76 -0
  24. package/ide/antigravity/.agents/workflows/codeninja-db-sync.md +70 -0
  25. package/ide/antigravity/.agents/workflows/codeninja-debug.md +82 -0
  26. package/ide/antigravity/.agents/workflows/codeninja-design.md +54 -0
  27. package/ide/antigravity/.agents/workflows/codeninja-explain.md +40 -0
  28. package/ide/antigravity/.agents/workflows/codeninja-init.md +336 -0
  29. package/ide/antigravity/.agents/workflows/codeninja-integrate-api.md +336 -0
  30. package/ide/antigravity/.agents/workflows/codeninja-modularize.md +216 -0
  31. package/ide/antigravity/.agents/workflows/codeninja-optimize.md +84 -0
  32. package/ide/antigravity/.agents/workflows/codeninja-refactor.md +68 -0
  33. package/ide/antigravity/.agents/workflows/codeninja-review.md +70 -0
  34. package/ide/antigravity/.agents/workflows/codeninja-sync.md +183 -0
  35. package/ide/antigravity/.agents/workflows/codeninja-test.md +61 -0
  36. package/ide/antigravity/.agents/workflows/codeninja-validate-page.md +250 -0
  37. package/ide/cursor/.cursor/mcp.json +8 -0
  38. package/ide/cursor/.cursor/rules/01-global-orchestrator.mdc +63 -0
  39. package/ide/cursor/.cursor/rules/02-mcp-and-context.mdc +38 -0
  40. package/ide/cursor/.cursor/rules/03-api-builder.mdc +124 -0
  41. package/ide/cursor/.cursor/rules/04-database.mdc +90 -0
  42. package/ide/cursor/.cursor/rules/05-reactjs.mdc +147 -0
  43. package/ide/cursor/.cursor/rules/06-code-intelligence.mdc +112 -0
  44. package/ide/vscode/.github/copilot-instructions.md +399 -0
  45. package/ide/vscode/.vscode/mcp.json +9 -0
  46. package/package.json +24 -23
@@ -0,0 +1,147 @@
1
+ ---
2
+ description: codeninja ReactJS Frontend — scaffolding, modularize, validate-page, integrate-api
3
+ globs: ["**/src/**/*.jsx", "**/src/**/*.js", "**/public/**", "**/.htaccess"]
4
+ alwaysApply: false
5
+ ---
6
+
7
+ # codeninja — ReactJS Frontend
8
+
9
+ ## Backend Linking Rule (enforced)
10
+ ReactJS service CANNOT initialize without a linked NodeJS service.
11
+ Security values (KEY, IV, API_KEY) are ALWAYS inherited from the linked backend — never asked from user.
12
+
13
+ ## /codeninja:init — ReactJS App Scaffolding
14
+
15
+ ### Phase 1 — Linking
16
+ - List available NodeJS services from context.services
17
+ - Ask: which NodeJS service to link to?
18
+ - Auto-inherit: encryption_key, encryption_iv, api_key from linked service
19
+ - Ask: service name, description
20
+
21
+ ### Phase 2 — Single Confirmation, Then Generate ALL Files
22
+
23
+ **Wave 1:** package.json, .env (inherited values), .env.example, .gitignore, README.md,
24
+ public/index.html, public/assets/css/style.css (empty reset), public/robots.txt,
25
+ public/favicon.ico (placeholder), .htaccess (root), public/.htaccess
26
+
27
+ **Wave 2:** src/api/apiClient.js, src/api/apiHandler.js
28
+
29
+ **Wave 3:** src/pages/Welcome/index.jsx, src/pages/Welcome/Welcome.module.css,
30
+ src/App.jsx, src/index.jsx, src/components/.gitkeep
31
+
32
+ **Wave 4:** Dockerfile, nginx.conf, .dockerignore
33
+
34
+ Completion gate — verify before proceeding:
35
+ - public/index.html, src/api/apiClient.js, src/api/apiHandler.js, src/App.jsx, src/index.jsx, .env
36
+
37
+ ### apiClient.js — 4 Responsibilities
38
+ 1. Static headers: `api-key` (from REACT_APP_API_KEY), `Accept-Language`, `Content-Type: text/plain`
39
+ 2. Request interceptor: encrypt body; attach AES-encrypted `token` from localStorage (`wa_token`) if present
40
+ 3. Response interceptor (success): decrypt body; parse JSON; code -1 → logout redirect
41
+ 4. Response interceptor (error): ERR_NETWORK / 401 → logout redirect + error message
42
+
43
+ ### apiHandler.js Standard
44
+ - One async function per API endpoint
45
+ - Each calls `axiosClient.post/get/put/patch/delete(path, payload)` and returns directly
46
+ - No try/catch, no decryption, no response shaping in this file
47
+ - Only place in frontend where API endpoint paths are written
48
+
49
+ ---
50
+
51
+ ## /codeninja:modularize — Extract Layout Components
52
+
53
+ **Rule:** Layout structure only — NEVER touch business logic, state, API calls, event handlers.
54
+ NEVER create a component that already exists — reuse it.
55
+
56
+ 1. Ask: which ReactJS service
57
+ 2. Ask: all pages OR specific page
58
+ 3. Inventory existing `src/components/` — record name, path, structural role, props
59
+ 4. Scan target pages — identify repeated layout blocks (header, nav, footer, sidebar, etc.)
60
+ 5. Cross-check: if block matches existing component → mark "reuse", else "new component needed"
61
+ 6. Group blocks by similarity across pages — only extract if appears in 2+ pages
62
+ 7. Show extraction plan with component names, props, files to create, pages to update
63
+ 8. Ask: "Apply? (yes / no / adjust)"
64
+ 9. Generate each new component:
65
+ - `src/components/<ComponentName>/index.jsx` — props for varying values
66
+ - `src/components/<ComponentName>/<ComponentName>.module.css`
67
+ 10. Update each page: add import, replace extracted JSX with `<ComponentName prop={value} />`,
68
+ remove now-unused imports, remove moved CSS classes
69
+ 11. Call `context_write` — append to context.services[<n>].components
70
+
71
+ ---
72
+
73
+ ## /codeninja:validate-page — Add Form Validation
74
+
75
+ **Rule:** ONE page per run. NEVER modify API calls or business logic. NEVER overwrite existing validation.
76
+
77
+ 1. Ask: which ReactJS service, which page path
78
+ 2. Ask: validation library (Yup | React Hook Form | Parsley | Validator.js | Custom)
79
+ 3. Scan page: find all `<form>`, `<input>`, `<select>`, `<textarea>`, `<button type="submit">`
80
+ 4. For each field: record type, name, id, placeholder, label text, existing validation
81
+ 5. Detect existing validation patterns — skip already-validated fields
82
+ 6. Infer semantic type from label/name/placeholder → assign standard error messages:
83
+ - email: "Please enter a valid email address."
84
+ - password: "Password must be at least 8 characters."
85
+ - confirmPassword: "Password and confirm password do not match."
86
+ - phone: "Please enter a valid phone number."
87
+ - required generic: "This field is required."
88
+ 7. Assign missing `name` and `id` attributes (camelCase from label text)
89
+ 8. Show validation plan — ask: "Apply? (yes / no / adjust)"
90
+ 9. Apply by library:
91
+ - **Yup:** validationSchema above component, validateForm async function, `{errors.field && <span>...}`
92
+ - **RHF:** useForm hook, `{...register('field', rules)}`, `{errors.field && <span>...}`
93
+ - **Parsley:** CDN scripts in index.html, data-parsley-* attributes, useEffect init
94
+ - **Validator.js:** import validator, validateForm function with validator.isEmail() etc.
95
+ - **Custom:** plain JS validateForm — no imports
96
+ 10. Add `.errorMsg` class to page's `.module.css`
97
+ 11. Add package to package.json if needed (yup/react-hook-form/validator)
98
+ 12. Call `context_write` — append to context.services[<n>].validated_pages
99
+
100
+ ---
101
+
102
+ ## /codeninja:integrate-api — Wire Forms to Backend
103
+
104
+ **Rule:** ONE page per run. NEVER modify layout, CSS, or validation. ALWAYS use apiHandler.js.
105
+
106
+ 1. Ask: which ReactJS service, which page path
107
+ 2. Ask: all forms/buttons OR specific form/button
108
+ 3. Load: linked backend service, context.api_routes for that backend, page content, apiHandler.js
109
+ 4. Scan page: identify all forms, action buttons, existing API calls
110
+ 5. For each integration point, determine match type:
111
+ - existing handler → use as-is
112
+ - matching route in context.api_routes → add new handler to apiHandler.js
113
+ - no route exists → add TODO placeholder
114
+ 6. Design state requirements (loading, error, data states) per form
115
+ 7. Show integration plan with handler names, routes, match types, files to modify
116
+ 8. Ask: "Apply? (yes / no / adjust)"
117
+ 9. Apply:
118
+ - Append new functions to apiHandler.js (for new_handler and no_route matches)
119
+ - Add imports, state declarations, handler functions to page file (surgically — never rewrite)
120
+ - Wire form onSubmit / button onClick
121
+ - Add `disabled={loading}` and conditional button text
122
+ - Add `{error && <p className={styles.apiError}>{error}</p>}` above submit button
123
+ - Add `{successMsg && <p className={styles.successMsg}>{successMsg}</p>}` for non-nav actions
124
+ - Add useEffect for data-fetching handlers
125
+ - Add .apiError and .successMsg CSS classes to page's .module.css
126
+ 10. Call `context_write` — append to context.services[<n>].integrated_pages
127
+
128
+ ## File Structure
129
+ ```
130
+ <service_name>/
131
+ public/
132
+ assets/css/style.css ← global styles
133
+ index.html ← single HTML shell
134
+ .htaccess ← SPA routing
135
+ src/
136
+ api/
137
+ apiClient.js ← Axios + encrypt/decrypt interceptors
138
+ apiHandler.js ← all API call functions
139
+ components/ ← shared reusable components
140
+ pages/<PageName>/ ← one directory per page
141
+ index.jsx
142
+ <PageName>.module.css
143
+ App.jsx ← React Router root
144
+ index.jsx ← ReactDOM.createRoot entry
145
+ .env ← REACT_APP_* (gitignored)
146
+ .env.example
147
+ ```
@@ -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,399 @@
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 | NodeJS / API Builder |
23
+ | react, frontend, ui, component, page | 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
+ - After every completed workflow → call `context_clear_scratchpad` for `current_*` key
32
+
33
+ ### Batch Generation Rule
34
+ ONE confirmation per operation. After user confirms → generate all files silently.
35
+ No per-file prompts during any scaffolding workflow.
36
+
37
+ ### Response Style
38
+ - One question at a time
39
+ - Confirm before creating or modifying files
40
+ - `database/` folder ALWAYS at repository root — never inside a service folder
41
+ - After scaffolding → always show final summary
42
+
43
+ ---
44
+
45
+ ## Section 2 — MCP Tools Reference
46
+
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 /codeninja:sync |
61
+ | `lint_file` | Lint generated file | After JS/SQL generation |
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
+ | `validate_redis_connection` | Test Redis | During init |
68
+ | `validate_postgres_connection` | Test DB | During init |
69
+
70
+ ---
71
+
72
+ ## Section 3 — /codeninja:init — Project Initialization
73
+
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[]
79
+
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).
87
+
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
97
+
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)
103
+
104
+ ### Phase 6 — Confirm, Then Generate ALL Files
105
+
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
109
+
110
+ Ask ONE question: "Confirm and generate all files? (yes / no / change a value)"
111
+
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
116
+
117
+ **NodeJS Wave 2**: config/database.js, utilities/ioRedis.js, utilities/response.js
118
+
119
+ **NodeJS Wave 3**: config/common.js, utilities/validator.js, utilities/notification.js, middleware/rateLimiter.js
120
+
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)
123
+
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
133
+
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
136
+
137
+ **ReactJS Wave 4** (Docker): Dockerfile, nginx.conf, .dockerignore
138
+
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"].
143
+
144
+ ---
145
+
146
+ ## Section 4 — /codeninja:api — Add API Endpoint
147
+
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
158
+
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
186
+
187
+ ## Section 8 — /codeninja:db:drop — Drop Table
188
+
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
195
+
196
+ ## Section 9 — /codeninja:db:seed — Add Seed Data
197
+
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
209
+
210
+ ---
211
+
212
+ ## Section 11 — /codeninja:modularize — Extract ReactJS Components
213
+
214
+ **Rules:** Layout only. Never touch business logic/state/API. Never duplicate existing components.
215
+
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
+ ---
230
+
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
254
+
255
+ ---
256
+
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
279
+
280
+ ---
281
+
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.
335
+
336
+ ---
337
+
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()`
343
+
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
+ ```
@@ -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
+ }