codeninja 3.2.0 → 4.0.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 (111) hide show
  1. package/README.md +13 -1
  2. package/agent/database-agent.md +24 -1
  3. package/agent/nodejs-agent.md +79 -0
  4. package/cli.js +27 -7
  5. package/commands/audit.workflow.md +4 -1
  6. package/commands/db-create-table.workflow.md +1 -1
  7. package/commands/initialize-project.workflow.md +21 -0
  8. package/ide/antigravity/.agents/personas/database-architect.md +431 -153
  9. package/ide/antigravity/.agents/personas/global-orchestrator.md +202 -85
  10. package/ide/antigravity/.agents/personas/nodejs-backend.md +368 -133
  11. package/ide/antigravity/.agents/personas/reactjs-frontend.md +182 -101
  12. package/ide/antigravity/.agents/skills/api-builder/SKILL.md +58 -0
  13. package/ide/antigravity/.agents/skills/code-intelligence/SKILL.md +22 -0
  14. package/ide/antigravity/.agents/skills/database/SKILL.md +32 -0
  15. package/ide/antigravity/.agents/skills/mcp-and-context/SKILL.md +76 -82
  16. package/ide/antigravity/.agents/skills/reactjs/SKILL.md +36 -0
  17. package/ide/antigravity/.agents/workflows/codeninja-api.md +76 -83
  18. package/ide/antigravity/.agents/workflows/codeninja-audit.md +82 -44
  19. package/ide/antigravity/.agents/workflows/codeninja-db-create.md +107 -94
  20. package/ide/antigravity/.agents/workflows/codeninja-db-drop.md +89 -67
  21. package/ide/antigravity/.agents/workflows/codeninja-db-index.md +86 -54
  22. package/ide/antigravity/.agents/workflows/codeninja-db-modify.md +126 -68
  23. package/ide/antigravity/.agents/workflows/codeninja-db-seed.md +87 -59
  24. package/ide/antigravity/.agents/workflows/codeninja-db-sync.md +77 -41
  25. package/ide/antigravity/.agents/workflows/codeninja-debug.md +35 -21
  26. package/ide/antigravity/.agents/workflows/codeninja-design.md +49 -35
  27. package/ide/antigravity/.agents/workflows/codeninja-explain.md +41 -20
  28. package/ide/antigravity/.agents/workflows/codeninja-init.md +479 -289
  29. package/ide/antigravity/.agents/workflows/codeninja-integrate-api.md +253 -136
  30. package/ide/antigravity/.agents/workflows/codeninja-modularize.md +250 -132
  31. package/ide/antigravity/.agents/workflows/codeninja-optimize.md +71 -29
  32. package/ide/antigravity/.agents/workflows/codeninja-refactor.md +50 -42
  33. package/ide/antigravity/.agents/workflows/codeninja-review.md +38 -21
  34. package/ide/antigravity/.agents/workflows/codeninja-sync.md +922 -141
  35. package/ide/antigravity/.agents/workflows/codeninja-test.md +34 -49
  36. package/ide/antigravity/.agents/workflows/codeninja-validate-page.md +449 -151
  37. package/ide/claude-code/.claude/CLAUDE.md +99 -0
  38. package/ide/claude-code/.claude/agents/database-agent.md +535 -0
  39. package/ide/claude-code/.claude/agents/nodejs-agent.md +493 -0
  40. package/ide/claude-code/.claude/agents/reactjs-agent.md +267 -0
  41. package/ide/claude-code/.claude/commands/codeninja-api.md +104 -0
  42. package/ide/claude-code/.claude/commands/codeninja-audit.md +119 -0
  43. package/ide/claude-code/.claude/commands/codeninja-db-create.md +138 -0
  44. package/ide/claude-code/.claude/commands/codeninja-db-drop.md +109 -0
  45. package/ide/claude-code/.claude/commands/codeninja-db-index.md +103 -0
  46. package/ide/claude-code/.claude/commands/codeninja-db-modify.md +165 -0
  47. package/ide/claude-code/.claude/commands/codeninja-db-seed.md +104 -0
  48. package/ide/claude-code/.claude/commands/codeninja-db-sync.md +106 -0
  49. package/ide/claude-code/.claude/commands/codeninja-debug.md +99 -0
  50. package/ide/claude-code/.claude/commands/codeninja-design.md +68 -0
  51. package/ide/claude-code/.claude/commands/codeninja-explain.md +61 -0
  52. package/ide/claude-code/.claude/commands/codeninja-init.md +529 -0
  53. package/ide/claude-code/.claude/commands/codeninja-integrate-api.md +453 -0
  54. package/ide/claude-code/.claude/commands/codeninja-modularize.md +334 -0
  55. package/ide/claude-code/.claude/commands/codeninja-optimize.md +129 -0
  56. package/ide/claude-code/.claude/commands/codeninja-refactor.md +76 -0
  57. package/ide/claude-code/.claude/commands/codeninja-review.md +87 -0
  58. package/ide/claude-code/.claude/commands/codeninja-sync.md +964 -0
  59. package/ide/claude-code/.claude/commands/codeninja-test.md +45 -0
  60. package/ide/claude-code/.claude/commands/codeninja-validate-page.md +548 -0
  61. package/ide/cursor/.cursor/rules/01-global-orchestrator.mdc +12 -13
  62. package/ide/cursor/.cursor/rules/02-mcp-and-context.mdc +47 -31
  63. package/ide/cursor/.cursor/rules/03-api-builder.mdc +32 -110
  64. package/ide/cursor/.cursor/rules/04-nodejs-generation.mdc +58 -0
  65. package/ide/cursor/.cursor/rules/05-database.mdc +54 -0
  66. package/ide/cursor/.cursor/rules/06-reactjs.mdc +36 -0
  67. package/ide/cursor/.cursor/rules/07-reactjs-generation.mdc +49 -0
  68. package/ide/cursor/.cursor/rules/08-code-intelligence.mdc +56 -0
  69. package/ide/cursor/.cursor/rules/09-workflow-steps.mdc +53 -0
  70. package/ide/vscode/.github/copilot-instructions.md +67 -382
  71. package/ide/vscode/.vscode/instructions/code-intelligence.instructions.md +58 -0
  72. package/ide/vscode/.vscode/instructions/database.instructions.md +55 -0
  73. package/ide/vscode/.vscode/instructions/nodejs.instructions.md +77 -0
  74. package/ide/vscode/.vscode/instructions/reactjs.instructions.md +42 -0
  75. package/package.json +2 -2
  76. package/tasks/ask-hashing-library.task.md +31 -0
  77. package/tasks/ask-language-type.task.md +26 -0
  78. package/tasks/ask-new-module-name.task.md +13 -0
  79. package/tasks/ask-new-service-name.task.md +13 -0
  80. package/tasks/ask-old-module-name.task.md +15 -0
  81. package/tasks/ask-old-service-name.task.md +13 -0
  82. package/tasks/ask-orm-type.task.md +26 -0
  83. package/tasks/collect-seed-data.task.md +19 -0
  84. package/tasks/generate-app.task.md +42 -0
  85. package/tasks/generate-common.task.md +13 -0
  86. package/tasks/generate-constants.task.md +13 -0
  87. package/tasks/generate-database.task.md +32 -0
  88. package/tasks/generate-encryption.task.md +28 -0
  89. package/tasks/generate-fast-defaults.task.md +7 -0
  90. package/tasks/generate-hashing.task.md +180 -0
  91. package/tasks/generate-headerValidator.task.md +13 -0
  92. package/tasks/generate-ioRedis.task.md +20 -0
  93. package/tasks/generate-language-en.task.md +12 -0
  94. package/tasks/generate-logging.task.md +12 -0
  95. package/tasks/generate-model.task.md +74 -6
  96. package/tasks/generate-notification.task.md +12 -0
  97. package/tasks/generate-package-json.task.md +69 -0
  98. package/tasks/generate-prisma-client.task.md +56 -0
  99. package/tasks/generate-prisma-schema.task.md +71 -0
  100. package/tasks/generate-rateLimiter.task.md +20 -0
  101. package/tasks/generate-readme.task.md +24 -0
  102. package/tasks/generate-response.task.md +27 -0
  103. package/tasks/generate-route-manager.task.md +32 -0
  104. package/tasks/generate-route.task.md +37 -0
  105. package/tasks/generate-swagger.task.md +8 -0
  106. package/tasks/generate-template.task.md +12 -0
  107. package/tasks/generate-tsconfig.task.md +38 -0
  108. package/tasks/generate-validator.task.md +31 -0
  109. package/ide/cursor/.cursor/rules/04-database.mdc +0 -90
  110. package/ide/cursor/.cursor/rules/05-reactjs.mdc +0 -147
  111. package/ide/cursor/.cursor/rules/06-code-intelligence.mdc +0 -112
@@ -1,399 +1,84 @@
1
- # codeninja — Project Intelligence for GitHub Copilot
1
+ # codeninja — Project Intelligence for GitHub Copilot (v4.0)
2
2
 
3
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
4
 
7
5
  ---
8
6
 
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)
7
+ ## Activation Sequence (every session)
14
8
  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 |
9
+ 2. Call `context_read` — load full project context
10
+ 3. Call `service_scan` — compare with `context.services`; if drift → suggest `/codeninja:sync`
11
+ 4. Load `context.project_info` — use for all suggestions throughout session
26
12
 
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
13
+ ## Context Rules
14
+ - NEVER read/write context.json directly — always `context_read` / `context_write`
15
+ - `context_write` deep-merges — never overwrites
30
16
  - `change_log` is append-only
31
- - After every completed workflow → call `context_clear_scratchpad` for `current_*` key
17
+ - After every completed workflow → call `context_clear_scratchpad` for relevant `current_*` key
32
18
 
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.
19
+ ## Keyword Routing
20
+ | Trigger | Specialist Domain |
21
+ |---|---|
22
+ | express, node, api, service, encryption, typescript | NodeJS standards |
23
+ | react, frontend, ui, component, page | ReactJS standards |
24
+ | postgres, mysql, db, schema, migration, table, prisma, orm | Database standards |
25
+ | `/codeninja:db:*` | always Database standards |
26
+
27
+ ## Batch Generation Rule
28
+ ONE confirmation per operation → generate ALL files silently after confirmation, no per-file prompts.
36
29
 
37
- ### Response Style
30
+ ## Response Style
38
31
  - One question at a time
39
32
  - 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
33
+ - `database/` folder ALWAYS at repository root
34
+ - After every scaffolding operation → show final summary
46
35
 
36
+ ## All Available Commands
37
+ | Command | Description |
38
+ |---|---|
39
+ | `/codeninja:init` | Bootstrap NodeJS service (JS/TS, raw/Prisma), ReactJS app, or database |
40
+ | `/codeninja:api` | Add new API endpoint (route + model + swagger) |
41
+ | `/codeninja:design` | Plan feature before coding |
42
+ | `/codeninja:audit` | Security and quality review |
43
+ | `/codeninja:test` | Generate Jest + Supertest tests |
44
+ | `/codeninja:refactor` | Rename/restructure with context tracking |
45
+ | `/codeninja:sync` | Rebuild context.json from repo |
46
+ | `/codeninja:explain` | Explain any file, function, or concept |
47
+ | `/codeninja:review` | Code review with severity-ranked findings |
48
+ | `/codeninja:debug` | Diagnose and fix bugs |
49
+ | `/codeninja:optimize` | Performance analysis with concrete fixes |
50
+ | `/codeninja:db:create` | New table with migration file |
51
+ | `/codeninja:db:modify` | Alter table via migration |
52
+ | `/codeninja:db:index` | Add index |
53
+ | `/codeninja:db:drop` | Drop table (safety-checked) |
54
+ | `/codeninja:db:seed` | Add seed data |
55
+ | `/codeninja:db:sync` | Rebuild DB schema context from migrations |
56
+ | `/codeninja:modularize` | Extract ReactJS layout components |
57
+ | `/codeninja:validate-page` | Add form validation to ReactJS page |
58
+ | `/codeninja:integrate-api` | Wire ReactJS forms to backend |
59
+
60
+ ## MCP Tools Quick Reference
47
61
  | Tool | Purpose | When |
48
62
  |---|---|---|
49
- | `context_read` | Load project context | FIRST on every activation |
50
- | `context_write` | Persist changes (deep-merge) | After every completed operation |
63
+ | `context_read` | Load context.json | First on every activation |
64
+ | `context_write` | Deep-merge updates | After every completed operation |
51
65
  | `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>
66
+ | `context_check_stale` | Detect unresolved ops | Step 0 of activation |
67
+ | `service_scan` | Discover services on disk | Step 2 of activation |
68
+ | `migration_next_number` | Next sequential migration # | Before any migration file |
69
+ | `file_insert_after` | Surgical insert | route_manager, swagger never rewrite |
70
+ | `file_contains` | Check for string | Before appending |
71
+ | `lint_file` | Lint generated JS/TS | After generation |
72
+
73
+ ## MCP Server Setup
74
+ Add to your VS Code MCP settings:
75
+ ```json
76
+ {
77
+ "mcpServers": {
78
+ "codeninja": {
79
+ "command": "node",
80
+ "args": ["${workspaceFolder}/.codeninja/mcp-server.js"]
81
+ }
82
+ }
83
+ }
399
84
  ```
@@ -0,0 +1,58 @@
1
+ ---
2
+ applyTo: "**/*"
3
+ ---
4
+
5
+ # codeninja — Code Intelligence Standards (v4.0)
6
+
7
+ ## /codeninja:audit Checklist
8
+
9
+ ### Security
10
+ - [ ] Passwords HASHED using `utilities/hashing.js` (bcrypt/argon2)? Not AES-encrypted?
11
+ - [ ] No direct bcrypt/argon2 imports in route/model files?
12
+ - [ ] Parameterized queries only — no string concatenation in SQL?
13
+ - [ ] API key validation on all routes?
14
+ - [ ] No hardcoded secrets in source?
15
+ - [ ] Middleware order: rateLimiter→extractLanguage→validateApiKey→[auth]→decryptRequest?
16
+
17
+ ### Architecture
18
+ - [ ] 2-layer rule enforced (no SQL in route, no res.json in model)?
19
+ - [ ] route_manager.js never fully rewritten (append-only via file_insert_after)?
20
+ - [ ] All routes in swagger_doc.json and context.api_routes?
21
+
22
+ ### v4.0 Checks
23
+ - [ ] orm="prisma": no `new PrismaClient()` in model files?
24
+ - [ ] language="typescript": all .ts files use import/export syntax?
25
+
26
+ ## /codeninja:debug Trace Path
27
+ 1. extractLanguage — Accept-Language header processed?
28
+ 2. validateApiKey — api-key header matches .env API_KEY?
29
+ 3. validateAuthToken (protected only) — JWT valid and not expired?
30
+ 4. rateLimiter — request not throttled?
31
+ 5. validatorjs rules — all required fields in request body?
32
+ 6. Model call — DB connection alive?
33
+ 7. Query — column names match context.db.schema?
34
+ 8. sendResponse — encrypted_transport handled?
35
+
36
+ **401:** middleware order or key mismatch | **400:** validation rules | **500:** DB/column issue
37
+
38
+ ## /codeninja:review Dimensions
39
+ - Security: auth middleware, parameterized queries, no hardcoded secrets, hashing not encryption
40
+ - Architecture: 2-layer rule, route_manager append-only, swagger/context coverage
41
+ - Code quality: JSDoc on all functions, no console.log, async try/catch
42
+ - Database: column names match context, FK indexes, LIMIT on list queries
43
+
44
+ ## /codeninja:optimize Patterns (ranked)
45
+ 1. Missing index → `CREATE INDEX CONCURRENTLY` (no table lock)
46
+ 2. `SELECT *` → explicit column list
47
+ 3. N+1 query → JOIN or IN clause
48
+ 4. `DATE(col)` in WHERE → range filter to use index
49
+ 5. `RANK()` with gaps → `DENSE_RANK()` for leaderboards
50
+ 6. Unbounded list query → add `LIMIT` and `OFFSET`
51
+ 7. Repeated identical queries → Redis cache opportunity
52
+ 8. `work_mem` for sort-heavy queries
53
+
54
+ ## /codeninja:refactor Types
55
+ - Rename DB column: ALTER migration + update model queries + context.change_log
56
+ - Rename service: update context.services key + context.change_log
57
+ - Rename table: ALTER migration + update all model references + context.change_log
58
+ - Rename module: rename files + update route_manager + context.change_log
@@ -0,0 +1,55 @@
1
+ ---
2
+ applyTo: "**/*.sql,**/database/**,**/prisma/**"
3
+ ---
4
+
5
+ # codeninja — Database Standards (v4.0)
6
+
7
+ ## Naming Conventions
8
+ | Element | Rule | Example |
9
+ |---|---|---|
10
+ | Table | `tbl_` prefix, lowercase, plural | `tbl_users` |
11
+ | Column | lowercase snake_case | `user_id`, `created_at` |
12
+ | PK | `id`, bigint identity, first column | always |
13
+ | FK | `<ref_table_singular_no_tbl>_id` | `user_id` refs `tbl_users` |
14
+ | Index (per-table) | `idx_<table_no_tbl>_<cols>` | `idx_users_email` |
15
+ | Shared indexes | `111-setup-database-indexes.sql` | always last file |
16
+
17
+ ## Column Types
18
+ | Use Case | PostgreSQL Type |
19
+ |---|---|
20
+ | PK | `bigint NOT NULL GENERATED ALWAYS AS IDENTITY (INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1)` |
21
+ | FK | `BIGINT NOT NULL DEFAULT 0` |
22
+ | Email | `VARCHAR(132) NOT NULL DEFAULT ''` |
23
+ | Password/token | `TEXT NOT NULL DEFAULT ''` |
24
+ | Status | `INTEGER NOT NULL DEFAULT 0 CHECK (status IN (0, 1))` |
25
+ | Soft delete | `BOOLEAN NOT NULL DEFAULT FALSE` |
26
+ | Timestamp | `TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP` |
27
+ | Financial | `NUMERIC(18,8) NOT NULL DEFAULT 0.00000000` |
28
+ | JSON | `JSON NOT NULL DEFAULT '{}'` |
29
+
30
+ NEVER use PostgreSQL ENUM — always `VARCHAR + CHECK constraint + COMMENT ON COLUMN`.
31
+
32
+ ## SQL File Content Order (strict)
33
+ 1. `-- Creating tbl_name for purpose`
34
+ 2. `DROP TABLE IF EXISTS public.tbl_name CASCADE;`
35
+ 3. `CREATE TABLE` block (id first, timestamps last)
36
+ 4. `COMMENT ON COLUMN` for every enum/flag/status column
37
+ 5. Per-table `CREATE INDEX` statements
38
+ 6. `ALTER TABLE ... OWNER TO <db_user>`
39
+ 7. `GRANT ALL ON TABLE ... TO <db_user>`
40
+ 8. Seed `INSERT` (reference/master tables only)
41
+
42
+ ## Index Strategy
43
+ Always index: every FK column; (status + is_deleted) compound; created_at DESC on log tables; email + is_deleted on user tables. Most selective column first in compound indexes.
44
+
45
+ ## create-schema.sql Maintenance
46
+ After every table operation: re-read the file → add/remove/reorder `\i` entries → write back.
47
+ ALTER files go immediately after their CREATE file. 111-indexes always last.
48
+
49
+ ## Prisma Conventions (v4.0)
50
+ - `tbl_users` → `model Users` (strip tbl_, PascalCase) + `@@map("tbl_users")`
51
+ - `id` BIGINT IDENTITY → `id BigInt @id @default(autoincrement())`
52
+ - `created_at` → `createdAt DateTime @default(now()) @map("created_at")`
53
+ - `is_deleted` → `isDeleted Boolean @default(false) @map("is_deleted")`
54
+ - FK `user_id` → `userId BigInt @map("user_id")` + relation field
55
+ - After any model addition → `npx prisma generate`
@@ -0,0 +1,77 @@
1
+ ---
2
+ applyTo: "**/*.js,**/*.ts"
3
+ ---
4
+
5
+ # codeninja — NodeJS Standards (v4.0)
6
+
7
+ ## The 2-Layer Rule (absolute)
8
+ - `route.js/ts` — HTTP only: validation, middleware, `res.json()` via sendResponse
9
+ - `<module>_model.js/ts` — DB only: queries, business logic, never `res.json()`
10
+
11
+ ## Middleware Order (never change)
12
+ ```
13
+ rateLimiter → extractLanguage → validateApiKey → [auth if protected] → decryptRequest → routeHandler
14
+ ```
15
+
16
+ ## Response Contract
17
+ ```javascript
18
+ sendResponse(req, res, 1, 'success_key', data) // success
19
+ sendResponse(req, res, 0, 'error_key', []) // error
20
+ sendResponse(req, res, -1, 'session_expired', []) // auth expired → frontend logout
21
+ ```
22
+
23
+ ## Password Hashing (v4.0 — CRITICAL)
24
+ - NEVER use `encryption.js` for passwords — reversible AES is a security vulnerability
25
+ - ALWAYS use `utilities/hashing.js`: `hashPassword(plain)` to store, `verifyPassword(plain, hash)` to check
26
+ - Import: `const { hashPassword, verifyPassword } = require('../../utilities/hashing')`
27
+ - TypeScript: `import { hashPassword, verifyPassword } from '../../utilities/hashing'`
28
+
29
+ ## ORM Branch (v4.0)
30
+ Read `context.db.orm` before generating any model:
31
+ - orm="none": parameterized SQL with `$1`, `$2` placeholders via pg/mysql2/mongoose
32
+ - orm="prisma": `prisma.tableName.operation()` — import singleton from `config/prisma`, never `new PrismaClient()`
33
+ - Prisma table access: `tbl_users` → `prisma.users` (lowercase, strip `tbl_` prefix)
34
+
35
+ ## TypeScript Support (v4.0)
36
+ Read `context.services[name].language`:
37
+ - "javascript": `.js` files, `require()`/`module.exports`, no tsconfig
38
+ - "typescript": `.ts` files, `import`/`export`, typed params, `tsconfig.json` in Wave 1
39
+
40
+ TypeScript patterns:
41
+ ```typescript
42
+ // route.ts
43
+ import { Router, Request, Response } from 'express';
44
+ router.post('/path', async (req: Request, res: Response) => { ... });
45
+ export default router;
46
+
47
+ // _model.ts
48
+ export async function functionName(request: RequestType, user_id: number, user_type: string): Promise<object> { ... }
49
+ ```
50
+
51
+ ## Localizify Rules
52
+ - ONLY `headerValidator.js/ts` and `response.js/ts` may call `t()` directly
53
+ - All other files use `sendResponse()`, `getMessage()`, or `req.t("key")`
54
+
55
+ ## Code Style
56
+ - JSDoc on every exported function (no exceptions)
57
+ - No inline `//` comments inside function bodies
58
+ - Route comment: `// POST /path — description` above each route handler
59
+ - No file-level header comments
60
+
61
+ ## .env Keys (NodeJS service)
62
+ ```
63
+ PORT=, API_KEY=, KEY=, IV=, ENCRYPTED_TRANSPORT=, SUPPORTED_LANGUAGES=,
64
+ DB_HOST=, DB_PORT=, DB_NAME=, DB_USER=, DB_PASSWORD=,
65
+ REDIS_HOST=, REDIS_PORT=,
66
+ DATABASE_URL= (Prisma only — replaces individual DB_* vars)
67
+ ```
68
+
69
+ ## Wave Generation Order
70
+ Before generating any file, read `.codeninja/tasks/generate-<name>.task.md`.
71
+
72
+ Wave 1: package.json, .env, .gitignore, README.md, config/constants, config/template, logger/logging, utilities/encryption, **utilities/hashing** (v4.0), languages/*, **tsconfig.json** (TS only, v4.0)
73
+ Wave 2: config/database OR config/prisma (v4.0 ORM branch), utilities/ioRedis, utilities/response
74
+ Wave 3: config/common, utilities/validator, utilities/notification, middleware/rateLimiter
75
+ Wave 4: middleware/headerValidator, modules/v1/<Name>/route, modules/v1/<Name>/_model, swagger_doc.json
76
+ Wave 5: modules/v1/route_manager, app.js/ts
77
+ Wave 6: Dockerfile, .dockerignore