Compare commits

..

159 Commits

Author SHA1 Message Date
admin 45a6416d27 fix(test): add CACHE_MANAGER mock to CorrespondenceController test
CI / CD Pipeline / build (push) Failing after 3m4s
CI / CD Pipeline / deploy (push) Has been skipped
The IdempotencyInterceptor requires CACHE_MANAGER dependency.
Added mock provider to test module to resolve dependency injection error.
2026-06-14 20:23:18 +07:00
admin 152caa25e9 fix(frontend): remove console.log from comment to fix linter false positive
CI / CD Pipeline / build (push) Failing after 3m57s
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-14 20:06:20 +07:00
admin 67da186672 feat(ai): implement unified prompt management UX/UI (ADR-037)
CI / CD Pipeline / build (push) Failing after 3m23s
CI / CD Pipeline / deploy (push) Has been skipped
- Add context config endpoints (GET/PUT /api/ai/prompts/:type/:version/context-config)
- Add execution profile endpoints (CRUD /api/ai/execution-profiles)
- Add sandbox RAG Prep endpoint (POST /api/ai/admin/sandbox/rag-prep)
- Create Prompt Management UI with multi-type support
- Add ContextConfigEditor, PromptEditor, RuntimeParametersPanel components
- Add SandboxTabs for 3-step workflow (OCR, Extract, RAG Prep)
- Add database deltas for ai_execution_profiles and additional prompt types
- Update quickstart.md with production backend URLs
- Add comprehensive test coverage for new features
2026-06-14 19:55:43 +07:00
admin 56f9544cb0 fix(numbering): correct error state handling in MetricsDashboard
CI / CD Pipeline / build (push) Successful in 5m33s
CI / CD Pipeline / deploy (push) Successful in 7m34s
- Change state type to allow undefined distinction from empty object
- Set undefined on error instead of empty object
- Fixes test failure where 'No metrics available' was not displayed
2026-06-14 07:03:10 +07:00
admin 7e8f4859cd feat(ai): add ADR-036 unified OCR architecture and frontend test coverage
CI / CD Pipeline / build (push) Failing after 6m24s
CI / CD Pipeline / deploy (push) Has been skipped
- Add ADR-036 unified OCR architecture (typhoon-ocr via Ollama)
- Extend AI execution profiles for OCR sandbox configuration
- Add comprehensive frontend test coverage (components, hooks, services)
- Add backend test coverage for document-numbering services
- Update OCR sidecar with typhoon-ocr integration
- Add AI policy service and execution profile management
- Update AGENTS.md and architecture documentation
2026-06-14 06:34:07 +07:00
admin e3503b6a77 test(frontend): add test coverage for drawing, organization, and migration services 2026-06-13 22:46:56 +07:00
admin 9c5df0abdb test(frontend): raise overall statement coverage to 30.42% for Phase 1 MVP 2026-06-13 22:33:11 +07:00
admin 190b9a3af5 690612:1407 ADR-035-235 #01
CI / CD Pipeline / build (push) Successful in 4m7s
CI / CD Pipeline / deploy (push) Successful in 6m24s
2026-06-12 14:07:14 +07:00
admin 2c5a0b6aef 690612:0931 ADR-035-235 #00.2 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-12 09:31:20 +07:00
admin d333d8a45a 690612:0900 ADR-035-235 #00.1 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-12 09:00:28 +07:00
admin 0227b7b982 feat(ai-runtime): complete ai runtime policy refactor (ADR-035)
CI / CD Pipeline / build (push) Successful in 4m16s
CI / CD Pipeline / deploy (push) Successful in 11m51s
2026-06-12 08:07:15 +07:00
admin 71c5e88181 690611:1705 ADR-035-235 #00 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-11 17:05:17 +07:00
admin cd7d20ccd4 690609:2223 Prepare to MOD AI flow [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-09 22:23:59 +07:00
admin 75d07b5ac9 690608:1520 ADR-035-135 #09
CI / CD Pipeline / build (push) Successful in 5m7s
CI / CD Pipeline / deploy (push) Successful in 4m40s
2026-06-08 15:20:34 +07:00
admin 52b96d01de 690608:0012 ADR-035-135 #08
CI / CD Pipeline / build (push) Successful in 5m5s
CI / CD Pipeline / deploy (push) Successful in 3m48s
2026-06-08 00:12:31 +07:00
admin a0f77ad121 690607:2321 ADR-035-135 #07
CI / CD Pipeline / build (push) Successful in 5m20s
CI / CD Pipeline / deploy (push) Successful in 6m42s
2026-06-07 23:21:55 +07:00
admin 16aab2279c 690606:1705 ADR-035-135 #06
CI / CD Pipeline / build (push) Successful in 5m19s
CI / CD Pipeline / deploy (push) Successful in 3m11s
2026-06-06 17:05:51 +07:00
admin 15dec6c3fc 690606:1538 ADR-035-135 #05
CI / CD Pipeline / build (push) Successful in 5m21s
CI / CD Pipeline / deploy (push) Successful in 3m14s
2026-06-06 15:38:10 +07:00
admin 33c3935164 690606:1441 ADR-035-135 #04.2
CI / CD Pipeline / build (push) Successful in 4m51s
CI / CD Pipeline / deploy (push) Successful in 7m18s
2026-06-06 14:41:26 +07:00
admin 6bcd1a5c58 690606:1413 ADR-035-135 #04.1
CI / CD Pipeline / build (push) Failing after 4m2s
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-06 14:13:59 +07:00
admin de4201d7d3 690606:1408 ADR-035-135 #04
CI / CD Pipeline / deploy (push) Has been cancelled
CI / CD Pipeline / build (push) Has been cancelled
2026-06-06 14:08:57 +07:00
admin e3e0de66e9 690606:1354 ADR-035-135 #03.1 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-06 13:54:36 +07:00
admin 866fea7946 690606:1253 ADR-035-135 #03
CI / CD Pipeline / build (push) Successful in 7m27s
CI / CD Pipeline / deploy (push) Successful in 3m19s
2026-06-06 12:53:37 +07:00
admin 85c7415b8a 260606:1127 ADR-035-234 #2.1 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-06 11:27:42 +07:00
admin ed1b302274 690606:1120 ADR-035-135 #02
CI / CD Pipeline / build (push) Successful in 5m11s
CI / CD Pipeline / deploy (push) Successful in 3m32s
2026-06-06 11:20:13 +07:00
admin 26cc71ce60 690605:2335 ADR-035-135 #1
CI / CD Pipeline / build (push) Successful in 4m54s
CI / CD Pipeline / deploy (push) Successful in 6m19s
2026-06-05 23:35:22 +07:00
admin 285c007dff Add specs/06-Decision-Records/ADR-035-addon.md
CI / CD Pipeline / build (push) Successful in 5m30s
CI / CD Pipeline / deploy (push) Successful in 1m32s
2026-06-05 19:20:56 +07:00
admin 03aa4efcf0 690605:1725 ADR-035-135 #0 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 17:25:40 +07:00
admin 4f90ed688f 690605:1517 ADR-034-134 #11 fix Step 2 #02
CI / CD Pipeline / build (push) Successful in 5m21s
CI / CD Pipeline / deploy (push) Successful in 4m27s
2026-06-05 15:17:54 +07:00
admin 548dba6476 690605:1247 ADR-034-134 #11 fix Step 2
CI / CD Pipeline / build (push) Successful in 6m5s
CI / CD Pipeline / deploy (push) Successful in 6m30s
2026-06-05 12:47:38 +07:00
admin 4a808dd9c4 690605:1126 ADR-034-134 #10.9 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 11:26:04 +07:00
admin e71602e90c 690605:1121 ADR-034-134 #10.8 [skip CI] 2026-06-05 11:21:57 +07:00
admin bd96c4122c 260605:1105 ADR-034-134 #10.7 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 11:05:55 +07:00
admin 661710f349 690605:1056 ADR-034-134 #10.6 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 10:56:42 +07:00
admin eae94cf1f3 690605:1032 ADR-034-134 #10.5 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 10:32:27 +07:00
admin eeb9f6c686 690605:1017 ADR-034-134 #10.4 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 10:17:28 +07:00
admin 37174788bf 690605:0941 ADR-034-134 #10.3 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 09:41:13 +07:00
admin 2db4810dfc 690605:0922 ADR-034-134 #10.2 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 09:22:41 +07:00
admin 8b6ef392f5 690605:0840 ADR-034-134 #10.1 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-05 08:40:29 +07:00
admin eef557675b 690604:1720 ADR-034-134 #10
CI / CD Pipeline / build (push) Successful in 4m57s
CI / CD Pipeline / deploy (push) Successful in 3m37s
2026-06-04 17:20:54 +07:00
admin 1a399400ff 690604:1613 ADR-034-134 #09.5 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-04 16:14:00 +07:00
admin 29314a7ec4 690604:1601 ADR-034-134 #09.4 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-04 16:01:24 +07:00
admin 70fbac1b49 690604:1554 ADR-034-134 #09.3 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-04 15:54:07 +07:00
admin 1c3d9906e4 690604:1549 ADR-034-134 #09.2 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-04 15:49:27 +07:00
admin c841be1b31 690604:1535 ADR-034-134 #09.1 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-04 15:35:24 +07:00
admin 94583bd30f 690604:1327 ADR-034-134 #09
CI / CD Pipeline / build (push) Successful in 5m5s
CI / CD Pipeline / deploy (push) Successful in 4m7s
2026-06-04 13:27:26 +07:00
admin 17dff31dec 690604:1305 ADR-034-134 #08.1 [skip CI]
CI / CD Pipeline / build (push) Has been skipped
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-04 13:05:23 +07:00
admin b14a0b3d58 690604:1208 ADR-034-134 #08
CI / CD Pipeline / build (push) Successful in 5m39s
CI / CD Pipeline / deploy (push) Successful in 7m54s
2026-06-04 12:08:19 +07:00
admin 03963fd896 690604:1203 ADR-034-134 #07.2 [skip CI]
CI / CD Pipeline / build (push) Has been cancelled
CI / CD Pipeline / deploy (push) Has been cancelled
2026-06-04 12:03:54 +07:00
admin 663ed13522 690604:1156 ADR-034-134 #07.1 [skip CI]
CI / CD Pipeline / build (push) Successful in 5m33s
CI / CD Pipeline / deploy (push) Has been cancelled
2026-06-04 11:56:35 +07:00
admin 9c122c8328 690604:1139 ADR-034-134 #07
CI / CD Pipeline / build (push) Successful in 5m16s
CI / CD Pipeline / deploy (push) Successful in 5m1s
2026-06-04 11:39:56 +07:00
admin 4d243c16e6 690604:1107 ADR-034-134 #06
CI / CD Pipeline / build (push) Successful in 5m32s
CI / CD Pipeline / deploy (push) Successful in 3m41s
2026-06-04 11:07:29 +07:00
admin 994b41aa37 690604:1043 ADR-034-134 #05
CI / CD Pipeline / build (push) Successful in 5m47s
CI / CD Pipeline / deploy (push) Successful in 7m4s
2026-06-04 10:43:34 +07:00
admin b79895e6fb 690604:1008 ADR-034-134 #04
CI / CD Pipeline / build (push) Successful in 4m58s
CI / CD Pipeline / deploy (push) Successful in 7m33s
2026-06-04 10:08:22 +07:00
admin fb224a116c 690604:0832 ADR-034-134 #03
CI / CD Pipeline / build (push) Successful in 4m57s
CI / CD Pipeline / deploy (push) Successful in 9m45s
2026-06-04 08:32:32 +07:00
admin e0eabfb350 690603:2146 ADR-034-134 #02
CI / CD Pipeline / build (push) Successful in 5m28s
CI / CD Pipeline / deploy (push) Successful in 7m11s
2026-06-03 21:46:10 +07:00
admin 3274dede7a 690603:2041 ADR-034-134 #01
CI / CD Pipeline / build (push) Failing after 4m28s
CI / CD Pipeline / deploy (push) Has been skipped
2026-06-03 20:41:42 +07:00
admin 754d609399 fix(ai): correct double-wrap in OCR engine endpoints causing e.map error
CI / CD Pipeline / build (push) Successful in 4m50s
CI / CD Pipeline / deploy (push) Successful in 14m18s
Controller was returning { data: engines } which TransformInterceptor
wrapped again into { data: { data: engines } }. extractData() only peeled
one layer, leaving an object instead of the array — causing .map() to fail
in OcrEngineSelector.

- Return data directly from getOcrEngines() and selectOcrEngine()
- Add Array.isArray guard in OcrEngineSelector as defensive layer
2026-06-02 15:49:39 +07:00
admin e4948ad4c8 690602:1503 ADR-033-233 #05
CI / CD Pipeline / build (push) Successful in 4m52s
CI / CD Pipeline / deploy (push) Successful in 9m57s
2026-06-02 15:03:27 +07:00
admin be851ee311 690602:1419 ADR-033-233 #04
CI / CD Pipeline / build (push) Successful in 5m44s
CI / CD Pipeline / deploy (push) Successful in 12m41s
2026-06-02 14:19:17 +07:00
admin cb9ecb2de6 690602:1334 ADR-033-233 #03
CI / CD Pipeline / build (push) Successful in 5m8s
CI / CD Pipeline / deploy (push) Successful in 7m57s
2026-06-02 13:34:22 +07:00
admin b939a25456 690602:1254 ADR-033-233 #02.1 [skip CI]
CI / CD Pipeline / build (push) Successful in 5m14s
CI / CD Pipeline / deploy (push) Successful in 2m4s
2026-06-02 12:54:23 +07:00
admin 8909629d8f 690602:1245 ADR-033-233 #02
CI / CD Pipeline / build (push) Successful in 4m59s
CI / CD Pipeline / deploy (push) Successful in 5m35s
2026-06-02 12:45:57 +07:00
admin bc754e66fd 690602:0957 ADR-033-233 #01
CI / CD Pipeline / build (push) Successful in 4m52s
CI / CD Pipeline / deploy (push) Successful in 17m39s
2026-06-02 09:57:48 +07:00
admin 7f35c3a585 690601:2213 ADR-032-232 #10 fix: add typhoon-ocr1.5-3b option to sandbox engine selector
CI / CD Pipeline / build (push) Successful in 4m55s
CI / CD Pipeline / deploy (push) Successful in 7m55s
2026-06-01 22:13:47 +07:00
admin 2cc07ee2e5 690601:2143 ADR-032-232 #09
CI / CD Pipeline / build (push) Successful in 4m34s
CI / CD Pipeline / deploy (push) Successful in 4m0s
2026-06-01 21:43:19 +07:00
admin 69db07fe35 690601:1934 ADR-032-232 #08.1 docs: update ADR-032 and tasks.md with multipart upload decision [skip CI][skip CI]
CI / CD Pipeline / build (push) Has been cancelled
CI / CD Pipeline / deploy (push) Has been cancelled
2026-06-01 19:34:24 +07:00
admin acc19f4a44 690601:1929 ADR-032-232 #08
CI / CD Pipeline / build (push) Successful in 5m21s
CI / CD Pipeline / deploy (push) Successful in 4m25s
2026-06-01 19:29:55 +07:00
admin 2bbe67b4c5 690601:1911 ADR-032-232 #07.2 [skip CI]
CI / CD Pipeline / build (push) Successful in 5m56s
CI / CD Pipeline / deploy (push) Successful in 1m51s
2026-06-01 19:11:36 +07:00
admin 7bc6eefad2 690601:1834 ADR-032-232 #07.1 [skip CI]
CI / CD Pipeline / build (push) Successful in 5m13s
CI / CD Pipeline / deploy (push) Successful in 1m50s
2026-06-01 18:34:41 +07:00
admin 09505f5793 690601:1816 ADR-032-232 #07
CI / CD Pipeline / build (push) Successful in 5m2s
CI / CD Pipeline / deploy (push) Successful in 4m1s
2026-06-01 18:16:25 +07:00
admin cd2bd5bf19 690601:1621 ADR-032-232 #06
CI / CD Pipeline / build (push) Successful in 5m23s
CI / CD Pipeline / deploy (push) Successful in 5m31s
2026-06-01 16:21:17 +07:00
admin 20f9fa1e85 690601:1221 ADR-032-232 #05
CI / CD Pipeline / build (push) Successful in 5m26s
CI / CD Pipeline / deploy (push) Successful in 4m49s
2026-06-01 12:21:54 +07:00
admin b8954b300d 690601:1020 ADR-032-232 #04
CI / CD Pipeline / build (push) Successful in 5m9s
CI / CD Pipeline / deploy (push) Successful in 4m24s
2026-06-01 10:20:50 +07:00
admin 00ae9d3067 690601:0957 ADR-032-232 #03
CI / CD Pipeline / build (push) Successful in 4m43s
CI / CD Pipeline / deploy (push) Successful in 4m48s
2026-06-01 09:57:50 +07:00
admin 3c80617ffb 690601:0914 ADR-032-232 #02
CI / CD Pipeline / build (push) Successful in 4m58s
CI / CD Pipeline / deploy (push) Successful in 4m4s
2026-06-01 09:14:57 +07:00
admin 268f34198b 690530:2238 ADR-032-232 #01.0 [skip ci] 2026-05-30 22:38:04 +07:00
admin ae1b1f35e1 feat(ai): ADR-032 Typhoon OCR integration - models, processors, cache, VRAM monitor, sandbox UI
CI / CD Pipeline / build (push) Successful in 4m51s
CI / CD Pipeline / deploy (push) Successful in 12m7s
2026-05-30 22:18:51 +07:00
admin f86fcc05f5 690530:1459 ADR-030-231-ocr-sandbox-two-step-flow #05.4 [skip ci] 2026-05-30 14:59:19 +07:00
admin 9404596012 690530:1448 ADR-030-231-ocr-sandbox-two-step-flow #05.3 [skip ci] 2026-05-30 14:48:53 +07:00
admin 10024a66c3 690530:1434 ADR-030-231-ocr-sandbox-two-step-flow #05.2 [skip ci] 2026-05-30 14:34:37 +07:00
admin b7a7b1e84d 690530:1420 ADR-030-231-ocr-sandbox-two-step-flow #05.1 [skip ci] 2026-05-30 14:20:54 +07:00
admin 30d9d721fb 690530:1345 ADR-030-231-ocr-sandbox-two-step-flow #05
CI / CD Pipeline / build (push) Successful in 5m43s
CI / CD Pipeline / deploy (push) Successful in 9m8s
2026-05-30 13:45:18 +07:00
admin c9edd62a0b 690530:1329 ADR-030-231-ocr-sandbox-two-step-flow #04.6 [skip ci] 2026-05-30 13:29:08 +07:00
admin ddc9332122 690530:1317 ADR-030-231-ocr-sandbox-two-step-flow #04.5 [skip ci] 2026-05-30 13:17:16 +07:00
admin e82cb0e68b 690530:1315 ADR-030-231-ocr-sandbox-two-step-flow #04.4 [skip ci] 2026-05-30 13:15:18 +07:00
admin b1c838a637 690530:1313 ADR-030-231-ocr-sandbox-two-step-flow #04.3 [skip ci] 2026-05-30 13:13:44 +07:00
admin d13d5a06cc 690530:1311 ADR-030-231-ocr-sandbox-two-step-flow #04.2 [skip ci] 2026-05-30 13:11:46 +07:00
admin 3bf0f506eb 690530:1305 ADR-030-231-ocr-sandbox-two-step-flow #04 [skip ci] 2026-05-30 13:05:48 +07:00
admin c88354347b 690530:1239 ADR-030-231-ocr-sandbox-two-step-flow #04
CI / CD Pipeline / build (push) Successful in 5m11s
CI / CD Pipeline / deploy (push) Successful in 4m23s
2026-05-30 12:39:17 +07:00
admin 33c62993d5 690530:1206 ADR-030-231-ocr-sandbox-two-step-flow #03
CI / CD Pipeline / build (push) Successful in 4m58s
CI / CD Pipeline / deploy (push) Successful in 8m36s
2026-05-30 12:06:32 +07:00
admin 499d787aa5 690530:1154 ADR-030-231-ocr-sandbox-two-step-flow #02
CI / CD Pipeline / build (push) Successful in 5m17s
CI / CD Pipeline / deploy (push) Failing after 1m12s
2026-05-30 11:54:23 +07:00
admin b0b7d12d5a 690530:1121 ADR-030-231-ocr-sandbox-two-step-flow #01
CI / CD Pipeline / build (push) Successful in 5m10s
CI / CD Pipeline / deploy (push) Failing after 3m15s
2026-05-30 11:21:37 +07:00
admin 1ba563aa70 690530:0906 ADR-030-230 context aware #12
CI / CD Pipeline / build (push) Successful in 4m54s
CI / CD Pipeline / deploy (push) Successful in 7m49s
2026-05-30 09:06:23 +07:00
admin 63ded10341 690530:0820 ADR-030-230 context aware #11
CI / CD Pipeline / build (push) Successful in 5m19s
CI / CD Pipeline / deploy (push) Successful in 4m19s
2026-05-30 08:20:08 +07:00
admin 32204c9305 690530:0805 ADR-030-230 context aware #10
CI / CD Pipeline / build (push) Failing after 4m32s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-30 08:05:48 +07:00
admin 6799cb1715 Update backend/Dockerfile
CI / CD Pipeline / build (push) Successful in 4m40s
CI / CD Pipeline / deploy (push) Failing after 3m4s
2026-05-29 22:34:24 +07:00
admin f33487f511 690529:1702 ADR-030-230 context aware #09
CI / CD Pipeline / build (push) Successful in 4m53s
CI / CD Pipeline / deploy (push) Failing after 2m16s
2026-05-29 17:02:12 +07:00
admin 8367ced926 fix(backend): fix expose name mapping bug in AiPromptResponseDto causing HTTP 500
CI / CD Pipeline / build (push) Successful in 4m27s
CI / CD Pipeline / deploy (push) Failing after 5m18s
2026-05-29 15:23:59 +07:00
admin 8b05f0f05c 690529:1520 ADR-030-230 context aware #08
CI / CD Pipeline / build (push) Successful in 4m22s
CI / CD Pipeline / deploy (push) Failing after 6m11s
2026-05-29 15:20:21 +07:00
admin d19131fa75 690529:1307 ADR-030-230 context aware #07
CI / CD Pipeline / build (push) Successful in 4m32s
CI / CD Pipeline / deploy (push) Successful in 5m52s
2026-05-29 13:07:45 +07:00
admin 95c1c31e1f 690529:1218 ADR-030-230 context aware #06
CI / CD Pipeline / build (push) Successful in 5m25s
CI / CD Pipeline / deploy (push) Successful in 6m11s
2026-05-29 12:18:53 +07:00
admin 0dcd7f460b 690529:1151 ADR-030-230 context aware #05
CI / CD Pipeline / build (push) Successful in 4m18s
CI / CD Pipeline / deploy (push) Successful in 9m30s
2026-05-29 11:51:57 +07:00
admin b68a750e4f 690529:1116 ADR-030-230 context aware #04
CI / CD Pipeline / build (push) Successful in 4m39s
CI / CD Pipeline / deploy (push) Successful in 7m59s
2026-05-29 11:16:03 +07:00
admin 5d46504c1d 690529:0926 ADR-030-230 context aware #03
CI / CD Pipeline / build (push) Successful in 5m3s
CI / CD Pipeline / deploy (push) Successful in 4m47s
2026-05-29 09:26:18 +07:00
admin 4391bbe61d 690528:1524 ADR-030-230 context aware #02
CI / CD Pipeline / build (push) Failing after 4m14s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-28 15:24:41 +07:00
admin 960cd78b8a 690526:1239 ADR-023-229 dynamic prompt #03
CI / CD Pipeline / build (push) Successful in 5m12s
CI / CD Pipeline / deploy (push) Successful in 6m42s
2026-05-26 12:39:29 +07:00
admin 01de542d15 fix(husky): use absolute paths in pre-commit for type checks
CI / CD Pipeline / build (push) Successful in 4m50s
CI / CD Pipeline / deploy (push) Successful in 1m37s
- Use git rev-parse --show-toplevel for absolute paths
- Fixes 'cd frontend: No such file or directory' error
- Fix type cast parsing error in virtual-column.service.spec.ts
2026-05-26 12:20:20 +07:00
admin 9502d789b9 chore(husky): revert pre-commit to lint-staged only
CI / CD Pipeline / build (push) Failing after 3m14s
CI / CD Pipeline / deploy (push) Has been skipped
Type check blocked by broken virtual-column.service.spec.ts.
Will fix test file separately and re-enable type check.
2026-05-26 11:40:50 +07:00
admin 83d1517afc fix(ai-prompts): import UserModule to resolve RbacGuard dependency
CI / CD Pipeline / build (push) Successful in 4m45s
CI / CD Pipeline / deploy (push) Successful in 4m20s
2026-05-26 11:10:03 +07:00
admin 1da666b090 Merge pull request '690525:2327 ADR-023-229 dynamic prompt #01' (#1) from 229-dynamic-prompt-management into main
CI / CD Pipeline / build (push) Successful in 4m23s
CI / CD Pipeline / deploy (push) Failing after 11m28s
Reviewed-on: #1
2026-05-26 10:36:19 +07:00
admin b3d3f6db95 690526:0905 ADR-023-229 dynamic prompt #02
CI / CD Pipeline / build (pull_request) Successful in 4m37s
CI / CD Pipeline / deploy (pull_request) Has been skipped
2026-05-26 09:05:34 +07:00
admin fd3bee394c 690526:0824 ADR-023-229 dynamic prompt #02 2026-05-26 08:24:04 +07:00
admin 82a0444013 690525:2327 ADR-023-229 dynamic prompt #01 2026-05-25 23:27:33 +07:00
admin 1139e54086 690525:1720 ADR-028-228-migration-OCR #06 dynamic prompt
CI / CD Pipeline / build (push) Successful in 4m29s
CI / CD Pipeline / deploy (push) Successful in 1m50s
2026-05-25 17:20:48 +07:00
admin d315488d83 690525:1541 ADR-028-228-migration-OCR #05 ocr-sidecar working
CI / CD Pipeline / build (push) Successful in 4m14s
CI / CD Pipeline / deploy (push) Successful in 5m0s
2026-05-25 15:41:56 +07:00
admin 87c3defc76 690525:1526 ADR-028-228-migration-OCR #05 [skip ci] 2026-05-25 15:26:46 +07:00
admin 1460ffb676 690525:1514 ADR-028-228-migration-OCR #04 [skip ci] 2026-05-25 15:14:06 +07:00
admin 4267f82db9 690525:1451 ADR-028-228-migration-OCR #03 [skip ci] 2026-05-25 14:51:28 +07:00
admin c9e578a33e 690525:1444 ADR-028-228-migration-OCR #02
CI / CD Pipeline / build (push) Successful in 4m32s
CI / CD Pipeline / deploy (push) Successful in 1m42s
2026-05-25 14:44:08 +07:00
admin 256a31b38c 690525:1418 ADR-028-228-migration-OCR #01
CI / CD Pipeline / build (push) Successful in 4m22s
CI / CD Pipeline / deploy (push) Successful in 3m58s
2026-05-25 14:18:02 +07:00
admin 001237ea35 690525:1320 ADR-028-228-migration #06
CI / CD Pipeline / build (push) Successful in 4m18s
CI / CD Pipeline / deploy (push) Successful in 7m41s
2026-05-25 13:20:17 +07:00
admin dcd1a9855e 690524:2148 ADR-028-228-migration #05
CI / CD Pipeline / build (push) Successful in 4m8s
CI / CD Pipeline / deploy (push) Successful in 3m42s
2026-05-24 21:48:30 +07:00
admin 1564f8648d 690524:1919 ADR-028-228-migration #04
CI / CD Pipeline / build (push) Successful in 4m10s
CI / CD Pipeline / deploy (push) Successful in 3m52s
2026-05-24 19:19:46 +07:00
admin 93fd95a6b3 690524:1435 ADR-028-228-migration #03
CI / CD Pipeline / build (push) Successful in 3m59s
CI / CD Pipeline / deploy (push) Successful in 5m18s
2026-05-24 14:35:05 +07:00
admin a63fe0fb5c 690524:1054 ADR-028-228-migration #02
CI / CD Pipeline / build (push) Successful in 4m7s
CI / CD Pipeline / deploy (push) Successful in 4m42s
2026-05-24 10:54:44 +07:00
admin 5a17f969b8 690523:2327 ADR-028-228-migration #01
CI / CD Pipeline / build (push) Successful in 4m38s
CI / CD Pipeline / deploy (push) Successful in 3m6s
2026-05-23 23:27:52 +07:00
admin ff5cadc9f2 690523:1623 ADR-028-228 #05
CI / CD Pipeline / build (push) Successful in 4m55s
CI / CD Pipeline / deploy (push) Successful in 5m49s
2026-05-23 16:23:12 +07:00
admin c04c5d1902 690522:2153 ADR-028-228 #04
CI / CD Pipeline / build (push) Failing after 4m13s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-22 21:53:41 +07:00
admin 3bf34ea840 690522:2140 ADR-028-228 #03
CI / CD Pipeline / build (push) Successful in 5m39s
CI / CD Pipeline / deploy (push) Failing after 3m9s
2026-05-22 21:40:19 +07:00
admin 433b149c85 690522:2125 ADR-028-228 #02
CI / CD Pipeline / build (push) Successful in 4m47s
CI / CD Pipeline / deploy (push) Failing after 5m39s
2026-05-22 21:25:08 +07:00
admin 942cda486c feat(migration): merge ADR-028 migration architecture refactor into main
CI / CD Pipeline / build (push) Successful in 5m45s
CI / CD Pipeline / deploy (push) Failing after 5m24s
Branch: 228-migration-arch-refactor
Tests: 670/670 PASS (Jest backend + Vitest frontend)
Validation: PASS 32/32 tasks, 18/18 FRs
ADR: ADR-028, ADR-023A, ADR-009, ADR-016, ADR-019, ADR-008, ADR-007
2026-05-22 17:12:20 +07:00
admin a2973be208 feat(migration): ADR-028 migration architecture refactor
- เพิ่ม POST /api/ai/jobs + GET /api/ai/jobs/:jobId endpoints (FR-001, FR-002)
- เพิ่ม BullMQ Worker MigrateDocumentWorker + OCR auto-detect (FR-003, FR-004)
- เพิ่ม cleanup-temp-files + expire-pending-reviews workers (FR-005, FR-005a/b)
- สร้าง SQL deltas: tags, correspondence_tags, alter migration_review_queue (FR-006, ADR-009)
- เพิ่ม MigrationReviewService.commitRecord() + SELECT FOR UPDATE (FR-007, FR-007a)
- เพิ่ม CASL permission migration.commit + MigrationReviewController (FR-007)
- สร้าง TagsModule + TagsService + TagsController (US3)
- สร้าง Migration Review Queue frontend page + ReviewQueueTable (US2)
- อัปเดต n8n guide: deterministic Idempotency-Key + token pre-flight (FR-001a, FR-010a/b)
- สร้าง spec.md, plan.md, tasks.md, data-model.md, contracts/, quickstart.md
- สร้าง ADR-028 document + validation-report.md (PASS 32/32 tasks, 173/173 tests)
2026-05-22 17:10:07 +07:00
admin 990d80e16d 690522:1227 ปรับปรุง Admin Panl #01
CI / CD Pipeline / build (push) Successful in 4m46s
CI / CD Pipeline / deploy (push) Successful in 4m35s
2026-05-22 12:27:07 +07:00
admin b5425d8b20 feat(ai): add system settings schema delta and resilience fallback try-catch
CI / CD Pipeline / build (push) Successful in 5m15s
CI / CD Pipeline / deploy (push) Successful in 4m38s
2026-05-22 10:14:27 +07:00
admin 2e50bcaa58 690522:0839 227 #02
CI / CD Pipeline / build (push) Successful in 5m27s
CI / CD Pipeline / deploy (push) Successful in 5m18s
2026-05-22 08:39:26 +07:00
admin f47363c24a 690522:0554 227 #01
CI / CD Pipeline / build (push) Successful in 5m25s
CI / CD Pipeline / deploy (push) Successful in 8m59s
2026-05-22 05:54:34 +07:00
admin a2952a32a4 test(backend): fix all typescript compiler type errors in test suites 2026-05-21 21:51:52 +07:00
admin 91e9c714df feat(ai-admin-console): complete implementation and resolve lint compilation errors 2026-05-21 21:42:25 +07:00
admin 1580ab2c18 690520:1652 224 to 226 AI #07
CI / CD Pipeline / build (push) Successful in 4m32s
CI / CD Pipeline / deploy (push) Successful in 5m48s
2026-05-20 16:52:20 +07:00
admin f17a81d363 690520:0859 224 to 226 AI #06
CI / CD Pipeline / build (push) Successful in 4m56s
CI / CD Pipeline / deploy (push) Failing after 4m13s
2026-05-20 08:59:33 +07:00
admin 080cbbdd85 690519:2152 224 to 226 AI #05
CI / CD Pipeline / build (push) Successful in 4m26s
CI / CD Pipeline / deploy (push) Failing after 4m59s
2026-05-19 21:52:26 +07:00
admin 4a2ff8aa22 690519:2142 224 to 226 AI #04
CI / CD Pipeline / build (push) Failing after 3m34s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-19 21:42:33 +07:00
admin a0b9b55130 690519:2118 224 to 226 AI #03
CI / CD Pipeline / build (push) Failing after 4m8s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-19 21:18:48 +07:00
admin 7259cbf67a 690519:1719 224 to 226 AI #02
CI / CD Pipeline / build (push) Successful in 4m47s
CI / CD Pipeline / deploy (push) Failing after 7m3s
2026-05-19 17:19:24 +07:00
admin ea5499123e 690519:1631 224 to 226 AI #01
CI / CD Pipeline / build (push) Failing after 3m57s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-19 16:31:50 +07:00
Nattanin 3e25097470 690519:0819 Prepare refactor AI [skip ci] 2026-05-19 08:19:40 +07:00
admin 7e6ad0d346 260518:1640 204 and 302 refactor #11
CI / CD Pipeline / build (push) Successful in 5m12s
CI / CD Pipeline / deploy (push) Successful in 1m58s
2026-05-18 16:40:16 +07:00
admin 0ed27f477f 690517:2120 204 and 302 refactor #10
CI / CD Pipeline / build (push) Successful in 4m57s
CI / CD Pipeline / deploy (push) Successful in 1m32s
2026-05-17 21:20:39 +07:00
admin bf997d85ac 690517:2048 204 and 302 refactor #09
CI / CD Pipeline / build (push) Successful in 5m5s
CI / CD Pipeline / deploy (push) Successful in 3m12s
2026-05-17 20:48:45 +07:00
admin 89bbd5ecd7 690517:2029 204 and 302 refactor #08
CI / CD Pipeline / build (push) Successful in 5m19s
CI / CD Pipeline / deploy (push) Failing after 4m23s
2026-05-17 20:29:42 +07:00
admin 7d6450d3f7 690517:1706 204 and 302 refactor #07
CI / CD Pipeline / build (push) Successful in 5m31s
CI / CD Pipeline / deploy (push) Failing after 4m11s
2026-05-17 17:06:24 +07:00
admin 9d000ae22a 690517:1650 204 and 302 refactor #06
CI / CD Pipeline / build (push) Successful in 5m42s
CI / CD Pipeline / deploy (push) Failing after 4m32s
2026-05-17 16:50:53 +07:00
admin af70e53f61 690517:1607 204 and 302 refactor #05
CI / CD Pipeline / build (push) Successful in 5m31s
CI / CD Pipeline / deploy (push) Failing after 10m56s
2026-05-17 16:07:52 +07:00
admin cb340ca1e4 690517:1456 204 and 302 refactor #04
CI / CD Pipeline / build (push) Successful in 5m21s
CI / CD Pipeline / deploy (push) Failing after 20m37s
2026-05-17 14:56:52 +07:00
admin 50bffdf38a 690517:1449 204 and 302 refactor #03
CI / CD Pipeline / build (push) Failing after 42s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-17 14:49:45 +07:00
admin 544bb30277 690516:1955 204 and 302 refactor #02
CI / CD Pipeline / build (push) Successful in 5m56s
CI / CD Pipeline / deploy (push) Failing after 4m29s
2026-05-16 19:55:51 +07:00
admin 1a162bf320 feat(rfa-ai): Complete RFA Approval Refactor and AI Model Revision
CI / CD Pipeline / build (push) Successful in 4m54s
CI / CD Pipeline / deploy (push) Failing after 12m9s
2026-05-16 10:59:53 +07:00
admin 6cb3ae10ee feat(ai): unify AI architecture, implement RAG and legacy migration
CI / CD Pipeline / build (push) Failing after 5m36s
CI / CD Pipeline / deploy (push) Has been skipped
2026-05-15 11:10:44 +07:00
1041 changed files with 118796 additions and 67191 deletions
+13 -12
View File
@@ -2,11 +2,12 @@
> **The Event Horizon of Software Quality.**
> _Adapted for Google Antigravity IDE from [github/spec-kit](https://github.com/github/spec-kit)._
>
> # Speckit Agent Infrastructure (v1.9.0)
>
>
> - Version: 1.9.0
> - Last Updated: 2026-05-13
> - Core Principle: **Sync with AGENTS.md v1.9.0**
> - Last Updated: 2026-05-22
> - Core Principle: **Sync with AGENTS.md v1.9.6**
---
@@ -94,18 +95,18 @@ The toolkit is organized into modular components that provide both the logic (Sc
│ └── util-speckit-*.md # Utilities (checklist, diff, migrate, etc.)
├── rules/ # Project Context & Validation Rules
│ ├── 00-project-context.md # Role, Persona, Rule Tiers (v1.9.0)
│ ├── 00-project-context.md # Role, Persona, Rule Tiers (v1.9.6)
│ ├── 01-adr-019-uuid.md # UUID Strategy (Critical)
│ ├── 02-security.md # Security Requirements
│ ├── 02-security.md # Security Requirements (ADR-023/023A)
│ ├── 03-typescript.md # TypeScript Standards
│ ├── 04-domain-terminology.md # DMS Glossary Compliance
│ ├── 05-forbidden-actions.md # Critical Prohibited Patterns
│ ├── 06-backend-patterns.md # NestJS Architecture Rules
│ ├── 07-frontend-patterns.md # Next.js App Router Rules
│ ├── 08-development-flow.md # Development Workflow
│ ├── 08-development-flow.md # Development Workflow (Tier 3 SPECIALIZED WORK)
│ ├── 09-commit-checklist.md # Pre-commit Validation
│ ├── 10-error-handling.md # ADR-007 Compliance
│ └── 11-ai-integration.md # ADR-018/020 AI Boundaries
│ └── 11-ai-integration.md # ADR-023/023A AI Boundaries
└── scripts/
├── bash/ # Bash Core (Kinetic logic)
@@ -264,9 +265,9 @@ If you change your mind mid-project:
---
## 🏗️ LCBP3-DMS Project Notes (v1.9.0)
## 🏗️ LCBP3-DMS Project Notes (v1.9.6)
### 📊 Current Status: Production Ready (2026-04-14)
### 📊 Current Status: Production Ready (2026-05-22)
| Area | Status |
| ------------- | ------------------------------- |
@@ -282,7 +283,7 @@ If you change your mind mid-project:
| เอกสาร | Path | ใช้เมื่อ |
| --------------- | ---------------------------------------------------------------- | ------------------- |
| Schema Tables | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | ก่อนเขียน Query |
| Schema Tables | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` | ก่อนเขียน Query |
| Data Dictionary | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | ตรวจ Business Rules |
| Edge Cases | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | 37 Rules |
| Migration Scope | `specs/03-Data-and-Storage/03-06-migration-business-scope.md` | Migration Bot |
@@ -305,7 +306,7 @@ If you change your mind mid-project:
- ❌ DO NOT bypass Release Gates before deploying — `04-08-release-management-policy.md`
- ❌ DO NOT start Migration without Gate #1 approval — `03-06-migration-business-scope.md`
- ❌ DO NOT use TypeORM Migrations — modify schema SQL directly (ADR-009)
- ❌ DO NOT give Ollama direct DB access — all writes via DMS API (ADR-018)
- ❌ DO NOT give Ollama direct DB access — all writes via DMS API (ADR-023/023A)
- ❌ DO NOT use `any` TypeScript type anywhere
---
@@ -324,7 +325,7 @@ If you change your mind mid-project:
# Run version validation
./scripts/bash/validate-versions.sh
# Fix by updating all files to v1.9.0
# Fix by updating all files to v1.9.6
# Then re-run validation to confirm
```
+146 -37
View File
@@ -1,55 +1,164 @@
# NAP-DMS Project Context & Core Rules
# NAP-DMS Project Context & Rules
- Version: 1.9.0
- Last Updated: 2026-05-13
- Status: Production Ready
- Canonical Source: AGENTS.md
- For: Devin Cascade (and compatible: Codex CLI, opencode, Amp, Antigravity, AGENTS.md tools)
- Version: 1.9.10 | Last synced from repo: 2026-06-06
- Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3)
- Skill pack: `.agents/skills/` (v1.9.0, 21 skills) — see [`skills/README.md`](./.agents/skills/README.md) + [`skills/_LCBP3-CONTEXT.md`](./.agents/skills/_LCBP3-CONTEXT.md)
## 🎭 Role & Persona
## 🧠 Role & Persona
Act as a **Senior Full Stack Developer** specialized in NestJS, Next.js, and TypeScript.
Focus on **Data Integrity, Security, Maintainability, and Performance**.
You are a **Document Intelligence Engine**every response must be precise, spec-compliant, and production-ready.
Act as **Senior Full Stack Developer** specialized in NestJS, Next.js, TypeScript, DMS. Focus: Data Integrity, Security, Maintainability, Performance.
You are a **Document Intelligence Engine**not a general chatbot. Every response must be **precise**, **spec-compliant**, and **production-ready**.
---
## 🔴 Tier 1 — CRITICAL (CI BLOCKER)
## 🧩 Thought & Planning Protocol (Powered by Everything-Claude-Code)
1. **Identifier Strategy (ADR-019)**
- ห้ามใช้ `parseInt()` บน UUID
- ใช้ `publicId` (string) สำหรับการติดต่อภายนอก (API/URL) เท่านั้น
2. **Database Management (ADR-009)**
- ห้ามใช้ TypeORM Migrations หรือ `synchronize: true`
- การแก้ Schema ต้องแก้ที่ SQL files ใน `specs/03-Data-and-Storage/` เท่านั้น
3. **Security (ADR-016)**
- ทุก API ต้องมี `CASL Guard` และตรวจสอบสิทธิ์ผ่าน RBAC Matrix
- การอัปโหลดไฟล์ต้องเป็น Two-Phase (Temp → Commit) และต้องสแกน ClamAV
4. **AI Boundary (ADR-018)**
- AI Agent ต้องทำงานผ่าน DMS API เท่านั้น ห้ามเขียนลง Database หรือ Storage โดยตรง
Before writing any code or taking any action in Tier 1 and Tier 2, the AI must demonstrate the following thinking process:
### 1. Analysis Phase (Explore & Analyze)
Problem Understanding: Restate what the user wants in clear, unambiguous terms.
Context Search: Identify the relevant Spec files or ADRs from the "Key Spec Files" table that must be read before starting.
Constraints Identification: Identify key constraints (e.g. Security rules, UUID patterns, or Domain terminology).
### 2. Planning Phase (Plan)
Alternative Exploration: Present at least 2 solution approaches (where possible) with pros/cons analysis.
Step-by-Step Roadmap: Write a file-by-file plan of changes before executing.
Verification Plan: Specify how to verify the work is complete (e.g. "which unit tests to write" or "which file to check the schema in").
### 3. Execution & Refinement (Execute & Refine)
Follow the plan step by step, and pause to ask if any uncertainty arises.
If significant logic changes are made, summarize what was done for the user after completion.
---
## 📐 TypeScript Rules & Coding Standards (v1.9.0)
## ⚙️ DMS Workflow Engine Protocol
- **File Header:** ทุกไฟล์ต้องขึ้นต้นด้วย `// File: path/filename`
- **Change Log:** ต้องมีส่วน `// Change Log` ที่หัวไฟล์
- **Language:** ตัวแปร/Logic เป็น English, Comment/JSDoc เป็น **Thai**
- **Explicit Typing:** กำหนด Type ให้ชัดเจนเสมอ ห้ามใช้ `any`
- **Cleanliness:** ห้ามมีบรรทัดว่างในฟังก์ชัน, Export ได้เพียง 1 symbol หลักต่อไฟล์
กฎนี้ใช้คุม Logic การไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกัน Race Condition และรักษาความถูกต้องของสถานะ:
- **State Management:** ตรวจสอบสถานะปัจจุบันจาก DB ก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน (ดู `05-06-code-snippets.md` `[workflow-transition]`)
- **Concurrency Control:** การจอนเลขที่เอกสารต้องใช้ **Redis Redlock** หรือ **TypeORM `@VersionColumn`** เท่านั้น (ADR-002)
- **Background Jobs:** งานนานหรือการแจ้งเตือนต้องส่งไปทำที่ **BullMQ** ห้ามเขียนแบบ Inline (ADR-008)
- **Term Consistency:** ห้ามใช้ "Approval Flow" ให้ใช้ **"Workflow Engine"** และห้ามใช้ "Letter" ให้ใช้ **"Correspondence"** (หมายเหตุ: "จดหมาย" ในคอมเมนต์ภาษาไทย = Correspondence ที่ครอบคลุมทุกประเภท)
---
## 📁 Specs Folder Organization (Hybrid Model)
## 🛡️ Security & Integrity Audit Protocol
- **Core (00-06):** ข้อมูลอ้างอิงถาวร (Permanent Source of Truth)
- **Feature (100-300):** สำหรับงาน Implementation ใหม่
- `100-Infrastructures/`
- `200-fullstacks/`
- `300-others/`
กฎนี้ให้ AI เป็น Gatekeeper ก่อน Commit โดยเน้น **Tier 1 — CRITICAL**:
- **UUID Validation:** ตรวจสอบว่าเป็น **UUIDv7** และห้ามใช้ `parseInt()` บน UUID (ADR-019)
- **RBAC Check:** API ใหม่ต้องมี **CASL Guard** และตรวจสอบ 4-Level RBAC Matrix (ADR-016)
- **Data Isolation:** AI ต้องรันผ่าน **Ollama บน Admin Desktop** เท่านั้น ห้ามเข้าถึง DB/storage โดยตรง (ADR-023)
- **Input Sanitization:** ไฟล์อัปโหลดต้องผ่าน **Two-Phase** (Temp → Commit) และสแกนด้วย **ClamAV** (ADR-016)
---
## 🔄 Workflow Engine (ADR-001/021)
- ใช้ DSL-based state machine
- การเปลี่ยนสถานะต้องตรวจสอบสถานะปัจจุบันจาก DB ก่อนเสมอ
- งานที่ใช้เวลานานต้องส่งไปที่ **BullMQ** เท่านั้น
## 🧭 Rule Enforcement Tiers
### 🔴 Tier 1 — CRITICAL (CI BLOCKER)
Build fails หากละเมิด:
- Security (Auth, RBAC, Validation)
- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID
- Database correctness — verify schema before writing queries
- File upload security (ClamAV + whitelist)
- AI validation boundary (ADR-023)
- Error handling strategy (ADR-007)
- Forbidden patterns: `any`, `console.log`, UUID misuse, `id ?? ''` fallback
### 🟡 Tier 2 — IMPORTANT (CODE REVIEW)
Must fix ก่อน merge:
- Architecture patterns (thin controller, business logic in service)
- Test coverage (80%+ business logic, 70%+ backend overall)
- Cache invalidation
- Naming conventions
- **TypeScript Standards:** Missing JSDoc, explicit types, or file headers
### 🟢 Tier 3 — SPECIALIZED WORK
Requires domain-specific knowledge:
- **ADR-021 Integration:** Workflow Engine & Context implementation
- **AI Infrastructure:** ADR-023/023A boundary enforcement and pipeline usage
- **AI Runtime Layer:** ADR-024 Intent Classification, ADR-025 Tool Layer, ADR-026 Chat UI, ADR-027 Admin Console
- **Migration Pipeline:** ADR-028 Staging Queue & post-migration cleanup
- **Complex Business Logic:** Multi-step workflows with state management
- **Performance Optimization:** Database queries, caching strategies, bulk operations
### 🔵 Tier 4 — GUIDELINES
Best practice — follow when possible:
- Code style / formatting (Prettier handles)
- Comment completeness
- Minor optimizations
---
## 📐 TypeScript Rules & Coding Standards
### 📝 Core Standards
- **Strict Mode** — all strict checks enforced.
- **ZERO `any` types** — use proper types or `unknown` + narrowing.
- **ZERO `console.log`** — use NestJS `Logger` (backend) or remove (frontend).
- **English for Code** — use English for all code identifiers, variables, and logic.
- **Thai for Comments** — use Thai for comments, documentation, and JSDoc.
- **Explicit Typing** — explicitly define types for all variables, parameters, and return values.
- **JSDoc** — use JSDoc for all public classes and methods.
### 🏗️ File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- **Change Log** — include `// Change Log` at the top of the file to track modifications.
- **Single Export** — export **only one main symbol** per file.
- **Function Style** — avoid unnecessary blank lines inside functions.
---
## 🚫 Forbidden Actions
| ❌ Forbidden | ✅ Correct Approach | ⚠️ Why |
| ----------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
| SQL Triggers for business logic | NestJS Service methods | Untestable; bypasses audit log |
| `.env` files in production | `docker-compose.yml` environment section | Secrets exposed in version control |
| TypeORM migration files | Edit schema SQL directly (ADR-009) | Migration drift risk; schema managed via SQL delta |
| Inventing table/column names | Verify against `schema-02-tables.sql` | Schema mismatch causes silent runtime errors |
| `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors |
| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage |
| `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable |
| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"0195…"` parsed to integer `19` — silently wrong |
| Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks |
| AI accessing DB/storage directly | AI → DMS API → DB (ADR-023/023A) | Bypasses RBAC, audit trail, and validation layer |
| Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail |
| Inline email/notification sending | BullMQ queue job (ADR-008) | Blocks request thread; no retry on transient failure |
| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | Unverified deploy risks data loss in production |
| AI direct cloud API calls | On-premises Ollama only (ADR-023/023A) | Data privacy violation; no audit control |
| AI outputs without human validation | Human-in-the-loop validation required (ADR-023/023A) | Unvalidated AI metadata corrupts document records |
| n8n calling Ollama/Qdrant directly | n8n → DMS API → BullMQ → Ollama (ADR-023A) | Bypasses audit log, RBAC, and error handling layer |
| Qdrant query without `projectPublicId` filter | `QdrantService.search(projectPublicId, ...)` (ADR-023A) | Cross-project data leak via vector search |
---
## 🚧 Out of Scope — Never Do Without Explicit Approval
| ❌ Never Do Autonomously | ⚠️ Why Approval Is Required |
| --------------------------------------------------------------- | ---------------------------------------------------------------- |
| `DROP` or `RENAME` a column / table | Irreversible data loss — requires DBA + PM sign-off |
| Push directly to `main` / `master` branch | Bypasses CI, code review, and release gates |
| Generate or insert seed data into production database | May corrupt live data or violate business state invariants |
| Delete files from permanent storage | Files may be referenced in active documents or audit trails |
| Modify RBAC permission matrix without security team approval | Defines access control for all users — security boundary change |
| Upgrade major library versions (NestJS, Next.js, TypeORM, etc.) | Breaking changes require full regression test cycle |
| Disable or modify authentication / authorization guards | Creates unguarded endpoints — immediate security risk |
| Change Redis lock TTL or disable Redlock | Risk of document number race condition (ADR-002) |
| Create or supersede an ADR unilaterally | Architecture decisions require team consensus and review process |
| Add new columns to production tables without schema review | Must update Data Dictionary + downstream queries simultaneously |
+5 -4
View File
@@ -1,4 +1,3 @@
# Security Rules (Non-Negotiable)
## Mandatory Security Requirements
@@ -10,9 +9,9 @@
5. **Password:** bcrypt 12 salt rounds, min 8 chars, rotate every 90 days
6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints
7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan
8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access
8. **AI Isolation (ADR-023/023A):** Ollama on Admin Desktop ONLY — NO direct DB/storage access; 2-model stack `gemma4:e4b Q8_0` + `nomic-embed-text`; all inference via BullMQ (`ai-realtime` / `ai-batch`)
9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages
10. **AI Integration (ADR-020):** RFA-First approach with unified pipeline architecture
10. **AI Integration (ADR-023/023A):** RFA-First approach; n8n orchestrates Migration Phase only via DMS API — never calls Ollama directly; `QdrantService.search()` requires `projectPublicId` as mandatory param
11. **AI Audit Trail:** Log all AI interactions and human validations
12. **Rate Limiting:** Apply to AI endpoints to prevent abuse
@@ -27,7 +26,9 @@
- [ ] No SQL injection vulnerabilities
- [ ] File upload validation (whitelist + ClamAV)
- [ ] Rate limiting applied to auth endpoints
- [ ] AI boundary enforcement (ADR-018) - no direct DB/storage access
- [ ] AI boundary enforcement (ADR-023/023A) - no direct DB/storage access
- [ ] AI audit logging implemented for AI interactions
- [ ] AI outputs validated before use (human-in-the-loop)
- [ ] Error handling follows ADR-007 layered classification
- [ ] Cache invalidation when data modified
- [ ] OWASP Top 10 review passed
+9 -1
View File
@@ -1,4 +1,4 @@
# TypeScript Rules (v1.9.0)
# TypeScript Rules
## Core Standards
@@ -13,10 +13,18 @@
## File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- Use **absolute path** from project root (e.g., `// File: backend/src/modules/correspondence/correspondence.service.ts`)
- Do NOT use relative path (e.g., `// File: src/example.service.ts`)
- **Change Log** — include `// Change Log` at the top of the file.
- **Single Export** — export **only one main symbol** per file.
- **Function Style** — avoid unnecessary blank lines inside functions.
## i18n Guidelines
- **No Hardcoded Text:** Use i18n keys for all user-facing text
- **Reference:** `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md`
- **Pattern:** Use `t('key.path')` from i18n hook instead of hardcoded strings
## Patterns
```typescript
+28 -22
View File
@@ -1,19 +1,18 @@
# Domain Terminology
## DMS Glossary
| ✅ Use | ❌ Don't Use |
| ------------------ | ------------------------------------- |
| Correspondence | Letter, Communication, Document |
| RFA | Approval Request, Submit for Approval |
| Transmittal | Delivery Note, Cover Letter |
| Circulation | Distribution, Routing |
| Shop Drawing | Construction Drawing |
| Contract Drawing | Design Drawing, Blueprint |
| Workflow Engine | Approval Flow, Process Engine |
| Document Numbering | Document ID, Auto Number |
| RBAC | Permission System (generic) |
| ✅ Use | ❌ Don't Use | คำอธิบายเพิ่มเติม |
| ------------------ | ------------------------------------- | ------------------------------------------------ |
| Correspondence | Letter, Communication, Document | ครอบคลุมทุกประเภท: Letter, RFA, Memo, ฯลฯ |
| RFA | Approval Request, Submit for Approval | เอกสารขออนุมัติ (ชนิดหนึ่งของ Correspondence) |
| Transmittal | Delivery Note, Cover Letter | เอกสารนำส่ง (ชนิดหนึ่งของ Correspondence) |
| Circulation | Distribution, Routing | ใบเวียนเอกสารภายใน (ชนิดหนึ่งของ Correspondence) |
| Shop Drawing | Construction Drawing | แบบก่อสร้าง |
| Contract Drawing | Design Drawing, Blueprint | แบบคู่สัญญา |
| Workflow Engine | Approval Flow, Process Engine | เครื่องมือจัดการลำดับงาน |
| Document Numbering | Document ID, Auto Number | ระบบจัดการเลขที่เอกสาร |
| RBAC | Permission System (generic) | การควบคุมสิทธิ์ตามบทบาท |
## Full Glossary
@@ -23,13 +22,20 @@
Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others
| Document | Path | Use When |
| ----------------------- | ----------------------------------------------------------------- | ------------------------------- |
| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology |
| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query |
| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules |
| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows |
| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work |
| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns |
| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns |
| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals |
| Document | Path | Use When |
| ------------------------------ | --------------------------------------------------------------------------- | --------------------------------- |
| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology |
| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` | Before writing any query |
| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules |
| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows |
| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work |
| **ADR-023 AI** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | AI integration work |
| **ADR-023A AI Model** | `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` | 2-model stack, BullMQ 2-queue |
| **ADR-024 Intent Class.** | `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` | Pattern→LLM Fallback; Redis cache |
| **ADR-025 AI Tool Layer** | `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` | Tool Registry; CASL-guarded |
| **ADR-026 Chat UI** | `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` | Side-panel; streaming SSE |
| **ADR-027 AI Admin Console** | `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` | Dynamic control; admin-only |
| **ADR-028 Migration Refactor** | `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` | Staging Queue; cleanup |
| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns |
| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns |
| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals |
+20 -19
View File
@@ -1,30 +1,31 @@
# Forbidden Actions
## ❌ Never Do This
| ❌ Forbidden | ✅ Correct Approach |
| ----------------------------------------------- | ----------------------------------------------- |
| SQL Triggers for business logic | NestJS Service methods |
| `.env` files in production | `docker-compose.yml` environment section |
| TypeORM migration files | Edit schema SQL directly (ADR-009) |
| Inventing table/column names | Verify against `schema-02-tables.sql` |
| `any` TypeScript type | Proper types / generics |
| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) |
| `req: any` in controllers | `RequestWithUser` typed interface |
| `parseInt()` on UUID values | Use UUID string directly (ADR-019) |
| Exposing INT PK in API responses | UUIDv7 (ADR-019) |
| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) |
| Direct file operations bypassing StorageService | `StorageService` for all file moves |
| Inline email/notification sending | BullMQ queue job |
| Deploying without Release Gates | Complete `04-08-release-management-policy.md` |
| AI direct cloud API calls | On-premises Ollama only (ADR-018) |
| AI outputs without human validation | Human-in-the-loop validation required (ADR-020) |
| ❌ Forbidden | ✅ Correct Approach | ⚠️ Why |
| ----------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
| SQL Triggers for business logic | NestJS Service methods | Untestable; bypasses audit log |
| `.env` files in production | `docker-compose.yml` environment section | Secrets exposed in version control |
| TypeORM migration files | Edit schema SQL directly (ADR-009) | Migration drift risk; schema managed via SQL delta |
| Inventing table/column names | Verify against `schema-02-tables.sql` | Schema mismatch causes silent runtime errors |
| `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors |
| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage |
| `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable |
| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"0195…"` parsed to integer `19` — silently wrong |
| Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks |
| AI accessing DB/storage directly | AI → DMS API → DB (ADR-023/023A) | Bypasses RBAC, audit trail, and validation layer |
| Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail |
| Inline email/notification sending | BullMQ queue job (ADR-008) | Blocks request thread; no retry on transient failure |
| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | Unverified deploy risks data loss in production |
| AI direct cloud API calls | On-premises Ollama only (ADR-023/023A) | Data privacy violation; no audit control |
| AI outputs without human validation | Human-in-the-loop validation required (ADR-023/023A) | Unvalidated AI metadata corrupts document records |
| n8n calling Ollama/Qdrant directly | n8n → DMS API → BullMQ → Ollama (ADR-023A) | Bypasses audit log, RBAC, and error handling layer |
| Qdrant query without `projectPublicId` filter | `QdrantService.search(projectPublicId, ...)` (ADR-023A) | Cross-project data leak via vector search |
## Schema Changes (ADR-009)
- **NO TypeORM migrations** — edit SQL schema directly
- Always check `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` before writing queries
- Always check `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` before writing queries
- Update Data Dictionary when changing fields
## UUID Handling
+3 -4
View File
@@ -1,4 +1,3 @@
# Backend Patterns (NestJS)
## Architecture
@@ -17,7 +16,7 @@ async create(@Body() dto: CreateCorrespondenceDto) {
// Resolve UUID to internal ID
const contract = await this.contractService.findOneByUuid(dto.contractUuid);
const contractId = contract.id; // Internal INT for DB queries
return this.service.create(dto, contractId);
}
@@ -40,8 +39,8 @@ async create(dto: CreateCorrespondenceDto, contractId: number) {
class Contract extends UuidBaseEntity {
@Column({ type: 'uuid' })
publicId: string;
@PrimaryKey()
@PrimaryGeneratedColumn()
@Exclude()
id: number;
}
+1 -2
View File
@@ -1,4 +1,3 @@
# Frontend Patterns (Next.js)
## Form Handling
@@ -17,7 +16,7 @@ interface ProjectOption {
}
// Select options
const options = contracts.map(c => ({
const options = contracts.map((c) => ({
label: `${c.contractName} (${c.contractCode})`,
value: c.publicId!, // Use publicId, no fallback to id
}));
+181 -14
View File
@@ -1,4 +1,3 @@
# Development Flow
## 🔴 Critical Work — DB / API / Security / Workflow Engine
@@ -7,17 +6,17 @@
1. **Glossary check** — verify domain terms in `00-02-glossary.md`
2. **Read the spec** — select from Key Spec Files table
3. **Check schema** — verify table/column in `schema-02-tables.sql`
3. **Check schema** — verify table/column in `lcbp3-v1.9.0-schema-02-tables.sql`
4. **Check data dictionary** — confirm field meanings + business rules
5. **Scan edge cases**`01-06-edge-cases-and-rules.md`
6. **Check ADRs** — verify decisions align (ADR-009, ADR-018, ADR-019)
6. **Check ADRs** — verify decisions align (ADR-009, ADR-019, ADR-023)
7. **Write code** — TypeScript strict, no `any`, no `console.log`
## 🟡 Normal Work — UI / Feature / Integration
- Follow existing patterns in codebase.
- Check spec for relevant module only.
- **Hybrid Specs Organization:**
- **Hybrid Specs Organization:**
- Place new Infrastructure tasks in `specs/100-Infrastructures/`
- Place new Feature/Workflow tasks in `specs/200-fullstacks/`
- Place Documentation/Research in `specs/300-others/`
@@ -29,15 +28,183 @@
- Add minimal test if logic changed
- Check forbidden patterns before commit
### 🟢 Specialized Work — ADR-021, AI Runtime Layer, Complex Logic
**MUST complete:**
1. **Domain Knowledge Check** - Read relevant ADRs (ADR-021, ADR-023/023A, ADR-024~028)
2. **Pattern Verification** - Check existing implementations in codebase
3. **Specialized Requirements** - Follow domain-specific patterns
4. **Complex Logic Testing** - Multi-scenario test coverage
5. **Performance Validation** - Load testing if applicable
**For ADR-021 Integration:**
- Read ADR-021 - Integrated workflow & step attachments
- Check ADR-001 - Unified workflow engine patterns
- Verify WorkflowEngineService - Polymorphic instance handling
- Add workflow fields - Expose workflowInstanceId, workflowState, availableActions
- Include IntegratedBanner - Frontend workflow lifecycle display
- Test workflow transitions - State changes and action validation
**For AI Infrastructure (ADR-023/023A):**
- Verify AI boundary enforcement - No direct DB/storage access
- Check BullMQ 2-queue setup - ai-realtime + ai-batch
- Validate Qdrant multi-tenancy - projectPublicId filter required
- Test human-in-the-loop validation workflows
- Audit AI interaction logging to ai_audit_logs
**For AI Runtime Layer (ADR-024/025/026/027):**
- ADR-024: Pattern Layer first (ai_intent_patterns DB + Redis cache 5 min) → LLM Fallback (gemma4:e4b, semaphore max=3)
- ADR-025: Tool Registry dispatch — AI Gateway → Tool → Business Service; ToolResult DTO must use publicId only
- ADR-026: useAiChat() hook + side-panel UI; streaming response via SSE; TanStack Query cache
- ADR-027: Admin Console — dynamic model/prompt/intent control; CASL-guarded admin-only endpoints
**For Migration Pipeline (ADR-028):**
- Use Staging Queue pattern — never write directly to production tables
- Post-migration cleanup process required after each batch
- Migration Validation Gates must pass before promoting to production
**Expected output:**
- Backend services expose specialized context fields
- Frontend components use domain-specific patterns
- Complex state management with proper validation
- Performance metrics within acceptable thresholds
- Comprehensive test coverage for edge cases
---
## Context-Aware Triggers
| Request | Files to Check | Expected Response |
| -------------------- | ------------------------------------------------------- | --------------------------------------------------- |
| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard |
| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases.md` | RHF+Zod + TanStack Query + Thai comments |
| "เพิ่ม field ใหม่" | `ADR-009`, `data-dictionary.md`, `schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity |
| "ตรวจสอบ UUID" | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor |
| "สร้าง migration" | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow |
| "ตรวจสอบ permission" | `seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix |
| "deploy production" | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy |
| "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns |
| Request | Files to Check | Expected Response |
| --------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard |
| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases-and-rules.md` | RHF+Zod + TanStack Query + Thai comments |
| "เพิ่ม field ใหม่" | `ADR-009`, `03-01-data-dictionary.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity |
| "ตรวจสอบ UUID" | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor |
| "สร้าง migration" | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow |
| "ตรวจสอบ permission" | `lcbp3-v1.9.0-seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix |
| "deploy production" | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy |
| "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns |
| "AI integration" | `ADR-023`, `ADR-023A`, `ADR-024`, `ADR-025` | AI boundary + 2-model stack + BullMQ queue policy + Intent/Tool Layer |
| "Error handling" | `ADR-007` | Layered error classification + recovery |
| "File upload" | `ADR-016`, `05-02-backend-guidelines.md`, `03-Data-and-Storage/03-03-file-storage.md` | Two-phase upload → temp → commit; ClamAV + whitelist |
| "Notifications / Queue" | `ADR-008`, `05-02-backend-guidelines.md` | BullMQ job — never inline; check retry + dead-letter |
| "Add i18n / translate" | `05-08-i18n-guidelines.md` | i18n keys only — no hardcoded text |
| "Workflow / DSL" | `ADR-001`, `01-03-modules/01-03-06-unified-workflow.md` | DSL state machine + WorkflowEngineService |
| "Document numbering" | `ADR-002`, `01-02-business-rules/01-02-02-doc-numbering-rules.md` | Redis Redlock + DB optimistic lock (double-lock) |
| "ตรวจสอบ Workflow" | `01-06-edge-cases-and-rules.md`, `05-02-backend-guidelines.md`, `ADR-001`, `ADR-002` | เช็คการเปลี่ยน State, คิว BullMQ และการล็อกเลขที่เอกสาร |
| "Transmittal submit" | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | submit() with EC-RFA-004 validation |
| "Circulation reassign" | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | reassignRouting() with EC-CIRC-001 |
| "สร้าง workflow ใหม่" | `ADR-001`, `ADR-021`, `specs/200-fullstacks/203-unified-workflow-engine/` | DSL workflow definition + WorkflowEngineService setup |
| "ตรวจสอบ AI boundary" | `ADR-023`, `ADR-023A` | Verify Ollama isolation + BullMQ queues + Qdrant projectPublicId filter |
| "Intent classification" | `ADR-024`, `specs/200-fullstacks/224-intent-classification/` | Pattern Layer → LLM Fallback; ai_intent_patterns; Redis cache 5 min |
| "AI Tool Layer" | `ADR-025`, `specs/200-fullstacks/225-ai-tool-layer-architecture/` | Tool Registry; CASL-guarded dispatch; ToolResult publicId only |
| "Document Chat UI" | `ADR-026`, `specs/200-fullstacks/226-document-chat-ui-pattern/` | Side-panel; useAiChat() hook; streaming SSE; TanStack Query cache |
| "AI Admin Console" | `ADR-027`, `specs/200-fullstacks/227-ai-admin-console/` | Dynamic model/prompt/intent control; admin-only CASL endpoints |
| "Migration refactor" | `ADR-028`, `specs/200-fullstacks/228-migration-arch-refactor/` | Staging Queue; post-migration cleanup; validation gates |
| "จัดการ document numbering" | `ADR-002`, `specs/03-Data-and-Storage/03-04-document-numbering.md` | Redis Redlock + template system + preview/override workflows |
| "Audit ความปลอดภัย" | `ADR-016`, `ADR-019`, `ADR-023`, `ADR-023A` | ตรวจสอบ UUID pattern, CASL Guard, AI Boundary และ Qdrant multi-tenancy |
| "แก้ bug / bugfix" | `.agents/workflows/bugfix.md`, `error-catalog.md` | ใช้ bugfix workflow สำหรับเคสที่สาเหตุชัดเจน |
| "ตรวจแอปจริง" | `.windsurf/workflows/check-real-app.md` | ตรวจ endpoint/UI/console หลัง build pass — No Fake Evidence |
| "งานค้าง / resume" | `.windsurf/workflows/resume-pending-work.md` | อ่าน checkpoint เดิม → ตรวจ build → วางแผนต่อโดยไม่ทำงานซ้ำ |
---
## 🔌 MCP MariaDB Tools
MCP MariaDB server ให้เครื่องมือสำหรับตรวจสอบและจัดการ database โดยตรง ใช้สำหรับ:
- ตรวจสอบ schema กับ spec file `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
- Debug ปัญหา database โดยไม่ต้องเข้า MySQL client
- ตรวจสอบ data ใน production/staging
- Validate การเปลี่ยนแปลง schema ก่อน deploy
### Available Tools
| Tool | หน้าที่ | ตัวอย่างการใช้งาน |
|------|----------|------------------|
| `mcp1_mysql_test_connection` | ทดสอบ connection กับ database | ตรวจสอบว่า MCP server เชื่อมต่อได้ |
| `mcp1_mysql_show_databases` | แสดง databases ทั้งหมด | ดูว่ามี database อะไรบ้าง |
| `mcp1_mysql_show_tables` | แสดง tables ทั้งหมดใน database | ดูรายชื่อ tables ใน `lcbp3` |
| `mcp1_mysql_describe_table` | ดู structure/columns ของ table | ตรวจสอบ columns, types, keys ของ `correspondences` |
| `mcp1_mysql_query` | รัน SELECT query | ดู data ใน table หรือ join query |
| `mcp1_mysql_insert` | INSERT data | เพิ่ม seed data หรือ test data |
| `mcp1_mysql_update` | UPDATE data | แก้ไข data ใน table |
| `mcp1_mysql_delete` | DELETE data | ลบ data ใน table |
### การใช้งานร่วมกับ Development Flow
**เมื่อเขียน query ใหม่:**
1. ใช้ `mcp1_mysql_describe_table` เพื่อตรวจสอบ columns และ types
2. เปรียบเทียบกับ `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
3. ใช้ `mcp1_mysql_query` เพื่อทดสอบ query ก่อน implement
**เมื่อเปลี่ยน schema (ADR-009):**
1. ใช้ `mcp1_mysql_describe_table` เพื่อดู structure ปัจจุบัน
2. สร้าง SQL delta ใน `specs/03-Data-and-Storage/deltas/`
3. ใช้ `mcp1_mysql_query` เพื่อตรวจสอบผลลัพธ์หลัง apply delta
**เมื่อ debug ปัญหา database:**
1. ใช้ `mcp1_mysql_query` เพื่อดู data จริง
2. เปรียบเทียบกับ spec และ data dictionary
3. ตรวจสอบ foreign keys และ constraints
### ข้อควรระวัง
- **❌ ห้ามใช้ MCP MariaDB สำหรับ DDL operations** (CREATE/ALTER/DROP) โดยตรง — ต้องใช้ SQL delta ตาม ADR-009
- **✅ ใช้สำหรับ DQL/DML operations** (SELECT/INSERT/UPDATE/DELETE) เพื่อ debug และ test เท่านั้น
- **⚠️ ระวัง DELETE operations** — อาจทำให้เสีย data ใน production
- **✅ ตรวจสอบ schema กับ spec file เสมอ** ก่อนเขียน query
---
## 🧠 MCP Memory Tools
MCP Memory server ให้เครื่องมือสำหรับจัดการ Knowledge Graph และ Long-term Memory ใช้สำหรับ:
- จัดเก็บความรู้และ context ของโปรเจกต์ในรูปแบบ Graph (Entities + Relations + Observations)
- ค้นหาและดึงข้อมูล context จาก memory ที่บันทึกไว้ใน session ก่อนหน้า
- สร้าง/แก้ไข/ลบ entities, relations, และ observations ใน knowledge graph
### Available Tools
| Tool | หน้าที่ | ตัวอย่างการใช้งาน |
|------|----------|------------------|
| `mcp3_create_entities` | สร้าง entities ใหม่หลายตัวพร้อม observations | สร้าง entity ใหม่เช่น Project, User, Task |
| `mcp3_create_relations` | สร้าง relations ระหว่าง entities | สร้าง relation: Project → has → User |
| `mcp3_add_observations` | เพิ่ม observations ให้ entity ที่มีอยู่แล้ว | เพิ่ม context เพิ่มเติมให้ entity |
| `mcp3_delete_entities` | ลบ entities และ relations ที่เกี่ยวข้อง | ลบ entity ที่ไม่ใช้แล้ว |
| `mcp3_delete_relations` | ลบ relations ระหว่าง entities | ลบ relation ที่ผิดหรือไม่ใช้แล้ว |
| `mcp3_delete_observations` | ลบ observations จาก entity | ลบ context ที่ผิดหรือล้าสุด |
| `mcp3_open_nodes` | ดึงข้อมูล entities ตามชื่อ | ดึง entity ที่ระบุชื่อ |
| `mcp3_read_graph` | อ่าน knowledge graph ทั้งหมด | ดูทั้ง graph structure |
| `mcp3_search_nodes` | ค้นหา entities ตาม query | ค้นหา entity จากชื่อ, type, หรือ observation |
### การใช้งานร่วมกับ Development Flow
**เมื่อบันทึก context ใหม่:**
1. ใช้ `mcp3_create_entities` เพื่อสร้าง entities ใหม่ (ถ้ายังไม่มี)
2. ใช้ `mcp3_create_relations` เพื่อเชื่อมโยง entities
3. ใช้ `mcp3_add_observations` เพื่อเพิ่ม context/observations
**เมื่อค้นหา context:**
1. ใช้ `mcp3_search_nodes` เพื่อค้นหา entities ที่เกี่ยวข้อง
2. ใช้ `mcp3_open_nodes` เพื่อดึงข้อมูล entities ที่ต้องการ
3. ใช้ `mcp3_read_graph` เพื่อดู relations ระหว่าง entities
**เมื่อแก้ไข context:**
1. ใช้ `mcp3_add_observations` เพื่อเพิ่ม observations ใหม่
2. ใช้ `mcp3_delete_observations` เพื่อลบ observations ที่ผิด
3. ใช้ `mcp3_create_relations` หรือ `mcp3_delete_relations` เพื่อปรับ relations
### ข้อควรระวัง
- **✅ ใช้สำหรับบันทึก context ที่ต้องใช้ร่วมกันหลาย session** — เช่น การตัดสินใจสำคัญ, architecture decisions, rollout history
- **⚠️ ระวังการลบ entities** — อาจทำให้เสีย context ที่ยังใช้งานอยู่
- **✅ ตรวจสอบว่า entity มีอยู่แล้วก่อนสร้าง** — ใช้ `mcp3_search_nodes` หรือ `mcp3_open_nodes` ก่อน
- **✅ ใช้ชื่อ entity ที่ชัดเจนและไม่ซ้ำกัน** — เพื่อป้องกันความสับสน
+1 -1
View File
@@ -1,4 +1,3 @@
# Commit Checklist
## Pre-Commit Verification
@@ -28,6 +27,7 @@ type(scope): description
Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
Examples:
- `feat(correspondence): add originator organization validation`
- `fix(uuid): correct parseInt usage to string comparison`
- `spec(agents): bump to v1.8.5 - refactor structure`
+6 -12
View File
@@ -1,4 +1,3 @@
# ADR-007 Error Handling Strategy
## CRITICAL RULES
@@ -11,23 +10,18 @@
## Error Classification
| Error Type | Description | User Message | Technical Log |
|------------|-------------|--------------|---------------|
| **Validation** | Input validation failures | Clear field-level errors | Full validation details |
| **Business** | Business rule violations | Actionable guidance | Business context + user ID |
| **System** | Infrastructure failures | Generic "try again" | Full stack trace + metrics |
| Error Type | Description | User Message | Technical Log |
| -------------- | ------------------------- | ------------------------ | -------------------------- |
| **Validation** | Input validation failures | Clear field-level errors | Full validation details |
| **Business** | Business rule violations | Actionable guidance | Business context + user ID |
| **System** | Infrastructure failures | Generic "try again" | Full stack trace + metrics |
## Backend Pattern (NestJS)
```typescript
// Custom Exception Hierarchy
export class BusinessException extends HttpException {
constructor(
message: string,
userMessage: string,
recoveryAction?: string,
errorCode?: string
) {
constructor(message: string, userMessage: string, recoveryAction?: string, errorCode?: string) {
super({ message, userMessage, recoveryAction, errorCode }, 400);
}
}
+74 -26
View File
@@ -1,30 +1,34 @@
# ADR-020 AI Integration Architecture
# ADR-023/023A AI Integration Architecture
## CRITICAL RULES
- **ALWAYS** follow ADR-018 AI boundary policy (isolation on Admin Desktop)
- **ALWAYS** use RFA-First approach for AI implementation
- **ALWAYS** follow ADR-023 AI boundary policy (isolation on Admin Desktop)
- **ALWAYS** use ADR-034 model stack (typhoon2.5-np-dms:latest + typhoon-np-dms-ocr:latest + nomic-embed-text)
- **ALWAYS** use BullMQ 2-queue (ai-realtime + ai-batch) for GPU overload prevention
- **NEVER** allow AI direct database/storage access
- **ALWAYS** implement human-in-the-loop validation
- **NEVER** send sensitive data to cloud AI services
- **ALWAYS** enforce Qdrant projectPublicId filter (compile-time enforcement)
- **NEVER** allow n8n to call Ollama/Qdrant directly (must go through DMS API → BullMQ)
## AI Integration Patterns
### Architecture Overview
```
Frontend → AI Gateway API → Admin Desktop (Ollama) → Backend Validation
Frontend → AI Gateway API → BullMQ → Admin Desktop (Ollama) → Backend Validation
n8n (Migration) → DMS API → BullMQ → Admin Desktop (Ollama) → Backend Validation
```
### Key Components
| Component | Location | Purpose |
|-----------|----------|---------|
| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging |
| **Ollama Engine** | Admin Desktop (Desk-5439) | LLM inference (Gemma 4) |
| **OCR Engine** | Admin Desktop (Desk-5439) | Thai/English text extraction |
| **Orchestrator** | QNAP NAS (n8n) | Workflow management |
| Component | Location | Purpose |
| ----------------- | ------------------------- | ------------------------------------------------------------------------ |
| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging |
| **BullMQ Queues** | Backend (NestJS) | ai-realtime (RAG/Suggest), ai-batch (OCR/Extract/Embed) |
| **Ollama Engine** | Admin Desktop (Desk-5439) | typhoon2.5-np-dms:latest (Main LLM) + typhoon-np-dms-ocr:latest (OCR, keep_alive:0) + nomic-embed-text (Embedding) |
| **OCR Engine** | Admin Desktop (Desk-5439) | Tesseract OCR + Typhoon OCR (via Ollama) + PyThaiNLP (Thai/English text extraction) |
| **Orchestrator** | QNAP NAS (n8n) | Migration Phase orchestrator only (calls DMS API, never Ollama directly) |
## Backend Implementation (NestJS)
@@ -32,24 +36,50 @@ Frontend → AI Gateway API → Admin Desktop (Ollama) → Backend Validation
// AI Module with boundary enforcement
@Module({
controllers: [AiController],
providers: [AiService, AiGateway],
providers: [AiService, AiGateway, QdrantService],
exports: [AiService],
})
export class AiModule {
constructor() {
// Enforce ADR-018 boundaries
// Enforce ADR-023 boundaries
}
}
// QdrantService with compile-time projectPublicId enforcement
@Injectable()
export class QdrantService {
async search(
projectPublicId: string, // required — compile-time enforcement
vector: number[],
topK: number = 5,
): Promise<QdrantSearchResult[]> {
return this.client.search('documents', {
vector,
limit: topK,
filter: {
must: [{ key: 'project_public_id', match: { value: projectPublicId } }],
},
});
}
async upsert(
projectPublicId: string, // required
chunks: DocumentChunk[],
): Promise<void> { ... }
// ❌ NEVER expose rawSearch() or method without projectPublicId filter
}
// AI Service with validation
@Injectable()
export class AiService {
async extractMetadata(documentId: string): Promise<AIMetadata> {
// 1. Validate permissions
// 2. Send to Admin Desktop AI
// 3. Validate AI response
// 4. Log audit trail
// 5. Return validated results
// 2. Queue job to BullMQ (ai-batch or ai-realtime)
// 3. Worker sends to Admin Desktop AI (typhoon2.5-np-dms:latest)
// 4. Validate AI response
// 5. Log audit trail to ai_audit_logs
// 6. Return validated results
}
}
```
@@ -74,24 +104,42 @@ const DocumentReviewForm = ({ document, aiSuggestions }) => {
## Security Requirements
- **AI Isolation:** All AI processing on Admin Desktop only
- **AI Isolation:** All AI processing on Admin Desktop only (Desk-5439)
- **Data Privacy:** No cloud AI services, on-premises only
- **Audit Trail:** Log all AI interactions and human validations
- **Audit Trail:** Log all AI interactions and human validations to ai_audit_logs
- **Rate Limiting:** Prevent AI abuse and resource exhaustion
- **Validation:** All AI outputs must be validated before use
- **Multi-tenant Isolation:** Qdrant queries MUST include projectPublicId filter (compile-time enforcement)
- **n8n Boundary:** n8n MUST call DMS API → BullMQ, NEVER Ollama/Qdrant directly
- **GPU Overload Prevention:** BullMQ 2-queue (ai-realtime + ai-batch) with concurrency=1
## ADR-034 Model Stack (supersedes ADR-023A §2.1)
- **3-Model Config:** typhoon2.5-np-dms:latest (Main) + typhoon-np-dms-ocr:latest (OCR, keep_alive:0) + nomic-embed-text (Embedding)
- **PDF 3-Page Limit:** Classification/Tagging uses first 3 pages only (NOT RAG embedding)
- **RAG Embedding:** Full document chunked at 512 tokens/64 tokens overlap
- **OCR Auto-Detect:** PyMuPDF chars > 100 → Fast path, else Tesseract OCR (with Typhoon OCR option)
- **Embed Auto-Trigger:** AUTO after commit (parallel), gap covered by DB search
- **Threshold Recalibration:** After 100-500 docs, based on ai_audit_logs analysis
## Required Implementation
- [ ] AiModule with ADR-018 boundary enforcement
- [ ] AiModule with ADR-023 boundary enforcement
- [ ] AI Gateway API endpoints with validation
- [ ] BullMQ 2-queue setup (ai-realtime + ai-batch)
- [ ] QdrantService with projectPublicId enforcement
- [ ] DocumentReviewForm reusable component
- [ ] Admin Desktop Ollama + PaddleOCR setup
- [ ] n8n workflow orchestration
- [ ] AI audit logging and monitoring
- [ ] Admin Desktop Ollama (typhoon2.5-np-dms:latest + typhoon-np-dms-ocr:latest + nomic-embed-text) setup
- [ ] n8n workflow orchestration (Migration Phase only)
- [ ] AI audit logging and monitoring (ai_audit_logs)
- [ ] Human-in-the-loop validation workflows
## Related Documents
- `specs/06-Decision-Records/ADR-018-ai-boundary.md`
- `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md`
- `specs/06-Decision-Records/ADR-017-ollama-data-migration.md`
- `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` (Base architecture)
- `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` (Model revision - current)
- `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` (Pattern→LLM Fallback)
- `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` (Tool Registry)
- `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` (Chat UI)
- `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` (Admin Console)
- `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` (Migration Pipeline)
+137
View File
@@ -0,0 +1,137 @@
# LCBP3 Agent Rules
Critical rules and guidelines for AI agents working on LCBP3-DMS.
## Version
- **Current:** v1.9.6
- **Last Updated:** 2026-05-22
- **Synced with:** `AGENTS.md` (v1.9.6)
## Purpose
This directory contains rule files that define:
- Project context and role expectations
- Critical Tier 1 rules (CI blockers)
- Coding standards and patterns
- Domain terminology and glossary
- Development workflows
- Security requirements
- AI integration architecture (ADR-023/023A)
## Rule Enforcement Tiers
### 🔴 Tier 1 — CRITICAL (CI BLOCKER)
Build fails immediately if violated:
- Security (Auth, RBAC, Validation)
- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID
- Database correctness — verify schema before writing queries
- File upload security (ClamAV + whitelist)
- AI validation boundary (ADR-023)
- Error handling strategy (ADR-007)
- Forbidden patterns: `any`, `console.log`, UUID misuse, `id ?? ''` fallback
### 🟡 Tier 2 — IMPORTANT (CODE REVIEW)
Must fix before merge:
- Architecture patterns (thin controller, business logic in service)
- Test coverage (80%+ business logic, 70%+ backend overall)
- Cache invalidation
- Naming conventions
- TypeScript Standards: Missing JSDoc, explicit types, or file headers
### 🟢 Tier 3 — SPECIALIZED WORK
Requires domain-specific knowledge:
- **ADR-021 Integration:** Workflow Engine & Context implementation
- **AI Infrastructure:** ADR-023/023A boundary enforcement and pipeline usage
- **AI Runtime Layer:** ADR-024 Intent Classification, ADR-025 Tool Layer, ADR-026 Chat UI, ADR-027 Admin Console
- **Migration Pipeline:** ADR-028 Staging Queue & post-migration cleanup
- **Complex Business Logic:** Multi-step workflows with state management
- **Performance Optimization:** Database queries, caching strategies, bulk operations
### 🔵 Tier 4 — GUIDELINES
Best practice — follow when possible:
- Code style / formatting (Prettier handles)
- Comment completeness
- Minor optimizations
## Rule Files
### Core Rules (Tier 1 - CRITICAL)
| File | Purpose |
| ----------------------- | ------------------------------------------------------------------------------- |
| `00-project-context.md` | Project context, role & persona, tier classification, specs folder organization |
| `01-adr-019-uuid.md` | UUID handling strategy — no parseInt, use publicId only |
| `02-security.md` | Security requirements, checklist, ADR-023/023A AI boundaries |
### Coding Standards
| File | Purpose |
| ------------------------- | ------------------------------------------------------- |
| `03-typescript.md` | TypeScript rules, file headers, i18n guidelines |
| `06-backend-patterns.md` | NestJS patterns, UUID resolution, API response patterns |
| `07-frontend-patterns.md` | Next.js patterns, RHF+Zod+TanStack Query, UUID handling |
### Domain & Workflow
| File | Purpose |
| -------------------------- | ------------------------------------------------------------- |
| `04-domain-terminology.md` | DMS glossary, key spec files priority table |
| `08-development-flow.md` | Development workflow by work type (Critical/Normal/Quick Fix) |
### Compliance & Architecture
| File | Purpose |
| ------------------------- | -------------------------------------------------------------- |
| `05-forbidden-actions.md` | Actions that must never be done, schema changes, UUID handling |
| `09-commit-checklist.md` | Pre-commit verification, commit message format |
| `10-error-handling.md` | ADR-007 error handling strategy, layered classification |
| `11-ai-integration.md` | ADR-023/023A AI architecture, 2-model stack, BullMQ 2-queue |
## Key Spec Files Priority
Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others
| Document | Path | Use When |
| ------------------------------ | --------------------------------------------------------------------------- | --------------------------------- |
| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology |
| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` | Before writing any query |
| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules |
| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows |
| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work |
| **ADR-023 AI** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | AI integration work |
| **ADR-023A AI Model** | `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` | 2-model stack, BullMQ 2-queue |
| **ADR-024 Intent Class.** | `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` | Pattern→LLM Fallback; Redis cache |
| **ADR-025 AI Tool Layer** | `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` | Tool Registry; CASL-guarded |
| **ADR-026 Chat UI** | `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` | Side-panel; streaming SSE |
| **ADR-027 AI Admin Console** | `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` | Dynamic control; admin-only |
| **ADR-028 Migration Refactor** | `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` | Staging Queue; cleanup |
| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns |
| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns |
| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals |
## Maintenance
When updating rules:
1. **Check AGENTS.md version** — Ensure rule files are synced
2. **Update version numbers** — Bump version in `00-project-context.md` only (03-typescript.md no longer has version)
3. **Review ADR references** — Ensure all ADR references are current (ADR-023, ADR-023A, ADR-024~028)
4. **Add new forbidden actions** — When new patterns are identified as violations
5. **Update key spec files table** — When new ADRs or guidelines are added
6. **Update Tier 3 SPECIALIZED WORK** — When new domain-specific workflows are added
## Related Documents
- `AGENTS.md` — Master agent configuration and context
- `specs/06-Decision-Records/` — All Architecture Decision Records
- `specs/05-Engineering-Guidelines/` — Backend, frontend, and testing guidelines
+1 -1
View File
@@ -42,7 +42,7 @@ init_agent_registry() {
[qwen]="Qwen Code"
[opencode]="opencode"
[codex]="Codex CLI"
[windsurf]="Windsurf"
[devin]="Devin"
[kilocode]="Kilo Code"
[auggie]="Auggie CLI"
[roo]="Roo Code"
+7 -8
View File
@@ -99,14 +99,13 @@ find_feature_dir_by_prefix() {
local prefix="${BASH_REMATCH[1]}"
# Search for directories in specs/ that start with this prefix
# Search for directories in specs/ that start with this prefix (supporting subdirectories)
local matches=()
if [[ -d "$specs_dir" ]]; then
for dir in "$specs_dir"/"$prefix"-*; do
if [[ -d "$dir" ]]; then
matches+=("$(basename "$dir")")
fi
done
# ค้นหาโฟลเดอร์ที่ตรงกับ prefix ในระบบย่อย
while IFS= read -r -d '' dir; do
matches+=("$dir")
done < <(find "$specs_dir" -maxdepth 3 -type d -name "${prefix}-*" -print0 2>/dev/null)
fi
# Handle results
@@ -115,12 +114,12 @@ find_feature_dir_by_prefix() {
echo "$specs_dir/$branch_name"
elif [[ ${#matches[@]} -eq 1 ]]; then
# Exactly one match - perfect!
echo "$specs_dir/${matches[0]}"
echo "${matches[0]}"
else
# Multiple matches - this shouldn't happen with proper naming convention
echo "ERROR: Multiple spec directories found with prefix '$prefix': ${matches[*]}" >&2
echo "Please ensure only one spec directory exists per numeric prefix." >&2
echo "$specs_dir/$branch_name" # Return something to avoid breaking the script
echo "${matches[0]}" # Return first match to avoid breaking the script
fi
}
+6 -6
View File
@@ -30,12 +30,12 @@
#
# 5. Multi-Agent Support
# - Handles agent-specific file paths and naming conventions
# - Supports: Claude, Gemini, Copilot, Cursor, Qwen, opencode, Codex, Windsurf, Kilo Code, Auggie CLI, Roo Code, CodeBuddy CLI, Qoder CLI, Amp, SHAI, or Amazon Q Developer CLI
# - Supports: Claude, Gemini, Copilot, Cursor, Qwen, opencode, Codex, Devin, Kilo Code, Auggie CLI, Roo Code, CodeBuddy CLI, Qoder CLI, Amp, SHAI, or Amazon Q Developer CLI
# - Can update single agents or all existing agent files
# - Creates default Claude file if no agent files exist
#
# Usage: ./update-agent-context.sh [agent_type]
# Agent types: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|shai|q|bob|qoder
# Agent types: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|devin|kilocode|auggie|shai|q|bob|qoder
# Leave empty to update all existing agent files
set -e
@@ -609,8 +609,8 @@ update_specific_agent() {
codex)
update_agent_file "$AGENTS_FILE" "Codex CLI"
;;
windsurf)
update_agent_file "$WINDSURF_FILE" "Windsurf"
devin)
update_agent_file "$DEVIN_FILE" "Devin"
;;
kilocode)
update_agent_file "$KILOCODE_FILE" "Kilo Code"
@@ -681,8 +681,8 @@ update_all_existing_agents() {
found_agent=true
fi
if [[ -f "$WINDSURF_FILE" ]]; then
update_agent_file "$WINDSURF_FILE" "Windsurf"
if [[ -f "$DEVIN_FILE" ]]; then
update_agent_file "$DEVIN_FILE" "Devin"
found_agent=true
fi
+19 -17
View File
@@ -1,8 +1,8 @@
# `.agents/skills/` — LCBP3 Agent Skill Pack
**Version:** 1.8.9 | **Last Updated:** 2026-04-22 | **Total Skills:** 20
**Version:** 1.9.0 | **Last Updated:** 2026-06-07 | **Total Skills:** 24
Agent skills for AI-assisted development in **Windsurf IDE** (and compatible agents: Codex CLI, opencode, Amp, Antigravity, AGENTS.md-aware tools).
Agent skills for AI-assisted development in **Devin IDE** (and compatible agents: Codex CLI, opencode, Amp, Antigravity, AGENTS.md-aware tools).
---
@@ -14,25 +14,27 @@ Agent skills for AI-assisted development in **Windsurf IDE** (and compatible age
├── skills.md # Overview + dependency matrix + health monitoring
├── _LCBP3-CONTEXT.md # Shared LCBP3 context injected into every speckit-* skill
├── README.md # (this file)
├── save-memory/ # Session log & project memory update
├── nestjs-best-practices/ # Backend rules (40 rules across 10 categories)
├── next-best-practices/ # Frontend rules (Next.js 15+)
├── e2e-testing/ # Playwright E2E testing patterns (POM, flaky tests, CI/CD)
├── verification-loop/ # Comprehensive verification (build, typecheck, lint, test, security)
├── security-review/ # OWASP Top 10 + ADR compliance checklist
└── speckit-*/ # 18 workflow skills (spec → plan → tasks → implement → …)
```
Each skill directory contains:
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.8.9`, `scope`, `depends-on`, `handoffs`) + instructions
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.9.0`, `scope`, `depends-on`, `handoffs`) + instructions
- `templates/` _(optional)_ — artifact templates (spec/plan/tasks/checklist)
- `rules/` _(nestjs only)_ — individual rule files grouped by prefix (`arch-`, `security-`, `db-`, etc.)
---
## 🚀 How Windsurf Invokes These Skills
## 🚀 How Devin Invokes These Skills
Windsurf exposes two entry points:
1. **Skill tool** — Windsurf discovers skills by scanning `.agents/skills/*/SKILL.md` frontmatter. Skills marked `user-invocable: false` are used silently by Cascade.
2. **Slash commands**`.windsurf/workflows/*.md` wraps each skill as a slash command (e.g. `/04-speckit.plan`). The workflow file is short; the heavy lifting is delegated to the skill via `skill` tool.
1. **Skill tool** — Devin discovers skills by scanning `.agents/skills/*/SKILL.md` frontmatter. Skills marked `user-invocable: false` are used silently by Cascade.
2. **Slash commands**`.devin/workflows/*.md` wraps each skill as a slash command (e.g. `/04-speckit.plan`). The workflow file is short; the heavy lifting is delegated to the skill via `skill` tool.
Both paths end up executing the same `SKILL.md` instructions.
@@ -62,14 +64,14 @@ Use `/00-speckit.all` to run specify → clarify → plan → tasks → analyze
From repo root:
| Script | Purpose |
| --- | --- |
| Script | Purpose |
| ------------------------------------------------------ | ---------------------------------------------------------- |
| `./.agents/scripts/bash/check-prerequisites.sh --json` | Emit `FEATURE_DIR` + `AVAILABLE_DOCS` for a feature branch |
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
| `./.agents/scripts/bash/update-agent-context.sh windsurf` | Append tech entries to `AGENTS.md` |
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.windsurf/workflows/*.md` wrapper |
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
| `./.agents/scripts/bash/update-agent-context.sh devin` | Append tech entries to `AGENTS.md` |
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.devin/workflows/*.md` wrapper |
All scripts mirror to `.agents/scripts/powershell/*.ps1` for Windows.
@@ -92,9 +94,9 @@ See [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md) for the complete list.
To add a new skill:
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.8.9`, `scope`, `depends-on`.
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.9.0`, `scope`, `depends-on`.
2. Append an LCBP3 context reference pointing to `_LCBP3-CONTEXT.md`.
3. Wrap with `.windsurf/workflows/NAME.md` so it becomes a slash command.
3. Wrap with `.devin/workflows/NAME.md` so it becomes a slash command.
4. Update [`skills.md`](./skills.md) dependency matrix.
5. Run `./.agents/scripts/bash/audit-skills.sh` → must pass.
+31 -24
View File
@@ -5,14 +5,14 @@
**Project:** NAP-DMS (LCBP3) — Laem Chabang Port Phase 3 Document Management System
**Stack:** NestJS 11 + Next.js 16 + TypeScript + MariaDB 11.8 + Redis + BullMQ + Elasticsearch + Ollama (on-prem AI)
**Version:** 1.8.9 (2026-04-18)
**Version:** 1.9.7 (2026-05-25)
---
## 📌 Canonical Rule Sources (read in this order)
1. **`AGENTS.md`** (repo root) — primary rule file for AI agents; supersedes legacy `GEMINI.md`.
2. **`specs/06-Decision-Records/`** — architectural decisions (22 ADRs); ADR priority > Engineering Guidelines.
2. **`specs/06-Decision-Records/`** — architectural decisions (29 ADRs); ADR priority > Engineering Guidelines.
3. **`specs/05-Engineering-Guidelines/`** — backend/frontend/testing/i18n/git patterns.
4. **`specs/00-Overview/00-02-glossary.md`** — domain terminology (Correspondence / RFA / Transmittal / Circulation).
5. **`specs/00-Overview/00-03-product-vision.md`** — project constitution (Vision, Strategic Pillars, Guardrails).
@@ -24,11 +24,12 @@
## 🔴 Tier 1 Non-Negotiables
- **ADR-019 UUID:** `publicId: string` exposed directly — **no** `@Expose({ name: 'id' })` rename; **no** `parseInt`/`Number`/`+` on UUID; **no** `id ?? ''` fallback in frontend.
- **ADR-009:** No TypeORM migrations — edit `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` or add a `deltas/*.sql` file.
- **ADR-009:** No TypeORM migrations — edit `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` or add a `deltas/*.sql` file.
- **ADR-016 Security:** JWT + CASL 4-Level RBAC; `@UseGuards(JwtAuthGuard, CaslAbilityGuard)` on every mutation controller; `ThrottlerGuard` on auth; bcrypt 12 rounds; `Idempotency-Key` required on POST/PUT/PATCH.
- **ADR-002 Document Numbering:** Redis Redlock + TypeORM `@VersionColumn` (double-lock). Never use application-side counter alone.
- **ADR-008 Notifications:** BullMQ queue — never inline email/notification in a request thread.
- **ADR-018 AI Boundary:** Ollama on Admin Desktop only; AI → DMS API → DB (never direct DB/storage). Human-in-the-loop validation required.
- **ADR-023/023A AI Boundary:** Ollama on Admin Desktop only; AI → DMS API → DB (never direct DB/storage). 2-model stack: `gemma4:e4b Q8_0` + `nomic-embed-text`. BullMQ `ai-realtime` / `ai-batch` queues. Human-in-the-loop validation required. (ADR-018 superseded by ADR-023)
- **ADR-029 Dynamic Prompt Management:** Prompt templates in DB (`ai_prompts`), never hardcoded in processor; Redis cache `ai:prompt:active:{type}` TTL 60s; `activate()` runs in DB transaction + Redis DEL after commit; `system.manage_all` guard on all mutations.
- **ADR-007 Error Handling:** Layered (Validation / Business / System); `BusinessException` hierarchy; user-friendly `userMessage` + `recoveryAction`; technical stack only in logs.
- **TypeScript Strict:** Zero `any`, zero `console.log` (use NestJS `Logger`).
- **i18n:** No hardcoded Thai/English strings in components — use i18n keys (see `05-08-i18n-guidelines.md`).
@@ -38,30 +39,36 @@
## 🏷️ Domain Glossary (reject generic terms)
| ✅ Use | ❌ Don't Use |
| --- | --- |
| Correspondence | Letter, Communication, Document |
| RFA | Approval Request, Submit for Approval |
| Transmittal | Delivery Note, Cover Letter |
| Circulation | Distribution, Routing |
| Shop Drawing | Construction Drawing |
| Contract Drawing | Design Drawing, Blueprint |
| Workflow Engine | Approval Flow, Process Engine |
| Document Numbering | Document ID, Auto Number |
| ✅ Use | ❌ Don't Use |
| ------------------ | ------------------------------------- |
| Correspondence | Letter, Communication, Document |
| RFA | Approval Request, Submit for Approval |
| Transmittal | Delivery Note, Cover Letter |
| Circulation | Distribution, Routing |
| Shop Drawing | Construction Drawing |
| Contract Drawing | Design Drawing, Blueprint |
| Workflow Engine | Approval Flow, Process Engine |
| Document Numbering | Document ID, Auto Number |
---
## 📁 Key Files for Generating / Validating Artifacts
| When you need... | Read |
| --- | --- |
| A new feature spec | `.agents/skills/speckit-specify/templates/spec-template.md` + `specs/01-Requirements/01-06-edge-cases-and-rules.md` |
| A plan | `.agents/skills/speckit-plan/templates/plan-template.md` + relevant ADRs |
| Task breakdown | `.agents/skills/speckit-tasks/templates/tasks-template.md` + existing patterns in `specs/08-Tasks/` |
| Acceptance criteria / UAT | `specs/01-Requirements/01-05-acceptance-criteria.md` |
| Schema / table definition | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` + `03-01-data-dictionary.md` |
| RBAC / permissions | `specs/03-Data-and-Storage/lcbp3-v1.8.0-seed-permissions.sql` + `01-02-01-rbac-matrix.md` |
| Release / hotfix | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` |
| When you need... | Read |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| A new feature spec | `.agents/skills/speckit-specify/templates/spec-template.md` + `specs/01-Requirements/01-06-edge-cases-and-rules.md` |
| A plan | `.agents/skills/speckit-plan/templates/plan-template.md` + relevant ADRs |
| Task breakdown | `.agents/skills/speckit-tasks/templates/tasks-template.md` + existing patterns in `specs/08-Tasks/` |
| Acceptance criteria / UAT | `specs/01-Requirements/01-05-acceptance-criteria.md` |
| Schema / table definition | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` + `03-01-data-dictionary.md` |
| RBAC / permissions | `specs/03-Data-and-Storage/lcbp3-v1.8.0-seed-permissions.sql` + `01-02-01-rbac-matrix.md` |
| Release / hotfix | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` |
| ADR-024 Intent Class. | `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` |
| ADR-025 AI Tool Layer | `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` |
| ADR-026 Chat UI | `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` |
| ADR-027 AI Admin Console | `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` |
| ADR-028 Migration Refactor | `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` |
| ADR-029 Dynamic Prompts | `specs/06-Decision-Records/ADR-029-dynamic-prompt-management.md` |
---
@@ -83,7 +90,7 @@
- [ ] Business comments in Thai, code identifiers in English
- [ ] Schema changes via SQL directly (not migration)
- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+)
- [ ] Relevant ADRs referenced (007/008/009/016/018/019/020/021)
- [ ] Relevant ADRs referenced (007/008/009/016/019/021/023/023A/024-029 for AI work)
- [ ] Domain glossary terms used correctly
- [ ] Error handling: `Logger` + `HttpException` / `BusinessException`
- [ ] i18n keys used (no hardcode text)
+354
View File
@@ -0,0 +1,354 @@
---
name: e2e-testing
description: Playwright E2E testing patterns, Page Object Model, configuration, CI/CD integration, artifact management, and flaky test strategies for LCBP3-DMS.
version: 1.9.0
scope: testing
depends-on: []
handoffs-to: [speckit-tester]
user-invocable: true
---
# E2E Testing Skill
Playwright E2E testing patterns adapted for LCBP3-DMS (NestJS + Next.js + MariaDB stack).
## LCBP3 Context
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific testing requirements:
- Backend: Jest (Unit + Integration + E2E)
- Frontend: Vitest (Unit) + Playwright (E2E)
- E2E test location: `frontend/e2e/workflow-adr021.spec.ts`
- Coverage goals: Backend 70%+, Business Logic 80%+
## When to Use
Invoke this skill when:
- Creating new E2E tests for frontend features
- Debugging flaky Playwright tests
- Setting up CI/CD integration for E2E tests
- Optimizing test performance and reliability
- Implementing Page Object Model (POM) patterns
## Test File Organization
```
frontend/
├── e2e/
│ ├── auth/
│ │ ├── login.spec.ts
│ │ └── logout.spec.ts
│ ├── correspondence/
│ │ ├── create.spec.ts
│ │ └── workflow.spec.ts
│ ├── transmittals/
│ │ ├── create.spec.ts
│ │ └── submit.spec.ts
│ ├── circulation/
│ │ ├── routing.spec.ts
│ │ └── approval.spec.ts
│ └── workflow-adr021.spec.ts # Existing ADR-021 integration test
├── playwright.config.ts
└── tests/
└── fixtures/
├── auth.ts
└── data.ts
```
## Page Object Model (POM)
```typescript
// frontend/e2e/pages/CorrespondencePage.ts
import { Page, Locator } from '@playwright/test'
export class CorrespondencePage {
readonly page: Page
readonly createButton: Locator
readonly subjectInput: Locator
readonly recipientSelect: Locator
readonly submitButton: Locator
readonly successMessage: Locator
constructor(page: Page) {
this.page = page
this.createButton = page.getByTestId('create-correspondence')
this.subjectInput = page.getByTestId('subject-input')
this.recipientSelect = page.getByTestId('recipient-select')
this.submitButton = page.getByTestId('submit-button')
this.successMessage = page.getByTestId('success-message')
}
async goto() {
await this.page.goto('/admin/doc-control/correspondences')
await this.page.waitForLoadState('networkidle')
}
async createCorrespondence(data: {
subject: string
recipientId: string
}) {
await this.createButton.click()
await this.subjectInput.fill(data.subject)
await this.recipientSelect.selectOption(data.recipientId)
await this.submitButton.click()
}
async verifySuccess() {
await expect(this.successMessage).toBeVisible()
}
}
```
## Test Structure
```typescript
// frontend/e2e/correspondence/create.spec.ts
import { test, expect } from '@playwright/test'
import { CorrespondencePage } from '../pages/CorrespondencePage'
test.describe('Correspondence Creation', () => {
let correspondencePage: CorrespondencePage
test.beforeEach(async ({ page }) => {
correspondencePage = new CorrespondencePage(page)
await correspondencePage.goto()
})
test('should create correspondence successfully', async ({ page }) => {
await correspondencePage.createCorrespondence({
subject: 'Test Correspondence',
recipientId: 'test-recipient-id'
})
await correspondencePage.verifySuccess()
await page.screenshot({ path: 'artifacts/correspondence-created.png' })
})
test('should validate required fields', async ({ page }) => {
await correspondencePage.createButton.click()
await correspondencePage.submitButton.click()
await expect(page.getByTestId('subject-error')).toBeVisible()
await expect(page.getByTestId('recipient-error')).toBeVisible()
})
})
```
## Playwright Configuration
```typescript
// frontend/playwright.config.ts
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
['html', { outputFolder: 'playwright-report' }],
['junit', { outputFile: 'playwright-results.xml' }],
['json', { outputFile: 'playwright-results.json' }]
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
actionTimeout: 10000,
navigationTimeout: 30000,
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
],
webServer: {
command: 'pnpm dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120000,
},
})
```
## Flaky Test Patterns
### Quarantine
```typescript
test('flaky: complex workflow', async ({ page }) => {
test.fixme(true, 'Flaky - Issue #123')
// test code...
})
test('conditional skip', async ({ page }) => {
test.skip(process.env.CI, 'Flaky in CI - Issue #123')
// test code...
})
```
### Identify Flakiness
```bash
cd frontend
npx playwright test e2e/correspondence/create.spec.ts --repeat-each=10
npx playwright test e2e/correspondence/create.spec.ts --retries=3
```
### Common Causes & Fixes
**Race conditions:**
```typescript
// Bad: assumes element is ready
await page.click('[data-testid="submit-button"]')
// Good: auto-wait locator
await page.locator('[data-testid="submit-button"]').click()
```
**Network timing:**
```typescript
// Bad: arbitrary timeout
await page.waitForTimeout(5000)
// Good: wait for specific condition
await page.waitForResponse(resp =>
resp.url().includes('/api/correspondences') && resp.status() === 201
)
```
**Animation timing:**
```typescript
// Bad: click during animation
await page.click('[data-testid="menu-item"]')
// Good: wait for stability
await page.locator('[data-testid="menu-item"]').waitFor({ state: 'visible' })
await page.waitForLoadState('networkidle')
await page.locator('[data-testid="menu-item"]').click()
```
## Artifact Management
### Screenshots
```typescript
await page.screenshot({ path: 'artifacts/after-login.png' })
await page.screenshot({ path: 'artifacts/full-page.png', fullPage: true })
await page.locator('[data-testid="workflow-banner"]').screenshot({
path: 'artifacts/workflow-banner.png'
})
```
### Traces
```typescript
// In playwright.config.ts
use: {
trace: 'on-first-retry'
}
// View trace
npx playwright show-trace trace.zip
```
### Video
```typescript
// In playwright.config.ts
use: {
video: 'retain-on-failure',
videosPath: 'artifacts/videos/'
}
```
## CI/CD Integration
```yaml
# .github/workflows/e2e.yml
name: E2E Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: pnpm install
- run: cd frontend && npx playwright install --with-deps
- run: cd frontend && npx playwright test
env:
BASE_URL: ${{ vars.STAGING_URL }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: frontend/playwright-report/
retention-days: 30
```
## Test Report Template
```markdown
# E2E Test Report
**Date:** YYYY-MM-DD HH:MM
**Duration:** Xm Ys
**Status:** PASSING / FAILING
## Summary
- Total: X | Passed: Y (Z%) | Failed: A | Flaky: B | Skipped: C
## Failed Tests
### correspondence-create
**File:** `frontend/e2e/correspondence/create.spec.ts:45`
**Error:** Expected element to be visible
**Screenshot:** artifacts/failed.png
**Recommended Fix:** Add waitForLoadState after form submission
## Artifacts
- HTML Report: frontend/playwright-report/index.html
- Screenshots: frontend/artifacts/*.png
- Videos: frontend/artifacts/videos/*.webm
- Traces: frontend/artifacts/*.zip
```
## Critical Flow Testing
```typescript
// frontend/e2e/workflow/adr021.spec.ts
test('workflow: correspondence → rfa → approval', async ({ page }) => {
// Create correspondence
await createCorrespondence(page)
await expect(page.getByTestId('correspondence-created')).toBeVisible()
// Submit for RFA
await page.getByTestId('submit-rfa').click()
await expect(page.getByTestId('rfa-submitted')).toBeVisible()
// Approve RFA
await page.goto('/admin/doc-control/rfa/123')
await page.getByTestId('approve-button').click()
await expect(page.getByTestId('approval-success')).toBeVisible()
// Verify workflow state
await expect(page.getByTestId('workflow-state')).toContainText('APPROVED')
})
```
## LCBP3-Specific Considerations
- **UUID Handling:** Use `publicId` (string UUID) in E2E tests, never `parseInt()` (ADR-019)
- **Authentication:** Mock auth tokens for E2E tests to avoid real auth flows
- **Workflow States:** Test ADR-021 workflow transitions (DRAFT → PENDING → APPROVED)
- **i18n:** Test with Thai language to verify i18n key resolution
- **RBAC:** Test different user roles (admin, user, reviewer) for permission checks
## References
- LCBP3 Testing Strategy: `specs/05-Engineering-Guidelines/05-04-testing-strategy.md`
- ADR-021 Workflow Context: `specs/06-Decision-Records/ADR-021-workflow-context.md`
- Existing E2E test: `frontend/e2e/workflow-adr021.spec.ts`
@@ -6454,7 +6454,7 @@ CREATE TABLE ai_audit_log (
user_id INT NOT NULL,
action VARCHAR(64) NOT NULL, -- 'ai.extract_metadata', 'ai.classify', etc.
file_id INT,
model VARCHAR(64), -- 'gemma-4:7b', 'paddleocr-v3'
model VARCHAR(64), -- 'gemma-4:7b', 'typhoon-np-dms-ocr', 'tesseract-ocr'
confidence DECIMAL(4,3),
input_hash CHAR(64), -- SHA-256 of input for replay detection
output_summary JSON,
@@ -126,7 +126,7 @@ These rules override general NestJS best practices for the NAP-DMS project:
### ADR-009: No TypeORM Migrations
- **ห้ามสร้างไฟล์ migration ของ TypeORM**
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql`
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
- ใช้ n8n workflow สำหรับ data migration ถ้าจำเป็น
### ADR-019: Hybrid Identifier Strategy (CRITICAL — March 2026 Pattern)
@@ -137,7 +137,7 @@ CREATE TABLE ai_audit_log (
user_id INT NOT NULL,
action VARCHAR(64) NOT NULL, -- 'ai.extract_metadata', 'ai.classify', etc.
file_id INT,
model VARCHAR(64), -- 'gemma-4:7b', 'paddleocr-v3'
model VARCHAR(64), -- 'gemma-4:7b', 'typhoon-np-dms-ocr', 'tesseract-ocr'
confidence DECIMAL(4,3),
input_hash CHAR(64), -- SHA-256 of input for replay detection
output_summary JSON,
+198
View File
@@ -0,0 +1,198 @@
---
name: save-memory
description: บันทึก session log และอัปเดต project memory ตามโครงสร้างใหม่
version: 1.9.0
scope: project-management
depends-on: []
user-invocable: true
---
# บันทึก Memory (Save Memory)
Skill นี้ใช้สำหรับบันทึก session log และอัปเดต project memory ตามโครงสร้างใหม่ที่ reorganization แล้ว
## โครงสร้าง Memory ใหม่
```
memory/
├── README.md (index + overview)
├── mcp-tools.md (MCP MariaDB + Memory Tools)
└── project-memory-override.md (OS rules, Current Decisions, Environment, Next Session Focus)
specs/88-logs/
├── rollouts.md (Recent rollouts table)
└── session-YYYY-MM-DD-[topic].md (Session logs)
```
## ขั้นตอนการบันทึก Memory
### 1. สร้าง Session Log (ถ้ามีงาน session ใหม่)
เมื่อทำงาน session ใหม่ให้:
1. **สร้างไฟล์ session log ใหม่** ใน `specs/88-logs/`
- ชื่อไฟล์: `session-YYYY-MM-DD-[topic].md`
- ตัวอย่าง: `session-2026-06-07-memory-reorganization.md`
2. **บันทึกเนื้อหาใน session log**:
```markdown
# Session [N] — YYYY-MM-DD ([Topic])
## Summary
[สรุปสิ่งที่ทำใน session นี้]
## ปัญหาที่พบ (Root Cause)
[อธิบายปัญหาและสาเหตุ]
## การแก้ไข (Fix)
| ไฟล์ | การเปลี่ยนแปลง |
| -------------- | ---------------------- |
| [path/to/file] | [อธิบายการเปลี่ยนแปลง] |
## กฎที่ Lock แล้ว
[บันทึก pattern หรือ decision ที่ตกลง]
## Verification
[วิธีตรวจสอบว่างานสำเร็จ]
```
3. **อัปเดต `specs/88-logs/rollouts.md`**
- เพิ่ม entry ใหม่ในตาราง Recent Rollouts
- รูปแบบ: `| วันที่ | Version | รายการ | สถานะ |`
### 2. อัปเดต Project Memory (ถ้ามี decision ใหม่)
เมื่อมีการตัดสินใจสำคัญใหม่ให้:
1. **เปิดไฟล์ `memory/project-memory-override.md`**
2. **อัปเดตตาราง "Current Decisions (Locked)"**
- เพิ่ม entry ใหม่ถ้ามี decision ใหม่
- รูปแบบ: `| ID | Decision | ADR |`
3. **อัปเดต "Next Session Focus"**
- เพิ่มงานใหม่ถ้ามี
- ทำเครื่องหมาย `[ ]` สำหรับงานที่ยังไม่เสร็จ
- ทำเครื่องหมาย `[X]` สำหรับงานที่เสร็จแล้ว
4. **อัปเดต "Environment & Services"** (ถ้ามีการเปลี่ยนแปลง)
- อัปเดต URL, port, หรือ notes ถ้ามีการเปลี่ยน infrastructure
### 3. อัปเดต MCP Tools (ถ้ามี tools ใหม่)
เมื่อมี MCP tools ใหม่ให้:
1. **เปิดไฟล์ `memory/mcp-tools.md`**
2. **เพิ่ม tool ใหม่ในตาราง "Available Tools"**
- รูปแบบ: `| Tool | Purpose | Example Usage |`
3. **เพิ่ม usage example และ warnings** ถ้าจำเป็น
### 4. อัปเดต Root Documentation (ถ้ามีการเปลี่ยนแปลง)
เมื่อมีการเปลี่ยนแปลงที่ส่งผลต่อเอกสารระดับ root ให้:
1. **ARCHITECTURE.md** — อัปเดตเมื่อ:
- เปลี่ยน architecture หลัก
- เพิ่ม/ลบ component สำคัญ
- เปลี่ยน data flow หรือ integration pattern
2. **CHANGELOG.md** — อัปเดตเมื่อ:
- Deploy version ใหม่
- เพิ่ม feature หรือ breaking change สำคัญ
- รูปแบบ: `## [version] (YYYY-MM-DD)``### feat(scope): description`
3. **CONTEXT.md** — อัปเดตเมื่อ:
- เปลี่ยน domain terminology หลัก
- เพิ่ม concept ใหม่ที่ใช้ทั่ว project
- อัปเดต glossary หรือ business rules
4. **CONTRIBUTING.md** — อัปเดตเมื่อ:
- เปลี่ยน workflow การทำงาน
- เพิ่ม/เปลี่ยน coding standards
- อัปเดต CI/CD process
5. **README.md** — อัปเดตเมื่อ:
- เปลี่ยน project structure
- เพิ่ม/เปลี่ยน installation steps
- อัปเดต feature overview หรือ tech stack
## Template สำหรับ Session Log
```markdown
# Session [N] — YYYY-MM-DD ([Topic])
## Summary
[สรุปสิ่งที่ทำใน session นี้ใน 1-2 ประโยค]
## ปัญหาที่พบ (Root Cause)
[อธิบายปัญหาและสาเหตุหลัก]
## การแก้ไข (Fix)
| ไฟล์ | การเปลี่ยนแปลง |
| -------------- | ---------------------- |
| `path/to/file` | [อธิบายการเปลี่ยนแปลง] |
## กฎที่ Lock แล้ว
[บันทึก pattern หรือ decision ที่ตกลงและไม่ควรเปลี่ยน]
## Verification
- [ ] [check 1]
- [ ] [check 2]
```
## ข้อควรระวัง
- **ห้าม** บันทึก rules ที่ซ้ำกับ specs/ (ADRs, glossary, guidelines)
- **ห้าม** บันทึก commands ที่ซ้ำกับ specs/05-Engineering-Guidelines/
- **ห้าม** บันทึก environment ที่ซ้ำกับ specs/04-Infrastructure-OPS/
- **ใช้** `specs/88-logs/` สำหรับ session history และ rollouts
- **ใช้** `memory/project-memory-override.md` สำหรับ OS rules, decisions, environment ที่ไม่มีใน specs
- **ใช้** `memory/mcp-tools.md` สำหรับ MCP tools documentation
- **อัปเดต Root Documentation** (ARCHITECTURE.md, CHANGELOG.md, CONTEXT.md, CONTRIBUTING.md, README.md) เฉพาะเมื่อมีการเปลี่ยนแปลงที่ส่งผลต่อ project architecture, version, terminology, workflow หรือ structure
## ตัวอย่างการใช้งาน
### กรณีที่ 1: ทำงาน session ใหม่
```
1. สร้างไฟล์ specs/88-logs/session-2026-06-07-bug-fix.md
2. บันทึกปัญหา, การแก้ไข, verification
3. อัปเดต specs/88-logs/rollouts.md
```
### กรณีที่ 2: มี decision ใหม่
```
1. เปิด memory/project-memory-override.md
2. เพิ่ม entry ใหม่ในตาราง Current Decisions
3. อัปเดต Next Session Focus
```
### กรณีที่ 3: เปลี่ยน infrastructure
```
1. เปิด memory/project-memory-override.md
2. อัปเดตตาราง Environment & Services
3. อัปเดต Key Environment Variables ถ้าจำเป็น
```
### กรณีที่ 4: อัปเดต Root Documentation
```
1. ตรวจสอบว่ามีการเปลี่ยนแปลงที่ส่งผลต่อ ARCHITECTURE.md, CHANGELOG.md, CONTEXT.md, CONTRIBUTING.md, หรือ README.md
2. อัปเดตไฟล์ที่เกี่ยวข้องตามรูปแบบที่กำหนด
3. ตรวจสอบว่าการเปลี่ยนแปลงสอดคล้องกับ specs/ และ ADRs
```
+517
View File
@@ -0,0 +1,517 @@
---
name: security-review
description: Comprehensive security review for LCBP3-DMS with OWASP Top 10 checklist, ADR compliance, and automated security testing patterns.
version: 1.9.0
scope: security
depends-on: []
handoffs-to: [speckit-reviewer, speckit-security-audit]
user-invocable: true
---
# Security Review Skill
Comprehensive security review for LCBP3-DMS ensuring all code follows security best practices and identifies potential vulnerabilities.
## LCBP3 Context
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific security requirements:
- **ADR-016**: Security & Authentication (JWT, CASL, RBAC, file upload)
- **ADR-018**: AI Boundary (Ollama on Admin Desktop only, no direct DB/storage access)
- **ADR-019**: UUID Strategy (no parseInt/Number/+ on UUID)
- **ADR-023**: Unified AI Architecture (AI via DMS API only)
- **ADR-007**: Error Handling (layered error classification)
## When to Activate
Invoke this skill:
- Implementing authentication or authorization
- Handling user input or file uploads
- Creating new API endpoints
- Working with secrets or credentials
- Integrating AI features (Ollama/Qdrant)
- Storing or transmitting sensitive data
- Integrating third-party APIs
## Security Checklist
### 1. Secrets Management
#### FAIL: NEVER Do This
```typescript
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
const dbPassword = "password123" // In source code
```
#### PASS: ALWAYS Do This
```typescript
const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL
// Verify secrets exist
if (!apiKey) {
throw new Error('OPENAI_API_KEY not configured')
}
```
#### Verification Steps
- [ ] No hardcoded API keys, tokens, or passwords
- [ ] All secrets in environment variables
- [ ] `.env.local` in .gitignore
- [ ] No secrets in git history
- [ ] Production secrets in QNAP docker-compose environment section (not .env files)
### 2. Input Validation
#### Always Validate User Input
```typescript
import { z } from 'zod'
// Define validation schema
const CreateCorrespondenceSchema = z.object({
subject: z.string().min(1).max(500),
recipientId: z.string().uuid(),
typeCode: z.string().min(1).max(50)
})
// Validate before processing
export async function createCorrespondence(input: unknown) {
try {
const validated = CreateCorrespondenceSchema.parse(input)
return await correspondenceService.create(validated)
} catch (error) {
if (error instanceof z.ZodError) {
throw new BadRequestException(error.errors)
}
throw error
}
}
```
#### File Upload Validation (ADR-016)
```typescript
function validateFileUpload(file: Express.Multer.File) {
// Size check (50MB max per ADR-016)
const maxSize = 50 * 1024 * 1024
if (file.size > maxSize) {
throw new BadRequestException('File too large (max 50MB)')
}
// Type check (whitelist: PDF, DWG, DOCX, XLSX, ZIP)
const allowedTypes = [
'application/pdf',
'application/vnd.dwg',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip'
]
if (!allowedTypes.includes(file.mimetype)) {
throw new BadRequestException('Invalid file type')
}
// Extension check
const allowedExtensions = ['.pdf', '.dwg', '.docx', '.xlsx', '.zip']
const extension = path.extname(file.originalname).toLowerCase()
if (!allowedExtensions.includes(extension)) {
throw new BadRequestException('Invalid file extension')
}
return true
}
```
#### Verification Steps
- [ ] All user inputs validated with Zod (frontend) + class-validator (backend)
- [ ] File uploads restricted (50MB max, whitelist types)
- [ ] No direct use of user input in queries
- [ ] Whitelist validation (not blacklist)
- [ ] Error messages don't leak sensitive info
### 3. SQL Injection Prevention
#### FAIL: NEVER Concatenate SQL
```typescript
// DANGEROUS - SQL Injection vulnerability
const query = `SELECT * FROM correspondences WHERE uuid = '${correspondenceUuid}'`
await this.connection.query(query)
```
#### PASS: ALWAYS Use TypeORM Parameterized Queries
```typescript
// Safe - TypeORM parameterized query
const correspondence = await this.correspondenceRepository.findOne({
where: { publicId: correspondenceUuid }
})
// Or with QueryBuilder
const result = await this.correspondenceRepository
.createQueryBuilder('c')
.where('c.publicId = :uuid', { uuid: correspondenceUuid })
.getOne()
```
#### Verification Steps
- [ ] All database queries use TypeORM parameterized queries
- [ ] No string concatenation in SQL
- [ ] TypeORM query builder used correctly
- [ ] Schema verified before writing queries (ADR-009)
### 4. Authentication & Authorization (ADR-016)
#### JWT Token Handling
```typescript
// FAIL: WRONG: localStorage (vulnerable to XSS)
localStorage.setItem('token', token)
// PASS: CORRECT: httpOnly cookies
response.setHeader('Set-Cookie',
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`
)
```
#### Authorization Checks (CASL)
```typescript
// Controller with CASL guard
@Post()
@UseGuards(JwtAuthGuard, RolesGuard, AbilitiesGuard)
@CheckAbilities({ action: 'create', subject: 'Correspondence' })
async create(@Body() dto: CreateCorrespondenceDto, @Request() req) {
// Service logic
}
```
#### RBAC Matrix (ADR-016)
- [ ] 4-Level RBAC matrix implemented (Admin, Manager, User, Viewer)
- [ ] CASL AbilityFactory configured with correct permissions
- [ ] JwtAuthGuard on all protected routes
- [ ] RolesGuard for role-based access
- [ ] AuditLogInterceptor on all mutation endpoints
#### Verification Steps
- [ ] Tokens stored in httpOnly cookies (not localStorage)
- [ ] Authorization checks before sensitive operations
- [ ] CASL abilities configured correctly
- [ ] Role-based access control implemented
- [ ] Session management secure
### 5. XSS Prevention
#### Sanitize HTML
```typescript
import DOMPurify from 'isomorphic-dompurify'
// ALWAYS sanitize user-provided HTML
function renderUserContent(html: string) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
ALLOWED_ATTR: []
})
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
```
#### Content Security Policy (Next.js)
```typescript
// next.config.js
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' http://localhost:3001 https://192.168.10.8;
`.replace(/\s{2,}/g, ' ').trim()
}
]
```
#### Verification Steps
- [ ] User-provided HTML sanitized
- [ ] CSP headers configured
- [ ] No unvalidated dynamic content rendering
- [ ] React's built-in XSS protection used
### 6. CSRF Protection
#### CSRF Tokens
```typescript
import { csrf } from '@/lib/csrf'
export async function POST(request: Request) {
const token = request.headers.get('X-CSRF-Token')
if (!csrf.verify(token)) {
return NextResponse.json(
{ error: 'Invalid CSRF token' },
{ status: 403 }
)
}
// Process request
}
```
#### SameSite Cookies
```typescript
response.setHeader('Set-Cookie',
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`
)
```
#### Verification Steps
- [ ] CSRF tokens on state-changing operations
- [ ] SameSite=Strict on all cookies
- [ ] Double-submit cookie pattern implemented
### 7. Rate Limiting (ADR-016)
#### API Rate Limiting
```typescript
import { ThrottlerGuard } from '@nestjs/throttler'
// Apply to auth endpoints
@UseGuards(ThrottlerGuard)
@Throttle({ default: { limit: 10, ttl: 60000 } })
async login(@Body() dto: LoginDto) {
// Login logic
}
```
#### Expensive Operations
```typescript
// Aggressive rate limiting for AI endpoints
@Throttle({ default: { limit: 5, ttl: 60000 } })
async extractMetadata(@Body() dto: ExtractMetadataDto) {
// AI extraction logic
}
```
#### Verification Steps
- [ ] Rate limiting on all auth endpoints (ADR-016)
- [ ] Rate limiting on AI endpoints (ADR-018/023)
- [ ] IP-based rate limiting
- [ ] User-based rate limiting (authenticated)
### 8. Sensitive Data Exposure
#### Logging
```typescript
// FAIL: WRONG: Logging sensitive data
this.logger.log('User login:', { email, password })
this.logger.log('Payment:', { cardNumber, cvv })
// PASS: CORRECT: Redact sensitive data
this.logger.log('User login:', { email, userId })
this.logger.log('Payment:', { last4: card.last4, userId })
```
#### Error Messages (ADR-007)
```typescript
// FAIL: WRONG: Exposing internal details
catch (error) {
return { error: error.message, stack: error.stack }
}
// PASS: CORRECT: Generic error messages
catch (error) {
this.logger.error('Internal error:', error)
throw new BadRequestException('An error occurred. Please try again.')
}
```
#### Verification Steps
- [ ] No passwords, tokens, or secrets in logs
- [ ] Error messages generic for users
- [ ] Detailed errors only in server logs
- [ ] No stack traces exposed to users
### 9. AI Boundary Enforcement (ADR-018/023)
#### FAIL: NEVER Do This
```typescript
// Direct AI access - FORBIDDEN
import ollama from 'ollama'
const response = await ollama.chat({ model: 'gemma4', messages })
// Direct Qdrant access - FORBIDDEN
import { QdrantClient } from '@qdrant/js-client-rest'
const client = new QdrantClient({ url: 'http://localhost:6333' })
```
#### PASS: ALWAYS Do This
```typescript
// AI via DMS API only
const response = await fetch('http://localhost:3001/api/ai/extract-metadata', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ documentId })
})
// Qdrant via DMS API only
const response = await fetch('http://localhost:3001/api/ai/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, projectPublicId })
})
```
#### Verification Steps
- [ ] AI processing on Admin Desktop only (Desk-5439)
- [ ] No direct Ollama calls from backend/frontend
- [ ] No direct Qdrant calls from backend/frontend
- [ ] All AI interactions via DMS API endpoints
- [ ] AI audit logging implemented (ADR-020)
- [ ] Human-in-the-loop validation for AI outputs
### 10. UUID Handling (ADR-019)
#### FAIL: NEVER Do This
```typescript
// parseInt on UUID - FORBIDDEN
const projectId = parseInt(projectUuid) // "0195..." → 19 (WRONG!)
// Number on UUID - FORBIDDEN
const projectId = Number(projectUuid)
// + operator on UUID - FORBIDDEN
const projectId = +projectUuid
// id ?? '' fallback - FORBIDDEN
const value = c.publicId ?? c.id ?? ''
```
#### PASS: ALWAYS Do This
```typescript
// Use UUID string directly
const projectId = projectUuid // "019505a1-7c3e-7000-8000-abc123def456"
// Backend: findOneByUuid returns entity with publicId
const project = await this.projectService.findOneByUuid(projectUuid)
const projectId = project.id // Internal INT for DB operations
// Frontend: use publicId only
interface ProjectOption {
publicId?: string; // No uuid fallback
projectName?: string;
}
const value = c.publicId // "019505a1-7c3e-7000-8000-abc123def456"
```
#### Verification Steps
- [ ] No `parseInt()` on UUID values
- [ ] No `Number()` on UUID values
- [ ] No `+` operator on UUID values
- [ ] No `id ?? ''` fallback patterns
- [ ] Use `publicId` (string UUID) in API responses
- [ ] Internal INT `id` marked with `@Exclude()` in entities
### 11. Dependency Security
#### Regular Updates
```bash
# Check for vulnerabilities
pnpm audit
# Fix automatically fixable issues
pnpm audit fix
# Update dependencies
pnpm update
# Check for outdated packages
pnpm outdated
```
#### Lock Files
```bash
# ALWAYS commit lock files
git add pnpm-lock.yaml
# Use in CI/CD for reproducible builds
pnpm install --frozen-lockfile
```
#### Verification Steps
- [ ] Dependencies up to date
- [ ] No known vulnerabilities (pnpm audit clean)
- [ ] Lock files committed
- [ ] Regular security updates
## Security Testing
### Automated Security Tests
```typescript
// Test authentication
test('requires authentication', async () => {
const response = await fetch('/api/correspondences')
expect(response.status).toBe(401)
})
// Test authorization
test('requires admin role', async () => {
const response = await fetch('/api/admin/users', {
headers: { Authorization: `Bearer ${userToken}` }
})
expect(response.status).toBe(403)
})
// Test input validation
test('rejects invalid input', async () => {
const response = await fetch('/api/correspondences', {
method: 'POST',
body: JSON.stringify({ subject: '', recipientId: 'invalid' })
})
expect(response.status).toBe(400)
})
// Test rate limiting
test('enforces rate limits', async () => {
const requests = Array(11).fill(null).map(() =>
fetch('/api/auth/login', { method: 'POST' })
)
const responses = await Promise.all(requests)
const tooManyRequests = responses.filter(r => r.status === 429)
expect(tooManyRequests.length).toBeGreaterThan(0)
})
```
## Pre-Deployment Security Checklist
Before ANY production deployment:
- [ ] **Secrets**: No hardcoded secrets, all in env vars
- [ ] **Input Validation**: All user inputs validated (Zod + class-validator)
- [ ] **SQL Injection**: All queries parameterized (TypeORM)
- [ ] **XSS**: User content sanitized
- [ ] **CSRF**: Protection enabled
- [ ] **Authentication**: Proper token handling (httpOnly cookies)
- [ ] **Authorization**: RBAC + CASL checks in place
- [ ] **Rate Limiting**: Enabled on auth and AI endpoints
- [ ] **HTTPS**: Enforced in production
- [ ] **Security Headers**: CSP, X-Frame-Options configured
- [ ] **Error Handling**: No sensitive data in errors (ADR-007)
- [ ] **Logging**: No sensitive data logged
- [ ] **Dependencies**: Up to date, no vulnerabilities
- [ ] **UUID Handling**: No parseInt/Number/+ on UUID (ADR-019)
- [ ] **AI Boundary**: AI via DMS API only (ADR-018/023)
- [ ] **File Uploads**: Validated (50MB max, whitelist types)
- [ ] **AI Audit**: All AI interactions logged (ADR-020)
## Resources
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [NestJS Security](https://docs.nestjs.com/security)
- [Next.js Security](https://nextjs.org/docs/security)
- [ADR-016 Security Authentication](../../specs/06-Decision-Records/ADR-016-security-authentication.md)
- [ADR-018 AI Boundary](../../specs/06-Decision-Records/ADR-018-ai-boundary.md)
- [ADR-019 UUID Strategy](../../specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md)
- [ADR-023 AI Architecture](../../specs/06-Decision-Records/ADR-023-unified-ai-architecture.md)
---
**Remember**: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution.
+31 -27
View File
@@ -1,8 +1,8 @@
# 🧠 NAP-DMS Agent Skills (v1.8.9)
# 🧠 NAP-DMS Agent Skills (v1.9.0)
ไฟล์นี้กำหนดทักษะและความสามารถเฉพาะทางของ Document Intelligence Engine สำหรับโครงการ LCBP3 v1.8.9 เพื่อรักษามาตรฐานสูงสุดด้าน Security และ Data Integrity
ไฟล์นี้กำหนดทักษะและความสามารถเฉพาะทางของ Document Intelligence Engine สำหรับโครงการ LCBP3 v1.9.0 เพื่อรักษามาตรฐานสูงสุดด้าน Security และ Data Integrity
**Status**: Production Ready | **Last Updated**: 2026-04-22 | **Total Skills**: 20
**Status**: Production Ready | **Last Updated**: 2026-06-07 | **Total Skills**: 24
> 📌 Shared context for all speckit-\* skills: see [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md).
@@ -57,28 +57,32 @@
## 🔄 Skill Dependency Matrix
| Skill | Dependencies | Handoffs To | Notes |
| -------------------------- | -------------------- | -------------------------------- | ----------------------------- |
| **speckit-constitution** | None | speckit-specify | Project governance foundation |
| **speckit-specify** | speckit-constitution | speckit-clarify | Feature specification |
| **speckit-clarify** | speckit-specify | speckit-plan | Resolve ambiguities |
| **speckit-plan** | speckit-clarify | speckit-tasks, speckit-checklist | Technical design |
| **speckit-tasks** | speckit-plan | speckit-implement | Task breakdown |
| **speckit-implement** | speckit-tasks | speckit-checker | Code implementation |
| **speckit-checker** | speckit-implement | speckit-tester | Static analysis |
| **speckit-tester** | speckit-checker | speckit-reviewer | Test execution |
| **speckit-reviewer** | speckit-tester | speckit-validate | Code review |
| **speckit-validate** | speckit-reviewer | None | Requirements validation |
| **speckit-analyze** | speckit-tasks | None | Cross-artifact consistency |
| **speckit-migrate** | None | speckit-plan | Legacy code import |
| **speckit-quizme** | speckit-specify | speckit-plan | Logic validation |
| **speckit-diff** | None | speckit-plan | Version comparison |
| **speckit-status** | None | None | Progress tracking |
| **speckit-taskstoissues** | speckit-tasks | None | Issue sync |
| **speckit-checklist** | speckit-plan | None | Requirements validation |
| **nestjs-best-practices** | None | speckit-implement | Backend patterns |
| **next-best-practices** | None | speckit-implement | Frontend patterns |
| **speckit-security-audit** | None | speckit-reviewer | Security validation |
| Skill | Dependencies | Handoffs To | Notes |
| -------------------------- | -------------------- | ---------------------------------------- | ----------------------------- |
| **speckit-constitution** | None | speckit-specify | Project governance foundation |
| **speckit-specify** | speckit-constitution | speckit-clarify | Feature specification |
| **speckit-clarify** | speckit-specify | speckit-plan | Resolve ambiguities |
| **speckit-plan** | speckit-clarify | speckit-tasks, speckit-checklist | Technical design |
| **speckit-tasks** | speckit-plan | speckit-implement | Task breakdown |
| **speckit-implement** | speckit-tasks | speckit-checker | Code implementation |
| **speckit-checker** | speckit-implement | speckit-tester | Static analysis |
| **speckit-tester** | speckit-checker | speckit-reviewer | Test execution |
| **speckit-reviewer** | speckit-tester | speckit-validate | Code review |
| **speckit-validate** | speckit-reviewer | None | Requirements validation |
| **speckit-analyze** | speckit-tasks | None | Cross-artifact consistency |
| **speckit-migrate** | None | speckit-plan | Legacy code import |
| **speckit-quizme** | speckit-specify | speckit-plan | Logic validation |
| **speckit-diff** | None | speckit-plan | Version comparison |
| **speckit-status** | None | None | Progress tracking |
| **speckit-taskstoissues** | speckit-tasks | None | Issue sync |
| **speckit-checklist** | speckit-plan | None | Requirements validation |
| **save-memory** | None | None | Session log & memory update |
| **nestjs-best-practices** | None | speckit-implement | Backend patterns |
| **next-best-practices** | None | speckit-implement | Frontend patterns |
| **speckit-security-audit** | None | speckit-reviewer | Security validation |
| **e2e-testing** | None | speckit-tester | Playwright E2E patterns |
| **verification-loop** | None | speckit-checker, speckit-tester | Comprehensive verification |
| **security-review** | None | speckit-reviewer, speckit-security-audit | OWASP Top 10 + ADR compliance |
---
@@ -96,8 +100,8 @@
### Health Metrics
- **Total Skills**: 20 implemented
- **Version Alignment**: v1.8.9 across all skills
- **Total Skills**: 24 implemented
- **Version Alignment**: v1.9.0 across all skills
- **Template Coverage**: 100% for skills requiring templates
- **Documentation**: Complete front matter + shared `_LCBP3-CONTEXT.md` appendix
+224
View File
@@ -0,0 +1,224 @@
---
name: verification-loop
description: A comprehensive verification system for LCBP3-DMS development sessions with build, type check, lint, test, security scan, and diff review phases.
version: 1.9.0
scope: verification
depends-on: []
handoffs-to: [speckit-checker, speckit-tester]
user-invocable: true
---
# Verification Loop Skill
A comprehensive verification system for LCBP3-DMS development sessions.
## LCBP3 Context
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific verification requirements:
- Backend: NestJS with TypeScript strict mode
- Frontend: Next.js with TypeScript strict mode
- Package manager: pnpm
- Coverage goals: Backend 70%+, Business Logic 80%+
- Security: ADR-016, ADR-018, ADR-019, ADR-023 compliance
## When to Use
Invoke this skill:
- After completing a feature or significant code change
- Before creating a PR
- When you want to ensure quality gates pass
- After refactoring
- Before deploying to staging/production
## Verification Phases
### Phase 1: Build Verification
```bash
# Backend build
cd backend
pnpm build 2>&1 | tail -20
# Frontend build
cd frontend
pnpm build 2>&1 | tail -20
```
If build fails, STOP and fix before continuing.
### Phase 2: Type Check
```bash
# Backend TypeScript
cd backend
pnpm typecheck 2>&1 | head -30
# Frontend TypeScript
cd frontend
pnpm typecheck 2>&1 | head -30
```
Report all type errors. Fix critical ones before continuing.
### Phase 3: Lint Check
```bash
# Backend lint
cd backend
pnpm lint 2>&1 | head -30
# Frontend lint
cd frontend
pnpm lint 2>&1 | head -30
```
### Phase 4: Test Suite
```bash
# Backend tests with coverage
cd backend
pnpm test -- --coverage 2>&1 | tail -50
# Frontend unit tests
cd frontend
pnpm test 2>&1 | tail -50
# Frontend E2E tests (if applicable)
cd frontend
npx playwright test 2>&1 | tail -50
```
Report:
- Total tests: X
- Passed: X
- Failed: X
- Coverage: X%
### Phase 5: Security Scan
```bash
# Check for hardcoded secrets
grep -rn "sk-" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
grep -rn "api_key" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
grep -rn "password" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
# Check for console.log (forbidden in committed code)
grep -rn "console.log" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
# Check for any types (forbidden)
grep -rn ": any" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
# Check for parseInt on UUID (ADR-019 violation)
grep -rn "parseInt(" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
```
### Phase 6: ADR Compliance Check
```bash
# Check for id ?? '' fallback (ADR-019 violation)
grep -rn "id ?? ''" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
# Check for Number() on UUID (ADR-019 violation)
grep -rn "Number(" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
# Check for + operator on UUID (ADR-019 violation)
grep -rn "+ publicId\|+ id" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
```
### Phase 7: Diff Review
```bash
# Show what changed
git diff --stat
git diff HEAD~1 --name-only
# Show detailed changes
git diff
```
Review each changed file for:
- Unintended changes
- Missing error handling (ADR-007)
- Potential edge cases
- UUID handling (ADR-019)
- Security vulnerabilities (ADR-016)
- AI boundary violations (ADR-018/023)
## Output Format
After running all phases, produce a verification report:
```
VERIFICATION REPORT
==================
Build: [PASS/FAIL]
Types: [PASS/FAIL] (X errors)
Lint: [PASS/FAIL] (X warnings)
Tests: [PASS/FAIL] (X/Y passed, Z% coverage)
Security: [PASS/FAIL] (X issues)
ADR: [PASS/FAIL] (X violations)
Diff: [X files changed]
Overall: [READY/NOT READY] for PR
Issues to Fix:
1. ...
2. ...
```
## Continuous Mode
For long sessions, run verification every 15 minutes or after major changes:
```markdown
Set a mental checkpoint:
- After completing each function
- After finishing a component
- Before moving to next task
Run: /verify
```
## Integration with LCBP3 Skills
This skill complements:
- **speckit-checker**: Runs static analysis (lint, typecheck)
- **speckit-tester**: Runs tests with coverage verification
- **speckit-security-audit**: Performs security review against OWASP Top 10
This skill provides a unified verification loop that combines all checks into a single report.
## LCBP3-Specific Checks
### Tier 1 — CRITICAL (CI BLOCKER)
- [ ] **Security**: Auth, RBAC, Validation implemented
- [ ] **UUID Strategy (ADR-019)**: No `parseInt` / `Number` / `+` on UUID
- [ ] **Database correctness**: Schema verified before writing queries
- [ ] **File upload security**: ClamAV + whitelist implemented
- [ ] **AI validation boundary (ADR-018/023)**: AI via DMS API only
- [ ] **Error handling (ADR-007)**: Layered error classification
- [ ] **Forbidden patterns**: Zero `any`, zero `console.log`, UUID misuse
### Tier 2 — IMPORTANT (CODE REVIEW)
- [ ] **Architecture patterns**: Thin controller, business logic in service
- [ ] **Test coverage**: 80%+ business logic, 70%+ backend overall
- [ ] **Cache invalidation**: Implemented when data modified
- [ ] **Naming conventions**: Follow domain terminology
### Tier 3 — GUIDELINES
- [ ] **Code style**: Prettier formatting
- [ ] **Comment completeness**: Thai comments, JSDoc on public methods
- [ ] **Minor optimizations**: Performance improvements where applicable
## References
- LCBP3 AGENTS.md: `AGENTS.md` (repo root)
- ADR-007 Error Handling: `specs/06-Decision-Records/ADR-007-error-handling-strategy.md`
- ADR-016 Security: `specs/06-Decision-Records/ADR-016-security-authentication.md`
- ADR-019 UUID: `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md`
- ADR-018 AI Boundary: `specs/06-Decision-Records/ADR-018-ai-boundary.md`
- ADR-023 AI Architecture: `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md`
+221 -192
View File
@@ -15,220 +15,249 @@ const WORKFLOWS_DIR = path.join(BASE_DIR, '.windsurf', 'workflows');
// Test utilities
class SkillTestSuite {
constructor() {
this.results = {
passed: 0,
failed: 0,
errors: []
};
constructor() {
this.results = {
passed: 0,
failed: 0,
errors: [],
};
}
log(message, type = 'info') {
const colors = {
info: '\x1b[36m', // Cyan
pass: '\x1b[32m', // Green
fail: '\x1b[31m', // Red
warn: '\x1b[33m', // Yellow
reset: '\x1b[0m',
};
const color = colors[type] || colors.info;
console.log(`${color}${message}${colors.reset}`);
}
assert(condition, message) {
if (condition) {
this.log(` PASS: ${message}`, 'pass');
this.results.passed++;
return true;
} else {
this.log(` FAIL: ${message}`, 'fail');
this.results.failed++;
this.results.errors.push(message);
return false;
}
}
testDirectoryExists(dirPath, description) {
const exists = fs.existsSync(dirPath);
this.assert(exists, `${description} exists at ${dirPath}`);
return exists;
}
testFileExists(filePath, description) {
const exists = fs.existsSync(filePath);
this.assert(exists, `${description} exists at ${filePath}`);
return exists;
}
testFileContent(filePath, pattern, description) {
if (!fs.existsSync(filePath)) {
this.assert(false, `${description} - file not found: ${filePath}`);
return false;
}
log(message, type = 'info') {
const colors = {
info: '\x1b[36m', // Cyan
pass: '\x1b[32m', // Green
fail: '\x1b[31m', // Red
warn: '\x1b[33m', // Yellow
reset: '\x1b[0m'
};
const color = colors[type] || colors.info;
console.log(`${color}${message}${colors.reset}`);
try {
const content = fs.readFileSync(filePath, 'utf8');
const matches = content.match(pattern);
this.assert(matches !== null, `${description} - pattern found in ${filePath}`);
return matches !== null;
} catch (error) {
this.assert(false, `${description} - error reading file: ${error.message}`);
return false;
}
}
assert(condition, message) {
if (condition) {
this.log(` PASS: ${message}`, 'pass');
this.results.passed++;
return true;
} else {
this.log(` FAIL: ${message}`, 'fail');
this.results.failed++;
this.results.errors.push(message);
return false;
}
}
testDirectoryExists(dirPath, description) {
const exists = fs.existsSync(dirPath);
this.assert(exists, `${description} exists at ${dirPath}`);
return exists;
}
testFileExists(filePath, description) {
const exists = fs.existsSync(filePath);
this.assert(exists, `${description} exists at ${filePath}`);
return exists;
}
testFileContent(filePath, pattern, description) {
if (!fs.existsSync(filePath)) {
this.assert(false, `${description} - file not found: ${filePath}`);
return false;
}
try {
const content = fs.readFileSync(filePath, 'utf8');
const matches = content.match(pattern);
this.assert(matches !== null, `${description} - pattern found in ${filePath}`);
return matches !== null;
} catch (error) {
this.assert(false, `${description} - error reading file: ${error.message}`);
return false;
}
}
runScript(scriptPath, description) {
try {
const output = execSync(scriptPath, { encoding: 'utf8', cwd: BASE_DIR });
this.log(` SCRIPT: ${description} executed successfully`, 'pass');
return { success: true, output };
} catch (error) {
this.log(` SCRIPT: ${description} failed - ${error.message}`, 'fail');
this.results.failed++;
this.results.errors.push(`${description}: ${error.message}`);
return { success: false, error: error.message };
}
runScript(scriptPath, description) {
try {
const output = execSync(scriptPath, { encoding: 'utf8', cwd: BASE_DIR });
this.log(` SCRIPT: ${description} executed successfully`, 'pass');
return { success: true, output };
} catch (error) {
this.log(` SCRIPT: ${description} failed - ${error.message}`, 'fail');
this.results.failed++;
this.results.errors.push(`${description}: ${error.message}`);
return { success: false, error: error.message };
}
}
}
// Test suite implementation
const testSuite = new SkillTestSuite();
function runAllTests() {
testSuite.log('=== .agents Integration Test Suite ===', 'info');
testSuite.log(`Base directory: ${BASE_DIR}`, 'info');
testSuite.log(`Started: ${new Date().toISOString()}`, 'info');
testSuite.log('');
testSuite.log('=== .agents Integration Test Suite ===', 'info');
testSuite.log(`Base directory: ${BASE_DIR}`, 'info');
testSuite.log(`Started: ${new Date().toISOString()}`, 'info');
testSuite.log('');
// Test 1: Directory Structure
testSuite.log('Test 1: Directory Structure', 'info');
testSuite.testDirectoryExists(AGENTS_DIR, '.agents directory');
testSuite.testDirectoryExists(SKILLS_DIR, 'skills directory');
testSuite.testDirectoryExists(WORKFLOWS_DIR, 'workflows directory');
testSuite.testDirectoryExists(path.join(AGENTS_DIR, 'scripts'), 'scripts directory');
testSuite.testDirectoryExists(path.join(AGENTS_DIR, 'rules'), 'rules directory');
testSuite.log('');
// Test 1: Directory Structure
testSuite.log('Test 1: Directory Structure', 'info');
testSuite.testDirectoryExists(AGENTS_DIR, '.agents directory');
testSuite.testDirectoryExists(SKILLS_DIR, 'skills directory');
testSuite.testDirectoryExists(WORKFLOWS_DIR, 'workflows directory');
testSuite.testDirectoryExists(path.join(AGENTS_DIR, 'scripts'), 'scripts directory');
testSuite.testDirectoryExists(path.join(AGENTS_DIR, 'rules'), 'rules directory');
testSuite.log('');
// Test 2: Core Files
testSuite.log('Test 2: Core Files', 'info');
testSuite.testFileExists(path.join(AGENTS_DIR, 'README.md'), 'README.md');
testSuite.testFileExists(path.join(SKILLS_DIR, 'VERSION'), 'skills VERSION file');
testSuite.testFileExists(path.join(SKILLS_DIR, 'skills.md'), 'skills.md documentation');
testSuite.log('');
// Test 2: Core Files
testSuite.log('Test 2: Core Files', 'info');
testSuite.testFileExists(path.join(AGENTS_DIR, 'README.md'), 'README.md');
testSuite.testFileExists(path.join(SKILLS_DIR, 'VERSION'), 'skills VERSION file');
testSuite.testFileExists(path.join(SKILLS_DIR, 'skills.md'), 'skills.md documentation');
testSuite.log('');
// Test 3: Script Files
testSuite.log('Test 3: Validation Scripts', 'info');
testSuite.testFileExists(path.join(AGENTS_DIR, 'scripts', 'bash', 'validate-versions.sh'), 'bash validate-versions.sh');
testSuite.testFileExists(path.join(AGENTS_DIR, 'scripts', 'bash', 'audit-skills.sh'), 'bash audit-skills.sh');
testSuite.testFileExists(path.join(AGENTS_DIR, 'scripts', 'bash', 'sync-workflows.sh'), 'bash sync-workflows.sh');
testSuite.testFileExists(path.join(AGENTS_DIR, 'scripts', 'powershell', 'validate-versions.ps1'), 'powershell validate-versions.ps1');
testSuite.testFileExists(path.join(AGENTS_DIR, 'scripts', 'powershell', 'audit-skills.ps1'), 'powershell audit-skills.ps1');
testSuite.log('');
// Test 3: Script Files
testSuite.log('Test 3: Validation Scripts', 'info');
testSuite.testFileExists(
path.join(AGENTS_DIR, 'scripts', 'bash', 'validate-versions.sh'),
'bash validate-versions.sh'
);
testSuite.testFileExists(path.join(AGENTS_DIR, 'scripts', 'bash', 'audit-skills.sh'), 'bash audit-skills.sh');
testSuite.testFileExists(path.join(AGENTS_DIR, 'scripts', 'bash', 'sync-workflows.sh'), 'bash sync-workflows.sh');
testSuite.testFileExists(
path.join(AGENTS_DIR, 'scripts', 'powershell', 'validate-versions.ps1'),
'powershell validate-versions.ps1'
);
testSuite.testFileExists(
path.join(AGENTS_DIR, 'scripts', 'powershell', 'audit-skills.ps1'),
'powershell audit-skills.ps1'
);
testSuite.log('');
// Test 4: Version Consistency
testSuite.log('Test 4: Version Consistency', 'info');
testSuite.testFileContent(path.join(AGENTS_DIR, 'README.md'), /v1\.8\.6/, 'README.md version');
testSuite.testFileContent(path.join(SKILLS_DIR, 'VERSION'), /version: 1\.8\.6/, 'skills VERSION file');
testSuite.testFileContent(path.join(SKILLS_DIR, 'skills.md'), /v1\.8\.6/, 'skills.md version');
testSuite.testFileContent(path.join(AGENTS_DIR, 'rules', '00-project-context.md'), /v1\.8\.6/, 'project context version');
testSuite.log('');
// Test 4: Version Consistency
testSuite.log('Test 4: Version Consistency', 'info');
testSuite.testFileContent(path.join(AGENTS_DIR, 'README.md'), /v1\.8\.6/, 'README.md version');
testSuite.testFileContent(path.join(SKILLS_DIR, 'VERSION'), /version: 1\.8\.6/, 'skills VERSION file');
testSuite.testFileContent(path.join(SKILLS_DIR, 'skills.md'), /v1\.8\.6/, 'skills.md version');
testSuite.testFileContent(
path.join(AGENTS_DIR, 'rules', '00-project-context.md'),
/v1\.8\.6/,
'project context version'
);
testSuite.log('');
// Test 5: Skills Structure
testSuite.log('Test 5: Skills Structure', 'info');
const skillDirs = fs.readdirSync(SKILLS_DIR).filter(item => {
const itemPath = path.join(SKILLS_DIR, item);
return fs.statSync(itemPath).isDirectory() && item.startsWith('speckit-') || item === 'nestjs-best-practices' || item === 'next-best-practices';
});
// Test 5: Skills Structure
testSuite.log('Test 5: Skills Structure', 'info');
const skillDirs = fs.readdirSync(SKILLS_DIR).filter((item) => {
const itemPath = path.join(SKILLS_DIR, item);
return (
(fs.statSync(itemPath).isDirectory() && item.startsWith('speckit-')) ||
item === 'nestjs-best-practices' ||
item === 'next-best-practices'
);
});
testSuite.assert(skillDirs.length >= 20, `Found at least 20 skill directories (found ${skillDirs.length})`);
// Test a few key skills
const keySkills = ['speckit-plan', 'speckit-implement', 'speckit-specify', 'speckit-validate'];
keySkills.forEach(skill => {
const skillPath = path.join(SKILLS_DIR, skill);
const skillMdPath = path.join(skillPath, 'SKILL.md');
testSuite.testDirectoryExists(skillPath, `${skill} directory`);
testSuite.testFileExists(skillMdPath, `${skill} SKILL.md`);
if (fs.existsSync(skillMdPath)) {
testSuite.testFileContent(skillMdPath, /^name:/, `${skill} has name field`);
testSuite.testFileContent(skillMdPath, /^description:/, `${skill} has description field`);
testSuite.testFileContent(skillMdPath, /^version:/, `${skill} has version field`);
testSuite.testFileContent(skillMdPath, /^## Role$/, `${skill} has Role section`);
testSuite.testFileContent(skillMdPath, /^## Task$/, `${skill} has Task section`);
}
});
testSuite.log('');
testSuite.assert(skillDirs.length >= 20, `Found at least 20 skill directories (found ${skillDirs.length})`);
// Test 6: Workflows Structure
testSuite.log('Test 6: Workflows Structure', 'info');
const workflowFiles = fs.readdirSync(WORKFLOWS_DIR).filter(item => item.endsWith('.md'));
testSuite.assert(workflowFiles.length >= 20, `Found at least 20 workflow files (found ${workflowFiles.length})`);
// Test key workflows
const keyWorkflows = ['00-speckit.all.md', '02-speckit.specify.md', '04-speckit.plan.md', '07-speckit.implement.md'];
keyWorkflows.forEach(workflow => {
const workflowPath = path.join(WORKFLOWS_DIR, workflow);
testSuite.testFileExists(workflowPath, `${workflow} file`);
});
testSuite.log('');
// Test a few key skills
const keySkills = ['speckit-plan', 'speckit-implement', 'speckit-specify', 'speckit-validate'];
keySkills.forEach((skill) => {
const skillPath = path.join(SKILLS_DIR, skill);
const skillMdPath = path.join(skillPath, 'SKILL.md');
testSuite.testDirectoryExists(skillPath, `${skill} directory`);
testSuite.testFileExists(skillMdPath, `${skill} SKILL.md`);
// Test 7: Rules Structure
testSuite.log('Test 7: Rules Structure', 'info');
const rulesDir = path.join(AGENTS_DIR, 'rules');
const ruleFiles = fs.readdirSync(rulesDir).filter(item => item.endsWith('.md'));
testSuite.assert(ruleFiles.length >= 10, `Found at least 10 rule files (found ${ruleFiles.length})`);
// Test key rules
const keyRules = ['00-project-context.md', '01-adr-019-uuid.md', '02-security.md'];
keyRules.forEach(rule => {
const rulePath = path.join(rulesDir, rule);
testSuite.testFileExists(rulePath, `${rule} file`);
});
testSuite.log('');
if (fs.existsSync(skillMdPath)) {
testSuite.testFileContent(skillMdPath, /^name:/, `${skill} has name field`);
testSuite.testFileContent(skillMdPath, /^description:/, `${skill} has description field`);
testSuite.testFileContent(skillMdPath, /^version:/, `${skill} has version field`);
testSuite.testFileContent(skillMdPath, /^## Role$/, `${skill} has Role section`);
testSuite.testFileContent(skillMdPath, /^## Task$/, `${skill} has Task section`);
}
});
testSuite.log('');
// Test 8: Script Execution (if on Unix-like system)
if (process.platform !== 'win32') {
testSuite.log('Test 8: Script Execution', 'info');
// Test version validation script
const versionScript = path.join(AGENTS_DIR, 'scripts', 'bash', 'validate-versions.sh');
if (fs.existsSync(versionScript)) {
try {
// Make executable
fs.chmodSync(versionScript, '755');
testSuite.runScript(versionScript, 'Version validation script');
} catch (error) {
testSuite.log(` SKIP: Cannot execute version script - ${error.message}`, 'warn');
}
}
testSuite.log('');
// Test 6: Workflows Structure
testSuite.log('Test 6: Workflows Structure', 'info');
const workflowFiles = fs.readdirSync(WORKFLOWS_DIR).filter((item) => item.endsWith('.md'));
testSuite.assert(workflowFiles.length >= 20, `Found at least 20 workflow files (found ${workflowFiles.length})`);
// Test key workflows
const keyWorkflows = ['00-speckit.all.md', '02-speckit.specify.md', '04-speckit.plan.md', '07-speckit.implement.md'];
keyWorkflows.forEach((workflow) => {
const workflowPath = path.join(WORKFLOWS_DIR, workflow);
testSuite.testFileExists(workflowPath, `${workflow} file`);
});
testSuite.log('');
// Test 7: Rules Structure
testSuite.log('Test 7: Rules Structure', 'info');
const rulesDir = path.join(AGENTS_DIR, 'rules');
const ruleFiles = fs.readdirSync(rulesDir).filter((item) => item.endsWith('.md'));
testSuite.assert(ruleFiles.length >= 10, `Found at least 10 rule files (found ${ruleFiles.length})`);
// Test key rules
const keyRules = ['00-project-context.md', '01-adr-019-uuid.md', '02-security.md'];
keyRules.forEach((rule) => {
const rulePath = path.join(rulesDir, rule);
testSuite.testFileExists(rulePath, `${rule} file`);
});
testSuite.log('');
// Test 8: Script Execution (if on Unix-like system)
if (process.platform !== 'win32') {
testSuite.log('Test 8: Script Execution', 'info');
// Test version validation script
const versionScript = path.join(AGENTS_DIR, 'scripts', 'bash', 'validate-versions.sh');
if (fs.existsSync(versionScript)) {
try {
// Make executable
fs.chmodSync(versionScript, '755');
testSuite.runScript(versionScript, 'Version validation script');
} catch (error) {
testSuite.log(` SKIP: Cannot execute version script - ${error.message}`, 'warn');
}
}
// Test 9: Documentation Quality
testSuite.log('Test 9: Documentation Quality', 'info');
testSuite.testFileContent(path.join(AGENTS_DIR, 'README.md'), /## Troubleshooting/, 'README.md has troubleshooting section');
testSuite.testFileContent(path.join(SKILLS_DIR, 'skills.md'), /## Skill Dependency Matrix/, 'skills.md has dependency matrix');
testSuite.testFileContent(path.join(AGENTS_DIR, 'README.md'), /## Architecture/, 'README.md has architecture section');
testSuite.log('');
}
// Results Summary
testSuite.log('=== Test Results Summary ===', 'info');
testSuite.log(`Passed: ${testSuite.results.passed}`, 'pass');
testSuite.log(`Failed: ${testSuite.results.failed}`, testSuite.results.failed > 0 ? 'fail' : 'pass');
if (testSuite.results.errors.length > 0) {
testSuite.log('Errors:', 'fail');
testSuite.results.errors.forEach(error => {
testSuite.log(` - ${error}`, 'fail');
});
}
testSuite.log(`Completed: ${new Date().toISOString()}`, 'info');
return testSuite.results.failed === 0;
// Test 9: Documentation Quality
testSuite.log('Test 9: Documentation Quality', 'info');
testSuite.testFileContent(
path.join(AGENTS_DIR, 'README.md'),
/## Troubleshooting/,
'README.md has troubleshooting section'
);
testSuite.testFileContent(
path.join(SKILLS_DIR, 'skills.md'),
/## Skill Dependency Matrix/,
'skills.md has dependency matrix'
);
testSuite.testFileContent(
path.join(AGENTS_DIR, 'README.md'),
/## Architecture/,
'README.md has architecture section'
);
testSuite.log('');
// Results Summary
testSuite.log('=== Test Results Summary ===', 'info');
testSuite.log(`Passed: ${testSuite.results.passed}`, 'pass');
testSuite.log(`Failed: ${testSuite.results.failed}`, testSuite.results.failed > 0 ? 'fail' : 'pass');
if (testSuite.results.errors.length > 0) {
testSuite.log('Errors:', 'fail');
testSuite.results.errors.forEach((error) => {
testSuite.log(` - ${error}`, 'fail');
});
}
testSuite.log(`Completed: ${new Date().toISOString()}`, 'info');
return testSuite.results.failed === 0;
}
// Export for use in other modules
@@ -236,6 +265,6 @@ module.exports = { SkillTestSuite, runAllTests };
// Run tests if called directly
if (require.main === module) {
const success = runAllTests();
process.exit(success ? 0 : 1);
const success = runAllTests();
process.exit(success ? 0 : 1);
}
+192 -190
View File
@@ -13,216 +13,218 @@ const AGENTS_DIR = path.join(BASE_DIR, '.agents');
// Test utilities
class WorkflowTestSuite {
constructor() {
this.results = {
passed: 0,
failed: 0,
errors: []
};
constructor() {
this.results = {
passed: 0,
failed: 0,
errors: [],
};
}
log(message, type = 'info') {
const colors = {
info: '\x1b[36m', // Cyan
pass: '\x1b[32m', // Green
fail: '\x1b[31m', // Red
warn: '\x1b[33m', // Yellow
reset: '\x1b[0m',
};
const color = colors[type] || colors.info;
console.log(`${color}${message}${colors.reset}`);
}
assert(condition, message) {
if (condition) {
this.log(` PASS: ${message}`, 'pass');
this.results.passed++;
return true;
} else {
this.log(` FAIL: ${message}`, 'fail');
this.results.failed++;
this.results.errors.push(message);
return false;
}
}
testWorkflowFile(filePath, expectedName) {
if (!fs.existsSync(filePath)) {
this.assert(false, `Workflow file exists: ${expectedName}`);
return false;
}
log(message, type = 'info') {
const colors = {
info: '\x1b[36m', // Cyan
pass: '\x1b[32m', // Green
fail: '\x1b[31m', // Red
warn: '\x1b[33m', // Yellow
reset: '\x1b[0m'
};
const color = colors[type] || colors.info;
console.log(`${color}${message}${colors.reset}`);
try {
const content = fs.readFileSync(filePath, 'utf8');
// Basic structure checks
this.assert(content.length > 0, `${expectedName} has content`);
this.assert(content.includes('#'), `${expectedName} has markdown headers`);
// Check for workflow-specific patterns
if (expectedName.includes('speckit-')) {
this.assert(content.includes('speckit-'), `${expectedName} contains speckit reference`);
}
// Check for proper markdown formatting
const lines = content.split('\n');
const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
this.assert(nonEmptyLines.length >= 5, `${expectedName} has sufficient content`);
return true;
} catch (error) {
this.assert(false, `${expectedName} - error reading file: ${error.message}`);
return false;
}
}
validateWorkflowDependency(workflowName, workflowContent) {
// Check if workflow references existing skills
const skillReferences = workflowContent.match(/@speckit-\w+/g) || [];
const skillsDir = path.join(AGENTS_DIR, 'skills');
for (const skillRef of skillReferences) {
const skillName = skillRef.replace('@', '');
const skillPath = path.join(skillsDir, skillName);
if (!fs.existsSync(skillPath)) {
this.assert(false, `${workflowName} references non-existent skill: ${skillRef}`);
return false;
}
}
assert(condition, message) {
if (condition) {
this.log(` PASS: ${message}`, 'pass');
this.results.passed++;
return true;
} else {
this.log(` FAIL: ${message}`, 'fail');
this.results.failed++;
this.results.errors.push(message);
return false;
}
}
testWorkflowFile(filePath, expectedName) {
if (!fs.existsSync(filePath)) {
this.assert(false, `Workflow file exists: ${expectedName}`);
return false;
}
try {
const content = fs.readFileSync(filePath, 'utf8');
// Basic structure checks
this.assert(content.length > 0, `${expectedName} has content`);
this.assert(content.includes('#'), `${expectedName} has markdown headers`);
// Check for workflow-specific patterns
if (expectedName.includes('speckit-')) {
this.assert(content.includes('speckit-'), `${expectedName} contains speckit reference`);
}
// Check for proper markdown formatting
const lines = content.split('\n');
const nonEmptyLines = lines.filter(line => line.trim().length > 0);
this.assert(nonEmptyLines.length >= 5, `${expectedName} has sufficient content`);
return true;
} catch (error) {
this.assert(false, `${expectedName} - error reading file: ${error.message}`);
return false;
}
}
validateWorkflowDependency(workflowName, workflowContent) {
// Check if workflow references existing skills
const skillReferences = workflowContent.match(/@speckit-\w+/g) || [];
const skillsDir = path.join(AGENTS_DIR, 'skills');
for (const skillRef of skillReferences) {
const skillName = skillRef.replace('@', '');
const skillPath = path.join(skillsDir, skillName);
if (!fs.existsSync(skillPath)) {
this.assert(false, `${workflowName} references non-existent skill: ${skillRef}`);
return false;
}
}
return true;
}
return true;
}
}
// Expected workflows mapping
const expectedWorkflows = {
'00-speckit.all.md': 'Full pipeline workflow',
'01-speckit.constitution.md': 'Constitution workflow',
'02-speckit.specify.md': 'Specification workflow',
'03-speckit.clarify.md': 'Clarification workflow',
'04-speckit.plan.md': 'Planning workflow',
'05-speckit.tasks.md': 'Task breakdown workflow',
'06-speckit.analyze.md': 'Analysis workflow',
'07-speckit.implement.md': 'Implementation workflow',
'08-speckit.checker.md': 'Static analysis workflow',
'09-speckit.tester.md': 'Testing workflow',
'10-speckit.reviewer.md': 'Code review workflow',
'11-speckit.validate.md': 'Validation workflow',
'speckit.prepare.md': 'Preparation workflow',
'schema-change.md': 'Schema change workflow',
'create-backend-module.md': 'Backend module creation',
'create-frontend-page.md': 'Frontend page creation',
'deploy.md': 'Deployment workflow',
'review.md': 'Code review workflow',
'util-speckit.checklist.md': 'Checklist utility',
'util-speckit.diff.md': 'Diff utility',
'util-speckit.migrate.md': 'Migration utility',
'util-speckit.quizme.md': 'Quiz utility',
'util-speckit.status.md': 'Status utility',
'util-speckit.taskstoissues.md': 'Task to issues utility'
'00-speckit.all.md': 'Full pipeline workflow',
'01-speckit.constitution.md': 'Constitution workflow',
'02-speckit.specify.md': 'Specification workflow',
'03-speckit.clarify.md': 'Clarification workflow',
'04-speckit.plan.md': 'Planning workflow',
'05-speckit.tasks.md': 'Task breakdown workflow',
'06-speckit.analyze.md': 'Analysis workflow',
'07-speckit.implement.md': 'Implementation workflow',
'08-speckit.checker.md': 'Static analysis workflow',
'09-speckit.tester.md': 'Testing workflow',
'10-speckit.reviewer.md': 'Code review workflow',
'11-speckit.validate.md': 'Validation workflow',
'speckit.prepare.md': 'Preparation workflow',
'schema-change.md': 'Schema change workflow',
'create-backend-module.md': 'Backend module creation',
'create-frontend-page.md': 'Frontend page creation',
'deploy.md': 'Deployment workflow',
'review.md': 'Code review workflow',
'util-speckit.checklist.md': 'Checklist utility',
'util-speckit.diff.md': 'Diff utility',
'util-speckit.migrate.md': 'Migration utility',
'util-speckit.quizme.md': 'Quiz utility',
'util-speckit.status.md': 'Status utility',
'util-speckit.taskstoissues.md': 'Task to issues utility',
};
// Test suite implementation
const workflowTestSuite = new WorkflowTestSuite();
function runWorkflowTests() {
workflowTestSuite.log('=== Workflow Validation Test Suite ===', 'info');
workflowTestSuite.log(`Workflows directory: ${WORKFLOWS_DIR}`, 'info');
workflowTestSuite.log(`Started: ${new Date().toISOString()}`, 'info');
workflowTestSuite.log('');
workflowTestSuite.log('=== Workflow Validation Test Suite ===', 'info');
workflowTestSuite.log(`Workflows directory: ${WORKFLOWS_DIR}`, 'info');
workflowTestSuite.log(`Started: ${new Date().toISOString()}`, 'info');
workflowTestSuite.log('');
// Test 1: Workflows directory exists
workflowTestSuite.log('Test 1: Directory Structure', 'info');
workflowTestSuite.assert(fs.existsSync(WORKFLOWS_DIR), 'Workflows directory exists');
workflowTestSuite.log('');
// Test 1: Workflows directory exists
workflowTestSuite.log('Test 1: Directory Structure', 'info');
workflowTestSuite.assert(fs.existsSync(WORKFLOWS_DIR), 'Workflows directory exists');
workflowTestSuite.log('');
// Test 2: Expected workflow files exist
workflowTestSuite.log('Test 2: Expected Workflow Files', 'info');
let foundWorkflows = 0;
for (const [filename, description] of Object.entries(expectedWorkflows)) {
const filePath = path.join(WORKFLOWS_DIR, filename);
workflowTestSuite.testWorkflowFile(filePath, description);
if (fs.existsSync(filePath)) {
foundWorkflows++;
}
}
workflowTestSuite.assert(foundWorkflows >= 20, `Found at least 20 workflows (found ${foundWorkflows})`);
workflowTestSuite.log('');
// Test 2: Expected workflow files exist
workflowTestSuite.log('Test 2: Expected Workflow Files', 'info');
let foundWorkflows = 0;
// Test 3: Workflow content validation
workflowTestSuite.log('Test 3: Content Validation', 'info');
for (const [filename, description] of Object.entries(expectedWorkflows)) {
const filePath = path.join(WORKFLOWS_DIR, filename);
if (fs.existsSync(filePath)) {
try {
const content = fs.readFileSync(filePath, 'utf8');
// Check for proper workflow structure
workflowTestSuite.assert(content.includes('#'), `${filename} has markdown headers`);
workflowTestSuite.assert(content.length > 100, `${filename} has substantial content`);
// Validate skill dependencies
workflowTestSuite.validateWorkflowDependency(filename, content);
} catch (error) {
workflowTestSuite.assert(false, `${filename} - content validation error: ${error.message}`);
}
}
for (const [filename, description] of Object.entries(expectedWorkflows)) {
const filePath = path.join(WORKFLOWS_DIR, filename);
workflowTestSuite.testWorkflowFile(filePath, description);
if (fs.existsSync(filePath)) {
foundWorkflows++;
}
workflowTestSuite.log('');
}
// Test 4: Workflow naming consistency
workflowTestSuite.log('Test 4: Naming Consistency', 'info');
const actualFiles = fs.readdirSync(WORKFLOWS_DIR).filter(file => file.endsWith('.md'));
for (const actualFile of actualFiles) {
if (!expectedWorkflows[actualFile]) {
workflowTestSuite.log(` UNEXPECTED: ${actualFile} not in expected list`, 'warn');
}
}
for (const expectedFile of Object.keys(expectedWorkflows)) {
if (!actualFiles.includes(expectedFile)) {
workflowTestSuite.assert(false, `Missing expected workflow: ${expectedFile}`);
}
}
workflowTestSuite.log('');
workflowTestSuite.assert(foundWorkflows >= 20, `Found at least 20 workflows (found ${foundWorkflows})`);
workflowTestSuite.log('');
// Test 5: Cross-reference validation
workflowTestSuite.log('Test 5: Cross-Reference Validation', 'info');
// Check if README.md references workflows correctly
const readmePath = path.join(AGENTS_DIR, 'README.md');
if (fs.existsSync(readmePath)) {
const readmeContent = fs.readFileSync(readmePath, 'utf8');
workflowTestSuite.assert(
readmeContent.includes('.windsurf/workflows'),
'README.md references correct workflows path'
);
}
workflowTestSuite.log('');
// Test 3: Workflow content validation
workflowTestSuite.log('Test 3: Content Validation', 'info');
// Results Summary
workflowTestSuite.log('=== Workflow Test Results Summary ===', 'info');
workflowTestSuite.log(`Passed: ${workflowTestSuite.results.passed}`, 'pass');
workflowTestSuite.log(`Failed: ${workflowTestSuite.results.failed}`, workflowTestSuite.results.failed > 0 ? 'fail' : 'pass');
if (workflowTestSuite.results.errors.length > 0) {
workflowTestSuite.log('Errors:', 'fail');
workflowTestSuite.results.errors.forEach(error => {
workflowTestSuite.log(` - ${error}`, 'fail');
});
for (const [filename, description] of Object.entries(expectedWorkflows)) {
const filePath = path.join(WORKFLOWS_DIR, filename);
if (fs.existsSync(filePath)) {
try {
const content = fs.readFileSync(filePath, 'utf8');
// Check for proper workflow structure
workflowTestSuite.assert(content.includes('#'), `${filename} has markdown headers`);
workflowTestSuite.assert(content.length > 100, `${filename} has substantial content`);
// Validate skill dependencies
workflowTestSuite.validateWorkflowDependency(filename, content);
} catch (error) {
workflowTestSuite.assert(false, `${filename} - content validation error: ${error.message}`);
}
}
workflowTestSuite.log(`Completed: ${new Date().toISOString()}`, 'info');
return workflowTestSuite.results.failed === 0;
}
workflowTestSuite.log('');
// Test 4: Workflow naming consistency
workflowTestSuite.log('Test 4: Naming Consistency', 'info');
const actualFiles = fs.readdirSync(WORKFLOWS_DIR).filter((file) => file.endsWith('.md'));
for (const actualFile of actualFiles) {
if (!expectedWorkflows[actualFile]) {
workflowTestSuite.log(` UNEXPECTED: ${actualFile} not in expected list`, 'warn');
}
}
for (const expectedFile of Object.keys(expectedWorkflows)) {
if (!actualFiles.includes(expectedFile)) {
workflowTestSuite.assert(false, `Missing expected workflow: ${expectedFile}`);
}
}
workflowTestSuite.log('');
// Test 5: Cross-reference validation
workflowTestSuite.log('Test 5: Cross-Reference Validation', 'info');
// Check if README.md references workflows correctly
const readmePath = path.join(AGENTS_DIR, 'README.md');
if (fs.existsSync(readmePath)) {
const readmeContent = fs.readFileSync(readmePath, 'utf8');
workflowTestSuite.assert(
readmeContent.includes('.windsurf/workflows'),
'README.md references correct workflows path'
);
}
workflowTestSuite.log('');
// Results Summary
workflowTestSuite.log('=== Workflow Test Results Summary ===', 'info');
workflowTestSuite.log(`Passed: ${workflowTestSuite.results.passed}`, 'pass');
workflowTestSuite.log(
`Failed: ${workflowTestSuite.results.failed}`,
workflowTestSuite.results.failed > 0 ? 'fail' : 'pass'
);
if (workflowTestSuite.results.errors.length > 0) {
workflowTestSuite.log('Errors:', 'fail');
workflowTestSuite.results.errors.forEach((error) => {
workflowTestSuite.log(` - ${error}`, 'fail');
});
}
workflowTestSuite.log(`Completed: ${new Date().toISOString()}`, 'info');
return workflowTestSuite.results.failed === 0;
}
// Export for use in other modules
@@ -230,6 +232,6 @@ module.exports = { WorkflowTestSuite, runWorkflowTests };
// Run tests if called directly
if (require.main === module) {
const success = runWorkflowTests();
process.exit(success ? 0 : 1);
const success = runWorkflowTests();
process.exit(success ? 0 : 1);
}
+83
View File
@@ -0,0 +1,83 @@
---
auto_execution_mode: 0
description: Manual real-app verification — ตรวจแอปจริงหลัง build pass เพื่อยืนยันว่าทำงานถูกต้องใน environment จริง (ไม่ใช่แค่ unit test)
---
# Workflow: check-real-app
ใช้เมื่อ build/lint/test ผ่านแล้ว แต่ต้องการยืนยันว่าแอปจริงทำงานถูกต้อง
เน้นการตรวจที่ unit test ตรวจไม่ได้: UI flow, API response จริง, console errors, network requests
## ขั้นตอน
### 1. เริ่ม Dev Server (ถ้ายังไม่รัน)
ตรวจก่อนว่ามี dev server รันอยู่แล้วหรือไม่ เพื่อป้องกันรันซ้ำ:
```bash
# Backend
pnpm --filter backend run start:dev
# Frontend
pnpm --filter frontend run dev
```
### 2. ตรวจ Endpoint / หน้าที่เปลี่ยน
- เปิด URL ที่เกี่ยวข้องกับงานที่เพิ่ง implement
- ตรวจ API endpoint ด้วย curl หรือ browser dev tools
- ดู network tab ว่า request/response ถูกต้อง
```bash
# ตัวอย่างตรวจ API จริง
curl -X GET http://localhost:3001/api/[endpoint] \
-H "Authorization: Bearer <token>" | jq .
```
### 3. ตรวจ Console / Log
- **Frontend**: เปิด browser DevTools → Console tab — ต้องไม่มี error หรือ warning ที่ไม่คาดเดา
- **Backend**: ดู terminal log — ตรวจว่าไม่มี unhandled exception หรือ SQL error
### 4. ตรวจ Happy Path + Edge Case หลัก
ตรวจ flow ที่เกี่ยวข้องอย่างน้อย:
- [ ] Happy path ทำงานถูกต้อง
- [ ] Input ผิดรูปแบบ → แสดง error message ที่เหมาะสม
- [ ] Unauthorized access → redirect/403 ถูกต้อง
- [ ] หน้าที่ไม่ได้แก้ยังทำงานปกติ (regression check)
### 5. ตรวจ NAP-DMS Specific
- [ ] UUID ใน URL และ response เป็น string format ถูกต้อง (ไม่ใช่ integer)
- [ ] ไม่มี `NaN` หรือ `undefined` ใน form values หรือ API payload
- [ ] Thai/English text แสดงผลถูกต้อง (i18n)
- [ ] RBAC: role ที่ไม่มีสิทธิ์ไม่เห็น/เข้าถึงไม่ได้
## 🚫 No Fake Evidence Rule
> **ห้ามรายงานว่าตรวจแอปจริงแล้ว ถ้าไม่ได้เปิดแอปและตรวจจริง**
> ถ้าตรวจไม่ได้ (เช่น ไม่มี DB, ไม่มี token) ให้ระบุเหตุผลชัดเจน
## ✅ Mandatory Output
รายงานท้ายงานต้องมีครบ:
### Commands run
```
✅ curl GET /api/correspondences → 200 OK, returned 3 records
✅ curl POST /api/correspondences → 201 Created, uuid: "019..."
❌ ไม่ได้ตรวจ: file upload flow → เหตุผล: ต้องการ ClamAV service ที่ไม่มีใน local
```
### Evidence
- URL ที่ตรวจ + HTTP status code
- Screenshot หรือ response body (ถ้า sensitive ให้ mask)
- Console log ที่พบ (ถ้ามี error ต้องระบุ)
### Limitations / Risks
- flow หรือ endpoint ที่ยังไม่ได้ตรวจ + เหตุผล
- ความเสี่ยงที่ควรตรวจใน staging ก่อน deploy
### Next steps
- งานที่ต้องทำต่อ หรือ flag สำหรับ QA
+13
View File
@@ -0,0 +1,13 @@
---
auto_execution_mode: 0
description: Playwright E2E testing patterns, Page Object Model, configuration, CI/CD integration, artifact management, and flaky test strategies for LCBP3-DMS
---
This workflow invokes the e2e-testing skill to help with Playwright E2E testing patterns for LCBP3-DMS.
Invoke the e2e-testing skill when:
- Creating new E2E tests for frontend features
- Debugging flaky Playwright tests
- Setting up CI/CD integration for E2E tests
- Optimizing test performance and reliability
- Implementing Page Object Model (POM) patterns
+100
View File
@@ -0,0 +1,100 @@
---
auto_execution_mode: 0
description: Resume pending multi-session work — อ่าน context เดิม, หา last checkpoint, สรุปสถานะปัจจุบัน และวางแผนต่อ โดยไม่ทำงานซ้ำ
---
# Workflow: resume-pending-work
ใช้เมื่อกลับมาทำงานที่ค้างไว้ข้าม session — เช่น งานใหญ่ที่แบ่งเป็น phase, งาน migration, หรืองานที่หยุดกลางคัน
## ขั้นตอน
### 1. อ่าน Context เดิม
ตรวจแหล่งข้อมูลเหล่านี้ตามลำดับ:
```
1. Memory system — ดู system-retrieved memories ที่เกี่ยวข้อง
2. specs/200-fullstacks/<feature>/tasks.md — ดู task status ล่าสุด
3. git log --oneline -20 — ดู commits ล่าสุด
4. progress.txt หรือ PROGRESS.md (ถ้ามี) — ดู notes ที่ทิ้งไว้
```
### 2. หา Last Checkpoint
ระบุให้ชัดว่า:
- **ทำไปถึงไหนแล้ว** — phase/task/file ที่ complete แล้ว
- **ค้างอยู่ที่ไหน** — step ที่กำลังทำอยู่ตอนหยุด
- **ยังไม่ได้ทำอะไร** — tasks ที่เหลือ
### 3. ตรวจสถานะ Build ปัจจุบัน
ก่อนทำงานต่อ ต้องรู้ว่า codebase ปัจจุบัน clean หรือไม่:
```bash
# ตรวจ TypeScript errors
pnpm --filter backend run build 2>&1 | tail -20
pnpm --filter frontend run build 2>&1 | tail -20
# ดู uncommitted changes
git status --short
git diff --stat HEAD
```
### 4. สรุปสถานะและวางแผนต่อ
ก่อนลงมือ ให้สรุปให้ผู้ใช้เห็นก่อน:
```
✅ เสร็จแล้ว:
- Phase 1: Entity + Migration (commit abc1234)
- Phase 2: Service layer (commit def5678)
🔄 ค้างอยู่:
- Phase 3: Controller — เขียนครึ่งนึง, ยังไม่มี tests
⏳ ยังไม่ได้ทำ:
- Phase 4: Frontend integration
- Phase 5: E2E tests
🚩 Issues ที่พบ:
- build error ที่ correspondence.service.ts:142
```
จากนั้นถามผู้ใช้ว่าต้องการ:
- ทำงานต่อจาก checkpoint เดิม
- Skip ขั้นตอนที่ค้าง (พร้อมระบุ risk)
- Re-verify งานที่ทำไปแล้วก่อน
### 5. ตรวจ NAP-DMS Specific
ก่อน resume ให้ตรวจ:
- [ ] ADR ที่เกี่ยวข้องยังไม่เปลี่ยนแปลง (ดู git log ที่ `specs/06-Decision-Records/`)
- [ ] Schema ที่ใช้อยู่ตรงกับ `lcbp3-v1.9.0-schema-02-tables.sql`
- [ ] ไม่มี merge conflict หรือ stash ค้าง
## 🚫 No Fake Resume Rule
> **ห้ามบอกว่า "ทำต่อจากตรงนี้" โดยไม่ได้อ่าน context เดิมจริง**
> ต้องระบุหลักฐานที่ชัดเจนว่า checkpoint อยู่ที่ไหน
## ✅ Mandatory Output
### Last checkpoint summary
```
- เสร็จแล้ว: [phase/commit/task]
- ค้างอยู่: [file:line หรือ task ที่หยุด]
- ยังไม่ได้ทำ: [tasks ที่เหลือ]
```
### Build status
```
✅ backend build → clean
❌ frontend build → 2 errors (ระบุ errors)
```
### Plan ต่อ
แผน 3-5 ข้อที่จะทำในส่วนที่เหลือ พร้อม verification method
### Risks / Blockers
สิ่งที่อาจ block งาน หรือต้องระวังก่อนทำต่อ
+1 -1
View File
@@ -40,7 +40,7 @@ The following are **CI-blocking issues** that must be caught in code review. The
- **❌ NO SQL Triggers for business logic** — use NestJS Service methods instead
- **❌ NO `.env` files in production** — use Docker environment variables
- **❌ NO direct table/column name invention** — verify against `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql`
- **❌ NO direct table/column name invention** — verify against `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
### Security (ADR-016)
+11
View File
@@ -0,0 +1,11 @@
---
description: บันทึก session log และอัปเดต project memory
---
# บันทึก Memory
ใช้ skill `save-memory` เพื่อบันทึก session log และอัปเดต project memory ตามโครงสร้างใหม่
```bash
skill save-memory
```
+15
View File
@@ -0,0 +1,15 @@
---
auto_execution_mode: 0
description: Comprehensive security review for LCBP3-DMS with OWASP Top 10 checklist, ADR compliance, and automated security testing patterns
---
This workflow invokes the security-review skill to perform comprehensive security review of LCBP3-DMS code changes.
Invoke the security-review skill when:
- Implementing authentication or authorization
- Handling user input or file uploads
- Creating new API endpoints
- Working with secrets or credentials
- Integrating AI features (Ollama/Qdrant)
- Storing or transmitting sensitive data
- Integrating third-party APIs
+50
View File
@@ -0,0 +1,50 @@
---
auto_execution_mode: 0
description: A comprehensive verification system for LCBP3-DMS development sessions with build, type check, lint, test, security scan, and diff review phases
---
This workflow invokes the verification-loop skill to perform comprehensive verification of LCBP3-DMS code changes.
Invoke the verification-loop skill when:
- After completing a feature or significant code change
- Before creating a PR
- When you want to ensure quality gates pass
- After refactoring
- Before deploying to staging/production
## 🚫 No Fake Evidence Rule
> **ห้ามรายงานว่า test ผ่าน / build สำเร็จ ถ้าไม่ได้รันจริง**
> ถ้ารันไม่ได้ ให้ระบุเหตุผลอย่างชัดเจนแทน
## ✅ Mandatory Output (ทุก verification ต้องมีครบ)
รายงานท้ายงานต้องมี 5 หัวข้อนี้เสมอ:
### 1. Pipeline trace
ลำดับขั้นตอนที่ทำจริง: Understand → Plan → Execute → Verify → Handoff
### 2. Commands run
รายการคำสั่งที่รันจริงพร้อมผลสรุป:
```
✅ pnpm run build → Pass (0 errors)
✅ pnpm run lint → Pass (0 warnings)
✅ pnpm run test → 42 passed, 0 failed
❌ ไม่ได้รัน: e2e tests → เหตุผล: ต้องการ DB จริง, ไม่มีใน CI environment
```
### 3. Verification / Evidence
หลักฐานจริง เช่น build output, test result, diff, screenshot, link
### 4. Limitations / Risks
สิ่งที่ยังไม่ได้ตรวจ, ความเสี่ยง, ข้อจำกัดของ environment
### 5. Next steps
งานที่ต้องทำต่อหลัง verification
+168
View File
@@ -0,0 +1,168 @@
---
trigger: always_on
---
# NAP-DMS Project Context & Rules
- For: Devin Cascade (and compatible: Codex CLI, opencode, Amp, Antigravity, AGENTS.md tools)
- Version: 1.9.10 | Last synced from repo: 2026-06-06
- Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3)
- Skill pack: `.agents/skills/` (v1.9.0, 21 skills) — see [`skills/README.md`](./.agents/skills/README.md) + [`skills/_LCBP3-CONTEXT.md`](./.agents/skills/_LCBP3-CONTEXT.md)
## 🧠 Role & Persona
Act as **Senior Full Stack Developer** specialized in NestJS, Next.js, TypeScript, DMS. Focus: Data Integrity, Security, Maintainability, Performance.
You are a **Document Intelligence Engine** — not a general chatbot. Every response must be **precise**, **spec-compliant**, and **production-ready**.
---
## 🧩 Thought & Planning Protocol (Powered by Everything-Claude-Code)
Before writing any code or taking any action in Tier 1 and Tier 2, the AI must demonstrate the following thinking process:
### 1. Analysis Phase (Explore & Analyze)
Problem Understanding: Restate what the user wants in clear, unambiguous terms.
Context Search: Identify the relevant Spec files or ADRs from the "Key Spec Files" table that must be read before starting.
Constraints Identification: Identify key constraints (e.g. Security rules, UUID patterns, or Domain terminology).
### 2. Planning Phase (Plan)
Alternative Exploration: Present at least 2 solution approaches (where possible) with pros/cons analysis.
Step-by-Step Roadmap: Write a file-by-file plan of changes before executing.
Verification Plan: Specify how to verify the work is complete (e.g. "which unit tests to write" or "which file to check the schema in").
### 3. Execution & Refinement (Execute & Refine)
Follow the plan step by step, and pause to ask if any uncertainty arises.
If significant logic changes are made, summarize what was done for the user after completion.
---
## ⚙️ DMS Workflow Engine Protocol
กฎนี้ใช้คุม Logic การไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกัน Race Condition และรักษาความถูกต้องของสถานะ:
- **State Management:** ตรวจสอบสถานะปัจจุบันจาก DB ก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน (ดู `05-06-code-snippets.md` `[workflow-transition]`)
- **Concurrency Control:** การจอนเลขที่เอกสารต้องใช้ **Redis Redlock** หรือ **TypeORM `@VersionColumn`** เท่านั้น (ADR-002)
- **Background Jobs:** งานนานหรือการแจ้งเตือนต้องส่งไปทำที่ **BullMQ** ห้ามเขียนแบบ Inline (ADR-008)
- **Term Consistency:** ห้ามใช้ "Approval Flow" ให้ใช้ **"Workflow Engine"** และห้ามใช้ "Letter" ให้ใช้ **"Correspondence"** (หมายเหตุ: "จดหมาย" ในคอมเมนต์ภาษาไทย = Correspondence ที่ครอบคลุมทุกประเภท)
---
## 🛡️ Security & Integrity Audit Protocol
กฎนี้ให้ AI เป็น Gatekeeper ก่อน Commit โดยเน้น **Tier 1 — CRITICAL**:
- **UUID Validation:** ตรวจสอบว่าเป็น **UUIDv7** และห้ามใช้ `parseInt()` บน UUID (ADR-019)
- **RBAC Check:** API ใหม่ต้องมี **CASL Guard** และตรวจสอบ 4-Level RBAC Matrix (ADR-016)
- **Data Isolation:** AI ต้องรันผ่าน **Ollama บน Admin Desktop** เท่านั้น ห้ามเข้าถึง DB/storage โดยตรง (ADR-023)
- **Input Sanitization:** ไฟล์อัปโหลดต้องผ่าน **Two-Phase** (Temp → Commit) และสแกนด้วย **ClamAV** (ADR-016)
---
## 🧭 Rule Enforcement Tiers
### 🔴 Tier 1 — CRITICAL (CI BLOCKER)
Build fails หากละเมิด:
- Security (Auth, RBAC, Validation)
- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID
- Database correctness — verify schema before writing queries
- File upload security (ClamAV + whitelist)
- AI validation boundary (ADR-023)
- Error handling strategy (ADR-007)
- Forbidden patterns: `any`, `console.log`, UUID misuse, `id ?? ''` fallback
### 🟡 Tier 2 — IMPORTANT (CODE REVIEW)
Must fix ก่อน merge:
- Architecture patterns (thin controller, business logic in service)
- Test coverage (80%+ business logic, 70%+ backend overall)
- Cache invalidation
- Naming conventions
- **TypeScript Standards:** Missing JSDoc, explicit types, or file headers
### 🟢 Tier 3 — SPECIALIZED WORK
Requires domain-specific knowledge:
- **ADR-021 Integration:** Workflow Engine & Context implementation
- **AI Infrastructure:** ADR-023/023A boundary enforcement and pipeline usage
- **AI Runtime Layer:** ADR-024 Intent Classification, ADR-025 Tool Layer, ADR-026 Chat UI, ADR-027 Admin Console
- **Migration Pipeline:** ADR-028 Staging Queue & post-migration cleanup
- **Complex Business Logic:** Multi-step workflows with state management
- **Performance Optimization:** Database queries, caching strategies, bulk operations
### 🔵 Tier 4 — GUIDELINES
Best practice — follow when possible:
- Code style / formatting (Prettier handles)
- Comment completeness
- Minor optimizations
---
## 📐 TypeScript Rules & Coding Standards
### 📝 Core Standards
- **Strict Mode** — all strict checks enforced.
- **ZERO `any` types** — use proper types or `unknown` + narrowing.
- **ZERO `console.log`** — use NestJS `Logger` (backend) or remove (frontend).
- **English for Code** — use English for all code identifiers, variables, and logic.
- **Thai for Comments** — use Thai for comments, documentation, and JSDoc.
- **Explicit Typing** — explicitly define types for all variables, parameters, and return values.
- **JSDoc** — use JSDoc for all public classes and methods.
### 🏗️ File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- **Change Log** — include `// Change Log` at the top of the file to track modifications.
- **Single Export** — export **only one main symbol** per file.
- **Function Style** — avoid unnecessary blank lines inside functions.
---
## 🚫 Forbidden Actions
| ❌ Forbidden | ✅ Correct Approach | ⚠️ Why |
| ----------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
| SQL Triggers for business logic | NestJS Service methods | Untestable; bypasses audit log |
| `.env` files in production | `docker-compose.yml` environment section | Secrets exposed in version control |
| TypeORM migration files | Edit schema SQL directly (ADR-009) | Migration drift risk; schema managed via SQL delta |
| Inventing table/column names | Verify against `schema-02-tables.sql` | Schema mismatch causes silent runtime errors |
| `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors |
| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage |
| `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable |
| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"0195…"` parsed to integer `19` — silently wrong |
| Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks |
| AI accessing DB/storage directly | AI → DMS API → DB (ADR-023/023A) | Bypasses RBAC, audit trail, and validation layer |
| Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail |
| Inline email/notification sending | BullMQ queue job (ADR-008) | Blocks request thread; no retry on transient failure |
| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | Unverified deploy risks data loss in production |
| AI direct cloud API calls | On-premises Ollama only (ADR-023/023A) | Data privacy violation; no audit control |
| AI outputs without human validation | Human-in-the-loop validation required (ADR-023/023A) | Unvalidated AI metadata corrupts document records |
| n8n calling Ollama/Qdrant directly | n8n → DMS API → BullMQ → Ollama (ADR-023A) | Bypasses audit log, RBAC, and error handling layer |
| Qdrant query without `projectPublicId` filter | `QdrantService.search(projectPublicId, ...)` (ADR-023A) | Cross-project data leak via vector search |
---
## 🚧 Out of Scope — Never Do Without Explicit Approval
| ❌ Never Do Autonomously | ⚠️ Why Approval Is Required |
| --------------------------------------------------------------- | ---------------------------------------------------------------- |
| `DROP` or `RENAME` a column / table | Irreversible data loss — requires DBA + PM sign-off |
| Push directly to `main` / `master` branch | Bypasses CI, code review, and release gates |
| Generate or insert seed data into production database | May corrupt live data or violate business state invariants |
| Delete files from permanent storage | Files may be referenced in active documents or audit trails |
| Modify RBAC permission matrix without security team approval | Defines access control for all users — security boundary change |
| Upgrade major library versions (NestJS, Next.js, TypeORM, etc.) | Breaking changes require full regression test cycle |
| Disable or modify authentication / authorization guards | Creates unguarded endpoints — immediate security risk |
| Change Redis lock TTL or disable Redlock | Risk of document number race condition (ADR-002) |
| Create or supersede an ADR unilaterally | Architecture decisions require team consensus and review process |
| Add new columns to production tables without schema review | Must update Data Dictionary + downstream queries simultaneously |
@@ -13,9 +13,9 @@ trigger: always_on
5. **Password:** bcrypt 12 salt rounds, min 8 chars, rotate every 90 days
6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints
7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan
8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access
8. **AI Isolation (ADR-023/023A):** Ollama on Admin Desktop ONLY — NO direct DB/storage access; 2-model stack `gemma4:e4b Q8_0` + `nomic-embed-text`; all inference via BullMQ (`ai-realtime` / `ai-batch`)
9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages
10. **AI Integration (ADR-020):** RFA-First approach with unified pipeline architecture
10. **AI Integration (ADR-023/023A):** RFA-First approach; n8n orchestrates Migration Phase only via DMS API — never calls Ollama directly; `QdrantService.search()` requires `projectPublicId` as mandatory param
11. **AI Audit Trail:** Log all AI interactions and human validations
12. **Rate Limiting:** Apply to AI endpoints to prevent abuse
@@ -30,7 +30,9 @@ trigger: always_on
- [ ] No SQL injection vulnerabilities
- [ ] File upload validation (whitelist + ClamAV)
- [ ] Rate limiting applied to auth endpoints
- [ ] AI boundary enforcement (ADR-018) - no direct DB/storage access
- [ ] AI boundary enforcement (ADR-023/023A) - no direct DB/storage access
- [ ] AI audit logging implemented for AI interactions
- [ ] AI outputs validated before use (human-in-the-loop)
- [ ] Error handling follows ADR-007 layered classification
- [ ] Cache invalidation when data modified
- [ ] OWASP Top 10 review passed
@@ -1,4 +1,8 @@
# TypeScript Rules (v1.9.0)
---
trigger: always_on
---
# TypeScript Rules
## Core Standards
@@ -13,10 +17,18 @@
## File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- Use **absolute path** from project root (e.g., `// File: backend/src/modules/correspondence/correspondence.service.ts`)
- Do NOT use relative path (e.g., `// File: src/example.service.ts`)
- **Change Log** — include `// Change Log` at the top of the file.
- **Single Export** — export **only one main symbol** per file.
- **Function Style** — avoid unnecessary blank lines inside functions.
## i18n Guidelines
- **No Hardcoded Text:** Use i18n keys for all user-facing text
- **Reference:** `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md`
- **Pattern:** Use `t('key.path')` from i18n hook instead of hardcoded strings
## Patterns
```typescript
+45
View File
@@ -0,0 +1,45 @@
---
trigger: always_on
---
# Domain Terminology
## DMS Glossary
| ✅ Use | ❌ Don't Use | คำอธิบายเพิ่มเติม |
| ------------------ | ------------------------------------- | ------------------------------------------------ |
| Correspondence | Letter, Communication, Document | ครอบคลุมทุกประเภท: Letter, RFA, Memo, ฯลฯ |
| RFA | Approval Request, Submit for Approval | เอกสารขออนุมัติ (ชนิดหนึ่งของ Correspondence) |
| Transmittal | Delivery Note, Cover Letter | เอกสารนำส่ง (ชนิดหนึ่งของ Correspondence) |
| Circulation | Distribution, Routing | ใบเวียนเอกสารภายใน (ชนิดหนึ่งของ Correspondence) |
| Shop Drawing | Construction Drawing | แบบก่อสร้าง |
| Contract Drawing | Design Drawing, Blueprint | แบบคู่สัญญา |
| Workflow Engine | Approval Flow, Process Engine | เครื่องมือจัดการลำดับงาน |
| Document Numbering | Document ID, Auto Number | ระบบจัดการเลขที่เอกสาร |
| RBAC | Permission System (generic) | การควบคุมสิทธิ์ตามบทบาท |
## Full Glossary
`specs/00-overview/00-02-glossary.md`
## Key Spec Files Priority
Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others
| Document | Path | Use When |
| ------------------------------ | --------------------------------------------------------------------------- | --------------------------------- |
| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology |
| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` | Before writing any query |
| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules |
| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows |
| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work |
| **ADR-023 AI** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | AI integration work |
| **ADR-023A AI Model** | `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` | 2-model stack, BullMQ 2-queue |
| **ADR-024 Intent Class.** | `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` | Pattern→LLM Fallback; Redis cache |
| **ADR-025 AI Tool Layer** | `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` | Tool Registry; CASL-guarded |
| **ADR-026 Chat UI** | `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` | Side-panel; streaming SSE |
| **ADR-027 AI Admin Console** | `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` | Dynamic control; admin-only |
| **ADR-028 Migration Refactor** | `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` | Staging Queue; cleanup |
| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns |
| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns |
| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals |
+43
View File
@@ -0,0 +1,43 @@
---
trigger: always_on
---
# Forbidden Actions
## ❌ Never Do This
| ❌ Forbidden | ✅ Correct Approach | ⚠️ Why |
| ----------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
| SQL Triggers for business logic | NestJS Service methods | Untestable; bypasses audit log |
| `.env` files in production | `docker-compose.yml` environment section | Secrets exposed in version control |
| TypeORM migration files | Edit schema SQL directly (ADR-009) | Migration drift risk; schema managed via SQL delta |
| Inventing table/column names | Verify against `schema-02-tables.sql` | Schema mismatch causes silent runtime errors |
| `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors |
| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage |
| `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable |
| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"0195…"` parsed to integer `19` — silently wrong |
| Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks |
| AI accessing DB/storage directly | AI → DMS API → DB (ADR-023/023A) | Bypasses RBAC, audit trail, and validation layer |
| Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail |
| Inline email/notification sending | BullMQ queue job (ADR-008) | Blocks request thread; no retry on transient failure |
| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | Unverified deploy risks data loss in production |
| AI direct cloud API calls | On-premises Ollama only (ADR-023/023A) | Data privacy violation; no audit control |
| AI outputs without human validation | Human-in-the-loop validation required (ADR-023/023A) | Unvalidated AI metadata corrupts document records |
| n8n calling Ollama/Qdrant directly | n8n → DMS API → BullMQ → Ollama (ADR-023A) | Bypasses audit log, RBAC, and error handling layer |
| Qdrant query without `projectPublicId` filter | `QdrantService.search(projectPublicId, ...)` (ADR-023A) | Cross-project data leak via vector search |
## Schema Changes (ADR-009)
- **NO TypeORM migrations** — edit SQL schema directly
- Always check `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` before writing queries
- Update Data Dictionary when changing fields
## UUID Handling
See `01-adr-019-uuid.md` for complete UUID rules.
Quick reminder:
- ❌ `parseInt(uuid)` → NEVER
- ❌ `Number(uuid)` → NEVER
- ✅ Use UUID string directly
@@ -1,10 +1,10 @@
---
trigger: glob
globs:
- "backend/**/*.service.ts"
- "backend/**/*.controller.ts"
- "backend/**/*.dto.ts"
- "backend/**/*.entity.ts"
- 'backend/**/*.service.ts'
- 'backend/**/*.controller.ts'
- 'backend/**/*.dto.ts'
- 'backend/**/*.entity.ts'
---
# Backend Patterns (NestJS)
@@ -25,7 +25,7 @@ async create(@Body() dto: CreateCorrespondenceDto) {
// Resolve UUID to internal ID
const contract = await this.contractService.findOneByUuid(dto.contractUuid);
const contractId = contract.id; // Internal INT for DB queries
return this.service.create(dto, contractId);
}
@@ -48,8 +48,8 @@ async create(dto: CreateCorrespondenceDto, contractId: number) {
class Contract extends UuidBaseEntity {
@Column({ type: 'uuid' })
publicId: string;
@PrimaryKey()
@PrimaryGeneratedColumn()
@Exclude()
id: number;
}
+214
View File
@@ -0,0 +1,214 @@
---
trigger: always_on
---
# Development Flow
## 🔴 Critical Work — DB / API / Security / Workflow Engine
**MUST complete all steps:**
1. **Glossary check** — verify domain terms in `00-02-glossary.md`
2. **Read the spec** — select from Key Spec Files table
3. **Check schema** — verify table/column in `lcbp3-v1.9.0-schema-02-tables.sql`
4. **Check data dictionary** — confirm field meanings + business rules
5. **Scan edge cases**`01-06-edge-cases-and-rules.md`
6. **Check ADRs** — verify decisions align (ADR-009, ADR-019, ADR-023)
7. **Write code** — TypeScript strict, no `any`, no `console.log`
## 🟡 Normal Work — UI / Feature / Integration
- Follow existing patterns in codebase.
- Check spec for relevant module only.
- **Hybrid Specs Organization:**
- Place new Infrastructure tasks in `specs/100-Infrastructures/`
- Place new Feature/Workflow tasks in `specs/200-fullstacks/`
- Place Documentation/Research in `specs/300-others/`
- Ensure no forbidden patterns (`any`, `console.log`, UUID misuse) are introduced.
## 🟢 Quick Fix — Bug Fix / Typo / Style
- Fix directly
- Add minimal test if logic changed
- Check forbidden patterns before commit
### 🟢 Specialized Work — ADR-021, AI Runtime Layer, Complex Logic
**MUST complete:**
1. **Domain Knowledge Check** - Read relevant ADRs (ADR-021, ADR-023/023A, ADR-024~028)
2. **Pattern Verification** - Check existing implementations in codebase
3. **Specialized Requirements** - Follow domain-specific patterns
4. **Complex Logic Testing** - Multi-scenario test coverage
5. **Performance Validation** - Load testing if applicable
**For ADR-021 Integration:**
- Read ADR-021 - Integrated workflow & step attachments
- Check ADR-001 - Unified workflow engine patterns
- Verify WorkflowEngineService - Polymorphic instance handling
- Add workflow fields - Expose workflowInstanceId, workflowState, availableActions
- Include IntegratedBanner - Frontend workflow lifecycle display
- Test workflow transitions - State changes and action validation
**For AI Infrastructure (ADR-023/023A):**
- Verify AI boundary enforcement - No direct DB/storage access
- Check BullMQ 2-queue setup - ai-realtime + ai-batch
- Validate Qdrant multi-tenancy - projectPublicId filter required
- Test human-in-the-loop validation workflows
- Audit AI interaction logging to ai_audit_logs
**For AI Runtime Layer (ADR-024/025/026/027):**
- ADR-024: Pattern Layer first (ai_intent_patterns DB + Redis cache 5 min) → LLM Fallback (gemma4:e4b, semaphore max=3)
- ADR-025: Tool Registry dispatch — AI Gateway → Tool → Business Service; ToolResult DTO must use publicId only
- ADR-026: useAiChat() hook + side-panel UI; streaming response via SSE; TanStack Query cache
- ADR-027: Admin Console — dynamic model/prompt/intent control; CASL-guarded admin-only endpoints
**For Migration Pipeline (ADR-028):**
- Use Staging Queue pattern — never write directly to production tables
- Post-migration cleanup process required after each batch
- Migration Validation Gates must pass before promoting to production
**Expected output:**
- Backend services expose specialized context fields
- Frontend components use domain-specific patterns
- Complex state management with proper validation
- Performance metrics within acceptable thresholds
- Comprehensive test coverage for edge cases
---
## Context-Aware Triggers
| Request | Files to Check | Expected Response |
| --------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard |
| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases-and-rules.md` | RHF+Zod + TanStack Query + Thai comments |
| "เพิ่ม field ใหม่" | `ADR-009`, `03-01-data-dictionary.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity |
| "ตรวจสอบ UUID" | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor |
| "สร้าง migration" | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow |
| "ตรวจสอบ permission" | `lcbp3-v1.9.0-seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix |
| "deploy production" | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy |
| "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns |
| "AI integration" | `ADR-023`, `ADR-023A`, `ADR-024`, `ADR-025` | AI boundary + 2-model stack + BullMQ queue policy + Intent/Tool Layer |
| "Error handling" | `ADR-007` | Layered error classification + recovery |
| "File upload" | `ADR-016`, `05-02-backend-guidelines.md`, `03-Data-and-Storage/03-03-file-storage.md` | Two-phase upload → temp → commit; ClamAV + whitelist |
| "Notifications / Queue" | `ADR-008`, `05-02-backend-guidelines.md` | BullMQ job — never inline; check retry + dead-letter |
| "Add i18n / translate" | `05-08-i18n-guidelines.md` | i18n keys only — no hardcoded text |
| "Workflow / DSL" | `ADR-001`, `01-03-modules/01-03-06-unified-workflow.md` | DSL state machine + WorkflowEngineService |
| "Document numbering" | `ADR-002`, `01-02-business-rules/01-02-02-doc-numbering-rules.md` | Redis Redlock + DB optimistic lock (double-lock) |
| "ตรวจสอบ Workflow" | `01-06-edge-cases-and-rules.md`, `05-02-backend-guidelines.md`, `ADR-001`, `ADR-002` | เช็คการเปลี่ยน State, คิว BullMQ และการล็อกเลขที่เอกสาร |
| "Transmittal submit" | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | submit() with EC-RFA-004 validation |
| "Circulation reassign" | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | reassignRouting() with EC-CIRC-001 |
| "สร้าง workflow ใหม่" | `ADR-001`, `ADR-021`, `specs/200-fullstacks/203-unified-workflow-engine/` | DSL workflow definition + WorkflowEngineService setup |
| "ตรวจสอบ AI boundary" | `ADR-023`, `ADR-023A` | Verify Ollama isolation + BullMQ queues + Qdrant projectPublicId filter |
| "Intent classification" | `ADR-024`, `specs/200-fullstacks/224-intent-classification/` | Pattern Layer → LLM Fallback; ai_intent_patterns; Redis cache 5 min |
| "AI Tool Layer" | `ADR-025`, `specs/200-fullstacks/225-ai-tool-layer-architecture/` | Tool Registry; CASL-guarded dispatch; ToolResult publicId only |
| "Document Chat UI" | `ADR-026`, `specs/200-fullstacks/226-document-chat-ui-pattern/` | Side-panel; useAiChat() hook; streaming SSE; TanStack Query cache |
| "AI Admin Console" | `ADR-027`, `specs/200-fullstacks/227-ai-admin-console/` | Dynamic model/prompt/intent control; admin-only CASL endpoints |
| "Migration refactor" | `ADR-028`, `specs/200-fullstacks/228-migration-arch-refactor/` | Staging Queue; post-migration cleanup; validation gates |
| "จัดการ document numbering" | `ADR-002`, `specs/03-Data-and-Storage/03-04-document-numbering.md` | Redis Redlock + template system + preview/override workflows |
| "Audit ความปลอดภัย" | `ADR-016`, `ADR-019`, `ADR-023`, `ADR-023A` | ตรวจสอบ UUID pattern, CASL Guard, AI Boundary และ Qdrant multi-tenancy |
| "แก้ bug / bugfix" | `.agents/workflows/bugfix.md`, `error-catalog.md` | ใช้ bugfix workflow สำหรับเคสที่สาเหตุชัดเจน |
| "ตรวจแอปจริง" | `.windsurf/workflows/check-real-app.md` | ตรวจ endpoint/UI/console หลัง build pass — No Fake Evidence |
| "งานค้าง / resume" | `.windsurf/workflows/resume-pending-work.md` | อ่าน checkpoint เดิม → ตรวจ build → วางแผนต่อโดยไม่ทำงานซ้ำ |
---
## 🔌 MCP MariaDB Tools
MCP MariaDB server ให้เครื่องมือสำหรับตรวจสอบและจัดการ database โดยตรง ใช้สำหรับ:
- ตรวจสอบ schema กับ spec file `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
- Debug ปัญหา database โดยไม่ต้องเข้า MySQL client
- ตรวจสอบ data ใน production/staging
- Validate การเปลี่ยนแปลง schema ก่อน deploy
### Available Tools
| Tool | หน้าที่ | ตัวอย่างการใช้งาน |
|------|----------|------------------|
| `mcp1_mysql_test_connection` | ทดสอบ connection กับ database | ตรวจสอบว่า MCP server เชื่อมต่อได้ |
| `mcp1_mysql_show_databases` | แสดง databases ทั้งหมด | ดูว่ามี database อะไรบ้าง |
| `mcp1_mysql_show_tables` | แสดง tables ทั้งหมดใน database | ดูรายชื่อ tables ใน `lcbp3` |
| `mcp1_mysql_describe_table` | ดู structure/columns ของ table | ตรวจสอบ columns, types, keys ของ `correspondences` |
| `mcp1_mysql_query` | รัน SELECT query | ดู data ใน table หรือ join query |
| `mcp1_mysql_insert` | INSERT data | เพิ่ม seed data หรือ test data |
| `mcp1_mysql_update` | UPDATE data | แก้ไข data ใน table |
| `mcp1_mysql_delete` | DELETE data | ลบ data ใน table |
### การใช้งานร่วมกับ Development Flow
**เมื่อเขียน query ใหม่:**
1. ใช้ `mcp1_mysql_describe_table` เพื่อตรวจสอบ columns และ types
2. เปรียบเทียบกับ `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
3. ใช้ `mcp1_mysql_query` เพื่อทดสอบ query ก่อน implement
**เมื่อเปลี่ยน schema (ADR-009):**
1. ใช้ `mcp1_mysql_describe_table` เพื่อดู structure ปัจจุบัน
2. สร้าง SQL delta ใน `specs/03-Data-and-Storage/deltas/`
3. ใช้ `mcp1_mysql_query` เพื่อตรวจสอบผลลัพธ์หลัง apply delta
**เมื่อ debug ปัญหา database:**
1. ใช้ `mcp1_mysql_query` เพื่อดู data จริง
2. เปรียบเทียบกับ spec และ data dictionary
3. ตรวจสอบ foreign keys และ constraints
### ข้อควรระวัง
- **❌ ห้ามใช้ MCP MariaDB สำหรับ DDL operations** (CREATE/ALTER/DROP) โดยตรง — ต้องใช้ SQL delta ตาม ADR-009
- **✅ ใช้สำหรับ DQL/DML operations** (SELECT/INSERT/UPDATE/DELETE) เพื่อ debug และ test เท่านั้น
- **⚠️ ระวัง DELETE operations** — อาจทำให้เสีย data ใน production
- **✅ ตรวจสอบ schema กับ spec file เสมอ** ก่อนเขียน query
---
## 🧠 MCP Memory Tools
MCP Memory server ให้เครื่องมือสำหรับจัดการ Knowledge Graph และ Long-term Memory ใช้สำหรับ:
- จัดเก็บความรู้และ context ของโปรเจกต์ในรูปแบบ Graph (Entities + Relations + Observations)
- ค้นหาและดึงข้อมูล context จาก memory ที่บันทึกไว้ใน session ก่อนหน้า
- สร้าง/แก้ไข/ลบ entities, relations, และ observations ใน knowledge graph
### Available Tools
| Tool | หน้าที่ | ตัวอย่างการใช้งาน |
|------|----------|------------------|
| `mcp3_create_entities` | สร้าง entities ใหม่หลายตัวพร้อม observations | สร้าง entity ใหม่เช่น Project, User, Task |
| `mcp3_create_relations` | สร้าง relations ระหว่าง entities | สร้าง relation: Project → has → User |
| `mcp3_add_observations` | เพิ่ม observations ให้ entity ที่มีอยู่แล้ว | เพิ่ม context เพิ่มเติมให้ entity |
| `mcp3_delete_entities` | ลบ entities และ relations ที่เกี่ยวข้อง | ลบ entity ที่ไม่ใช้แล้ว |
| `mcp3_delete_relations` | ลบ relations ระหว่าง entities | ลบ relation ที่ผิดหรือไม่ใช้แล้ว |
| `mcp3_delete_observations` | ลบ observations จาก entity | ลบ context ที่ผิดหรือล้าสุด |
| `mcp3_open_nodes` | ดึงข้อมูล entities ตามชื่อ | ดึง entity ที่ระบุชื่อ |
| `mcp3_read_graph` | อ่าน knowledge graph ทั้งหมด | ดูทั้ง graph structure |
| `mcp3_search_nodes` | ค้นหา entities ตาม query | ค้นหา entity จากชื่อ, type, หรือ observation |
### การใช้งานร่วมกับ Development Flow
**เมื่อบันทึก context ใหม่:**
1. ใช้ `mcp3_create_entities` เพื่อสร้าง entities ใหม่ (ถ้ายังไม่มี)
2. ใช้ `mcp3_create_relations` เพื่อเชื่อมโยง entities
3. ใช้ `mcp3_add_observations` เพื่อเพิ่ม context/observations
**เมื่อค้นหา context:**
1. ใช้ `mcp3_search_nodes` เพื่อค้นหา entities ที่เกี่ยวข้อง
2. ใช้ `mcp3_open_nodes` เพื่อดึงข้อมูล entities ที่ต้องการ
3. ใช้ `mcp3_read_graph` เพื่อดู relations ระหว่าง entities
**เมื่อแก้ไข context:**
1. ใช้ `mcp3_add_observations` เพื่อเพิ่ม observations ใหม่
2. ใช้ `mcp3_delete_observations` เพื่อลบ observations ที่ผิด
3. ใช้ `mcp3_create_relations` หรือ `mcp3_delete_relations` เพื่อปรับ relations
### ข้อควรระวัง
- **✅ ใช้สำหรับบันทึก context ที่ต้องใช้ร่วมกันหลาย session** — เช่น การตัดสินใจสำคัญ, architecture decisions, rollout history
- **⚠️ ระวังการลบ entities** — อาจทำให้เสีย context ที่ยังใช้งานอยู่
- **✅ ตรวจสอบว่า entity มีอยู่แล้วก่อนสร้าง** — ใช้ `mcp3_search_nodes` หรือ `mcp3_open_nodes` ก่อน
- **✅ ใช้ชื่อ entity ที่ชัดเจนและไม่ซ้ำกัน** — เพื่อป้องกันความสับสน
+149
View File
@@ -0,0 +1,149 @@
---
trigger: always_on
---
# ADR-023/023A AI Integration Architecture
## CRITICAL RULES
- **ALWAYS** follow ADR-023 AI boundary policy (isolation on Admin Desktop)
- **ALWAYS** use ADR-023A 2-model stack (gemma4:e2b + nomic-embed-text)
- **ALWAYS** use BullMQ 2-queue (ai-realtime + ai-batch) for GPU overload prevention
- **NEVER** allow AI direct database/storage access
- **ALWAYS** implement human-in-the-loop validation
- **NEVER** send sensitive data to cloud AI services
- **ALWAYS** enforce Qdrant projectPublicId filter (compile-time enforcement)
- **NEVER** allow n8n to call Ollama/Qdrant directly (must go through DMS API → BullMQ)
## AI Integration Patterns
### Architecture Overview
```
Frontend → AI Gateway API → BullMQ → Admin Desktop (Ollama) → Backend Validation
n8n (Migration) → DMS API → BullMQ → Admin Desktop (Ollama) → Backend Validation
```
### Key Components
| Component | Location | Purpose |
| ----------------- | ------------------------- | ------------------------------------------------------------------------ |
| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging |
| **BullMQ Queues** | Backend (NestJS) | ai-realtime (RAG/Suggest), ai-batch (OCR/Extract/Embed) |
| **Ollama Engine** | Admin Desktop (Desk-5439) | gemma4:e2b (LLM) + nomic-embed-text (Embedding) |
| **OCR Engine** | Admin Desktop (Desk-5439) | PaddleOCR + PyThaiNLP (Thai/English text extraction) |
| **Orchestrator** | QNAP NAS (n8n) | Migration Phase orchestrator only (calls DMS API, never Ollama directly) |
## Backend Implementation (NestJS)
```typescript
// AI Module with boundary enforcement
@Module({
controllers: [AiController],
providers: [AiService, AiGateway, QdrantService],
exports: [AiService],
})
export class AiModule {
constructor() {
// Enforce ADR-023 boundaries
}
}
// QdrantService with compile-time projectPublicId enforcement
@Injectable()
export class QdrantService {
async search(
projectPublicId: string, // required — compile-time enforcement
vector: number[],
topK: number = 5,
): Promise<QdrantSearchResult[]> {
return this.client.search('documents', {
vector,
limit: topK,
filter: {
must: [{ key: 'project_public_id', match: { value: projectPublicId } }],
},
});
}
async upsert(
projectPublicId: string, // required
chunks: DocumentChunk[],
): Promise<void> { ... }
// ❌ NEVER expose rawSearch() or method without projectPublicId filter
}
// AI Service with validation
@Injectable()
export class AiService {
async extractMetadata(documentId: string): Promise<AIMetadata> {
// 1. Validate permissions
// 2. Queue job to BullMQ (ai-batch or ai-realtime)
// 3. Worker sends to Admin Desktop AI (gemma4:e2b)
// 4. Validate AI response
// 5. Log audit trail to ai_audit_logs
// 6. Return validated results
}
}
```
## Frontend Pattern (Next.js)
```typescript
// Document Review Form (reusable component)
const DocumentReviewForm = ({ document, aiSuggestions }) => {
return (
<form>
<Field label="Document Type" suggestions={aiSuggestions.documentType} />
<Field label="Project Code" suggestions={aiSuggestions.projectCode} />
<Field label="Discipline" suggestions={aiSuggestions.discipline} />
<ConfidenceScore score={aiSuggestions.confidence} />
<HumanValidationActions />
</form>
);
};
```
## Security Requirements
- **AI Isolation:** All AI processing on Admin Desktop only (Desk-5439)
- **Data Privacy:** No cloud AI services, on-premises only
- **Audit Trail:** Log all AI interactions and human validations to ai_audit_logs
- **Rate Limiting:** Prevent AI abuse and resource exhaustion
- **Validation:** All AI outputs must be validated before use
- **Multi-tenant Isolation:** Qdrant queries MUST include projectPublicId filter (compile-time enforcement)
- **n8n Boundary:** n8n MUST call DMS API → BullMQ, NEVER Ollama/Qdrant directly
- **GPU Overload Prevention:** BullMQ 2-queue (ai-realtime + ai-batch) with concurrency=1
## ADR-023A Specific Rules
- **2-Model Stack:** gemma4:e2b + nomic-embed-text
- **PDF 3-Page Limit:** Classification/Tagging uses first 3 pages only (NOT RAG embedding)
- **RAG Embedding:** Full document chunked at 512 tokens/64 tokens overlap
- **OCR Auto-Detect:** PyMuPDF chars > 100 → Fast path, else PaddleOCR
- **Embed Auto-Trigger:** AUTO after commit (parallel), gap covered by DB search
- **Threshold Recalibration:** After 100-500 docs, based on ai_audit_logs analysis
## Required Implementation
- [ ] AiModule with ADR-023 boundary enforcement
- [ ] AI Gateway API endpoints with validation
- [ ] BullMQ 2-queue setup (ai-realtime + ai-batch)
- [ ] QdrantService with projectPublicId enforcement
- [ ] DocumentReviewForm reusable component
- [ ] Admin Desktop Ollama (gemma4:e2b + nomic-embed-text) + PaddleOCR setup
- [ ] n8n workflow orchestration (Migration Phase only)
- [ ] AI audit logging and monitoring (ai_audit_logs)
- [ ] Human-in-the-loop validation workflows
## Related Documents
- `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` (Base architecture)
- `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` (Model revision - current)
- `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` (Pattern→LLM Fallback)
- `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` (Tool Registry)
- `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` (Chat UI)
- `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` (Admin Console)
- `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` (Migration Pipeline)
+141
View File
@@ -0,0 +1,141 @@
---
trigger: always_on
---
# LCBP3 Agent Rules
Critical rules and guidelines for AI agents working on LCBP3-DMS.
## Version
- **Current:** v1.9.6
- **Last Updated:** 2026-05-22
- **Synced with:** `AGENTS.md` (v1.9.6)
## Purpose
This directory contains rule files that define:
- Project context and role expectations
- Critical Tier 1 rules (CI blockers)
- Coding standards and patterns
- Domain terminology and glossary
- Development workflows
- Security requirements
- AI integration architecture (ADR-023/023A)
## Rule Enforcement Tiers
### 🔴 Tier 1 — CRITICAL (CI BLOCKER)
Build fails immediately if violated:
- Security (Auth, RBAC, Validation)
- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID
- Database correctness — verify schema before writing queries
- File upload security (ClamAV + whitelist)
- AI validation boundary (ADR-023)
- Error handling strategy (ADR-007)
- Forbidden patterns: `any`, `console.log`, UUID misuse, `id ?? ''` fallback
### 🟡 Tier 2 — IMPORTANT (CODE REVIEW)
Must fix before merge:
- Architecture patterns (thin controller, business logic in service)
- Test coverage (80%+ business logic, 70%+ backend overall)
- Cache invalidation
- Naming conventions
- TypeScript Standards: Missing JSDoc, explicit types, or file headers
### 🟢 Tier 3 — SPECIALIZED WORK
Requires domain-specific knowledge:
- **ADR-021 Integration:** Workflow Engine & Context implementation
- **AI Infrastructure:** ADR-023/023A boundary enforcement and pipeline usage
- **AI Runtime Layer:** ADR-024 Intent Classification, ADR-025 Tool Layer, ADR-026 Chat UI, ADR-027 Admin Console
- **Migration Pipeline:** ADR-028 Staging Queue & post-migration cleanup
- **Complex Business Logic:** Multi-step workflows with state management
- **Performance Optimization:** Database queries, caching strategies, bulk operations
### 🔵 Tier 4 — GUIDELINES
Best practice — follow when possible:
- Code style / formatting (Prettier handles)
- Comment completeness
- Minor optimizations
## Rule Files
### Core Rules (Tier 1 - CRITICAL)
| File | Purpose |
| ----------------------- | ------------------------------------------------------------------------------- |
| `00-project-context.md` | Project context, role & persona, tier classification, specs folder organization |
| `01-adr-019-uuid.md` | UUID handling strategy — no parseInt, use publicId only |
| `02-security.md` | Security requirements, checklist, ADR-023/023A AI boundaries |
### Coding Standards
| File | Purpose |
| ------------------------- | ------------------------------------------------------- |
| `03-typescript.md` | TypeScript rules, file headers, i18n guidelines |
| `06-backend-patterns.md` | NestJS patterns, UUID resolution, API response patterns |
| `07-frontend-patterns.md` | Next.js patterns, RHF+Zod+TanStack Query, UUID handling |
### Domain & Workflow
| File | Purpose |
| -------------------------- | ------------------------------------------------------------- |
| `04-domain-terminology.md` | DMS glossary, key spec files priority table |
| `08-development-flow.md` | Development workflow by work type (Critical/Normal/Quick Fix) |
### Compliance & Architecture
| File | Purpose |
| ------------------------- | -------------------------------------------------------------- |
| `05-forbidden-actions.md` | Actions that must never be done, schema changes, UUID handling |
| `09-commit-checklist.md` | Pre-commit verification, commit message format |
| `10-error-handling.md` | ADR-007 error handling strategy, layered classification |
| `11-ai-integration.md` | ADR-023/023A AI architecture, 2-model stack, BullMQ 2-queue |
## Key Spec Files Priority
Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others
| Document | Path | Use When |
| ------------------------------ | --------------------------------------------------------------------------- | --------------------------------- |
| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology |
| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` | Before writing any query |
| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules |
| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows |
| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work |
| **ADR-023 AI** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | AI integration work |
| **ADR-023A AI Model** | `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` | 2-model stack, BullMQ 2-queue |
| **ADR-024 Intent Class.** | `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` | Pattern→LLM Fallback; Redis cache |
| **ADR-025 AI Tool Layer** | `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` | Tool Registry; CASL-guarded |
| **ADR-026 Chat UI** | `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` | Side-panel; streaming SSE |
| **ADR-027 AI Admin Console** | `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` | Dynamic control; admin-only |
| **ADR-028 Migration Refactor** | `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` | Staging Queue; cleanup |
| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns |
| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns |
| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals |
## Maintenance
When updating rules:
1. **Check AGENTS.md version** — Ensure rule files are synced
2. **Update version numbers** — Bump version in `00-project-context.md` only (03-typescript.md no longer has version)
3. **Review ADR references** — Ensure all ADR references are current (ADR-023, ADR-023A, ADR-024~028)
4. **Add new forbidden actions** — When new patterns are identified as violations
5. **Update key spec files table** — When new ADRs or guidelines are added
6. **Update Tier 3 SPECIALIZED WORK** — When new domain-specific workflows are added
## Related Documents
- `AGENTS.md` — Master agent configuration and context
- `specs/06-Decision-Records/` — All Architecture Decision Records
- `specs/05-Engineering-Guidelines/` — Backend, frontend, and testing guidelines
+30
View File
@@ -0,0 +1,30 @@
# lcbp3 Development Guidelines
Auto-generated from all feature plans. Last updated: 2026-05-30
## Active Technologies
- TypeScript 5.x (NestJS 11 backend, Next.js 16 frontend), Python 3.11 (OCR sidecar) + Ollama (AI runtime), BullMQ (job queues), TypeORM (ORM), Redis (caching/locks), MariaDB 11.8 (database) (232-typhoon-ocr-integration)
## Project Structure
```text
backend/
frontend/
tests/
```
## Commands
cd src [ONLY COMMANDS FOR ACTIVE TECHNOLOGIES][ONLY COMMANDS FOR ACTIVE TECHNOLOGIES] pytest [ONLY COMMANDS FOR ACTIVE TECHNOLOGIES][ONLY COMMANDS FOR ACTIVE TECHNOLOGIES] ruff check .
## Code Style
TypeScript 5.x (NestJS 11 backend, Next.js 16 frontend), Python 3.11 (OCR sidecar) : Follow standard conventions
## Recent Changes
- 232-typhoon-ocr-integration: Added TypeScript 5.x (NestJS 11 backend, Next.js 16 frontend), Python 3.11 (OCR sidecar) + Ollama (AI runtime), BullMQ (job queues), TypeORM (ORM), Redis (caching/locks), MariaDB 11.8 (database)
<!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END -->
@@ -1,8 +1,8 @@
# `.agents/skills/` — LCBP3 Agent Skill Pack
**Version:** 1.8.9 | **Last Updated:** 2026-04-22 | **Total Skills:** 20
**Version:** 1.9.0 | **Last Updated:** 2026-06-07 | **Total Skills:** 24
Agent skills for AI-assisted development in **Windsurf IDE** (and compatible agents: Codex CLI, opencode, Amp, Antigravity, AGENTS.md-aware tools).
Agent skills for AI-assisted development in **Devin IDE** (and compatible agents: Codex CLI, opencode, Amp, Antigravity, AGENTS.md-aware tools).
---
@@ -14,25 +14,27 @@ Agent skills for AI-assisted development in **Windsurf IDE** (and compatible age
├── skills.md # Overview + dependency matrix + health monitoring
├── _LCBP3-CONTEXT.md # Shared LCBP3 context injected into every speckit-* skill
├── README.md # (this file)
├── save-memory/ # Session log & project memory update
├── nestjs-best-practices/ # Backend rules (40 rules across 10 categories)
├── next-best-practices/ # Frontend rules (Next.js 15+)
├── e2e-testing/ # Playwright E2E testing patterns (POM, flaky tests, CI/CD)
├── verification-loop/ # Comprehensive verification (build, typecheck, lint, test, security)
├── security-review/ # OWASP Top 10 + ADR compliance checklist
└── speckit-*/ # 18 workflow skills (spec → plan → tasks → implement → …)
```
Each skill directory contains:
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.8.9`, `scope`, `depends-on`, `handoffs`) + instructions
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.9.0`, `scope`, `depends-on`, `handoffs`) + instructions
- `templates/` _(optional)_ — artifact templates (spec/plan/tasks/checklist)
- `rules/` _(nestjs only)_ — individual rule files grouped by prefix (`arch-`, `security-`, `db-`, etc.)
---
## 🚀 How Windsurf Invokes These Skills
## 🚀 How Devin Invokes These Skills
Windsurf exposes two entry points:
1. **Skill tool** — Windsurf discovers skills by scanning `.agents/skills/*/SKILL.md` frontmatter. Skills marked `user-invocable: false` are used silently by Cascade.
2. **Slash commands**`.windsurf/workflows/*.md` wraps each skill as a slash command (e.g. `/04-speckit.plan`). The workflow file is short; the heavy lifting is delegated to the skill via `skill` tool.
1. **Skill tool** — Devin discovers skills by scanning `.agents/skills/*/SKILL.md` frontmatter. Skills marked `user-invocable: false` are used silently by Cascade.
2. **Slash commands**`.devin/workflows/*.md` wraps each skill as a slash command (e.g. `/04-speckit.plan`). The workflow file is short; the heavy lifting is delegated to the skill via `skill` tool.
Both paths end up executing the same `SKILL.md` instructions.
@@ -62,14 +64,14 @@ Use `/00-speckit.all` to run specify → clarify → plan → tasks → analyze
From repo root:
| Script | Purpose |
| --- | --- |
| Script | Purpose |
| ------------------------------------------------------ | ---------------------------------------------------------- |
| `./.agents/scripts/bash/check-prerequisites.sh --json` | Emit `FEATURE_DIR` + `AVAILABLE_DOCS` for a feature branch |
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
| `./.agents/scripts/bash/update-agent-context.sh windsurf` | Append tech entries to `AGENTS.md` |
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.windsurf/workflows/*.md` wrapper |
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
| `./.agents/scripts/bash/update-agent-context.sh devin` | Append tech entries to `AGENTS.md` |
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.devin/workflows/*.md` wrapper |
All scripts mirror to `.agents/scripts/powershell/*.ps1` for Windows.
@@ -92,9 +94,9 @@ See [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md) for the complete list.
To add a new skill:
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.8.9`, `scope`, `depends-on`.
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.9.0`, `scope`, `depends-on`.
2. Append an LCBP3 context reference pointing to `_LCBP3-CONTEXT.md`.
3. Wrap with `.windsurf/workflows/NAME.md` so it becomes a slash command.
3. Wrap with `.devin/workflows/NAME.md` so it becomes a slash command.
4. Update [`skills.md`](./skills.md) dependency matrix.
5. Run `./.agents/scripts/bash/audit-skills.sh` → must pass.
+98
View File
@@ -0,0 +1,98 @@
# 🧭 LCBP3-DMS Context Appendix (Shared)
> This file is included/referenced by every Speckit skill as the authoritative project context.
> Skills **must** load it (or the files it links to) before generating any artifact.
**Project:** NAP-DMS (LCBP3) — Laem Chabang Port Phase 3 Document Management System
**Stack:** NestJS 11 + Next.js 16 + TypeScript + MariaDB 11.8 + Redis + BullMQ + Elasticsearch + Ollama (on-prem AI)
**Version:** 1.9.7 (2026-05-25)
---
## 📌 Canonical Rule Sources (read in this order)
1. **`AGENTS.md`** (repo root) — primary rule file for AI agents; supersedes legacy `GEMINI.md`.
2. **`specs/06-Decision-Records/`** — architectural decisions (29 ADRs); ADR priority > Engineering Guidelines.
3. **`specs/05-Engineering-Guidelines/`** — backend/frontend/testing/i18n/git patterns.
4. **`specs/00-Overview/00-02-glossary.md`** — domain terminology (Correspondence / RFA / Transmittal / Circulation).
5. **`specs/00-Overview/00-03-product-vision.md`** — project constitution (Vision, Strategic Pillars, Guardrails).
6. **`CONTRIBUTING.md`** — spec writing standards, PR template, review levels.
7. **`README.md`** — technology stack + getting started.
---
## 🔴 Tier 1 Non-Negotiables
- **ADR-019 UUID:** `publicId: string` exposed directly — **no** `@Expose({ name: 'id' })` rename; **no** `parseInt`/`Number`/`+` on UUID; **no** `id ?? ''` fallback in frontend.
- **ADR-009:** No TypeORM migrations — edit `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` or add a `deltas/*.sql` file.
- **ADR-016 Security:** JWT + CASL 4-Level RBAC; `@UseGuards(JwtAuthGuard, CaslAbilityGuard)` on every mutation controller; `ThrottlerGuard` on auth; bcrypt 12 rounds; `Idempotency-Key` required on POST/PUT/PATCH.
- **ADR-002 Document Numbering:** Redis Redlock + TypeORM `@VersionColumn` (double-lock). Never use application-side counter alone.
- **ADR-008 Notifications:** BullMQ queue — never inline email/notification in a request thread.
- **ADR-023/023A AI Boundary:** Ollama on Admin Desktop only; AI → DMS API → DB (never direct DB/storage). 2-model stack: `gemma4:e4b Q8_0` + `nomic-embed-text`. BullMQ `ai-realtime` / `ai-batch` queues. Human-in-the-loop validation required. (ADR-018 superseded by ADR-023)
- **ADR-029 Dynamic Prompt Management:** Prompt templates in DB (`ai_prompts`), never hardcoded in processor; Redis cache `ai:prompt:active:{type}` TTL 60s; `activate()` runs in DB transaction + Redis DEL after commit; `system.manage_all` guard on all mutations.
- **ADR-007 Error Handling:** Layered (Validation / Business / System); `BusinessException` hierarchy; user-friendly `userMessage` + `recoveryAction`; technical stack only in logs.
- **TypeScript Strict:** Zero `any`, zero `console.log` (use NestJS `Logger`).
- **i18n:** No hardcoded Thai/English strings in components — use i18n keys (see `05-08-i18n-guidelines.md`).
- **File Upload:** Two-phase (Temp → ClamAV → Permanent), whitelist `PDF/DWG/DOCX/XLSX/ZIP`, max 50MB, `StorageService` only.
---
## 🏷️ Domain Glossary (reject generic terms)
| ✅ Use | ❌ Don't Use |
| ------------------ | ------------------------------------- |
| Correspondence | Letter, Communication, Document |
| RFA | Approval Request, Submit for Approval |
| Transmittal | Delivery Note, Cover Letter |
| Circulation | Distribution, Routing |
| Shop Drawing | Construction Drawing |
| Contract Drawing | Design Drawing, Blueprint |
| Workflow Engine | Approval Flow, Process Engine |
| Document Numbering | Document ID, Auto Number |
---
## 📁 Key Files for Generating / Validating Artifacts
| When you need... | Read |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| A new feature spec | `.agents/skills/speckit-specify/templates/spec-template.md` + `specs/01-Requirements/01-06-edge-cases-and-rules.md` |
| A plan | `.agents/skills/speckit-plan/templates/plan-template.md` + relevant ADRs |
| Task breakdown | `.agents/skills/speckit-tasks/templates/tasks-template.md` + existing patterns in `specs/08-Tasks/` |
| Acceptance criteria / UAT | `specs/01-Requirements/01-05-acceptance-criteria.md` |
| Schema / table definition | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` + `03-01-data-dictionary.md` |
| RBAC / permissions | `specs/03-Data-and-Storage/lcbp3-v1.8.0-seed-permissions.sql` + `01-02-01-rbac-matrix.md` |
| Release / hotfix | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` |
| ADR-024 Intent Class. | `specs/06-Decision-Records/ADR-024-intent-classification-strategy.md` |
| ADR-025 AI Tool Layer | `specs/06-Decision-Records/ADR-025-ai-tool-layer-architecture.md` |
| ADR-026 Chat UI | `specs/06-Decision-Records/ADR-026-document-chat-ui-pattern.md` |
| ADR-027 AI Admin Console | `specs/06-Decision-Records/ADR-027-ai-admin-console-and-dynamic-control.md` |
| ADR-028 Migration Refactor | `specs/06-Decision-Records/ADR-028-migration-architecture-refactor.md` |
| ADR-029 Dynamic Prompts | `specs/06-Decision-Records/ADR-029-dynamic-prompt-management.md` |
---
## 🛠️ Helper Scripts (real paths in this repo)
- `./.agents/scripts/bash/check-prerequisites.sh` / `powershell/*.ps1`
- `./.agents/scripts/bash/setup-plan.sh`
- `./.agents/scripts/bash/update-agent-context.sh windsurf`
- `./.agents/scripts/bash/audit-skills.sh`
- `./.agents/scripts/bash/validate-versions.sh`
- `./.agents/scripts/bash/sync-workflows.sh`
---
## ✅ Commit Checklist (applied automatically by speckit-implement)
- [ ] UUID pattern verified (no `parseInt` / `Number` / `+` on UUID, no `id ?? ''` fallback)
- [ ] No `any`, no `console.log` in committed code
- [ ] Business comments in Thai, code identifiers in English
- [ ] Schema changes via SQL directly (not migration)
- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+)
- [ ] Relevant ADRs referenced (007/008/009/016/019/021/023/023A/024-029 for AI work)
- [ ] Domain glossary terms used correctly
- [ ] Error handling: `Logger` + `HttpException` / `BusinessException`
- [ ] i18n keys used (no hardcode text)
- [ ] Cache invalidation when data mutated
- [ ] OWASP Top 10 review passed
+354
View File
@@ -0,0 +1,354 @@
---
name: e2e-testing
description: Playwright E2E testing patterns, Page Object Model, configuration, CI/CD integration, artifact management, and flaky test strategies for LCBP3-DMS.
version: 1.9.0
scope: testing
depends-on: []
handoffs-to: [speckit-tester]
user-invocable: true
---
# E2E Testing Skill
Playwright E2E testing patterns adapted for LCBP3-DMS (NestJS + Next.js + MariaDB stack).
## LCBP3 Context
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific testing requirements:
- Backend: Jest (Unit + Integration + E2E)
- Frontend: Vitest (Unit) + Playwright (E2E)
- E2E test location: `frontend/e2e/workflow-adr021.spec.ts`
- Coverage goals: Backend 70%+, Business Logic 80%+
## When to Use
Invoke this skill when:
- Creating new E2E tests for frontend features
- Debugging flaky Playwright tests
- Setting up CI/CD integration for E2E tests
- Optimizing test performance and reliability
- Implementing Page Object Model (POM) patterns
## Test File Organization
```
frontend/
├── e2e/
│ ├── auth/
│ │ ├── login.spec.ts
│ │ └── logout.spec.ts
│ ├── correspondence/
│ │ ├── create.spec.ts
│ │ └── workflow.spec.ts
│ ├── transmittals/
│ │ ├── create.spec.ts
│ │ └── submit.spec.ts
│ ├── circulation/
│ │ ├── routing.spec.ts
│ │ └── approval.spec.ts
│ └── workflow-adr021.spec.ts # Existing ADR-021 integration test
├── playwright.config.ts
└── tests/
└── fixtures/
├── auth.ts
└── data.ts
```
## Page Object Model (POM)
```typescript
// frontend/e2e/pages/CorrespondencePage.ts
import { Page, Locator } from '@playwright/test'
export class CorrespondencePage {
readonly page: Page
readonly createButton: Locator
readonly subjectInput: Locator
readonly recipientSelect: Locator
readonly submitButton: Locator
readonly successMessage: Locator
constructor(page: Page) {
this.page = page
this.createButton = page.getByTestId('create-correspondence')
this.subjectInput = page.getByTestId('subject-input')
this.recipientSelect = page.getByTestId('recipient-select')
this.submitButton = page.getByTestId('submit-button')
this.successMessage = page.getByTestId('success-message')
}
async goto() {
await this.page.goto('/admin/doc-control/correspondences')
await this.page.waitForLoadState('networkidle')
}
async createCorrespondence(data: {
subject: string
recipientId: string
}) {
await this.createButton.click()
await this.subjectInput.fill(data.subject)
await this.recipientSelect.selectOption(data.recipientId)
await this.submitButton.click()
}
async verifySuccess() {
await expect(this.successMessage).toBeVisible()
}
}
```
## Test Structure
```typescript
// frontend/e2e/correspondence/create.spec.ts
import { test, expect } from '@playwright/test'
import { CorrespondencePage } from '../pages/CorrespondencePage'
test.describe('Correspondence Creation', () => {
let correspondencePage: CorrespondencePage
test.beforeEach(async ({ page }) => {
correspondencePage = new CorrespondencePage(page)
await correspondencePage.goto()
})
test('should create correspondence successfully', async ({ page }) => {
await correspondencePage.createCorrespondence({
subject: 'Test Correspondence',
recipientId: 'test-recipient-id'
})
await correspondencePage.verifySuccess()
await page.screenshot({ path: 'artifacts/correspondence-created.png' })
})
test('should validate required fields', async ({ page }) => {
await correspondencePage.createButton.click()
await correspondencePage.submitButton.click()
await expect(page.getByTestId('subject-error')).toBeVisible()
await expect(page.getByTestId('recipient-error')).toBeVisible()
})
})
```
## Playwright Configuration
```typescript
// frontend/playwright.config.ts
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
['html', { outputFolder: 'playwright-report' }],
['junit', { outputFile: 'playwright-results.xml' }],
['json', { outputFile: 'playwright-results.json' }]
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
actionTimeout: 10000,
navigationTimeout: 30000,
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
],
webServer: {
command: 'pnpm dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120000,
},
})
```
## Flaky Test Patterns
### Quarantine
```typescript
test('flaky: complex workflow', async ({ page }) => {
test.fixme(true, 'Flaky - Issue #123')
// test code...
})
test('conditional skip', async ({ page }) => {
test.skip(process.env.CI, 'Flaky in CI - Issue #123')
// test code...
})
```
### Identify Flakiness
```bash
cd frontend
npx playwright test e2e/correspondence/create.spec.ts --repeat-each=10
npx playwright test e2e/correspondence/create.spec.ts --retries=3
```
### Common Causes & Fixes
**Race conditions:**
```typescript
// Bad: assumes element is ready
await page.click('[data-testid="submit-button"]')
// Good: auto-wait locator
await page.locator('[data-testid="submit-button"]').click()
```
**Network timing:**
```typescript
// Bad: arbitrary timeout
await page.waitForTimeout(5000)
// Good: wait for specific condition
await page.waitForResponse(resp =>
resp.url().includes('/api/correspondences') && resp.status() === 201
)
```
**Animation timing:**
```typescript
// Bad: click during animation
await page.click('[data-testid="menu-item"]')
// Good: wait for stability
await page.locator('[data-testid="menu-item"]').waitFor({ state: 'visible' })
await page.waitForLoadState('networkidle')
await page.locator('[data-testid="menu-item"]').click()
```
## Artifact Management
### Screenshots
```typescript
await page.screenshot({ path: 'artifacts/after-login.png' })
await page.screenshot({ path: 'artifacts/full-page.png', fullPage: true })
await page.locator('[data-testid="workflow-banner"]').screenshot({
path: 'artifacts/workflow-banner.png'
})
```
### Traces
```typescript
// In playwright.config.ts
use: {
trace: 'on-first-retry'
}
// View trace
npx playwright show-trace trace.zip
```
### Video
```typescript
// In playwright.config.ts
use: {
video: 'retain-on-failure',
videosPath: 'artifacts/videos/'
}
```
## CI/CD Integration
```yaml
# .github/workflows/e2e.yml
name: E2E Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: pnpm install
- run: cd frontend && npx playwright install --with-deps
- run: cd frontend && npx playwright test
env:
BASE_URL: ${{ vars.STAGING_URL }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: frontend/playwright-report/
retention-days: 30
```
## Test Report Template
```markdown
# E2E Test Report
**Date:** YYYY-MM-DD HH:MM
**Duration:** Xm Ys
**Status:** PASSING / FAILING
## Summary
- Total: X | Passed: Y (Z%) | Failed: A | Flaky: B | Skipped: C
## Failed Tests
### correspondence-create
**File:** `frontend/e2e/correspondence/create.spec.ts:45`
**Error:** Expected element to be visible
**Screenshot:** artifacts/failed.png
**Recommended Fix:** Add waitForLoadState after form submission
## Artifacts
- HTML Report: frontend/playwright-report/index.html
- Screenshots: frontend/artifacts/*.png
- Videos: frontend/artifacts/videos/*.webm
- Traces: frontend/artifacts/*.zip
```
## Critical Flow Testing
```typescript
// frontend/e2e/workflow/adr021.spec.ts
test('workflow: correspondence → rfa → approval', async ({ page }) => {
// Create correspondence
await createCorrespondence(page)
await expect(page.getByTestId('correspondence-created')).toBeVisible()
// Submit for RFA
await page.getByTestId('submit-rfa').click()
await expect(page.getByTestId('rfa-submitted')).toBeVisible()
// Approve RFA
await page.goto('/admin/doc-control/rfa/123')
await page.getByTestId('approve-button').click()
await expect(page.getByTestId('approval-success')).toBeVisible()
// Verify workflow state
await expect(page.getByTestId('workflow-state')).toContainText('APPROVED')
})
```
## LCBP3-Specific Considerations
- **UUID Handling:** Use `publicId` (string UUID) in E2E tests, never `parseInt()` (ADR-019)
- **Authentication:** Mock auth tokens for E2E tests to avoid real auth flows
- **Workflow States:** Test ADR-021 workflow transitions (DRAFT → PENDING → APPROVED)
- **i18n:** Test with Thai language to verify i18n key resolution
- **RBAC:** Test different user roles (admin, user, reviewer) for permission checks
## References
- LCBP3 Testing Strategy: `specs/05-Engineering-Guidelines/05-04-testing-strategy.md`
- ADR-021 Workflow Context: `specs/06-Decision-Records/ADR-021-workflow-context.md`
- Existing E2E test: `frontend/e2e/workflow-adr021.spec.ts`
@@ -6454,7 +6454,7 @@ CREATE TABLE ai_audit_log (
user_id INT NOT NULL,
action VARCHAR(64) NOT NULL, -- 'ai.extract_metadata', 'ai.classify', etc.
file_id INT,
model VARCHAR(64), -- 'gemma-4:7b', 'paddleocr-v3'
model VARCHAR(64), -- 'gemma-4:7b', 'typhoon-np-dms-ocr', 'tesseract-ocr'
confidence DECIMAL(4,3),
input_hash CHAR(64), -- SHA-256 of input for replay detection
output_summary JSON,
@@ -126,7 +126,7 @@ These rules override general NestJS best practices for the NAP-DMS project:
### ADR-009: No TypeORM Migrations
- **ห้ามสร้างไฟล์ migration ของ TypeORM**
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql`
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
- ใช้ n8n workflow สำหรับ data migration ถ้าจำเป็น
### ADR-019: Hybrid Identifier Strategy (CRITICAL — March 2026 Pattern)
@@ -137,7 +137,7 @@ CREATE TABLE ai_audit_log (
user_id INT NOT NULL,
action VARCHAR(64) NOT NULL, -- 'ai.extract_metadata', 'ai.classify', etc.
file_id INT,
model VARCHAR(64), -- 'gemma-4:7b', 'paddleocr-v3'
model VARCHAR(64), -- 'gemma-4:7b', 'typhoon-np-dms-ocr', 'tesseract-ocr'
confidence DECIMAL(4,3),
input_hash CHAR(64), -- SHA-256 of input for replay detection
output_summary JSON,

Some files were not shown because too many files have changed in this diff Show More