ai-developer-skill-os 9.1.1 → 9.3.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 (63) hide show
  1. package/.agents/AGENTS.md +139 -42
  2. package/.agents/DEV_PROFILE.md +95 -0
  3. package/.agents/registry/capability-graph.yml +171 -334
  4. package/.agents/registry/graph.json +52 -18
  5. package/.agents/registry/index.yaml +66 -12
  6. package/.agents/registry/skills-index.yml +204 -447
  7. package/.agents/rules/coding.md +23 -0
  8. package/.agents/rules/global.md +44 -30
  9. package/.agents/skills/_template/SKILL.md +2 -300
  10. package/.agents/skills/qk-access-policy/SKILL.md +98 -393
  11. package/.agents/skills/qk-agent-observability/SKILL.md +3 -359
  12. package/.agents/skills/qk-ai-builder/SKILL.md +132 -485
  13. package/.agents/skills/qk-api-consumer/SKILL.md +256 -0
  14. package/.agents/skills/qk-api-consumer/capability.yaml +21 -0
  15. package/.agents/skills/qk-api-consumer/evals/scorecard.yaml +29 -0
  16. package/.agents/skills/qk-api-lifecycle/SKILL.md +133 -376
  17. package/.agents/skills/qk-bug-resolution/SKILL.md +128 -481
  18. package/.agents/skills/qk-code-review/SKILL.md +142 -340
  19. package/.agents/skills/qk-context-loader/SKILL.md +99 -391
  20. package/.agents/skills/qk-data-engineer/SKILL.md +253 -0
  21. package/.agents/skills/qk-data-lifecycle/SKILL.md +89 -408
  22. package/.agents/skills/qk-db-optimizer/SKILL.md +102 -408
  23. package/.agents/skills/qk-design-system-engineering/SKILL.md +76 -381
  24. package/.agents/skills/qk-devops-platform/SKILL.md +77 -383
  25. package/.agents/skills/qk-docs/SKILL.md +88 -414
  26. package/.agents/skills/qk-engineering-standard/SKILL.md +4 -508
  27. package/.agents/skills/qk-fe-api-integration/SKILL.md +343 -263
  28. package/.agents/skills/qk-fe-api-integration/evals/scorecard.yaml +29 -29
  29. package/.agents/skills/qk-feature-delivery/SKILL.md +137 -365
  30. package/.agents/skills/qk-feature-delivery/evals/scorecard.yaml +1 -1
  31. package/.agents/skills/qk-frontend-architecture/SKILL.md +5 -399
  32. package/.agents/skills/qk-help/evals/scorecard.yaml +13 -13
  33. package/.agents/skills/qk-orchestrator/SKILL.md +63 -422
  34. package/.agents/skills/qk-orchestrator/references/routing-table.md +10 -14
  35. package/.agents/skills/qk-product-specification/SKILL.md +70 -399
  36. package/.agents/skills/qk-production-release/SKILL.md +80 -457
  37. package/.agents/skills/qk-project-audit/SKILL.md +174 -0
  38. package/.agents/skills/qk-project-bootstrap/SKILL.md +244 -392
  39. package/.agents/skills/qk-project-health/SKILL.md +97 -416
  40. package/.agents/skills/qk-project-memory/SKILL.md +76 -21
  41. package/.agents/skills/qk-refactor/SKILL.md +167 -304
  42. package/.agents/skills/qk-security-audit/SKILL.md +141 -383
  43. package/.agents/skills/qk-security-audit/capability.yaml +1 -2
  44. package/.agents/skills/qk-system-evolution/SKILL.md +343 -263
  45. package/.agents/skills/qk-system-evolution/evals/scorecard.yaml +26 -26
  46. package/.agents/skills/qk-test-engineering/SKILL.md +119 -429
  47. package/.agents/skills/qk-ui-audit/SKILL.md +73 -457
  48. package/.agents/skills/qk-ui-builder/SKILL.md +521 -482
  49. package/.agents/skills/qk-ui-system-builder/SKILL.md +68 -434
  50. package/.agents/skills/qk-upgrade/SKILL.md +301 -0
  51. package/.agents/skills/qk-upgrade/capability.yaml +24 -0
  52. package/.agents/skills/qk-upgrade/evals/scorecard.yaml +26 -0
  53. package/.agents/skills/qk-validation-gate/SKILL.md +4 -523
  54. package/.agents/skills/qk-web-quality-gate/SKILL.md +85 -383
  55. package/.agents/workflows/bug-resolution.yml +6 -6
  56. package/.agents/workflows/context-discovery.yml +94 -0
  57. package/.agents/workflows/feature-delivery.yml +8 -4
  58. package/.agents/workflows/refactor.yml +6 -3
  59. package/.agents/workflows/shared/quality-gate.yml +94 -0
  60. package/.agents/workflows/skin-governance.yml +115 -0
  61. package/README.md +152 -67
  62. package/package.json +2 -2
  63. package/tooling/build-registry.js +30 -8
@@ -1,9 +1,9 @@
1
- ---
1
+ ---
2
2
  # ── Identity ───────────────────────────────────────────────
3
3
  name: qk-db-optimizer
4
- version: 9.1.0
4
+ version: 9.2.0
5
5
  status: stable
6
- description: "Tối ưu Database dựa trên bằng chứng: EXPLAIN phân tích index/joinkhông đoán mò."
6
+ description: "Tối ưu hiệu năng Database dựa trên bằng chứng kỹ thuật: phân tích EXPLAIN/ANALYZE, phát hiện N+1 queries, thiết kế Composite/Partial Index, refactor câu truy vấn chậm. Dùng skill này khi user nhắc đến: tối ưu query, query chậm, optimize db, thêm index, explain, slow query, n+1 query, lag database kể cả khi chỉ nói 'câu SQL này chạy mất 5 giây'."
7
7
  platforms: [antigravity, claude-code, cursor, windsurf, kilo-code]
8
8
 
9
9
  # ── V9: Classification ─────────────────────────────────────
@@ -17,15 +17,20 @@ complexity:
17
17
  level: high
18
18
  criteria:
19
19
  files_affected: "1-5"
20
- has_behavior_change: true
20
+ has_behavior_change: false
21
21
  has_external_dependency: true
22
22
  has_breaking_change: false
23
23
 
24
- triggers:
25
- - "tối ưu query"
26
- - "query chậm"
27
- - "optimize db"
28
- - "thêm index"
24
+ triggers:
25
+ - "tối ưu query"
26
+ - "query chậm"
27
+ - "optimize db"
28
+ - "thêm index"
29
+ - "explain"
30
+ - "slow query"
31
+ - "n+1 query"
32
+ - "lag database"
33
+
29
34
 
30
35
  # ── V8: References ─────────────────────────────────────────
31
36
  workflow: refactor
@@ -40,11 +45,13 @@ tools:
40
45
 
41
46
  related_skills:
42
47
  - qk-data-lifecycle
48
+ - qk-refactor
43
49
 
44
50
  knowledge_scope:
45
51
  owns:
46
52
  - database-performance
47
53
  - query-optimization
54
+ - index-engineering
48
55
  references:
49
56
  - architecture
50
57
  - anti-patterns
@@ -71,446 +78,133 @@ produces: [code, report]
71
78
  consumes: [query-log, source-code]
72
79
 
73
80
  token_budget:
74
- max_files_read: 3
75
- max_lines_per_read: 100
81
+ max_files_read: 5
82
+ max_lines_per_read: 150
76
83
  max_shell_commands: 2
77
84
  stop_early: true
78
85
 
79
- exit_codes: [SUCCESS, BLOCKED, FAILED, PARTIAL]
86
+ exit_codes: [SUCCESS, BLOCKED, FAILED, PARTIAL]
80
87
  ---
81
88
 
82
- # qk-db-optimizer — Database Performance Tuner
89
+ # qk-db-optimizer — Evidence-Based Database Performance Tuner
83
90
 
84
91
  > **Language rule:** Code, identifiers, file names → English. Explanations, summaries → Vietnamese.
85
92
 
93
+ Chịu trách nhiệm chẩn đoán và khắc phục điểm nghẽn hiệu năng cơ sở dữ liệu dựa trên **bằng chứng đo lường thực tế**: `EXPLAIN (ANALYZE, BUFFERS)` → tìm root cause → đề xuất Index / Query Rewrite — **tuyệt đối không đoán mò**.
94
+
86
95
  ---
87
96
 
88
- ## Memory Workflow
89
-
90
- ### 0. Self-Init Protocol (Khởi Tạo Bộ Nhớ Local & Gitignore)
91
- - Trước khi tra cứu hoặc lưu trữ tri thức, BẮT BUỘC kiểm tra sự tồn tại của thư mục `.ai-local/` tại gốc dự án:
92
- - **Tự động tạo mới:** Nếu `.ai-local/` chưa tồn tại, AI phải tự động tạo cấu trúc thư mục `.ai-local/knowledge/` (và file `index.yaml` nếu cần thiết) cùng `.ai-local/candidates/`. Tuyệt đối không ngưng chạy hay hỏi ý kiến người dùng về thao tác khởi tạo tiêu chuẩn này.
93
- - **Bảo mật Gitignore:** BẮT BUỘC kiểm tra file `.gitignore` của dự án, nếu chưa có dòng `.ai-local/` thì phải tự động thêm vào để tuyệt đối bảo mật tri thức cá nhân và tránh lộ lọt lên Git.
94
-
95
- ---
96
-
97
- ### Pre-flight Retrieve (Trước khi thực thi)
98
- - Trước các task có tính lặp lại, debug, refactor, kiến trúc hoặc rủi ro cao:
99
- bắt buộc tra cứu:
100
- - `.ai-local/knowledge/index.yaml` (Private Local Knowledge)
101
-
102
- - Ưu tiên sử dụng các Knowledge đang có trạng thái `Active` thuộc:
103
- - Architecture
104
- - Hard Bug
105
- - Convention
106
- - Pattern
107
- - Tech Debt Pattern
108
- - 👉 *Domain Focus:* Pattern / Hard Bug (vd: lỗi slow query từng gặp, kế hoạch index đã duyệt).
109
-
110
- - Memory chỉ đóng vai trò **Navigator (bản đồ chỉ đường)**.
111
- Không được xem Memory là Source of Truth.
112
- Luôn xác minh lại bằng source code, configuration và trạng thái hiện tại của dự án trước khi áp dụng.
113
-
114
- ---
115
-
116
- ### Learning Flow (AI tự học có kiểm soát)
117
- - Trong quá trình làm việc, AI được phép tự phát hiện và tạo **Candidate Memory** khi nhận thấy:
118
- - Hard Bug có khả năng tái diễn.
119
- - Pattern làm việc lặp lại trong dự án.
120
- - Convention hoặc quy tắc kiến trúc mới.
121
- - Quyết định Architecture quan trọng.
122
- - Tech Debt Pattern hoặc Code Smell có tính hệ thống.
123
- - 👉 *Domain Harvest:* Quyết định Architecture hoặc Pattern tối ưu (vd: chuẩn composite index, partition strategy).
124
-
125
- - Candidate Memory chỉ là bản nháp quan sát, chưa phải tri thức chính thức.
126
- - Candidate Memory có thể lưu tạm tại: `.ai-local/candidates/`
127
- - AI không được tự động Promote Candidate Memory thành Project Knowledge.
128
-
129
- ---
130
-
131
- ### Post-flight Harvest (Đề xuất → Phê duyệt)
132
- Sau khi hoàn thành task:
133
- - AI đánh giá các Candidate Memory đã tạo.
134
- - Nếu phát hiện tri thức có giá trị tái sử dụng:
135
- - Đề xuất người dùng xem xét.
136
- - Gửi yêu cầu phê duyệt thông qua:
137
- - `/learn`
138
- - `qk-project-memory`
139
- - Chỉ sau khi được phê duyệt, Candidate Memory mới được chuyển thành Knowledge chính thức:
140
-
141
- ```
142
- .ai-local/candidates/ ──(Approve)──> .ai-local/knowledge/index.yaml
143
- ```
144
-
145
- - Project Knowledge phải được xem như tài sản kỹ thuật của dự án:
146
- - Có thể review, cập nhật, loại bỏ và có lịch sử thay đổi.
147
-
148
- ---
149
-
150
- ### Ignore (Không đưa vào Memory)
151
- Không lưu:
152
- - Trace log của một session đơn lẻ.
153
- - Temporary debugging data.
154
- - Output của một lần chạy test/scan.
155
- - Report health tạm thời của một đợt kiểm tra.
156
- - Lỗi nhỏ chỉ xảy ra một lần.
157
- - Thông tin không có khả năng tái sử dụng.
158
- - 👉 *Domain Ignore:* Dữ liệu kết quả EXPLAIN tạm thời của 1 query.
159
-
160
- ---
161
-
162
- ### Golden Rule
163
- > **AI được phép học, nhưng không được tự quyết định tri thức chính thức.**
164
- > **AI quan sát → Đề xuất → Con người phê duyệt → Dự án tiến hóa.**
165
-
166
- ---
167
-
168
-
169
-
170
- ### Pre-flight Retrieve (Trước khi thực thi)
171
- - Trước các task có tính lặp lại, debug, refactor, kiến trúc hoặc rủi ro cao:
172
- bắt buộc tra cứu:
173
- - `.agents/knowledge/index.yaml` (Shared Project Knowledge)
174
- - `.ai-local/knowledge/index.yaml` (Private Local Knowledge)
175
-
176
- - Ưu tiên sử dụng các Knowledge đang có trạng thái `Active` thuộc:
177
- - Architecture
178
- - Hard Bug
179
- - Convention
180
- - Pattern
181
- - Tech Debt Pattern
182
- - 👉 *Domain Focus:* Pattern / Hard Bug (vd: lỗi slow query từng gặp, kế hoạch index đã duyệt).
183
-
184
- - Memory chỉ đóng vai trò **Navigator (bản đồ chỉ đường)**.
185
- Không được xem Memory là Source of Truth.
186
- Luôn xác minh lại bằng source code, configuration và trạng thái hiện tại của dự án trước khi áp dụng.
187
-
188
- ---
189
-
190
- ### Learning Flow (AI tự học có kiểm soát)
191
- - Trong quá trình làm việc, AI được phép tự phát hiện và tạo **Candidate Memory** khi nhận thấy:
192
- - Hard Bug có khả năng tái diễn.
193
- - Pattern làm việc lặp lại trong dự án.
194
- - Convention hoặc quy tắc kiến trúc mới.
195
- - Quyết định Architecture quan trọng.
196
- - Tech Debt Pattern hoặc Code Smell có tính hệ thống.
197
- - 👉 *Domain Harvest:* Quyết định Architecture hoặc Pattern tối ưu (vd: chuẩn composite index, partition strategy).
198
-
199
- - Candidate Memory chỉ là bản nháp quan sát, chưa phải tri thức chính thức.
200
- - Candidate Memory có thể lưu tạm tại: `.ai-local/candidates/`
201
- - AI không được tự động Promote Candidate Memory thành Project Knowledge.
202
-
203
- ---
204
-
205
- ### Post-flight Harvest (Đề xuất → Phê duyệt)
206
- Sau khi hoàn thành task:
207
- - AI đánh giá các Candidate Memory đã tạo.
208
- - Nếu phát hiện tri thức có giá trị tái sử dụng:
209
- - Đề xuất người dùng xem xét.
210
- - Gửi yêu cầu phê duyệt thông qua:
211
- - `/learn`
212
- - `qk-project-memory`
213
- - Chỉ sau khi được phê duyệt, Candidate Memory mới được chuyển thành Knowledge chính thức:
214
-
215
- ```
216
- .ai-local/candidates/ ──(Approve)──> .agents/knowledge/index.yaml
217
- ```
218
-
219
- - Project Knowledge phải được xem như tài sản kỹ thuật của dự án:
220
- - Có thể review, cập nhật, loại bỏ và có lịch sử thay đổi.
221
-
222
- ---
223
-
224
- ### Ignore (Không đưa vào Memory)
225
- Không lưu:
226
- - Trace log của một session đơn lẻ.
227
- - Temporary debugging data.
228
- - Output của một lần chạy test/scan.
229
- - Report health tạm thời của một đợt kiểm tra.
230
- - Lỗi nhỏ chỉ xảy ra một lần.
231
- - Thông tin không có khả năng tái sử dụng.
232
- - 👉 *Domain Ignore:* Dữ liệu kết quả EXPLAIN tạm thời của 1 query.
233
-
234
- ---
235
-
236
- ### Golden Rule
237
- > **AI được phép học, nhưng không được tự quyết định tri thức chính thức.**
238
- > **AI quan sát → Đề xuất → Con người phê duyệt → Dự án tiến hóa.**
239
-
240
- ---
241
- ---
242
-
243
- ### Learning Flow (AI tự học có kiểm soát)
244
- - Trong quá trình làm việc, AI được phép tự phát hiện và tạo **Candidate Memory** khi nhận thấy:
245
- - Hard Bug có khả năng tái diễn.
246
- - Pattern làm việc lặp lại trong dự án.
247
- - Convention hoặc quy tắc kiến trúc mới.
248
- - Quyết định Architecture quan trọng.
249
- - Tech Debt Pattern hoặc Code Smell có tính hệ thống.
250
- - 👉 *Domain Harvest:* Quyết định Architecture hoặc Pattern tối ưu (vd: chuẩn composite index, partition strategy).
251
-
252
- - Candidate Memory chỉ là bản nháp quan sát, chưa phải tri thức chính thức.
253
- - Candidate Memory có thể lưu tạm tại: `.ai-local/candidates/`
254
- - AI không được tự động Promote Candidate Memory thành Project Knowledge.
255
-
256
- ---
257
-
258
- ### Post-flight Harvest (Đề xuất → Phê duyệt)
259
- Sau khi hoàn thành task:
260
- - AI đánh giá các Candidate Memory đã tạo.
261
- - Nếu phát hiện tri thức có giá trị tái sử dụng:
262
- - Đề xuất người dùng xem xét.
263
- - Gửi yêu cầu phê duyệt thông qua:
264
- - `/learn`
265
- - `qk-project-memory`
266
- - Chỉ sau khi được phê duyệt, Candidate Memory mới được chuyển thành Knowledge chính thức:
267
-
268
- ```
269
- .ai-local/candidates/ ──(Approve)──> .agents/knowledge/index.yaml
270
- ```
271
-
272
- - Project Knowledge phải được xem như tài sản kỹ thuật của dự án:
273
- - Có thể review, cập nhật, loại bỏ và có lịch sử thay đổi.
274
-
275
- ---
276
-
277
- ### Ignore (Không đưa vào Memory)
278
- Không lưu:
279
- - Trace log của một session đơn lẻ.
280
- - Temporary debugging data.
281
- - Output của một lần chạy test/scan.
282
- - Report health tạm thời của một đợt kiểm tra.
283
- - Lỗi nhỏ chỉ xảy ra một lần.
284
- - Thông tin không có khả năng tái sử dụng.
285
- - 👉 *Domain Ignore:* Dữ liệu kết quả EXPLAIN tạm thời của 1 query.
286
-
287
- ---
288
-
289
- ### Golden Rule
290
- > **AI được phép học, nhưng không được tự quyết định tri thức chính thức.**
291
- > **AI quan sát → Đề xuất → Con người phê duyệt → Dự án tiến hóa.**
292
-
293
- ---
294
- ---
295
-
296
- ### Learning Flow (AI tự học có kiểm soát)
297
- - Trong quá trình làm việc, AI được phép tự phát hiện và tạo **Candidate Memory** khi nhận thấy:
298
- - Hard Bug có khả năng tái diễn.
299
- - Pattern làm việc lặp lại trong dự án.
300
- - Convention hoặc quy tắc kiến trúc mới.
301
- - Quyết định Architecture quan trọng.
302
- - Tech Debt Pattern hoặc Code Smell có tính hệ thống.
303
- - 👉 *Domain Harvest:* Quyết định Architecture hoặc Pattern tối ưu (vd: chuẩn composite index, partition strategy).
304
-
305
- - Candidate Memory chỉ là bản nháp quan sát, chưa phải tri thức chính thức.
306
- - Candidate Memory có thể lưu tạm tại: `.ai-local/candidates/`
307
- - AI không được tự động Promote Candidate Memory thành Project Knowledge.
308
-
309
- ---
310
-
311
- ### Post-flight Harvest (Đề xuất → Phê duyệt)
312
- Sau khi hoàn thành task:
313
- - AI đánh giá các Candidate Memory đã tạo.
314
- - Nếu phát hiện tri thức có giá trị tái sử dụng:
315
- - Đề xuất người dùng xem xét.
316
- - Gửi yêu cầu phê duyệt thông qua:
317
- - `/learn`
318
- - `qk-project-memory`
319
- - Chỉ sau khi được phê duyệt, Candidate Memory mới được chuyển thành Knowledge chính thức:
320
-
321
- ```
322
- .ai-local/candidates/ ──(Approve)──> .agents/knowledge/index.yaml
323
- ```
324
-
325
- - Project Knowledge phải được xem như tài sản kỹ thuật của dự án:
326
- - Có thể review, cập nhật, loại bỏ và có lịch sử thay đổi.
327
-
328
- ---
329
-
330
- ### Ignore (Không đưa vào Memory)
331
- Không lưu:
332
- - Trace log của một session đơn lẻ.
333
- - Temporary debugging data.
334
- - Output của một lần chạy test/scan.
335
- - Report health tạm thời của một đợt kiểm tra.
336
- - Lỗi nhỏ chỉ xảy ra một lần.
337
- - Thông tin không có khả năng tái sử dụng.
338
- - 👉 *Domain Ignore:* Dữ liệu kết quả EXPLAIN tạm thời của 1 query.
339
-
340
- ---
341
-
342
- ### Golden Rule
343
- > **AI được phép học, nhưng không được tự quyết định tri thức chính thức.**
344
- > **AI quan sát → Đề xuất → Con người phê duyệt → Dự án tiến hóa.**
345
-
346
- ---
347
- ---
348
- ---
349
- ---
350
-
351
97
  ## Preconditions
352
- - [ ] Slow query log OR specific slow query is provided
353
- - [ ] Database schema/ORM models accessible
354
98
 
355
- ```
356
- On missing precondition:
357
- EXIT: BLOCKED
358
- Message: "Cần: slow query log hoặc query cụ thể cần tối ưu."
359
- ```
99
+ Trước khi đề xuất tối ưu, AI BẮT BUỘC xác nhận:
100
+
101
+ - [ ] Đoạn query cụ thể (SQL thô hoặc câu gọi ORM) đang bị chậm.
102
+ - [ ] Schema định nghĩa bảng **danh sách index hiện có** trên các cột liên quan.
103
+ - [ ] Output `EXPLAIN` hoặc `EXPLAIN ANALYZE` (nếu môi trường cho phép chạy query).
104
+ - [ ] Quy mô dữ liệu ước tính (e.g. bảng có 1.000 rows hay 50.000.000 rows).
105
+
106
+ *Nếu user yêu cầu "tối ưu database" mà không cung cấp query cụ thể hoặc slow log:*
107
+ → **EXIT: BLOCKED**
108
+ → Phản hồi: "Vui lòng cung cấp câu query bị chậm hoặc output log EXPLAIN để phân tích chính xác."
360
109
 
361
110
  ---
362
111
 
363
112
  ## Scope
364
- - ✅ Analyze EXPLAIN/query plans before adding indexes
365
- - ✅ Solve N+1 with Data Loaders or explicit Joins
366
- - ✅ Validate performance improvement
367
-
368
- ## Non-Goals
369
- - ❌ Add indexes without slow query evidence
370
- - ❌ Add overlapping or redundant indexes
371
- - ❌ Optimize queries not shown in slow query log
372
113
 
373
- ---
114
+ ✅ Skill này làm:
115
+ - Phân tích Execution Plan: Xác định `Seq Scan` trên bảng lớn, `Nested Loop` kém hiệu quả, `Temporary disk spill`, hoặc `Filter cost` cao.
116
+ - Phát hiện và giải quyết triệt để **N+1 queries** trong ORM (Prisma, Drizzle, Hibernate, ActiveRecord).
117
+ - Thiết kế Index chính xác: Composite Index (tuân thủ quy tắc Left-to-Right prefix), Partial Index (lọc `WHERE is_deleted = false`), Covering Index (`INCLUDE`).
118
+ - Tái cấu trúc câu truy vấn (Query rewrite): Chuyển `OFFSET` lớn sang Keyset Pagination (Cursor-based), thay `NOT IN` bằng `NOT EXISTS` hoặc `LEFT JOIN ... IS NULL`.
119
+ - Báo cáo định lượng trước và sau (Before / After Cost & Execution Time).
374
120
 
375
- ## Priority Order
376
- | P | Issue Type | Action | Skip Threshold |
377
- |---|-----------|--------|----------------|
378
- | P1 | Sequential scan on large table (> 10k rows) | Add composite index | Never |
379
- | P2 | N+1 query pattern | Eager load / DataLoader (Ưu tiên theo chuẩn dự án, không tự chế query lồng) | Budget < 30% |
380
- | P3 | Missing JOIN (multiple queries for related data) | Rewrite with JOIN | Budget < 50% |
381
- | P4 | SELECT * (over-fetching) | Select specific columns | Budget < 60% |
121
+ Skill này KHÔNG làm:
122
+ - Thêm index bừa bãi vào mọi cột (làm chậm `INSERT`, `UPDATE`, tăng dung lượng đĩa).
123
+ - Tự ý thay đổi cấu trúc bảng hoặc drop cột (thuộc `qk-data-lifecycle`).
124
+ - Can thiệp phần cứng DB hoặc tune memory server nếu không file cấu hình repo.
382
125
 
383
126
  ---
384
127
 
385
- ## EXPLAIN Decision Tree
128
+ ## Execution Steps
386
129
 
130
+ ### Step 1 — Thu thập Query & Phân tích EXPLAIN Plan
387
131
  ```
388
- Run EXPLAIN ANALYZE on slow query
389
-
390
- IF "Seq Scan" on table > 10k rows
391
- Check cardinality of filter column
392
- IF cardinality > 100 add B-tree index
393
- IF low cardinality add partial index or reconsider query
394
-
395
- IF "Nested Loop" with many iterations
396
- → Check: is this N+1?
397
- → IF yes → rewrite as single JOIN or use DataLoader
398
-
399
- IF "Sort" without index
400
- → Add index on ORDER BY column
401
-
402
- IF index exists but not used ("Index Scan" missing)
403
- → Check: is WHERE clause using non-leading column of composite index?
404
- → Reorder composite index columns
132
+ Inputs: Slow query SQL/ORM, Schema & Existing Indexes
133
+ Actions:
134
+ - Đọc câu query: xác định predicates (WHERE, JOIN, ORDER BY, GROUP BY).
135
+ - Đọc EXPLAIN output (nếu có):
136
+ - Tìm Node `Cost` cao nhất.
137
+ - Kiểm tra `Rows Removed by Filter` (dấu hiệu thiếu index).
138
+ - Kiểm tra Sort method (in-memory quicksort hay external merge on disk).
405
139
  ```
406
140
 
407
- ---
408
-
409
- ## Workflow
410
-
411
- ### Phase 1 — Evidence Collection
412
- 1. Read slow query log or provided query
413
- 2. Run EXPLAIN ANALYZE (1 command) — or analyze ORM-generated SQL
414
- 3. Identify bottleneck pattern (seq scan / N+1 / sort / over-fetch)
415
-
416
- ### Phase 2 — Solution Design
417
- 1. Apply Decision Tree above
418
- 2. Design minimal index or query rewrite
419
-
420
- ### Phase 3 — Apply & Verify
421
- 1. Apply change (add index migration OR rewrite query via `replace_file_content`)
422
- 2. (Optional) Re-run EXPLAIN to verify improvement (2nd command)
423
-
424
- **Decision:**
141
+ ### Step 2 — Chẩn đoán Root Cause
425
142
  ```
426
- IF improvement verified EXIT: SUCCESS
427
- IF improvement not measurable EXIT: PARTIAL, note "verify in production"
143
+ Xác định vấn đề cốt lõi:
144
+ - Missing Index: Cột lọc không index dẫn tới Full Table Scan.
145
+ - Sub-optimal Index: Có index nhưng sai thứ tự cột trong Composite Index.
146
+ - Implicit Type Casting: So sánh varchar với int làm database vô hiệu hóa index.
147
+ - N+1 Query: Gọi loop query con thay vì batch load.
148
+ - Expensive Pagination: `OFFSET 100000` quét qua 100.000 dòng rồi vứt bỏ.
428
149
  ```
429
150
 
430
- ---
431
-
432
- ## Evidence Format
151
+ ### Step 3 — Thiết kế Giải pháp Tối ưu
433
152
  ```
434
- [SEVERITY] query in src/repositories/[name].ts:LINE
435
- Pattern: [SEQ_SCAN | N+1 | MISSING_JOIN | OVER_FETCH | UNUSED_INDEX]
436
- Table: [table_name] (~N rows estimated)
437
- Confidence: HIGH
438
- Fix: [specific index or rewrite]
439
- Estimated improvement: [X% reduction in scan rows]
153
+ Actions:
154
+ - Chiến lược Index:
155
+ - Composite Index: Đặt cột equality (`=`) trước, cột range (`<`, `>`, `BETWEEN`) sau.
156
+ - Partial Index: Khi chỉ query tập con dữ liệu (VD: `WHERE status = 'PENDING'`).
157
+ - Chiến lược Query Rewrite:
158
+ - Viết lại sang Cursor Pagination (`WHERE id > :last_id LIMIT 20`).
159
+ - Dùng CTE hoặc Window functions thay cho multiple subqueries lặp lại.
160
+ - Chiến lược ORM: Thêm `include`/`select` cụ thể, tránh `SELECT *`, áp dụng batch loader.
440
161
  ```
441
162
 
442
- ---
443
-
444
- ## Exit Codes
445
- | Code | Meaning | When |
446
- |------|---------|------|
447
- | SUCCESS | Index added or query rewritten, improvement verified | Post-optimization |
448
- | PARTIAL | Optimization applied but could not verify via EXPLAIN | DB access blocked |
449
- | BLOCKED | Log not provided or DB engine unknown | Missing inputs |
450
- | FAILED | Optimization breaks existing test or query syntax | Logic error |
451
-
452
- ---
453
-
454
- ## Confidence Model
455
- | Level | Condition | Action |
456
- |-------|-----------|--------|
457
- | HIGH | EXPLAIN plan shows SEQ SCAN, user confirms index is missing | Add index / rewrite |
458
- | MEDIUM | Query looks inefficient but no EXPLAIN available | Ask to run EXPLAIN |
459
- | LOW | "Make DB faster" with no slow query log | EXIT: BLOCKED |
163
+ ### Step 4 — Verification & So sánh định lượng
164
+ ```
165
+ Actions:
166
+ - Đối chiếu Expected Cost trước và sau tối ưu:
167
+ Before: Seq Scan on orders (cost=0.00..45210.00 rows=1200000)
168
+ After: Index Scan using idx_orders_customer_created (cost=0.43..8.45 rows=20)
169
+ - Đảm bảo câu query sau khi rewrite trả về đúng 100% dữ liệu như câu query cũ.
170
+ ```
460
171
 
461
172
  ---
462
173
 
463
- ## Severity
464
- | Level | Definition | Example |
465
- |-------|-----------|---------|
466
- | CRITICAL | Query locking table in production | Long running UPDATE |
467
- | HIGH | Missing index on frequently joined table | Full scan on million rows |
468
- | MEDIUM | N+1 queries due to missing JOIN | ORM fetching relations in loop |
469
- | LOW | Over-fetching columns | `SELECT *` instead of specific |
174
+ ## Prompt Template
470
175
 
471
- ---
472
-
473
- ## Retry Policy
474
176
  ```
475
- EXPLAIN query fails
476
- └─ Check SQL syntax error vs connection error
477
- ├─ Syntax error correct SQL → retry EXPLAIN
478
- └─ Do NOT retry more than 1 time risk of locking
177
+ DB Engine: [PostgreSQL / MySQL / SQLite / MongoDB]
178
+ Slow Query: [Câu SQL hoặc đoạn code ORM cần tối ưu]
179
+ Schema: [Định nghĩa bảng index hiện tại]
180
+ Triệu chứng: [Chạy mất bao lâu / Execution Plan nếu có]
181
+ Volume: [Số lượng bản ghi trong các bảng liên quan]
479
182
  ```
480
183
 
481
- ---
184
+ ### Ví dụ theo Stack:
482
185
 
483
- ## Escalation Rules
186
+ **PostgreSQL (Composite Index & Keyset Pagination)**
484
187
  ```
485
- BLOCKED: Slow query log not provided
486
- Missing:
487
- - The actual slow query SQL
488
- - Current schema of the involved tables
489
- Questions:
490
- 1. Câu query nào đang bị chậm? (Xin SQL / ORM log)
491
- 2. Bảng này hiện đang có những index nào?
492
- Recommended Assumptions:
493
- - Do NOT assume table size or indexes blindly
188
+ DB Engine: PostgreSQL 15
189
+ Slow Query: SELECT * FROM orders WHERE customer_id = 123 AND status = 'COMPLETED' ORDER BY created_at DESC LIMIT 20 OFFSET 50000;
190
+ Volume: Bảng orders 10 triệu records. Hiện có index trên (customer_id).
494
191
  ```
495
-
496
- ---
497
-
498
- ## Handoff Contract
499
- ### Consumes
500
- ```json
501
- {
502
- "from": "user",
503
- "required_fields": ["slow_query"],
504
- "optional_fields": ["schema", "explain_plan", "db_engine"]
505
- }
192
+ → AI chẩn đoán:
193
+ 1. Offset 50.000 buộc engine quét qua 50.000 index entries.
194
+ 2. Index hiện tại thiếu `status` và `created_at`.
195
+ AI giải pháp:
196
+ 1. Đề xuất Composite Index: `CREATE INDEX CONCURRENTLY idx_orders_cust_stat_created ON orders (customer_id, status, created_at DESC);`
197
+ 2. Rewrite sang Cursor Pagination: `SELECT id, total, created_at FROM orders WHERE customer_id = 123 AND status = 'COMPLETED' AND created_at < :last_created_at ORDER BY created_at DESC LIMIT 20;`
198
+
199
+ **Prisma ORM (Khắc phục N+1 Query)**
506
200
  ```
507
- ### Produces
508
- ```json
509
- {
510
- "to": "user",
511
- "output_fields": ["optimized_query", "migration_file", "explain_diff", "exit_code"]
512
- }
201
+ ORM: Prisma
202
+ Code:
203
+ const users = await prisma.user.findMany({ take: 50 });
204
+ for (const user of users) {
205
+ user.posts = await prisma.post.findMany({ where: { authorId: user.id } });
206
+ }
513
207
  ```
514
-
515
- ---
208
+ → AI sửa thành single query batching với eager load:
209
+ `const users = await prisma.user.findMany({ take: 50, include: { posts: { select: { id: true, title: true } } } });`
516
210