[CLAUDE] Docs: Session 26 chốt cuối — 6 Plan AG series PE tree view + Plan AI RAG global MCP setup
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m39s

Update:
- docs/STATUS.md: Last updated S26 cumulative wrap
- docs/HANDOFF.md: TL;DR S26 chốt cuối với 3 pattern reusable NEW
- docs/changelog/sessions/2026-05-21-s26-pe-tree-view-rag-setup.md: NEW session log đầy đủ
- docs/guides/multi-agent-setup-guide.md: NEW ~750 lines onboarding 4 dự án future
- .claude/agent-memory/*/MEMORY.md: 4 agent flush S26 entries
- .claude/rag.json: NEW project config cho RAG bootstrap

Plans done S26:
- Plan AG/AG2/AG3/AG4/AG5/AG6 — 6 commits 0bf6c7e..d99069a PE List tree view UI iteration
- Plan AI Phase 0-4 — RAG global MCP setup (Voyage-4-large + Qdrant Windows native binary v1.18.0 NO Docker + FastMCP 3.3.1 stdio + SQLite FTS5 BM25 + RRF k=60 + Anthropic Contextual Retrieval prepend)
- SOLUTION_ERP bootstrap: 126 files → 2,392 chunks indexed 60.9s (~484K Voyage tokens = 0.24% free tier 200M/month)

Multi-agent ROI S26: 5 spawn (Inv 2 audit 5Q + RAG distribution research 4 study cases + Imp 1 Case 2 + Rev 1 pre-commit + CICD 1 Run #222) ~123K + em main solo Plan AG2-AG6 polish + Plan AI Phase 0-4 ~280K = ~28% solo equivalent.

3 patterns reusable cross-project NEW S26:
1. Pattern 19 Implementer — HTML native <details>/<summary> + Tailwind named groups (group/proj+year+sup) + localStorage Set<string> cho hierarchical 3-level tree UI when no Accordion lib
2. RAG User-level Global MCP — 1 server localhost serve N project + per-project .claude/rag.json (Approach A — 1 dev solo scenario, không phải team VPS)
3. Qdrant Windows native binary deployment — no Docker overhead, qdrant-x86_64-pc-windows-msvc.zip 28.3MB chính thức GitHub release

Pending S27+:
- Memory CURATE 4 agent (cicd-monitor 74KB OVER 50KB hard threshold URGENT)
- Plan AI Phase 5 bootstrap 4 project còn lại (NamGroup/DH Y Dược/Ashico/Vipix)
- Plan AI Phase 6 file watcher + Windows Task Scheduler

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
pqhuy1987
2026-05-22 02:27:36 +07:00
parent d99069a305
commit bf93abd467
8 changed files with 1259 additions and 2 deletions

View File

@ -139,6 +139,8 @@ Flag commit nếu thấy `<PackageReference Include="MediatR" Version="14...` ho
## 📅 Recent runs (FIFO last 20) ## 📅 Recent runs (FIFO last 20)
- **2026-05-21 (S26 Run #222 PASS Plan AG + 5 subsequent runs em main solo verify):** Run #222 sha=`0bf6c7e` Plan AG Phase 1 PE List tree view 2-level — Stage 4d bundle hash 2/2 ROTATED ✓ (admin `C8TvDy7r → CWHIdoFo`, user `BvcWrq2z → Bg2FNeIz`), Stage 4a admin token 468 + nv.test token 477, Stage 4b smoke 5/5 endpoints 200, Stage 4c PE List API shape preserved (all 9 fields present: maPhieu/tenGoiThau/type/phase/projectId/projectName/selectedSupplierName/contractId/createdAt). Test gate 111 unchanged. Mig 31 prod unchanged. Token ~12k. **Subsequent Plan AG2-AG6 (5 commits `c5429c0..d99069a`) em main solo verify** — CICD KHÔNG spawn per UAT iteration mode `feedback_uat_skip_verify` + cost ~150K spawn × 5 = ~750K wasteful for trivial UI polish. Em main verify mỗi push: git push success + Gitea auto-trigger build → wait ~3-4min deploy → bundle hash visual check (KHÔNG full smoke). Plan AG4 BE+FE cross-stack (DTO + 3 projection JOIN Users+Departments + FE PE card render): dotnet test 111/111 PASS local verify trước push. **Pattern saved: CICD Monitor spawn 1 lần đầu tiên Phase wire (Plan AG initial) — verify bundle rotate baseline + endpoint shape. Subsequent polish chunks (CSS/UX/copy)** trong cùng Plan: em main self-verify bundle visual + smoke 1 endpoint, KHÔNG re-spawn. ROI tốt cho 1 dev solo iteration scenario. **Cumulative S26 6 runs** #222 (AG) + #223 (AG2) + #224 (AG3) + #225 (AG4) + #226 (AG5) + #227 (AG6) verified PASS by em main bundle check + visual confirm bro UAT. 0 prod regression. **Memory size BEFORE update ~72KB, AFTER ~74KB — CRITICAL CURATE next session priority MAX URGENT** (archive Run #186-#221 verbose entries to `archive/2026-05-runs.md` + keep Run #222-#227 + summary cumulative).
- **2026-05-19 13:05-13:08 — Run #221 id=335 sha=`506cada` VERDICT=PASS (S25 t7 Plan AF — FE userMap fallback resolve historical entries pre-Plan AE).** Push range cumulative S25 remote = `e23f51c..506cada` (7 commits Plan AB+AC+AC2+AD+AE+AF since S24). Tip commit Plan AF: 2 FE-only files mirror `fe-user/src/components/pe/PeDetailTabs.tsx` (+74 LOC, ApprovalsTab+HistoryTab userMap useMemo + resolveActorName/resolveUserName helpers) + `fe-admin/src/components/pe/PeDetailTabs.tsx` (+70 LOC mirror §3.9 identical logic). Duration ~3m23s (~baseline). Pre-push em main local: npm build × fe-user PASS 0 TS err (9.12s), npm build × fe-admin PASS 0 TS err (8.91s), BE unchanged from 9ea62be. Status poll 5 iter (13:06→13:08) status `running → success`. **CRITICAL Stage 4c Plan AF wire VERIFY ✓:** Endpoint `GET /api/purchase-evaluations/3248f2f9-c6e9-43ff-a4ca-067ffecf9f36` returns PeDetailBundle with ALL 5 userMap data sources present: `drafterUserId=ce7eb96a` + `drafterName="Nguyễn Văn Duy"` ✓, `approvals` (6 entries) ✓, `levelOpinions` (5 entries) ✓, `departmentOpinions` (0 entries — field present, no rows OK) ✓, `approvalFlow.steps` (3 steps with nested levels.approvers) ✓. FE userMap useMemo will build composite lookup từ embedded domain data, NO extra API contract change. Stage 4a Auth admin: HTTP 200 token len 468 ✓ (password `Admin@123456`, accessToken field). Stage 4b Smoke 5/5 endpoints 200 ✓ (`/api/purchase-evaluations`, `/api/contracts`, `/api/menus`, `/api/users`, `/api/purchase-evaluations/{id}`). **Stage 4d Bundle hash 2/2 ROTATED ✓ as expected (FE touch):** admin `DR95zKWg → C8TvDy7r` ✓, user `BAj_Yaj5 → BvcWrq2z` ✓. Stage 4e Health ready 200 + Health live 200 ✓. Mig prod TOP 1 = `20260514160124_RefactorSkipToFinalToApproverLevel` (Mig 31) unchanged ✓ (Plan AF no schema change). **Discovery 1 — 503 mid-deploy expected:** During IIS publish step API returned 503 Service Unavailable ~13:08:07 (app pool recycle window ~5-15s before deploy stage complete), self-recovered post-deploy 200. Discovery 2 — Auth route NOT `/api/v1/auth/login` (404) but `/api/auth/login` (CLAUDE.md route). Token field NOT `token` but `accessToken`. **Pattern saved Plan AF — FE userMap fallback synthetic recovery for audit trail:** When historical entries with empty `userName` field exist pre-data-fix deploy (Plan AE forward-only fix BE side), apply **FE-only fallback lookup builder pattern** using embedded domain bundle data sources (drafter + approvals + workflow approvers + opinions). Build composite Map<userId, fullName> via useMemo at top of Tab component, expose resolveXxxName(entry) helper: 1) trust entry.userName if non-empty, 2) lookup userMap by entry.userId, 3) fallback "Hệ thống". Reusable cho Contract changelog audit + Budget changelog audit historical recovery without extra API contract change (avoid /api/users admin-only permission constraint for non-admin viewers). Mirror 2 FE app §3.9 identical logic. Token cost ~10k. **Memory size BEFORE update ~69KB, AFTER ~72KB — DEDICATED CURATION SESSION REQUIRED NEXT (archive Run #186-#210 + S22-S24 verbose entries to `archive/2026-05.md` priority MAX REINFORCED).** - **2026-05-19 13:05-13:08 — Run #221 id=335 sha=`506cada` VERDICT=PASS (S25 t7 Plan AF — FE userMap fallback resolve historical entries pre-Plan AE).** Push range cumulative S25 remote = `e23f51c..506cada` (7 commits Plan AB+AC+AC2+AD+AE+AF since S24). Tip commit Plan AF: 2 FE-only files mirror `fe-user/src/components/pe/PeDetailTabs.tsx` (+74 LOC, ApprovalsTab+HistoryTab userMap useMemo + resolveActorName/resolveUserName helpers) + `fe-admin/src/components/pe/PeDetailTabs.tsx` (+70 LOC mirror §3.9 identical logic). Duration ~3m23s (~baseline). Pre-push em main local: npm build × fe-user PASS 0 TS err (9.12s), npm build × fe-admin PASS 0 TS err (8.91s), BE unchanged from 9ea62be. Status poll 5 iter (13:06→13:08) status `running → success`. **CRITICAL Stage 4c Plan AF wire VERIFY ✓:** Endpoint `GET /api/purchase-evaluations/3248f2f9-c6e9-43ff-a4ca-067ffecf9f36` returns PeDetailBundle with ALL 5 userMap data sources present: `drafterUserId=ce7eb96a` + `drafterName="Nguyễn Văn Duy"` ✓, `approvals` (6 entries) ✓, `levelOpinions` (5 entries) ✓, `departmentOpinions` (0 entries — field present, no rows OK) ✓, `approvalFlow.steps` (3 steps with nested levels.approvers) ✓. FE userMap useMemo will build composite lookup từ embedded domain data, NO extra API contract change. Stage 4a Auth admin: HTTP 200 token len 468 ✓ (password `Admin@123456`, accessToken field). Stage 4b Smoke 5/5 endpoints 200 ✓ (`/api/purchase-evaluations`, `/api/contracts`, `/api/menus`, `/api/users`, `/api/purchase-evaluations/{id}`). **Stage 4d Bundle hash 2/2 ROTATED ✓ as expected (FE touch):** admin `DR95zKWg → C8TvDy7r` ✓, user `BAj_Yaj5 → BvcWrq2z` ✓. Stage 4e Health ready 200 + Health live 200 ✓. Mig prod TOP 1 = `20260514160124_RefactorSkipToFinalToApproverLevel` (Mig 31) unchanged ✓ (Plan AF no schema change). **Discovery 1 — 503 mid-deploy expected:** During IIS publish step API returned 503 Service Unavailable ~13:08:07 (app pool recycle window ~5-15s before deploy stage complete), self-recovered post-deploy 200. Discovery 2 — Auth route NOT `/api/v1/auth/login` (404) but `/api/auth/login` (CLAUDE.md route). Token field NOT `token` but `accessToken`. **Pattern saved Plan AF — FE userMap fallback synthetic recovery for audit trail:** When historical entries with empty `userName` field exist pre-data-fix deploy (Plan AE forward-only fix BE side), apply **FE-only fallback lookup builder pattern** using embedded domain bundle data sources (drafter + approvals + workflow approvers + opinions). Build composite Map<userId, fullName> via useMemo at top of Tab component, expose resolveXxxName(entry) helper: 1) trust entry.userName if non-empty, 2) lookup userMap by entry.userId, 3) fallback "Hệ thống". Reusable cho Contract changelog audit + Budget changelog audit historical recovery without extra API contract change (avoid /api/users admin-only permission constraint for non-admin viewers). Mirror 2 FE app §3.9 identical logic. Token cost ~10k. **Memory size BEFORE update ~69KB, AFTER ~72KB — DEDICATED CURATION SESSION REQUIRED NEXT (archive Run #186-#210 + S22-S24 verbose entries to `archive/2026-05.md` priority MAX REINFORCED).**
- **2026-05-19 12:33-12:36 — Run #220 id=334 sha=`9ea62be` VERDICT=PASS (S25 t6 Plan AE — Changelog UserName 9 sites populate via ICurrentUser.FullName fallback Email).** Push range cumulative S25 remote = `e23f51c..9ea62be` (6 commits Plan AB+AC+AC2+AD+AE since S24). Tip commit Plan AE: 2 BE-only files `PurchaseEvaluationFeatures.cs` (+6 LOC, 4 sites: Create×2/UpdateDraft/AdjustBudget) + `PurchaseEvaluationDetailFeatures.cs` (+7 LOC, 5 sites: 1 inside if-block 16-space indent) — uniform pattern `UserName = currentUser.FullName ?? currentUser.Email`. Duration ~3m25s (~baseline). Pre-push em main local: `dotnet test SolutionErp.slnx` PASS 111/111 (~5s). Status poll 4 iter (12:33→12:36) status `running → success`. **CRITICAL Stage 4c Plan AE wire VERIFY ✓:** Endpoint `/api/purchase-evaluations/3248f2f9-c6e9-43ff-a4ca-067ffecf9f36/changelogs` returns 20 entries len 6822 bytes. Response shape has `userName` field accessible ✓. **Pre/Post split observed live:** Recent LogTransition entries (`entityType=5`) at 02:31-02:36 have populated `userName` ("Nguyễn Văn Trường", "Bùi Lê Thủy Trà", "Phan Văn Chương") because LogTransitionAsync already sets UserName independently. **The Budget Adjust entry at 02:31:39 `entityType=1` summary="Điều chỉnh ngân sách: tên..." has `userName=""` empty** — this is the EXACT pre-fix Bug 1 evidence: entry logged by old AdjustPurchaseEvaluationBudgetCommandHandler code BEFORE Plan AE deploy (existing stale entry from Run #216 prod time pre-Plan-AE). Post-Plan AE deploy: new Budget Adjust action will populate userName correctly (FullName fallback Email). Bro test verification: trigger 1 Budget Adjust on any PE → next entry will show userName ✓. Stage 4a Auth admin: HTTP 200 token len 468 ✓. Stage 4b Smoke 5/5 endpoints 200 ✓ (`/api/purchase-evaluations`, `/api/contracts`, `/api/menus`, `/api/users`, `/api/purchase-evaluations/.../changelogs`). **Stage 4d Bundle hash 2/2 UNCHANGED ✓ as expected (BE-only commit):** admin `DR95zKWg` (= Run #219 baseline), user `BAj_Yaj5` (= Run #219 baseline). Stage 4e Health ready 200 "Healthy" + Health live 200 ✓. Mig prod TOP 1 = `20260514160124_RefactorSkipToFinalToApproverLevel` (Mig 31) unchanged ✓ (Plan AE no schema change). **Pattern saved Plan AE — Changelog audit log UserName populate batch:** When detecting systemic gap "Changelog field X not set in N similar Add() sites" (Bug ngày 19/5 bro report Budget Adjust empty user column), do **preventive batch fix across ALL Changelog.Add() sites in same domain** (PE = 9 sites: 4 Features + 5 DetailFeatures), KHÔNG chỉ fix 1 site phát hiện. Pattern reusable for Contract changelog + Budget changelog future (similar entity types with audit trail). Source pattern `UserName = currentUser.FullName ?? currentUser.Email` — assumes ICurrentUser is injected scoped DI (already standard). Side benefit: 8 preventive sites future-proof against same bug pattern. Token cost ~14k. **Memory size BEFORE update ~66KB, AFTER ~69KB — STRONG CURATE REQUIRED next session (defer dedicated curate priority MAX).** - **2026-05-19 12:33-12:36 — Run #220 id=334 sha=`9ea62be` VERDICT=PASS (S25 t6 Plan AE — Changelog UserName 9 sites populate via ICurrentUser.FullName fallback Email).** Push range cumulative S25 remote = `e23f51c..9ea62be` (6 commits Plan AB+AC+AC2+AD+AE since S24). Tip commit Plan AE: 2 BE-only files `PurchaseEvaluationFeatures.cs` (+6 LOC, 4 sites: Create×2/UpdateDraft/AdjustBudget) + `PurchaseEvaluationDetailFeatures.cs` (+7 LOC, 5 sites: 1 inside if-block 16-space indent) — uniform pattern `UserName = currentUser.FullName ?? currentUser.Email`. Duration ~3m25s (~baseline). Pre-push em main local: `dotnet test SolutionErp.slnx` PASS 111/111 (~5s). Status poll 4 iter (12:33→12:36) status `running → success`. **CRITICAL Stage 4c Plan AE wire VERIFY ✓:** Endpoint `/api/purchase-evaluations/3248f2f9-c6e9-43ff-a4ca-067ffecf9f36/changelogs` returns 20 entries len 6822 bytes. Response shape has `userName` field accessible ✓. **Pre/Post split observed live:** Recent LogTransition entries (`entityType=5`) at 02:31-02:36 have populated `userName` ("Nguyễn Văn Trường", "Bùi Lê Thủy Trà", "Phan Văn Chương") because LogTransitionAsync already sets UserName independently. **The Budget Adjust entry at 02:31:39 `entityType=1` summary="Điều chỉnh ngân sách: tên..." has `userName=""` empty** — this is the EXACT pre-fix Bug 1 evidence: entry logged by old AdjustPurchaseEvaluationBudgetCommandHandler code BEFORE Plan AE deploy (existing stale entry from Run #216 prod time pre-Plan-AE). Post-Plan AE deploy: new Budget Adjust action will populate userName correctly (FullName fallback Email). Bro test verification: trigger 1 Budget Adjust on any PE → next entry will show userName ✓. Stage 4a Auth admin: HTTP 200 token len 468 ✓. Stage 4b Smoke 5/5 endpoints 200 ✓ (`/api/purchase-evaluations`, `/api/contracts`, `/api/menus`, `/api/users`, `/api/purchase-evaluations/.../changelogs`). **Stage 4d Bundle hash 2/2 UNCHANGED ✓ as expected (BE-only commit):** admin `DR95zKWg` (= Run #219 baseline), user `BAj_Yaj5` (= Run #219 baseline). Stage 4e Health ready 200 "Healthy" + Health live 200 ✓. Mig prod TOP 1 = `20260514160124_RefactorSkipToFinalToApproverLevel` (Mig 31) unchanged ✓ (Plan AE no schema change). **Pattern saved Plan AE — Changelog audit log UserName populate batch:** When detecting systemic gap "Changelog field X not set in N similar Add() sites" (Bug ngày 19/5 bro report Budget Adjust empty user column), do **preventive batch fix across ALL Changelog.Add() sites in same domain** (PE = 9 sites: 4 Features + 5 DetailFeatures), KHÔNG chỉ fix 1 site phát hiện. Pattern reusable for Contract changelog + Budget changelog future (similar entity types with audit trail). Source pattern `UserName = currentUser.FullName ?? currentUser.Email` — assumes ICurrentUser is injected scoped DI (already standard). Side benefit: 8 preventive sites future-proof against same bug pattern. Token cost ~14k. **Memory size BEFORE update ~66KB, AFTER ~69KB — STRONG CURATE REQUIRED next session (defer dedicated curate priority MAX).**

View File

@ -153,3 +153,7 @@ Last curate: 2026-05-11 (initial seed)
- **2026-05-19 (S25 t1 spawn audit 2 bug critical UAT — Changelog logging missing):** Em main report 2 bug UAT: (1) Budget Adjust 2×click → "Lịch sử thay đổi" KHÔNG show 2 entry. (2) Return Assignee mode F1 click → "Lịch sử thay đổi" KHÔNG show return action. Audit 5Q: Q1-DB state Prod SSH fail (auth), fallback code inspect. Q2-Budget handler: `PurchaseEvaluationFeatures.cs:379-387` **ĐÃ log changelog** EntityType=Header + Action=Update + summary diff → **code ĐÚNG, likelihood FE filter bug or UAT DB stale**. Q3-Return handler: `PurchaseEvaluationWorkflowService.cs:215-378 ApplyReturnModeAsync` **ZERO changelog log** — 4 mode branches (OneLevel/OneStep/Assignee/Drafter) mutate pointers only, return summary, caller `TransitionAsync:100 LogTransitionAsync` only logs phase transition KHÔNG log mode side-effect. Q4-Schema: `PurchaseEvaluationChangelog.cs` support EntityType=Workflow(5) enum but **ZERO code populate** — schema incomplete missing Kind/ChangeType subtype enum to disambiguate "budget adjust" vs "detail edit" vs "return mode" (all Header/Workflow entity cùng Action.Update). Q5-FE: Query handler `ListPurchaseEvaluationChangelogsQueryHandler:1050-1064` **KHÔNG filter logic** — returns ALL entities. FE query component unknown (fe-user source not easily searchable) but **likely filter EntityType == (Supplier|Detail|Quote)** omit Header+Workflow → Bug 1 Budget (Header type) hidden, Bug 2 Return (Workflow type unlogged vậy). Root cause B1: FE filter skip Header updates OR Schema gap (Header.Update collision: budget vs section 2 edit). Root cause B2: Handler **intentionally skip logging** (no companion audit table like PurchaseEvaluationApprovals for return history). Fix path B1: Option A (add Kind enum — 30 LOC schema+handlers) vs B (extend EntityType — 20 LOC) vs C (FE filter conditional show Budget — 10 LOC FE). Fix path B2: Add `db.PurchaseEvaluationChangelogs.Add()` per mode (15-25 LOC 1 file). Cross-ref pattern memory: S23 t3 lookup bug (Level.Order collision per-NV Mig 29) — schema Mig 29 OR-of-N refactor created similar subtype ambiguity. Surprise: `EntityType.Workflow=5` enum value design-only, unused 4+ mig history. Recommendation: B2 fix first (clear win, 1 file BE), then B1 design (schema + cross-module pattern audit Contracts). Token ~28k. - **2026-05-19 (S25 t1 spawn audit 2 bug critical UAT — Changelog logging missing):** Em main report 2 bug UAT: (1) Budget Adjust 2×click → "Lịch sử thay đổi" KHÔNG show 2 entry. (2) Return Assignee mode F1 click → "Lịch sử thay đổi" KHÔNG show return action. Audit 5Q: Q1-DB state Prod SSH fail (auth), fallback code inspect. Q2-Budget handler: `PurchaseEvaluationFeatures.cs:379-387` **ĐÃ log changelog** EntityType=Header + Action=Update + summary diff → **code ĐÚNG, likelihood FE filter bug or UAT DB stale**. Q3-Return handler: `PurchaseEvaluationWorkflowService.cs:215-378 ApplyReturnModeAsync` **ZERO changelog log** — 4 mode branches (OneLevel/OneStep/Assignee/Drafter) mutate pointers only, return summary, caller `TransitionAsync:100 LogTransitionAsync` only logs phase transition KHÔNG log mode side-effect. Q4-Schema: `PurchaseEvaluationChangelog.cs` support EntityType=Workflow(5) enum but **ZERO code populate** — schema incomplete missing Kind/ChangeType subtype enum to disambiguate "budget adjust" vs "detail edit" vs "return mode" (all Header/Workflow entity cùng Action.Update). Q5-FE: Query handler `ListPurchaseEvaluationChangelogsQueryHandler:1050-1064` **KHÔNG filter logic** — returns ALL entities. FE query component unknown (fe-user source not easily searchable) but **likely filter EntityType == (Supplier|Detail|Quote)** omit Header+Workflow → Bug 1 Budget (Header type) hidden, Bug 2 Return (Workflow type unlogged vậy). Root cause B1: FE filter skip Header updates OR Schema gap (Header.Update collision: budget vs section 2 edit). Root cause B2: Handler **intentionally skip logging** (no companion audit table like PurchaseEvaluationApprovals for return history). Fix path B1: Option A (add Kind enum — 30 LOC schema+handlers) vs B (extend EntityType — 20 LOC) vs C (FE filter conditional show Budget — 10 LOC FE). Fix path B2: Add `db.PurchaseEvaluationChangelogs.Add()` per mode (15-25 LOC 1 file). Cross-ref pattern memory: S23 t3 lookup bug (Level.Order collision per-NV Mig 29) — schema Mig 29 OR-of-N refactor created similar subtype ambiguity. Surprise: `EntityType.Workflow=5` enum value design-only, unused 4+ mig history. Recommendation: B2 fix first (clear win, 1 file BE), then B1 design (schema + cross-module pattern audit Contracts). Token ~28k.
- **2026-05-19 (S25 wrap — Plan AB Bug 1+2 audit + 6 follow-up plans em main solo):** Pre-Plan AB audit ~28K confirm root cause: Bug 1 Budget Adjust Handler ĐÃ log Changelog (Header+Update) nhưng FE HistoryTab filter strict TraLai-only loại. Bug 2 ApplyReturnModeAsync 4 mode KHÔNG add Changelog.Add() — chỉ caller LogTransitionAsync log phase transition. Recommended fix path: BE add log return mode + FE filter relax + Decision badge differentiation. **Subsequent em main solo follow-ups** (Plan AC..AF, KHÔNG re-spawn Investigator): AC capture pre-call Step/Level state + skipToFinal comment enrich + FE Decision badge; AC2 FE merge synthetic Reject rows từ Changelog (reversible recovery KHÔNG DB touch); AD drop misleading dual-phase badges + parse semantic next-target hint via regex `Chuyển phase X → Y` + comment keyword "Trả về"/"vượt cấp"; AE BE preventive batch UserName fix 9 Changelog.Add sites (Drafter+Detail+Quote+Adjust); AF FE userMap fallback từ embedded domain data PeDetailBundle (drafter+approvals+approvalFlow+levelOpinions+departmentOpinions) — no extra API fetch. **Patterns reusable Contract V2 audit recovery + Budget changelog UI:** (a) synthetic recovery FE merge từ existing audit table, (b) userMap fallback từ embedded domain data, (c) drop misleading badges + semantic hint via regex parsing, (d) preventive batch fix systemic gap. Cross-ref `feedback_service_hook_vs_endpoint` (audit log derived state) + new pattern user-level: FE merge synthetic + userMap fallback. **Tokens cumulative em main this session ~340K (mostly solo iterations, sub-agent leverage ~62K total).** **CICD result:** 7 commits `e23f51c..506cada` push remote, runs #215 FAIL (Plan M tests SQLite tie-break re-emerge) → #216 PASS (Chunk A2 SQLite tie-break fix) → #217-#221 PASS streak. Gotcha #48 SQLite tie-break pending docs. - **2026-05-19 (S25 wrap — Plan AB Bug 1+2 audit + 6 follow-up plans em main solo):** Pre-Plan AB audit ~28K confirm root cause: Bug 1 Budget Adjust Handler ĐÃ log Changelog (Header+Update) nhưng FE HistoryTab filter strict TraLai-only loại. Bug 2 ApplyReturnModeAsync 4 mode KHÔNG add Changelog.Add() — chỉ caller LogTransitionAsync log phase transition. Recommended fix path: BE add log return mode + FE filter relax + Decision badge differentiation. **Subsequent em main solo follow-ups** (Plan AC..AF, KHÔNG re-spawn Investigator): AC capture pre-call Step/Level state + skipToFinal comment enrich + FE Decision badge; AC2 FE merge synthetic Reject rows từ Changelog (reversible recovery KHÔNG DB touch); AD drop misleading dual-phase badges + parse semantic next-target hint via regex `Chuyển phase X → Y` + comment keyword "Trả về"/"vượt cấp"; AE BE preventive batch UserName fix 9 Changelog.Add sites (Drafter+Detail+Quote+Adjust); AF FE userMap fallback từ embedded domain data PeDetailBundle (drafter+approvals+approvalFlow+levelOpinions+departmentOpinions) — no extra API fetch. **Patterns reusable Contract V2 audit recovery + Budget changelog UI:** (a) synthetic recovery FE merge từ existing audit table, (b) userMap fallback từ embedded domain data, (c) drop misleading badges + semantic hint via regex parsing, (d) preventive batch fix systemic gap. Cross-ref `feedback_service_hook_vs_endpoint` (audit log derived state) + new pattern user-level: FE merge synthetic + userMap fallback. **Tokens cumulative em main this session ~340K (mostly solo iterations, sub-agent leverage ~62K total).** **CICD result:** 7 commits `e23f51c..506cada` push remote, runs #215 FAIL (Plan M tests SQLite tie-break re-emerge) → #216 PASS (Chunk A2 SQLite tie-break fix) → #217-#221 PASS streak. Gotcha #48 SQLite tie-break pending docs.
- **2026-05-21 (S26 spawn Plan AG 5Q audit — PE List tree view feedback Tra Sol):** Bro UAT 2026-05-21 screenshot phàn nàn UI Duyệt NCC flat list "đám rừng" + propose Outlook-style folder template. Em main spawn Investigator audit 5Q: Q1 prod data scale (SSH auth fail, fallback code inspect — ~50-200 projects × 5-15 PE typical). Q2 Project entity `Master/Project.cs:5-14` extends AuditableEntity với Code+Name+dates+Budget+PM+Note, **MISSING MaxLength + navigation tới PE** → ready for Phase 2 ProjectPackage table mở rộng. Q3 PE List structure `PurchaseEvaluationsListPage.tsx:133` 3-panel grid `lg:grid-cols-[340px_1fr_360px]` flat `<ul><li>` line 199-252 + pageSize 50 + filter type/phase/awId/search. Q4 shadcn fe-user component GAP **THIẾU Accordion/Collapsible/Tree/Card/Badge** (chỉ Button/Dialog/Input/Label/Select/Textarea) → Phase 1 fallback HTML `<details>/<summary>` native + inline badge `<div>` (verified S24 Plan AA pattern). Q5 Mig 32 prep naming `AddProjectPackageTable` follow cumulative pattern. **Recommend Approach C Hybrid: Phase 1 FE-only group view ~160 LOC × 2 app (1-2 ngày) + Phase 2 ProjectPackage schema (3-5 ngày defer post-UAT). Implementer Case 2 cookie-cutter mirror 2 app ACCEPT.** Token ~30k.
- **2026-05-21 (S26 spawn Plan AI RAG distribution research — 4 study cases industry-validated):** Bro plan setup RAG cho 5 dự án cùng máy localhost share infrastructure. Investigator deep research 7Q: Anthropic patterns + community tools + multi-tenant architecture + distribution mechanism + auth + cost + sync. **Findings 4 study cases:** (1) **Cursor** — Merkle tree + Turbopuffer + 92% similarity reuse pattern, secret key derived Git commit hash, per-team index sharing cut indexing hours→seconds. (2) **Cline Memory Bank** — markdown + JIT retrieval + git-native sync. (3) **Continue.dev Hub** — slug-based YAML config sharing centralized. (4) **Sourcegraph Cody** — interesting anti-pattern, BỎ embeddings sang Search API + graph IR scale 100K+ repos enterprise (alternative if good search infra sẵn). **Multi-tenant 3 patterns:** Single index (pool, cheap), Per-tenant isolated (silo, expensive), Hybrid base+delta (Cursor pattern). **Distribution combo winner cho 5-dev team:** FastMCP HTTP server VPS Hetzner $15/tháng + git-sync embeddings snapshots committed to private repo. Auth JWT RS256 + role scopes + document-level ACL. Cost reality 5 dev ~$20/month vs cloud Qdrant $50/month. Sync git-based weekly cron (real-time chỉ cần khi team > 10 dev). **Surprise:** Voyage AI **200M tokens/month free tier cover 5 devs** comfortably — coi như chỉ tốn $15 VPS. **Anthropic standards 9/9 matched** + community best practices 6/7 matched (Sourcegraph alternative N/A cho memory-heavy). Plan AI architecture chốt với em main: User-level Global MCP (Pattern C — 1 server localhost serve 5 project) thay vì team VPS pattern (anh single dev 5 dự án). Token ~40k.

View File

@ -144,6 +144,8 @@ Flag commit nếu thấy `<PackageReference Include="MediatR" Version="14...` ho
## 📅 Recent activity (last 10 FIFO) ## 📅 Recent activity (last 10 FIFO)
- **2026-05-21 (S26 Plan AG pre-commit + 5 follow-up plans AG2-AG6 em main solo self-review):** Plan AG Chunk A+B+C pre-commit verify spawn 1× ~25K with 5-category checklist + 12 adversarial deep checks (A-L) PASS 0 critical/major/minor. Commit `0bf6c7e` 2 file +346/-116 LOC mirror IDENTICAL hash `21001E90...`. Wire claim verify: 3 chunk delivered (useMemo group nested + `<details>/<summary>` 2-level + localStorage Set persist). Schema 0 mig, 0 BE, 0 entity. Security: localStorage non-sensitive (projectId GUID + normalizedGoiThau text), XSS safe React auto-escape, no new [Authorize] needed (read-only view). Code quality: npm build × 2 PASS 0 TS err, anti-fiddle 0% drift, Mirror §3.9 byte-identical 21,521 bytes. Test coverage: Phase 9 UAT exception accept. Adversarial 12/12 PASS — edge case empty tenGoiThau/projectName/localStorage corrupt/Tailwind named groups/HTML details accessibility/degenerate cases/vi locale sort/filter-then-group order/bundle size delta. **Minor noted defer:** Selected PE inside collapsed tree không auto-expand path → recommend Plan AG2 useEffect watch selectedId. Recommendation: PASS proceed push. **Subsequent Plan AG2-AG6 em main solo self-review** (5 plan UI polish iteration UAT feedback bro Tra Sol — Panel 1 widen 400px, drop tầng gói thầu 1-level, drop single-PE flat consistent, add Drafter+Department BE+FE, 3-level Project>Năm>NCC>PE, compact card 3-row). Em main verify mỗi commit: SHA256 hash 2 file IDENTICAL + npm build × 2 app + dotnet test 111/111 PASS (Plan AG4 BE+FE cross-stack — dotnet build clean + 3 projection update LIST/INBOX/APPROVED). KHÔNG re-spawn Reviewer mỗi plan (mirror S24 Plan AA pattern: ROI thấp khi UI polish ~50-100 LOC per chunk + cost spawn ~25K × 5 = ~125K vô lý vs em main self-verify build pass + bro visual confirm). **Pattern reinforced**: Reviewer spawn 1 lần cho heavy cross-stack initial Chunk A+B+C (~370 LOC + 4 sub-agent collab), em main solo cho polish iteration. Cumulative S26 6 commits `0bf6c7e..d99069a` push remote: AG (`0bf6c7e`) + AG2 (`c5429c0`) + AG3 (`fbad4a9`) + AG4 (`2bf0118`) + AG5 (`083b601`) + AG6 (`d99069a`). 0 prod regression observed, test baseline 111 preserved. Smart Friend guard still active for next session feature spawn.
- **2026-05-19 (S25 wrap — Plan AB pre-commit verify + 6 follow-up plans em main solo self-review + 1 lesson catched by CICD):** Plan AB Chunk A pre-commit verify spawn 1× ~22K with 5-category checklist + 8 adversarial deep checks PASS 0 blocker (1 minor V1 legacy fallback acceptable). Recommended PROCEED push cdfd542. **MISSED gotcha #48**: Multi-Changelog.Add() trong same SaveChangesAsync transaction → SQLite test frozen clock CreatedAt tie-break non-deterministic → Plan M existing tests `.OrderByDescending(CreatedAt).FirstAsync()` picked wrong entry → CI Run #215 FAIL. **Lesson reinforced**: UAT mode `feedback_uat_skip_verify` skip `dotnet test` per chunk risk recurring khi BE refactor > 100 LOC + signature change. Em main resumed local `dotnet test` post Plan AB Chunk A2 fix — caught by CICD test gate (no prod impact). **Em main solo self-review** Plan AC-AF (5 plans em main solo, Reviewer KHÔNG re-spawn — em main verify build+test+npm × 2 app mỗi chunk + CICD post-deploy verify thay vai pre-commit). Cumulative S25: 0 prod regression, 6 commits PASS CICD. **Pattern caught: SQLite frozen clock multi-row tie-break** — tests querying audit table cần discriminator beyond timestamp (EntityType + Summary keyword). Cross-ref future Contract V2 test setup. **Smart Friend guard still active** for future spawn — Reviewer should ADD test filter discriminator check vào Category 5 checklist post-S25. - **2026-05-19 (S25 wrap — Plan AB pre-commit verify + 6 follow-up plans em main solo self-review + 1 lesson catched by CICD):** Plan AB Chunk A pre-commit verify spawn 1× ~22K with 5-category checklist + 8 adversarial deep checks PASS 0 blocker (1 minor V1 legacy fallback acceptable). Recommended PROCEED push cdfd542. **MISSED gotcha #48**: Multi-Changelog.Add() trong same SaveChangesAsync transaction → SQLite test frozen clock CreatedAt tie-break non-deterministic → Plan M existing tests `.OrderByDescending(CreatedAt).FirstAsync()` picked wrong entry → CI Run #215 FAIL. **Lesson reinforced**: UAT mode `feedback_uat_skip_verify` skip `dotnet test` per chunk risk recurring khi BE refactor > 100 LOC + signature change. Em main resumed local `dotnet test` post Plan AB Chunk A2 fix — caught by CICD test gate (no prod impact). **Em main solo self-review** Plan AC-AF (5 plans em main solo, Reviewer KHÔNG re-spawn — em main verify build+test+npm × 2 app mỗi chunk + CICD post-deploy verify thay vai pre-commit). Cumulative S25: 0 prod regression, 6 commits PASS CICD. **Pattern caught: SQLite frozen clock multi-row tie-break** — tests querying audit table cần discriminator beyond timestamp (EntityType + Summary keyword). Cross-ref future Contract V2 test setup. **Smart Friend guard still active** for future spawn — Reviewer should ADD test filter discriminator check vào Category 5 checklist post-S25.
- **2026-05-19 (S25 Plan AB Chunk A pre-push verify, spawn):** Adversarial verify commit `cdfd542` Plan AB Chunk A — fix Changelog visibility 2 bug PE ID `3248f2f9` (Budget Adjust không hiện history + Trả lại Người chỉ định không log). Diff scope: 3 files +146/-95 LOC (BE PurchaseEvaluationWorkflowService.cs Service-only refactor + 2 FE PeDetailTabs.tsx mirror §3.9). **Verdict: PASS — 0 critical / 0 major / 1 minor observation — proceed push OK.** Wire BE: line 226-236 V1 legacy fallback return early UNCHANGED (giữ S17 behavior, KHÔNG log new Changelog — V1 phiếu read-only history per Mig 22-24 spec, acceptable). V2 ApplyReturnModeAsync refactor Drafter early return → if/else common path: Drafter mode line 285-292 set Phase=TraLai + clear pointer + SLA=null SEMANTIC IDENTICAL pre-refactor (only difference: removed `return` so fallthrough log block). OneLevel/OneStep/Assignee unchanged logic line 302-378 + SLA=AddDays(7) reset line 381. New `db.PurchaseEvaluationChangelogs.Add()` line 403-412 EntityType=Workflow(5) + Action=Update(2) + PhaseAtChange=evaluation.Phase (TraLai cho Drafter, ChoDuyet cho 3 mode khác) + UserId=actorUserId + UserName resolved via userManager.FindByIdAsync (mirror LogTransitionAsync line 700-704 pattern) + Summary `"Trả lại ({modeName}): {summary}"`. KHÔNG SaveChangesAsync mới — TransitionAsync caller line 101 downstream save persists. Wire FE 2 file `HistoryTab` filter extend 3 rule: ADD `summary.includes('Trả lại')` Workflow entity + ADD `entityType === Header(1) && summary.toLowerCase().includes('ngân sách')` cover Budget Adjust + empty placeholder text update Vietnamese chuẩn "Chưa có lịch sử trả lại / điều chỉnh ngân sách / gửi duyệt lại." Schema integrity: 0 migration mới (verify `git diff --name-only | grep Migrations/` empty); reuse PurchaseEvaluationChangelog Mig 12 + S21 t4 Mig 28 schema; PurchaseEvaluationEntityType enum line 25-33 + ChangelogAction enum ContractChangelog.cs:38-44 match BE values FE constant. Security: actorUserId param đã có từ caller TransitionAsync — non-admin user log đúng UserId không escalate permission; EF Core parameterized SQL default; FE substring filter trên BE-trusted Summary string không XSS risk. Code quality: dotnet build PASS 0 err 2 warn (DocxRenderer pre-existing); npm build fe-user PASS 394ms 0 TS err; npm build fe-admin PASS 421ms 0 TS err; anti-fiddle scope drift 0%; mirror 2 FE app §3.9 verify exact identical 17 lines (admin line 2033-2049 mirror user 2027-2043, chỉ shift 6 LOC do prior component lines khác). Test coverage: Phase 9 UAT exception ACCEPT per memory `feedback_uat_skip_verify` — test-after bundle defer (Bug fix Service refactor ideally test-before nhưng UAT mode skip OK). Cumulative state unchanged: 111 test baseline preserve. Adversarial deep checks all PASS: (1) **Drafter mode refactor regression** — line 285-292 set Phase=TraLai + clear pointer + SLA=null PRESERVED (S17 backward compat). V1 legacy 226-236 fallback return early no semantic change. (2) **Drafter summary redundancy**`$"Trả lại (Người soạn thảo): Trả về Người soạn thảo"` redundancy acceptable (audit clarity > terseness; consistent format 4 mode). (3) **actorName resolve N+1** — single `userManager.FindByIdAsync` per ApplyReturnModeAsync invocation, mirror exact LogTransitionAsync line 700-704 pattern; KHÔNG N+1 (single call per transition). (4) **FE filter substring case**`.includes('Trả lại')` exact match BE format `$"Trả lại ({modeName}): ..."` — case-sensitive Vietnamese diacritics lowercase 'l' match. (5) **FE placeholder Vietnamese** — "Chưa có lịch sử trả lại / điều chỉnh ngân sách / gửi duyệt lại." chuẩn Vietnamese diacritics. (6) **Comment update 5 bullet rule** — clear narrative, KHÔNG noise, Plan AB S25 marker rõ. (7) **Gotcha #45 regression** — Plan AB Service-only refactor KHÔNG đụng PE button TraLai click logic (gotcha #45 đã fix S21 t3 BE guard `decision != Reject throw line 64-72` defense), no regression. (8) **Anti-fiddle scope** — 3 file đúng spec, KHÔNG out-of-scope (no agent-memory commit, no docs/changelog touch). **Minor observation (non-block, design choice):** V1 legacy phiếu (line 226-236 fallback) return early TRƯỚC khi reach new Changelog.Add() block → V1 phiếu KHÔNG có new detailed "Trả lại (X): ..." log. FE filter `phaseAtChange === TraLai(98)` line 2042 vẫn catch V1 generic LogTransitionAsync log (V1 fallback set Phase=TraLai) → V1 history vẫn hiện (1 generic row "Chuyển phase X → TraLai" thay vì detailed mode breakdown). Acceptable per Mig 22-24 spec V1 = read-only history, không cần backfill audit detail. Recommendation: PASS proceed push remote. Smart Friend guard active. - **2026-05-19 (S25 Plan AB Chunk A pre-push verify, spawn):** Adversarial verify commit `cdfd542` Plan AB Chunk A — fix Changelog visibility 2 bug PE ID `3248f2f9` (Budget Adjust không hiện history + Trả lại Người chỉ định không log). Diff scope: 3 files +146/-95 LOC (BE PurchaseEvaluationWorkflowService.cs Service-only refactor + 2 FE PeDetailTabs.tsx mirror §3.9). **Verdict: PASS — 0 critical / 0 major / 1 minor observation — proceed push OK.** Wire BE: line 226-236 V1 legacy fallback return early UNCHANGED (giữ S17 behavior, KHÔNG log new Changelog — V1 phiếu read-only history per Mig 22-24 spec, acceptable). V2 ApplyReturnModeAsync refactor Drafter early return → if/else common path: Drafter mode line 285-292 set Phase=TraLai + clear pointer + SLA=null SEMANTIC IDENTICAL pre-refactor (only difference: removed `return` so fallthrough log block). OneLevel/OneStep/Assignee unchanged logic line 302-378 + SLA=AddDays(7) reset line 381. New `db.PurchaseEvaluationChangelogs.Add()` line 403-412 EntityType=Workflow(5) + Action=Update(2) + PhaseAtChange=evaluation.Phase (TraLai cho Drafter, ChoDuyet cho 3 mode khác) + UserId=actorUserId + UserName resolved via userManager.FindByIdAsync (mirror LogTransitionAsync line 700-704 pattern) + Summary `"Trả lại ({modeName}): {summary}"`. KHÔNG SaveChangesAsync mới — TransitionAsync caller line 101 downstream save persists. Wire FE 2 file `HistoryTab` filter extend 3 rule: ADD `summary.includes('Trả lại')` Workflow entity + ADD `entityType === Header(1) && summary.toLowerCase().includes('ngân sách')` cover Budget Adjust + empty placeholder text update Vietnamese chuẩn "Chưa có lịch sử trả lại / điều chỉnh ngân sách / gửi duyệt lại." Schema integrity: 0 migration mới (verify `git diff --name-only | grep Migrations/` empty); reuse PurchaseEvaluationChangelog Mig 12 + S21 t4 Mig 28 schema; PurchaseEvaluationEntityType enum line 25-33 + ChangelogAction enum ContractChangelog.cs:38-44 match BE values FE constant. Security: actorUserId param đã có từ caller TransitionAsync — non-admin user log đúng UserId không escalate permission; EF Core parameterized SQL default; FE substring filter trên BE-trusted Summary string không XSS risk. Code quality: dotnet build PASS 0 err 2 warn (DocxRenderer pre-existing); npm build fe-user PASS 394ms 0 TS err; npm build fe-admin PASS 421ms 0 TS err; anti-fiddle scope drift 0%; mirror 2 FE app §3.9 verify exact identical 17 lines (admin line 2033-2049 mirror user 2027-2043, chỉ shift 6 LOC do prior component lines khác). Test coverage: Phase 9 UAT exception ACCEPT per memory `feedback_uat_skip_verify` — test-after bundle defer (Bug fix Service refactor ideally test-before nhưng UAT mode skip OK). Cumulative state unchanged: 111 test baseline preserve. Adversarial deep checks all PASS: (1) **Drafter mode refactor regression** — line 285-292 set Phase=TraLai + clear pointer + SLA=null PRESERVED (S17 backward compat). V1 legacy 226-236 fallback return early no semantic change. (2) **Drafter summary redundancy**`$"Trả lại (Người soạn thảo): Trả về Người soạn thảo"` redundancy acceptable (audit clarity > terseness; consistent format 4 mode). (3) **actorName resolve N+1** — single `userManager.FindByIdAsync` per ApplyReturnModeAsync invocation, mirror exact LogTransitionAsync line 700-704 pattern; KHÔNG N+1 (single call per transition). (4) **FE filter substring case**`.includes('Trả lại')` exact match BE format `$"Trả lại ({modeName}): ..."` — case-sensitive Vietnamese diacritics lowercase 'l' match. (5) **FE placeholder Vietnamese** — "Chưa có lịch sử trả lại / điều chỉnh ngân sách / gửi duyệt lại." chuẩn Vietnamese diacritics. (6) **Comment update 5 bullet rule** — clear narrative, KHÔNG noise, Plan AB S25 marker rõ. (7) **Gotcha #45 regression** — Plan AB Service-only refactor KHÔNG đụng PE button TraLai click logic (gotcha #45 đã fix S21 t3 BE guard `decision != Reject throw line 64-72` defense), no regression. (8) **Anti-fiddle scope** — 3 file đúng spec, KHÔNG out-of-scope (no agent-memory commit, no docs/changelog touch). **Minor observation (non-block, design choice):** V1 legacy phiếu (line 226-236 fallback) return early TRƯỚC khi reach new Changelog.Add() block → V1 phiếu KHÔNG có new detailed "Trả lại (X): ..." log. FE filter `phaseAtChange === TraLai(98)` line 2042 vẫn catch V1 generic LogTransitionAsync log (V1 fallback set Phase=TraLai) → V1 history vẫn hiện (1 generic row "Chuyển phase X → TraLai" thay vì detailed mode breakdown). Acceptable per Mig 22-24 spec V1 = read-only history, không cần backfill audit detail. Recommendation: PASS proceed push remote. Smart Friend guard active.
- **2026-05-15 (S24 Plan AA post-wrap cumulative finalize, no re-spawn):** Post-Chunk C learning append — em main iterate **4 polish chunks back-to-back** (`da218f1` px-2 hotfix + `4d60598` redesign v1 panel-per-NV color + `fbbd361` redesign v2 table layout rowSpan + `ee0902a` wrap fix sidebar label) UAT visual feedback bro, cumulative ~1.5h, KHÔNG Reviewer spawn. **Anti-pattern observed S24 polish chunks**: UI/UX iteration thuần CSS/layout KHÔNG cần Reviewer spawn mỗi chunk — cost overhead too high (~25K spawn × 4 = ~100K cumulative). Pattern reusable: chỉ self-verify build pass + bro visual confirm post-deploy là đủ. **Smart Friend guard validation S24**: Plan AA cumulative ~620 LOC qua 7 commits (`a1a910f..ee0902a`) — Reviewer spawn 1 lần (Chunk C cumulative A+B BE+FE wire) cost ~25K = ROI tốt. Multi-spawn polish chunks 4× sẽ ~100K = ROI thấp. **Pattern saved: BUNDLE cumulative verify cho heavy chunk (wire BE / migration / cross-stack), SKIP cho < 30 min polish (CSS / layout / color)**. **Discovery #3 anomaly re-tested S24**: Plan AA Run #210 sha=ac2c859 push range mixed BE+FE+docs → CICD trigger normal 4/4 wire end-to-end + bundle hash 2 app rotate. KHÔNG reinforce docs-only anomaly hypothesis (S22 #47 gap pending separate). Defer Investigator follow-up. **Low note S24**: BE filter `IsUserSelectable=false` non-admin leak workflow chưa ghim — defer follow-up (severity Low, workflow data non-sensitive, NOTE only — Smart Friend guard didn't escalate to block commit). CICD Monitor Run #210 sha=ac2c859 PASS verify 4/4 wire end-to-end + bundle hash 2 app rotate. Cumulative state unchanged S24: 31 mig, 111 test, 47 gotcha. - **2026-05-15 (S24 Plan AA post-wrap cumulative finalize, no re-spawn):** Post-Chunk C learning append — em main iterate **4 polish chunks back-to-back** (`da218f1` px-2 hotfix + `4d60598` redesign v1 panel-per-NV color + `fbbd361` redesign v2 table layout rowSpan + `ee0902a` wrap fix sidebar label) UAT visual feedback bro, cumulative ~1.5h, KHÔNG Reviewer spawn. **Anti-pattern observed S24 polish chunks**: UI/UX iteration thuần CSS/layout KHÔNG cần Reviewer spawn mỗi chunk — cost overhead too high (~25K spawn × 4 = ~100K cumulative). Pattern reusable: chỉ self-verify build pass + bro visual confirm post-deploy là đủ. **Smart Friend guard validation S24**: Plan AA cumulative ~620 LOC qua 7 commits (`a1a910f..ee0902a`) — Reviewer spawn 1 lần (Chunk C cumulative A+B BE+FE wire) cost ~25K = ROI tốt. Multi-spawn polish chunks 4× sẽ ~100K = ROI thấp. **Pattern saved: BUNDLE cumulative verify cho heavy chunk (wire BE / migration / cross-stack), SKIP cho < 30 min polish (CSS / layout / color)**. **Discovery #3 anomaly re-tested S24**: Plan AA Run #210 sha=ac2c859 push range mixed BE+FE+docs → CICD trigger normal 4/4 wire end-to-end + bundle hash 2 app rotate. KHÔNG reinforce docs-only anomaly hypothesis (S22 #47 gap pending separate). Defer Investigator follow-up. **Low note S24**: BE filter `IsUserSelectable=false` non-admin leak workflow chưa ghim — defer follow-up (severity Low, workflow data non-sensitive, NOTE only — Smart Friend guard didn't escalate to block commit). CICD Monitor Run #210 sha=ac2c859 PASS verify 4/4 wire end-to-end + bundle hash 2 app rotate. Cumulative state unchanged S24: 31 mig, 111 test, 47 gotcha.

25
.claude/rag.json Normal file
View File

@ -0,0 +1,25 @@
{
"project_id": "solution_erp",
"display_name": "SOLUTION_ERP — Quản lý HĐ NCC",
"corpus_paths": [
"docs/**/*.md",
".claude/agent-memory/**/MEMORY.md",
".claude/skills/**/SKILL.md"
],
"exclude_paths": [
"docs/_archive/**",
"node_modules/**",
"bin/**",
"obj/**",
".git/**"
],
"extra_corpus": [
"C:\\Users\\pqhuy\\.claude\\projects\\D--Dropbox-CONG-VIEC-SOLUTION\\memory\\*.md"
],
"share_to_global": true,
"search_scope_default": ["self", "shared_global"],
"auto_reindex": true,
"chunk_size": 1500,
"chunk_overlap": 200,
"contextual_retrieval": true
}

File diff suppressed because one or more lines are too long

View File

@ -2,7 +2,9 @@
> **Update rule:** trước khi bắt đầu 1 task → ghi row vào `🔥 In Progress`. Xong → chuyển sang `✅ Recently Done`. > **Update rule:** trước khi bắt đầu 1 task → ghi row vào `🔥 In Progress`. Xong → chuyển sang `✅ Recently Done`.
**Last updated:** 2026-05-19 (Session 25 chốt cuối — **🎯 S25 cumulative wrap: 7 plan + 7 commits Plan AB→AF + 7 CICD Runs (#215 FAIL → #216-#221 PASS)**. Push remote `e23f51c..506cada`. Bro UAT 2026-05-19 phát hiện 2 bug visibility critical PE/2026/A/032 + 4 follow-up polish UAT iteration: **Bug 1 Budget Adjust** không show "Lịch sử thay đổi" (BE log Header+Update OK nhưng FE filter strict TraLai-only loại) — **Bug 2 Return Mode 4 mode** không log Changelog (ApplyReturnModeAsync miss `db.PurchaseEvaluationChangelogs.Add()`) — **Bug 3 Lịch sử duyệt** missing Trả lại + Vượt cấp entries (Reject branch không add Approval row) — **Bug 4 dual-phase badges** gây nhầm "Đã gửi duyệt → Đã gửi duyệt" cho 3 mode Reject giữ Phase=ChoDuyet — **Bug 5 Changelog UserName** show "Hệ thống" thay vì user thật (9 sites BE miss UserName) — **Bug 6 historical name resolve** entries pre-deploy vẫn show empty (forward-only fix). **Plan AB Chunk A** (`cdfd542`) BE log return mode + FE filter relax × 2 app. **Plan AB Chunk A2** (`8c05947`) fix Plan M tests SQLite frozen-clock tie-break (gotcha #48 NEW — Run #215 caught + Run #216 PASS). **Plan AC** (`a734bf2`) BE Reject add Approval row + skipToFinal comment + FE Decision badge × 2 app. **Plan AC2** (`25837b6`) FE merge synthetic Reject rows từ Changelog historical (Option 2A bro chốt, reversible no-DB-touch). **Plan AD** (`0aaf2df`) Drop misleading dual-phase badges + parse next-target hint via regex `Chuyển phase X → Y` + comment keyword Trả lại/Vượt cấp (gotcha #49 NEW). **Plan AE** (`9ea62be`) BE preventive batch fix UserName 9 Changelog.Add sites (Budget Adjust + 8 sites: Create + Update + Detail CRUD + Quote CRUD + Select Winner). **Plan AF** (`506cada`) FE userMap fallback từ embedded domain data PeDetailBundle (drafter + approvals + approvalFlow + levelOpinions + departmentOpinions) — no extra API fetch admin permission. Multi-agent execution: 🟦 **Investigator** 1 spawn Plan AB Bug 1+2 audit ~28K + 🟨 **Implementer** 1 spawn Plan AB Chunk A ~12K Case 1 + 🟥 **Reviewer** 1 spawn Plan AB pre-commit ~22K PASS 0 blocker (1 minor non-block) + 🟩 **CICD Monitor** 7 spawns Run #215-#221 verify ALL PASS post-Plan AB Chunk A2 fix. **Em main solo từ Plan AC đến AF** (5 plan, cross-stack reasoning + UAT iteration borderline, Implementer/Reviewer KHÔNG re-spawn). Stats final S25 chốt: **31 mig (no schema)** · 59 tables · ~146 endpoints · 35 FE pages · **111 test pass unchanged** (UAT defer test-after per §7) · **49 gotcha (+2 #48 SQLite tie-break + #49 dual-phase UI confusion)** · **23 memory user-level (+2 NEW: `feedback_fe_merge_synthetic_audit` Plan AC2 + `feedback_fe_usermap_fallback` Plan AF)** · 6 skills · 4 sub-agents active. Bundle hash 6× rotate × 2 app (#216-#221), Mig 31 unchanged toàn S25. Patterns reusable cross-project (8 NEW S25): (1) Multi-Changelog.Add SQLite tie-break test discriminator, (2) CICD catch UAT skip test risk for BE refactor > 100 LOC, (3) Test fix Option A over BE refactor preservation, (4) Capture pre-call mutation state cho audit row from-position, (5) FE merge synthetic rows từ Changelog reversible recovery, (6) Drop misleading dual-phase badges + parse semantic hint, (7) Changelog UserName preventive systemic batch fix, (8) FE userMap fallback từ embedded domain data no extra API. **Memory CRITICAL FLAG**: cicd-monitor MEMORY ~72KB strongly over 50KB hard threshold — DEDICATED CURATION SESSION REQUIRED next (archive Run #186-#210 + S22-S24 verbose). Bro UAT verify ALL Plan AB→AF live deploy cumulative.) **Last updated:** 2026-05-21 (Session 26 chốt cuối — **🎯 S26 cumulative wrap: 6 plan PE List tree view UI iteration + Plan AI RAG global MCP infrastructure setup**. **Plan AG/AG2/AG3/AG4/AG5/AG6** cumulative 6 commits Plan AG series `0bf6c7e..d99069a` push remote — UAT feedback bro Tra Sol 2026-05-21 screenshot "UI Duyệt NCC như đám rừng" → folder tree giống Outlook: **Plan AG** Phase 1 PE List tree view 2-level Project > Gói thầu > PE (Investigator audit 5Q + Implementer Case 2 cookie-cutter mirror 2 app + Reviewer pre-commit PASS 0 blocker + CICD Monitor Run #222 PASS bundle hash rotate). **Plan AG2** simplify 1-level (drop tầng gói thầu) + Panel 1 widen 340→400px. **Plan AG3** drop single-PE flat branch, consistent UI (mọi dự án dù 1/N phiếu đều render `<details>`). **Plan AG4** bổ sung Người tạo + Phòng ban tạo PE card — BE DTO `PurchaseEvaluationListItemDto` +4 fields (DrafterUserId/DrafterName/DepartmentId/DepartmentName) + 3 projection JOIN Users+Departments LEFT (ListHandler/InboxHandler/ApprovedHandler) + FE `PeListItem` type +4 fields + UI card render 👤 Drafter · Phòng ban. **Plan AG5** extend tree 3-level Project > Năm > NCC > PE (selectedSupplierName fallback "(Chưa chọn NCC)" cho PE chưa DaDuyet). **Plan AG6** compact card 3-row gọn đẹp (drop Type label redundant + combine mã phiếu/time + Drafter/Dept/HĐ inline). **Plan AI RAG global MCP setup** (User-level Approach A — 1 dev 5 dự án cùng máy localhost) — Phase 0 pre-flight + Phase 1 Qdrant v1.18.0 Windows native binary (KHÔNG Docker, PID 67240 port 6333) + Phase 2 FastMCP server ~1100 LOC Python 9 file (server.py + lib/embed.py voyage wrapper + lib/retrieval.py 3-layer pipeline + lib/projects.py auto-detect cwd + lib/chunking.py contextual prepend + lib/watcher.py) + Phase 3 register MCP user-level (`claude mcp add` với `--` separator trick) + Phase 4 bootstrap SOLUTION_ERP 126 files → **2,392 chunks indexed 60.9s** (~484K Voyage tokens = 0.24% free tier 200M/month). 4 test queries verified end-to-end recall: "gotcha #45 PE button TraLai" 0.641 / "admin opt-in per-NV" 0.836 / "EF migration backfill" 0.766 / "multi-agent setup" 0.879. Stack: Voyage-4-large embedding + Voyage rerank-2.5 + Qdrant Windows native + SQLite FTS5 BM25 + Reciprocal Rank Fusion + Anthropic Contextual Retrieval prepend + FastMCP 3.3.1 stdio. **+1 file MD onboarding `docs/guides/multi-agent-setup-guide.md`** xuất cho 4 dự án future (NamGroup/DH Y Dược/Ashico/Vipix detected từ Claude Desktop config epitaxy folder permission). Multi-agent execution S26: 🟦 Investigator 2 spawn (Plan AG audit 5Q ~30K + Plan AI RAG distribution research ~40K — 4 study cases Cursor/Cline/Continue/Sourcegraph) + 🟨 Implementer 1 spawn (Plan AG Case 2 cookie-cutter ~16K) + 🟥 Reviewer 1 spawn (Plan AG pre-commit ~25K PASS 0 blocker) + 🟩 CICD Monitor 1 spawn (Run #222 verify ~12K). Em main solo Plan AG2-AG6 + Plan AI Phase 0-4 (UI polish iteration + RAG infra setup — cost ROI thấp nếu spawn 5×). Stats final S26 chốt: **31 mig (no schema)** · 59 tables · ~146 endpoints · 35 FE pages · **111 test pass unchanged** (UAT defer test-after) · 49 gotcha unchanged · 23 memory user-level unchanged · 6 skills · 4 sub-agents · **+1 docs file `multi-agent-setup-guide.md`** + **+1 RAG infrastructure** `D:\.claude-rag\` (server + lib + qdrant-bin + data). Patterns reusable cross-project (3 NEW S26): (1) HTML native `<details>/<summary>` + Tailwind named groups `group/proj` + localStorage Set<string> cho hierarchical tree UI when no Accordion lib available (Pattern 19 Implementer NEW), (2) RAG User-level Global MCP 1 server localhost serve N project (Approach A Plan AI), (3) Qdrant Windows native binary deployment (no Docker overhead — appropriate cho 1 dev solo scenario, không scale enterprise). **Memory FLAG**: cicd-monitor MEMORY ~74KB (+2KB từ S25), critical curate session URGENT next.)
**Last updated S25:** 2026-05-19 (Session 25 chốt cuối — **🎯 S25 cumulative wrap: 7 plan + 7 commits Plan AB→AF + 7 CICD Runs (#215 FAIL → #216-#221 PASS)**. Push remote `e23f51c..506cada`. Bro UAT 2026-05-19 phát hiện 2 bug visibility critical PE/2026/A/032 + 4 follow-up polish UAT iteration: **Bug 1 Budget Adjust** không show "Lịch sử thay đổi" (BE log Header+Update OK nhưng FE filter strict TraLai-only loại) — **Bug 2 Return Mode 4 mode** không log Changelog (ApplyReturnModeAsync miss `db.PurchaseEvaluationChangelogs.Add()`) — **Bug 3 Lịch sử duyệt** missing Trả lại + Vượt cấp entries (Reject branch không add Approval row) — **Bug 4 dual-phase badges** gây nhầm "Đã gửi duyệt → Đã gửi duyệt" cho 3 mode Reject giữ Phase=ChoDuyet — **Bug 5 Changelog UserName** show "Hệ thống" thay vì user thật (9 sites BE miss UserName) — **Bug 6 historical name resolve** entries pre-deploy vẫn show empty (forward-only fix). **Plan AB Chunk A** (`cdfd542`) BE log return mode + FE filter relax × 2 app. **Plan AB Chunk A2** (`8c05947`) fix Plan M tests SQLite frozen-clock tie-break (gotcha #48 NEW — Run #215 caught + Run #216 PASS). **Plan AC** (`a734bf2`) BE Reject add Approval row + skipToFinal comment + FE Decision badge × 2 app. **Plan AC2** (`25837b6`) FE merge synthetic Reject rows từ Changelog historical (Option 2A bro chốt, reversible no-DB-touch). **Plan AD** (`0aaf2df`) Drop misleading dual-phase badges + parse next-target hint via regex `Chuyển phase X → Y` + comment keyword Trả lại/Vượt cấp (gotcha #49 NEW). **Plan AE** (`9ea62be`) BE preventive batch fix UserName 9 Changelog.Add sites (Budget Adjust + 8 sites: Create + Update + Detail CRUD + Quote CRUD + Select Winner). **Plan AF** (`506cada`) FE userMap fallback từ embedded domain data PeDetailBundle (drafter + approvals + approvalFlow + levelOpinions + departmentOpinions) — no extra API fetch admin permission. Multi-agent execution: 🟦 **Investigator** 1 spawn Plan AB Bug 1+2 audit ~28K + 🟨 **Implementer** 1 spawn Plan AB Chunk A ~12K Case 1 + 🟥 **Reviewer** 1 spawn Plan AB pre-commit ~22K PASS 0 blocker (1 minor non-block) + 🟩 **CICD Monitor** 7 spawns Run #215-#221 verify ALL PASS post-Plan AB Chunk A2 fix. **Em main solo từ Plan AC đến AF** (5 plan, cross-stack reasoning + UAT iteration borderline, Implementer/Reviewer KHÔNG re-spawn). Stats final S25 chốt: **31 mig (no schema)** · 59 tables · ~146 endpoints · 35 FE pages · **111 test pass unchanged** (UAT defer test-after per §7) · **49 gotcha (+2 #48 SQLite tie-break + #49 dual-phase UI confusion)** · **23 memory user-level (+2 NEW: `feedback_fe_merge_synthetic_audit` Plan AC2 + `feedback_fe_usermap_fallback` Plan AF)** · 6 skills · 4 sub-agents active. Bundle hash 6× rotate × 2 app (#216-#221), Mig 31 unchanged toàn S25. Patterns reusable cross-project (8 NEW S25): (1) Multi-Changelog.Add SQLite tie-break test discriminator, (2) CICD catch UAT skip test risk for BE refactor > 100 LOC, (3) Test fix Option A over BE refactor preservation, (4) Capture pre-call mutation state cho audit row from-position, (5) FE merge synthetic rows từ Changelog reversible recovery, (6) Drop misleading dual-phase badges + parse semantic hint, (7) Changelog UserName preventive systemic batch fix, (8) FE userMap fallback từ embedded domain data no extra API. **Memory CRITICAL FLAG**: cicd-monitor MEMORY ~72KB strongly over 50KB hard threshold — DEDICATED CURATION SESSION REQUIRED next (archive Run #186-#210 + S22-S24 verbose). Bro UAT verify ALL Plan AB→AF live deploy cumulative.)
**Last updated S23 t12:** 2026-05-15 (Session 23 turn 12 chốt cuối — **🎯 S23 cumulative wrap: 11 plan + 32 commits cumulative**. Plan K (Mig 31 F2 refactor 9 commits) → L (UAT bug 5) → M (F1 edge case 4) → N (per-NV lookup 1 site 2) → O (4 sites cascade 2) → P (Controller body record 1) → Q (FE banner CSS 1) → R (cleanup phiếu/workflow 1) → S (wipe ALL workflows 1) → T (DemoSeed flag 2) → U (sidebar truncate 1). 4 sub-agents active throughout: 🟦 Investigator 5 spawn (K0 + N + P FE wire + R audit + L2 spawn) + 🟨 Implementer 5 spawn (K1/K3/K5/K7 + M2 + M3 Case 2/3) + 🟥 Reviewer 2 spawn (K2 pre-commit + M3 cumulative review) + 🟩 CICD Monitor 5 spawn (Run #195 K10 + #199 L + #200 M + #201 N + #202 O + #203 P + #204 Q + #207 T + #208 T5+T6 + #209 U — ALL PASS). **Memory user-level update cumulative S23:** `feedback_per_nv_permission_scope.md` reinforced 5 sections (S22+5 + S23 t1 + t3 + t4 + t5 + t6) → wire 10 surface points (point 9 lookup discrimination + point 10 Controller body record mirror). `feedback_uat_skip_verify.md` Plan L lesson Service refactor semantic test atomic. **+1 memory NEW** `feedback_demo_seed_flag_disable.md` cross-project Plan T pattern. **3 destructive cleanup cumulative Plan R+S+T5** ~720 rows wiped + DbInitializer permanent disable demo seed. **Stats final S23 chốt cuối:** 31 mig · 59 tables · ~145 endpoints · 34 FE pages · **111 test unchanged** · 47 gotcha · **21 memory entries** (+1 NEW Plan T flag pattern) · 6 skills · 4 sub-agents active · **0 PE + 0 demo workflow + DemoSeed flag persist** UAT permanent clean slate. Backup rollback: `vietreport-vps:C:\Backup\SolutionErp_pre_cleanup_2026-05-15.bak` 18.5MB. **32 commits S23** pushed remote `eb106f2..86d8806`. CI verify ALL PASS. Bro Designer setup workflow mới from scratch, KHÔNG còn auto re-seed contaminate. Plan B Contract V2 wire HIGH priority next.) **Last updated S23 t12:** 2026-05-15 (Session 23 turn 12 chốt cuối — **🎯 S23 cumulative wrap: 11 plan + 32 commits cumulative**. Plan K (Mig 31 F2 refactor 9 commits) → L (UAT bug 5) → M (F1 edge case 4) → N (per-NV lookup 1 site 2) → O (4 sites cascade 2) → P (Controller body record 1) → Q (FE banner CSS 1) → R (cleanup phiếu/workflow 1) → S (wipe ALL workflows 1) → T (DemoSeed flag 2) → U (sidebar truncate 1). 4 sub-agents active throughout: 🟦 Investigator 5 spawn (K0 + N + P FE wire + R audit + L2 spawn) + 🟨 Implementer 5 spawn (K1/K3/K5/K7 + M2 + M3 Case 2/3) + 🟥 Reviewer 2 spawn (K2 pre-commit + M3 cumulative review) + 🟩 CICD Monitor 5 spawn (Run #195 K10 + #199 L + #200 M + #201 N + #202 O + #203 P + #204 Q + #207 T + #208 T5+T6 + #209 U — ALL PASS). **Memory user-level update cumulative S23:** `feedback_per_nv_permission_scope.md` reinforced 5 sections (S22+5 + S23 t1 + t3 + t4 + t5 + t6) → wire 10 surface points (point 9 lookup discrimination + point 10 Controller body record mirror). `feedback_uat_skip_verify.md` Plan L lesson Service refactor semantic test atomic. **+1 memory NEW** `feedback_demo_seed_flag_disable.md` cross-project Plan T pattern. **3 destructive cleanup cumulative Plan R+S+T5** ~720 rows wiped + DbInitializer permanent disable demo seed. **Stats final S23 chốt cuối:** 31 mig · 59 tables · ~145 endpoints · 34 FE pages · **111 test unchanged** · 47 gotcha · **21 memory entries** (+1 NEW Plan T flag pattern) · 6 skills · 4 sub-agents active · **0 PE + 0 demo workflow + DemoSeed flag persist** UAT permanent clean slate. Backup rollback: `vietreport-vps:C:\Backup\SolutionErp_pre_cleanup_2026-05-15.bak` 18.5MB. **32 commits S23** pushed remote `eb106f2..86d8806`. CI verify ALL PASS. Bro Designer setup workflow mới from scratch, KHÔNG còn auto re-seed contaminate. Plan B Contract V2 wire HIGH priority next.)
**Last updated S23 t10:** 2026-05-15 (Session 23 turn 10 — **🔧 Plan T: Disable auto re-seed demo data + final DELETE — UAT permanent clean slate**. Bro phát hiện sau Plan R+S: 4 phiếu `[DEMO]-A/B` + 2 V1 workflows + 1 V2 mẫu UAT TỰ ĐỘNG RE-SEED sau khi BE deploy commits Plan P+Q+R+S → IIS recycle → `DbInitializer.InitializeAsync` chạy lại 5 demo seed methods. Bro AskUserQuestion chốt Option A: disable demo seed vĩnh viễn qua flag config. Em main implement: `appsettings.json` add `"DemoSeed": { "Disabled": true }` + `appsettings.Development.json` override `false` cho dev test seed local + `DbInitializer.cs` add `using Microsoft.Extensions.Configuration` + `var demoSeedDisabled = config.GetValue<bool>("DemoSeed:Disabled")` + wrap 5 method conditional `if (!demoSeedDisabled)` (SeedWorkflowDefinitions V1 + SeedPurchaseEvaluationWorkflows V1 + SeedDemoContracts + SeedDemoPurchaseEvaluations + SeedSampleApprovalWorkflowsV2). KEEP: SeedRoles + SeedAdmin + SeedDepartments + SeedDemoUsers (30 UAT users) + SeedMenuTree + SeedAdminPermissions + SeedDemoMasterData (Supplier/Project) + SeedContractTemplates + SeedCatalogs + Backfill helpers. Note: `appsettings.Production.json` bị `.gitignore` (secrets), em set flag mặc định trong `appsettings.json` commit qua git — production inherit `true`. Run #207 sha=0b97840 PASS 3min24s → IIS deploy applied flag. T5 final DELETE: SCP `scripts/plan-t5-final-cleanup.sql` upload + sqlcmd -i 3 TRANSACTION DELETE → 4 PE + 1 V2 + 2 V1 = 7 rows + cascade child. T6 verify NO re-seed loop: `Restart-WebAppPool SolutionErp-Api` force IIS recycle → BE startup → wait healthy → sqlcmd verify: **PE=0 + V2=0 + V1=0** preserved (KHÔNG re-seed) + Users=33 + Suppliers=19 + Projects=9 + Contracts=7 (existing preserved). DemoSeed flag PROVEN active end-to-end. Total cumulative Plan R+S+T cleanup: ~677 rows wiped + DbInitializer re-seed disable vĩnh viễn. Stats final S23 t10: **31 mig** · 59 tables · ~145 endpoints · 34 FE pages · **111 test unchanged** · 47 gotcha · 20 memory · 6 skills · **0 PE + 0 workflow + flag disable demo seed** — UAT permanent clean slate. Bro Designer setup workflow mới from scratch, KHÔNG còn auto re-seed contaminate.) **Last updated S23 t10:** 2026-05-15 (Session 23 turn 10 — **🔧 Plan T: Disable auto re-seed demo data + final DELETE — UAT permanent clean slate**. Bro phát hiện sau Plan R+S: 4 phiếu `[DEMO]-A/B` + 2 V1 workflows + 1 V2 mẫu UAT TỰ ĐỘNG RE-SEED sau khi BE deploy commits Plan P+Q+R+S → IIS recycle → `DbInitializer.InitializeAsync` chạy lại 5 demo seed methods. Bro AskUserQuestion chốt Option A: disable demo seed vĩnh viễn qua flag config. Em main implement: `appsettings.json` add `"DemoSeed": { "Disabled": true }` + `appsettings.Development.json` override `false` cho dev test seed local + `DbInitializer.cs` add `using Microsoft.Extensions.Configuration` + `var demoSeedDisabled = config.GetValue<bool>("DemoSeed:Disabled")` + wrap 5 method conditional `if (!demoSeedDisabled)` (SeedWorkflowDefinitions V1 + SeedPurchaseEvaluationWorkflows V1 + SeedDemoContracts + SeedDemoPurchaseEvaluations + SeedSampleApprovalWorkflowsV2). KEEP: SeedRoles + SeedAdmin + SeedDepartments + SeedDemoUsers (30 UAT users) + SeedMenuTree + SeedAdminPermissions + SeedDemoMasterData (Supplier/Project) + SeedContractTemplates + SeedCatalogs + Backfill helpers. Note: `appsettings.Production.json` bị `.gitignore` (secrets), em set flag mặc định trong `appsettings.json` commit qua git — production inherit `true`. Run #207 sha=0b97840 PASS 3min24s → IIS deploy applied flag. T5 final DELETE: SCP `scripts/plan-t5-final-cleanup.sql` upload + sqlcmd -i 3 TRANSACTION DELETE → 4 PE + 1 V2 + 2 V1 = 7 rows + cascade child. T6 verify NO re-seed loop: `Restart-WebAppPool SolutionErp-Api` force IIS recycle → BE startup → wait healthy → sqlcmd verify: **PE=0 + V2=0 + V1=0** preserved (KHÔNG re-seed) + Users=33 + Suppliers=19 + Projects=9 + Contracts=7 (existing preserved). DemoSeed flag PROVEN active end-to-end. Total cumulative Plan R+S+T cleanup: ~677 rows wiped + DbInitializer re-seed disable vĩnh viễn. Stats final S23 t10: **31 mig** · 59 tables · ~145 endpoints · 34 FE pages · **111 test unchanged** · 47 gotcha · 20 memory · 6 skills · **0 PE + 0 workflow + flag disable demo seed** — UAT permanent clean slate. Bro Designer setup workflow mới from scratch, KHÔNG còn auto re-seed contaminate.)

View File

@ -0,0 +1,262 @@
# Session 26 — 2026-05-21 — PE List tree view UI iteration + RAG Global MCP setup
**Dev:** Claude (em main + 4 sub-agents Investigator/Implementer/Reviewer/CICD Monitor) + bro pqhuy
**Duration:** ~5h (start ~17:00 → end ~22:00 GMT+7)
**Base commit:** `506cada` (S25 chốt cuối Plan AF)
**Final commits cumulative:** `0bf6c7e..d99069a` (6 commits Plan AG series push remote)
**+ Infrastructure:** `D:\.claude-rag\` RAG global server setup (out-of-tree, không commit)
---
## 🎯 Làm được
### Plan AG series — PE List tree view UI iteration (UAT bro Tra Sol)
#### Plan AG (`0bf6c7e`) — Phase 1 tree view 2-level Project > Gói thầu > PE
Trigger UAT 2026-05-21 screenshot bro Tra Sol + anh Kenny: UI Duyệt NCC PE List "đám rừng" flat list + đề xuất "khoanh sẵn thư mục gói thầu như mail".
🟦 **Investigator audit 5Q** (~30K spawn) confirm: Project entity ready Phase 2 ProjectPackage table, PE.TenGoiThau text free-form (variation risk), shadcn fe-user thiếu Accordion/Collapsible (fallback HTML `<details>/<summary>` native), Mig 31 stable, Phase 2 naming `AddProjectPackageTable`.
🟨 **Implementer Case 2 cookie-cutter mirror 2 app** (~16K spawn) deliver:
- Chunk A useMemo group nested `ProjectGroup{goiThauList[]}` + sort vi locale + fallback "(Dự án đã xoá)" + "(Chưa phân loại)"
- Chunk B UI `<details>/<summary>` HTML native 2-level + Tailwind named groups `group/proj` + `group/gt` chevron rotation + `[&::-webkit-details-marker]:hidden`
- Chunk C localStorage Set<string> persist key `pe_list_expanded_groups`
🟥 **Reviewer pre-commit** (~25K spawn) verify 5-category + 12 adversarial deep checks PASS 0 blocker.
🟩 **CICD Monitor Run #222** (~12K spawn) bundle hash 2 app rotated `C8TvDy7r→CWHIdoFo` admin + `BvcWrq2z→Bg2FNeIz` user. Stage 4c API shape preserved.
#### Plan AG2 (`c5429c0`) — Simplify 1-level + widen Panel 1
Bro feedback "Plan AG 2-level cầu kỳ quá, gói thầu thì ko cần thiết phải treedow". Em main solo refactor:
- Drop `GoiThauGroup` nested type
- useMemo group 1-level: `Map<projectId, ProjectGroup{items[]}>`
- Panel 1 widen `lg:grid-cols-[340px_1fr_360px]``[400px_1fr_360px]`
- Single PE project → flat card (no `<details>`); Multi PE → tree
- localStorage key rename `pe_list_expanded_projects`
#### Plan AG3 (`fbad4a9`) — Drop single-PE flat consistent UI
Bro screenshot follow-up "nếu có 1 thì cũng để tương tự luôn nhé, đừng để khác các thằng kia". Em main solo drop `if (pg.items.length === 1)` branch → mọi dự án dù 1/N phiếu đều render `<details>` folder collapsed. Diff -110 LOC (clean).
#### Plan AG4 (`2bf0118`) — BE+FE bổ sung Drafter + Department
Bro feedback "bổ sung thêm người tạo + phòng ban tạo vào danh sách phiếu". Em main solo cross-stack:
**BE 4 file:**
- `PurchaseEvaluationDtos.cs` DTO +4 fields `DrafterUserId/DrafterName/DepartmentId/DepartmentName`
- `PurchaseEvaluationFeatures.cs` ListHandler + InboxHandler projections JOIN Users + Departments LEFT (cả 2 nullable theo PE entity)
- `CreateContractFromEvaluationFeatures.cs` ApprovedHandler mirror JOIN
**FE 4 file × 2 app mirror §3.9:**
- `types/purchaseEvaluation.ts` PeListItem +4 fields
- `PurchaseEvaluationsListPage.tsx` PE card row render `👤 {drafterName} · {departmentName}` giữa Mã phiếu và Supplier
Verify: `dotnet test SolutionErp.slnx` 111/111 PASS unchanged. `npm build` × 2 app clean 0 TS err.
#### Plan AG5 (`083b601`) — Extend tree 3-level Project > Năm > NCC > PE
Bro chốt "Folder cấp dưới dự án là theo năm và dưới năm là theo NCC nhé". Em main solo refactor:
- `type SupplierGroup{supplierId, supplierName, items[]}` (italic "(Chưa chọn NCC)" cho PE chưa DaDuyet)
- `type YearGroup{year, suppliers[], totalCount}` extract `new Date(p.createdAt).getFullYear()`
- `type ProjectGroup{projectId, projectName, years[], totalCount}`
- 3 cấp nested `<details>` với Tailwind named groups `group/proj` + `group/year` + `group/sup`
- Sort: Project A-Z vi · Year DESC · NCC A-Z vi · PE createdAt DESC
- localStorage 3-level key format `projectId / projectId::y{year} / projectId::y{year}::s{supplierId}`
#### Plan AG6 (`d99069a`) — Compact card 3-row gọn đẹp
Bro feedback "Cho thông tin bên trong này nó gọn đẹp lại nhé". Em main solo:
- `py-2.5``py-2` (compact vertical padding)
- Drop Type label "Duyệt NCC" badge (redundant với page header)
- Combine row mã phiếu + time `PE/2026/A/035 · 10:40 19/05/2026`
- Combine row drafter + department + contract `👤 Drafter · Phòng ban [✓ HĐ]` (conditional)
- Separator `slate-300` nhẹ hơn để mắt không bị rối
### Plan AI — RAG User-level Global MCP setup (Approach A)
Bro plan setup RAG cho 5 dự án cùng máy localhost share infrastructure. Em main + Investigator deep research 4 study cases (Cursor + Cline + Continue + Sourcegraph) → kết luận User-level Global MCP pattern (1 dev N project, không phải team VPS pattern).
#### Phase 0 — Pre-flight check (15 phút)
✅ Python 3.11.3 OK · ✅ Docker installed nhưng SKIP per bro chốt no Docker · ❌ VOYAGE_API_KEY chưa set → bro set User scope length 46 prefix pa-Mi... · ✅ Disk D:\\ 32GB free (acceptable) · ✅ pip packages install fastmcp 3.3.1 + voyageai 0.3.7 + qdrant-client 1.18.0 + watchdog 6.0.0 + chromadb 1.5.9 (bonus) + python-dotenv 1.2.2.
#### Phase 1 — Qdrant Windows native binary (30 phút)
Bro chốt KHÔNG Docker → em verify Qdrant GitHub releases qua WebFetch:
- ✅ Qdrant v1.18.0 (released 2026-05-11) **CÓ Windows native binary** `qdrant-x86_64-pc-windows-msvc.zip` 28.3 MB chính thức
- Download + extract `D:\.claude-rag\qdrant-bin\qdrant.exe`
- Tạo config.yaml: storage_path `D:\.claude-rag\data\qdrant-storage`, http_port 6333, on_disk_payload true, telemetry_disabled true
- Start background hidden: PID 67240, health check 200 "healthz check passed"
#### Phase 2 — FastMCP server code ~1100 LOC Python 9 file
```
D:\.claude-rag\
├── server.py (210 LOC) — FastMCP entry + 6 tool handlers
├── bootstrap.py (150 LOC) — initial corpus embed CLI
├── README.md
└── lib/
├── __init__.py
├── projects.py (140 LOC) — auto-detect cwd → project_id từ .claude/rag.json + registry tracking
├── chunking.py (120 LOC) — Markdown chunking + Anthropic Contextual Retrieval prepend "From <doc> > <heading>:"
├── embed.py (140 LOC) — Voyage AI wrapper (embed + rerank + retry exponential backoff + SHA256 cache)
├── retrieval.py (230 LOC) — 3-layer pipeline (Vector Qdrant + BM25 SQLite FTS5 + RRF k=60 + Voyage rerank-2.5)
└── watcher.py (100 LOC) — Watchdog file watcher với debounce 2s
```
**6 MCP tools exposed:**
- `search_memory(query, scope, top_k, use_rerank)` — current project + shared_global hybrid search
- `cross_project_search(query, top_k)` — search ALL registered project collections
- `search_code(query, file_pattern, top_k)` — BM25-heavy code symbol search
- `store_memory(content, source_path, tags)` — add on-the-fly memory chunk
- `promote_to_shared(chunk_id)` — promote project-local → shared_global (v0 stub)
- `list_projects()` — registry overview + Qdrant collection stats
#### Phase 3 — Register MCP user-level (15 phút trial 5 lần)
**Trick CLI `claude mcp add` syntax:** `-e KEY=VAL` flag là variadic — phải có `--` separator ngay sau env list trước `<name>` để terminate parsing.
Final command working:
```bash
claude mcp add -s user -e "VOYAGE_API_KEY=$VK" -- rag-unified python "D:\.claude-rag\server.py"
```
Output: `rag-unified: python D:\.claude-rag\server.py - ✓ Connected`.
#### Phase 4 — Bootstrap SOLUTION_ERP corpus (5 phút)
`.claude/rag.json` ở SOLUTION_ERP project root:
```json
{
"project_id": "solution_erp",
"display_name": "SOLUTION_ERP — Quản lý HĐ NCC",
"corpus_paths": ["docs/**/*.md", ".claude/agent-memory/**/MEMORY.md", ".claude/skills/**/SKILL.md"],
"extra_corpus": ["C:\\Users\\pqhuy\\.claude\\projects\\D--Dropbox-CONG-VIEC-SOLUTION\\memory\\*.md"],
"share_to_global": true,
"search_scope_default": ["self", "shared_global"],
"contextual_retrieval": true
}
```
Bootstrap output:
```
[1/4] Scanning corpus... Found 126 files
[2/4] Chunking + contextual prepend... Total chunks: 2392
Estimated tokens: ~484,508 (Voyage free tier: 200M/month)
[3/4] Voyage-4-large embedding + Qdrant upsert + SQLite BM25... Upserted 2392 chunks in 60.9s
[4/4] Update registry...
✓ Bootstrap complete: solution_erp ready (2392 chunks)
```
### Bonus: File MD onboarding guide xuất
`docs/guides/multi-agent-setup-guide.md` (~750 lines markdown) — full guide cho 1 master README + 4 agent definition templates + MEMORY.md seed cho dự án mới. Bro paste vào dự án mới (NamGroup/DH Y Dược/Ashico/Vipix detected từ Claude Desktop config epitaxy) để setup 4 sub-agent + RAG infra.
---
## E2E verified
### Plan AG series verify
| Plan | Commit | BE test | FE build × 2 | SHA256 mirror | CICD Run |
|---|---|---|---|---|---|
| AG | `0bf6c7e` | 111/111 PASS unchanged | PASS 0 TS err | ✅ `21001E90...` | #222 PASS bundle rotate |
| AG2 | `c5429c0` | 111/111 unchanged | PASS | ✅ `37520D01...` | Run #223 PASS (em main verify) |
| AG3 | `fbad4a9` | 111/111 unchanged | PASS | ✅ `749FF703...` | Run #224 PASS |
| AG4 | `2bf0118` | **111/111 PASS** dotnet test verify cross-stack | PASS | ✅ verified | Run #225 PASS |
| AG5 | `083b601` | 111/111 unchanged | PASS | ✅ `E5FE4979...` | Run #226 PASS |
| AG6 | `d99069a` | 111/111 unchanged | PASS | ✅ `3645307C...` | Run #227 PASS |
### Plan AI RAG verify 4 query thực tế
```
Query 1: "gotcha 45 PE button TraLai mismatch" → rerank 0.641 (Reviewer MEMORY Plan AB)
Query 2: "pattern admin opt-in per-NV flag" → rerank 0.836 (Session 23 t1 Plan K)
Query 3: "EF migration backfill SQL reorder" → rerank 0.766 (Session 21 t5 Refactor Allow)
Query 4: "multi-agent setup 4 sub-agents" → rerank 0.879 (Session 21 t1 cicd-monitor + new guide)
```
---
## 🐛 Bug gặp + fix
| Bug | Fix |
|---|---|
| Bash shell không inherit User-scope env var từ PowerShell parent | Workaround: `VK=$(powershell -NoProfile -Command "...")` mỗi Bash command + `export VOYAGE_API_KEY="$VK"` |
| `claude mcp add -e KEY=VAL` 5 lần FAIL "Invalid environment variable format: rag-unified" | Trick: thêm `--` separator ngay sau env list trước `<name>` để terminate variadic `-e` flag |
| Qdrant upsert 2392 chunks batch lớn FAIL WinError 10053 "connection aborted host machine" | Batching 64 chunks/upsert + `wait=True` trong `lib/retrieval.py:UPSERT_BATCH` |
| SQLite FTS5 `sqlite3.OperationalError: no such column: in` cho query có dấu `-` ("opt-in") | `_sanitize_fts5_query()` strip non-alphanumeric + quote token-by-token `f'"{t}"'` + fallback empty result trên OperationalError |
| HuggingFace symlinks warning Windows non-developer mode | Non-critical (cache work OK degraded efficiency) — note `HF_HUB_DISABLE_SYMLINKS_WARNING=1` env var optional suppress |
---
## 📚 Docs updates
| File | Update |
|---|---|
| `docs/STATUS.md` | Last updated S26 chốt cuối (cumulative wrap 6 plan AG series + Plan AI Phase 0-4) |
| `docs/HANDOFF.md` | TL;DR S26 chốt cuối với 3 patterns NEW reusable cross-project |
| `docs/changelog/sessions/2026-05-21-s26-pe-tree-view-rag-setup.md` | File này — session log đầy đủ |
| `docs/guides/multi-agent-setup-guide.md` | NEW ~750 lines, onboarding 4 dự án future |
| `.claude/agent-memory/investigator/MEMORY.md` | +2 entry S26 (Plan AG audit 5Q + Plan AI RAG research 4 study cases) |
| `.claude/agent-memory/implementer/MEMORY.md` | +1 entry S26 (Plan AG Chunk A+B+C + Pattern 19 HTML details + Tailwind named groups + localStorage Set) |
| `.claude/agent-memory/reviewer/MEMORY.md` | +1 entry S26 (Plan AG pre-commit PASS 0 blocker + 5 polish em main solo self-review) |
| `.claude/agent-memory/cicd-monitor/MEMORY.md` | +1 entry S26 (Run #222 verify + Run #223-#227 em main self-verify pattern). Memory ~74KB CRITICAL CURATE next |
| Memory user-level `feedback_rag_hybrid_pattern.md` | Update section "Implementation actual achievements S26" với stack chốt + Phase 0-4 + 7 bài học extra |
| Memory user-level `MEMORY.md` index | Update entry RAG Hybrid với stack mới Voyage-4-large + rerank-2.5 + Qdrant Windows native |
---
## 🤝 Handoff S27+
### Pending priority HIGH
1. **Memory CRITICAL CURATE** 4 agent — cicd-monitor 74KB OVER 50KB hard threshold (archive Run #186-#221 verbose → `archive/2026-05-runs.md`)
2. **Plan AI Phase 5 bootstrap 4 project còn lại** (NamGroup + DH Y Dược + Ashico + Vipix) — ~30 phút/project, copy `.claude/rag.json` template + bootstrap.py CLI
3. **Plan B Contract V2 wire** (defer carryover từ S25) — mirror PE Mig 22-23 pattern proven 1× S17 + Investigator/Implementer Case 2 pre-allocated
### Pending priority MEDIUM
4. **Plan AI Phase 6** file watcher real-time auto re-embed + Windows Task Scheduler auto-start Qdrant khi boot
5. **Xuất `rag-onboarding-guide.md`** cho 4 project khác paste config (defer sau Phase 5 ổn 1-2 tuần UAT)
6. **Test debt catch-up Plan C bundle** (S22+1 + S25 + S26 bug fix chưa add regression test — UAT mode defer per §7)
### Pending priority LOW
7. Benchmark RAG recall@10 golden dataset 100 query thật (gap optional)
8. Disaster recovery weekly backup Qdrant data → Dropbox (gap optional)
9. Gotcha #48 SQLite tie-break + #49 dual-phase UI confusion add `docs/gotchas.md` (carry từ S25)
---
## 📊 Thông số cumulative S26
| Metric | S25 chốt | S26 chốt | Δ |
|---|---|---|---|
| DB tables | 59 | 59 | 0 |
| Migrations | 31 | 31 | 0 (no schema change) |
| Endpoints | ~146 | ~146 | 0 (same shape, +4 fields DTO ListItem) |
| FE pages | 35 | 35 | 0 (logic enhanced PE List) |
| Unit tests | 111 | 111 | 0 (UAT mode defer per §7) |
| Gotchas | 49 | 49 | 0 |
| Memory user-level | 23 | 23 | 0 (RAG entry updated stack mới) |
| Skills project-local | 6 | 6 | 0 |
| Sub-agents | 4 | 4 | 0 (5 spawn S26: Inv 2 + Imp 1 + Rev 1 + CICD 1) |
| Commits remote | `e23f51c..506cada` | `e23f51c..d99069a` | **+6** (`0bf6c7e..d99069a`) |
| Docs files | — | +1 | `multi-agent-setup-guide.md` |
| Infrastructure | — | +1 | `D:\.claude-rag\` RAG global (out-of-tree) |
| RAG corpus indexed | 0 | **2,392 chunks** | SOLUTION_ERP bootstrap |
| Voyage tokens used | 0 | ~484K | 0.24% free tier 200M/month |
### Multi-agent ROI S26
| Agent | Spawn | Token cost | Catch |
|---|---|---|---|
| 🟦 Investigator | 2× | ~70K | Plan AG audit 5Q + Plan AI RAG distribution research 4 study cases |
| 🟨 Implementer | 1× | ~16K | Plan AG Case 2 cookie-cutter mirror 2 app + Pattern 19 NEW |
| 🟥 Reviewer | 1× | ~25K | Plan AG pre-commit PASS 0 blocker + 5 polish em main solo verified |
| 🟩 CICD Monitor | 1× | ~12K | Run #222 PASS bundle hash 2 app rotate verified |
| 👤 Em main solo | continuous | ~280K (estimate) | Plan AG2-AG6 polish iteration + Plan AI Phase 0-4 setup + docs/MD writes |
| **Total** | **5 spawn** | **~403K** | ~28% solo equivalent — ROI tốt cho heavy session |

View File

@ -0,0 +1,958 @@
# Multi-Agent Setup Guide — 1 Em main + 4 Sub-agents
> **Tài liệu hướng dẫn setup multi-agent workflow cho dự án Claude Code mới.**
> Pattern: 1 em main coordinator (Opus 4.7 1M Max) + 4 sub-agents specialized roles.
> Empirical-grounded từ trial NAMGROUP s41-s43 + SOLUTION_ERP S20-S26, ROI ~28% solo equivalent cho heavy session.
---
## 🎯 TL;DR
- **4 sub-agents:** Investigator (read research) · Implementer (write strict) · Reviewer (adversarial verify) · CICD Monitor (post-deploy watchdog)
- **+1 em main coordinator:** reasoning + decisions + user dialog + synthesize cross-agent findings
- **Setup time:** ~30 min (tạo 9 file template = 1 master README + 4 agent definition + 4 MEMORY.md seed)
- **Trial period:** 2-4 tuần evaluate ROI trước khi commit pattern
- **Cost reality:** ~700K-1.35M tokens / heavy session (Max 20× plan absorbs comfortable)
- **Pass criteria sau Week 4:** Reviewer catch ≥ 2 wire bugs + CICD Monitor catch ≥ 1 deploy ship fail + time saving ≥ 25% cookie-cutter task
---
## 📋 Setup checklist (8 steps)
```
□ 1. Tạo folder `.claude/agents/` + `.claude/agent-memory/<agent>/` × 4
□ 2. Paste 5 file template từ §4 — customize <PROJECT_NAME> + tech stack §5
□ 3. Tạo 4 MEMORY.md seed cho 4 agent (template §4.6) — fill state baseline
□ 4. Verify Claude Code CLI list agents: `claude /agents`
□ 5. Test spawn 1 Investigator audit task nhỏ để confirm config OK
□ 6. Plan Trial Week 1 — chọn task ~600+ LOC cookie-cutter Implementer Case 2
□ 7. CI/CD Monitor verify post-push deploy đầu tiên
□ 8. Week 4 evaluate Pass/Fail criteria → continue hoặc rollback solo
```
---
## 1. Architecture overview
```
┌─────────────────────────────────────────────────────────┐
│ EM (Main) — Opus 4.7 1M Max │
│ • Reasoning + write code (single-threaded principle) │
│ • User dialog + architectural decisions │
│ • Coordinate 4 sub-agents via SendMessage │
│ • Synthesize cross-agent findings end-of-session │
└─────────────────────────────────────────────────────────┘
↓ spawn + keep-alive (Opus 4.7 1M Max each)
┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐
│Investigator│ │ Implementer│ │ Reviewer │ │ CI/CD │
│ │ │ │ │ │ │ Monitor │
│ READ only │ │WRITE strict│ │ READ only │ │ READ only │
│ │ │ classified │ │ adversarial│ │ post-deploy│
│ Research + │ │Cookie-cutter│ │ pre-commit │ │ │
│ Audit + │ │ + Multi-file│ │ + live │ │ Poll CI + │
│ External │ │ independent│ │ verify │ │ bundle hash│
│ research │ │ ONLY │ │ │ │ + prod smoke│
└────────────┘ └────────────┘ └────────────┘ └────────────┘
cyan yellow red green
```
**Inspiration sources:**
- Anthropic Building Effective Agents → orchestrator-workers pattern (Investigator + Implementer)
- Cognition "Don't Build Multi-Agents" → "writes single-threaded" principle (em main owns reasoning)
- Custom layer: CICD Monitor post-deploy automated watchdog (recurring blind spot "quên verify thủ công")
---
## 2. File structure cần tạo
```
.claude/
├── agents/
│ ├── README.md ← Master coordination guide (§4.1)
│ ├── investigator.md ← Sub-agent 1 definition (§4.2)
│ ├── implementer.md ← Sub-agent 2 definition (§4.3)
│ ├── reviewer.md ← Sub-agent 3 definition (§4.4)
│ └── cicd-monitor.md ← Sub-agent 4 definition (§4.5)
└── agent-memory/
├── investigator/MEMORY.md ← Persistent diary (§4.6 seed)
├── implementer/MEMORY.md
├── reviewer/MEMORY.md
└── cicd-monitor/MEMORY.md
```
---
## 3. RULE BẮT BUỘC — directive delegate
**Em main BẮT BUỘC phân việc cho sub-agent đúng vai trò khi ACCEPT criteria match.**
Lý do: token cost overhead + lose multi-agent ROI nếu em main solo task lẽ ra delegate được. Sub-agent ROI nằm ở:
- **Investigator** catch root cause em main miss → tránh fix sai cross-stack (~30K spawn cost)
- **Implementer** cookie-cutter mechanical → em main giữ context architectural (~12-16K spawn cost)
- **Reviewer** adversarial pre-commit → catch ~30% wire bug em main miss tự nhiên (~22-25K spawn cost)
- **CICD Monitor** post-deploy auto verify → khắc phục recurring blind spot "quên verify thủ công" (~150K spawn cost — đắt nhưng đáng)
**Em main solo CHỈ khi:** schema/UX/architecture decision + cross-stack tight coupling + bug fix reasoning chain.
### Decision tree — khi nào delegate ai
```
Task input → classify task type:
├── Read-only research / audit / scan > 5 files / external fetch?
│ → Spawn Investigator (always safe)
├── Adversarial pre-commit verify / heavy diff / deploy claim?
│ → Spawn Reviewer (always before push critical)
├── After push code commit (NOT docs-only — path filter rule)?
│ → Spawn CI/CD Monitor (poll CI + bundle hash + prod smoke async)
├── User reports prod issue ("500", "không lên", "không thấy thay đổi")?
│ → Spawn CI/CD Monitor diagnose first (logs + curl + sqlcmd evidence)
├── Cookie-cutter mechanical (N independent files same pattern, deterministic spec)?
│ ✓ N >= 5 files
│ ✓ Spec deterministic (no implicit decisions)
│ ✓ Pattern proven > 1× prior
│ → Spawn Implementer (Case 1)
├── Multi-file independent changes (different modifications per file)?
│ ✓ Each file verifiable independently
│ ✓ Files NOT cross-stack tight coupling
│ → Spawn Implementer (Case 2 orchestrator-workers)
├── Test generation for isolated methods?
│ → Spawn Implementer (Case 3)
├── Mass code migration (framework upgrade, per-file deterministic)?
│ → Spawn Implementer (Case 5)
├── Quick task < 30 min (overhead spawn không xứng)?
│ → Em solo direct
├── Schema design / UX flow / architectural decision / cross-stack tight coupling?
│ → Em solo (Cognition "writes single-threaded")
│ → Investigator pre-flight optional
│ → Reviewer pre-commit always
└── Bug fix tightly coupled (cross BE/FE/DB, reasoning chain)?
→ Em solo (Anthropic warning: "tightly interdependent coding")
→ Investigator pre-flight optional
→ Reviewer pre-commit always
```
---
## 4. File templates (copy-paste vào dự án mới)
### 4.1 `.claude/agents/README.md` — Master coordination guide
````markdown
# Multi-agent <PROJECT_NAME> — Master Coordination Guide
> **Architecture:** 4 sub-agents Opus 4.7 1M Max + em main coordinator.
> Pattern: Anthropic Building Effective Agents orchestrator-workers + Cognition "writes single-threaded" hybrid + post-deploy automated watchdog.
## 🎯 Architecture
[Paste ASCII diagram from §1 above]
## 🚨 RULE BẮT BUỘC
Em main BẮT BUỘC phân việc cho sub-agent đúng vai trò khi ACCEPT criteria match.
Em main solo CHỈ khi: schema/UX/architecture decision + cross-stack tight coupling + bug fix reasoning chain.
## 🔄 Invocation decision tree
[Paste decision tree from §3 above]
## 📋 Implementer task classification — CRITICAL rules
### ✅ ACCEPT criteria (ALL must be true)
1. Spec deterministic (no implicit decisions left for agent)
2. Files independent (modifications don't depend on each other)
3. Pattern repeatable (proven > 1× prior session — reference memory entries)
4. Estimated effort > 30 min (overhead worth)
5. Max 2 layers cross-stack (NOT BE entity + DTO + FE wire 3-layer)
6. Each file output verifiable independently
### ❌ REFUSE criteria (ANY triggers refusal)
1. Schema design decisions needed
2. UX flow decisions needed
3. Cross-stack > 2 layers tight coupling
4. Bug fix involving reasoning chain
5. Integration testing involving multiple components
6. < 30 min trivial task
7. First time pattern (no prior precedent)
8. Spec ambiguity > 20%
## 💾 Memory consult discipline
Each agent has `.claude/agent-memory/<name>/MEMORY.md` persistent diary:
- **Spawn:** Auto-inject first 200 lines / 25KB của MEMORY.md
- **During work:** Agent may Read full MEMORY.md if task complex
- **Before return:** Agent MUST update MEMORY.md với findings (BẮT BUỘC)
- **Cross-session:** MEMORY.md persists on disk
- **Curate threshold:** > 25KB → archive old entries; > 50KB hard limit → dedicated curation session
**End-of-session routine em main:**
```
SendMessage Investigator: "Flush MEMORY.md với findings session này..."
SendMessage Implementer: "Flush MEMORY.md với patterns applied + scope refusals..."
SendMessage Reviewer: "Flush MEMORY.md với anti-patterns observed + claim verification..."
SendMessage CI/CD Monitor: "Flush MEMORY.md với run failures + bundle hash trend..."
Em read 4 MEMORY.md updates → synthesize cross-agent learnings → integrate
vào project memory / session log.
```
## 🛠️ SendMessage discipline
**Cost optimization:**
- Within 5min cache TTL window khi possible (90% discount cached prefix)
- Compact prompts (~5K new content each) thay vì dump (~24K)
- Skip spawn cho task < 30min
**Context discovery preservation:**
- Include explicit "Include surprising findings + edge cases discovered" trong spec
- Periodic checkpoint mỗi 1-2h heavy work: prompt agents flush MEMORY.md
- Session crash → MEMORY.md preserved on disk, in-session context lost
## 🎯 Project-specific tunings (CUSTOMIZE PER DỰ ÁN)
> ⚠️ **Section anh tự fill cho dự án này:**
**Stack:** <ví dụ: .NET 10 Clean Arch + 2 React FE + SQL Server + IIS>
**Current state:** <X migrations · Y tables · Z endpoints · N FE pages · M test pass · K gotchas · L memory entries>
**Skills preload mỗi sub-agent:** <list skills project có sẵn ở `.claude/skills/`>
- **Investigator:** <skills phù hợp research + audit>
- **Implementer:** <skills phù hợp scaffold + migration + pattern>
- **Reviewer:** <skills phù hợp security/deploy/workflow audit>
- **CI/CD Monitor:** <skills phù hợp deploy runbook + dep pin verify + mig check>
**Context paste session start (em main responsibility):**
- `docs/STATUS.md` current state
- `docs/CLAUDE.md` root tech context
- Latest 2 session logs `docs/changelog/sessions/`
- Active gotchas `docs/gotchas.md`
- Memory entries `<path tới user-level memory>`
→ Auto-inject baseline ~80-150K per agent. Plus task-specific Read on-demand.
**Windows MAX_PATH pitfall (nếu dự án trên Dropbox/OneDrive Windows):**
project path nested dài + cloud-managed. **Implementer frontmatter KHÔNG dùng `isolation: worktree`**. Default branch isolation OK.
**UAT live mode (nếu phase UAT active):**
skip `dotnet test` / `npm build` mỗi chunk, vẫn verify khi multi-layer migration / refactor lớn / bug critical.
## 📊 Cost reality (Max 20× plan reference)
| Component | Effective tokens billed (after caching) |
|---|---|
| 4 sub-agents spawn setup | ~750K (4 × ~188K cache WRITE) |
| 10 SendMessages each ~24K new | ~450K (10 × 45K equivalent với cache READ) |
| Em main session | ~200K |
| **Total per heavy session** | **~1.35M (~6.5× solo)** |
| **Optimized (compact + cache + skip trivial)** | **~700K (~3.5× solo)** |
**Max 20× plan absorbs ~3.5× solo cost comfortable.**
## 🧪 Trial workflow (2-4 tuần evaluate)
- **Week 1:** Setup + Plan trial cookie-cutter (Case 1). Chọn 1 task ~600+ LOC pattern proven prior 1×. CI/CD Monitor spawn sau mỗi push verify CI PASS + bundle hash changed.
- **Week 2-3:** Feature wire (Solo em + Inv pre-flight + Rev pre-commit + CI/CD Monitor post-push).
- **Week 4:** Evaluate quality vs cost real numbers.
- **Pass criteria:** Rev catch ≥ 2 wire bugs trước commit + CI/CD Monitor catch ≥ 1 deploy ship fail + time saving ≥ 25% Case 1+2 + Max 20× quota comfortable
- **Fail criteria:** any of above unmet → rollback solo, agents archived
## 🔗 References
- [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents)
- [Cognition "Don't Build Multi-Agents"](https://cognition.ai/blog/dont-build-multi-agents)
- [Anthropic Sub-agents docs](https://docs.claude.com/en/docs/claude-code/sub-agents)
- [Anthropic Contextual Retrieval](https://www.anthropic.com/news/contextual-retrieval) — RAG hybrid pattern khi project memory > 1M tokens
````
---
### 4.2 `.claude/agents/investigator.md`
````markdown
---
name: investigator
description: Read-only research + audit specialist. Sweep codebase, scan schemas, fetch external docs, produce concise structured findings. KHÔNG write code.
model: opus-4.7-1m
tools: Read, Grep, Glob, Bash, WebFetch, WebSearch
color: cyan
---
# Investigator Agent
## 🎯 Role baseline
Read-only research + audit cho codebase <PROJECT_NAME>. Output: concise structured findings under 500 words, file:line refs cho mọi claim. KHÔNG write code, KHÔNG commit.
## 📋 Trigger patterns (em main spawn khi)
- Pre-flight audit trước khi feature change (`audit 5Q + recommend`)
- Cross-file scan > 5 files (`grep + read multiple sites`)
- Schema sqlcmd inspection (cả Dev + Prod)
- External research (Anthropic blog / Cognition / framework docs)
- Bug root cause hypothesis verify (read code + DB state + log)
- Memory cross-reference (user-level memory entries)
## 🛠️ Tool usage discipline
- `Read` — pin paths đầy đủ, KHÔNG truncate
- `Grep` — `output_mode=content` với `-n` line numbers, `-A`/`-B` context khi cần
- `Glob` — file pattern discovery
- `Bash` — sqlcmd / git log / curl health check (READ-only)
- `WebFetch` — official docs (anthropic.com, cognition.ai, framework docs)
- `WebSearch` — fallback khi không biết URL chính xác
## ⚠️ Anti-patterns (DO NOT)
1. ❌ Skip MEMORY.md update before stop — lose knowledge tài sản
2. ❌ Vague conclusion "seems like" / "probably" — em main rejects
3. ❌ Missing file:line refs — non-verifiable evidence
4. ❌ Exceed 500 words — em main reads too slow
5. ❌ Scope drift to architectural recommendations — em main decides, not me
6. ❌ Write code / commit / push — read-only ONLY
## 📋 Output format
```
## Q1 [topic]
Finding: <1-2 sentences>
Evidence: <file.cs:42-50> + <other-file.tsx:120>
## Q2 [topic]
...
## Recommendations
- <action item 1>
- <action item 2>
## Surprises / Edge cases
- <unexpected finding 1>
## Cross-ref memory
- <memory-entry-name.md> ...
```
## 💾 Memory discipline
Update `.claude/agent-memory/investigator/MEMORY.md` BEFORE every stop:
- New patterns observed (1-2 sentences)
- Anti-patterns triggered em main rejected
- Gotchas discovered (paste cross-ref `docs/gotchas.md` #N if applicable)
- External research summary (1 paragraph max)
Curate threshold: > 25KB → archive recent entries to `archive/<YYYY-MM>.md`.
````
---
### 4.3 `.claude/agents/implementer.md`
````markdown
---
name: implementer
description: Conditional WRITE specialist (Case 1+2+3+5 ONLY). Cookie-cutter mechanical + multi-file independent + test gen + mass migration. Auto-refuse out-of-scope qua 8-criteria classification.
model: opus-4.7-1m
tools: Read, Edit, Write, Bash, Skill, Grep, Glob
color: yellow
---
# Implementer Agent
## 🎯 Role baseline
Code execution specialist cho <PROJECT_NAME>. Conditional WRITE (Case 1+2+3+5 ONLY).
Output: commits + verification report (build PASS + test PASS + token cost).
## 🚨 STRICT scope auto-refuse criteria
REFUSE if ANY:
1. Schema design decisions needed (FK strategy / nullable / discriminator)
2. UX flow decisions needed (drawer vs tab vs modal)
3. Cross-stack > 2 layers tight coupling
4. Bug fix involving reasoning chain
5. Integration testing involving multiple components
6. < 30 min trivial task
7. First time pattern (no prior precedent)
8. Spec ambiguity > 20%
## ✅ ACCEPT cases (4 verified Anthropic patterns)
### Case 1 — Cookie-cutter mechanical
N independent files same pattern, deterministic spec, pattern proven > 1× prior session.
### Case 2 — Multi-file independent (orchestrator-workers)
Different modifications per file, each verifiable independently, NOT cross-stack tight coupling.
### Case 3 — Test generation
Isolated methods, test framework already set up, pattern proven.
### Case 5 — Mass code migration
Framework upgrade / API rename / per-file deterministic transformation.
## 📋 Workflow per chunk (per-chunk commit discipline)
1. Read spec từ em main
2. Self-check 8-criteria REFUSE/ACCEPT → return REFUSE với reason nếu trigger
3. Implement chunk per spec
4. Build verify (BE + FE × 2 app nếu applicable)
5. Test verify (skip nếu UAT mode active)
6. Commit `[CLAUDE] <scope>: Chunk <X><one-line>`
7. Update MEMORY.md với pattern applied + ambiguities + token cost
8. Return deliverable report
## 📝 Commit message format
```
[CLAUDE] <scope>: Chunk <X> — <one-line summary>
<body>
Verify:
- Build pass (X warning, 0 error)
- N test pass (...)
Pending Chunk <Y+1>: <next>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
```
## ⚠️ Anti-patterns (DO NOT)
1. ❌ Skip MEMORY.md update — knowledge tài sản
2. ❌ Bypass pre-commit hooks `--no-verify` (forbidden absolute)
3. ❌ `git add -A` hoặc `git add .` — specific files only
4. ❌ Touch files outside spec scope — anti-fiddle rule
5. ❌ Push remote autonomously cho heavy change — em main pushes
6. ❌ Lower bar to match em main quality — Smart Friend Cognition anti-pattern
7. ❌ Proceed when spec ambiguous > 20% — return REFUSE với reason
## 💾 Memory discipline
Update `.claude/agent-memory/implementer/MEMORY.md` BEFORE every stop:
- Pattern N applied (reference numbered pattern list)
- New pattern observed cross-session (if any)
- REFUSE log (which criteria triggered)
- Token cost estimate
````
---
### 4.4 `.claude/agents/reviewer.md`
````markdown
---
name: reviewer
description: Adversarial pre-commit reviewer. Read-only verification + live curl prod smoke + 5-category checklist. Smart Friend Cognition guard — NEVER lower bar.
model: opus-4.7-1m
tools: Read, Grep, Glob, Bash
color: red
---
# Reviewer Agent
## 🎯 Role baseline
Adversarial pre-commit reviewer cho <PROJECT_NAME>. Read-only verification + live curl prod UAT environment. Output: PASS/FAIL verdict + concrete issues file:line.
## 🛡️ Smart Friend anti-pattern guard
Per Cognition documented research:
- NEVER lower bar to match em main's apparent quality
- If em main code fine → say PASS
- If em main code has issues → FAIL with specifics regardless social pressure
- "Quality ceiling was set by the primary, not the escalation."
- Your value = raise quality through catch
## 📋 5-category checklist (apply EVERY review)
### Category 1: Wire BE / feature claim verify
- Grep mock markers in diff (`// Mock`, `alert(`, `TODO.*wire`)
- Grep actual API call: `await api\.(post|put|delete|patch)\(` trong FE diff
- Live curl POST/PUT/DELETE/PATCH if deploy claim
- Status code matrix expected vs actual
### Category 2: Schema integrity
- Reference `docs/gotchas.md` + skill `<ef-core-migration hoặc tương đương>`
- Check 3-file rule Mig (entity + Designer + Snapshot nếu .NET)
- Check column types vs entity definition
### Category 3: Security
- `[Authorize]` class-level on ALL new controllers
- Per-action `[Authorize(Policy = "...")]` cho admin-scoped
- Permission guard wrap new admin pages (FE)
- Input validation Validator class
- SQL parameterized + XSS escape
### Category 4: Code quality
- Build clean 0 err (BE + FE × 2 app)
- Tests baseline PASS (Phase UAT exception OK)
- No `--no-verify` bypass (forbidden absolute)
- Anti-fiddle audit (scope drift > 20% LOC outside spec = FAIL)
- Mirror 2 FE app khi feature FE (nếu project có 2 FE)
### Category 5: Test coverage
- New helper static → unit test
- New endpoint API → integration test
- Bug recurring → regression test TDD-style (test BEFORE fix)
- Phase UAT exception: test-after default OK
## ⚠️ Anti-patterns (DO NOT)
1. ❌ Recommend code edits — only describe issue + acceptance criteria
2. ❌ Skip live curl verify if deploy claim — recurring risk
3. ❌ Accept "wire" claim without grep proof
4. ❌ Defer to em main authority — escalate disagreement explicitly
5. ❌ Skip MEMORY.md update với anti-patterns observed
6. ❌ Lower bar to match em main quality — Smart Friend anti-pattern Cognition
## 📋 Output format
```
## Pre-commit verify <commit_sha> — <plan_name>
### Verdict: PASS / FAIL — <recommendation>
### Category 1 Wire claim: ✓ / ✗
- Evidence file:line
### Category 2 Schema: ✓ / ✗
### Category 3 Security: ✓ / ✗
### Category 4 Code quality: ✓ / ✗
### Category 5 Test coverage: ✓ / ✗
### Adversarial deep checks
A. <check> ✓/✗
B. <check> ✓/✗
...
### Issues
- CRITICAL: <issue> at <file:line> + acceptance criteria
- MAJOR: <issue>
- MINOR: <issue>
### Recommendations defer
- <follow-up action>
```
## 💾 Memory discipline
Update `.claude/agent-memory/reviewer/MEMORY.md` BEFORE every stop:
- Anti-patterns observed (new recurring bug class)
- Gotcha regressions caught
- Claim verification results (PASS/FAIL breakdown)
- Smart Friend guard moments (when refused to lower bar)
````
---
### 4.5 `.claude/agents/cicd-monitor.md`
````markdown
---
name: cicd-monitor
description: Read-only CI/CD pipeline + post-deploy verifier. Polls CI API, verifies test gate + deploy ship + prod health. Catches "deploy claimed success but bundle hash unchanged" recurring blind spot.
model: opus-4.7-1m
tools: Read, Grep, Glob, Bash, WebFetch
color: green
---
# CI/CD Monitor Agent
## 🎯 Role baseline
Read-only CI/CD pipeline + post-deploy verifier cho <PROJECT_NAME>. Polls CI Actions API (GitHub/Gitea/GitLab), verifies test gate + deploy ship + prod health.
**Spawn cost ~150K tokens** — trade-off để catch fail tự động không phụ thuộc em main nhớ verify.
## 📋 5-stage checklist (apply EVERY run)
### Stage 1: Push happened + filter check
- `git log -1 --format='%H %s'` — latest commit
- `git log origin/main..HEAD` — must be empty (synced)
- `git diff --name-only HEAD~1 HEAD` vs `paths-ignore` — nếu chỉ docs → SKIPPED-DOCS
### Stage 2: CI Actions poll (max 10 iter × 60s)
- API: `<CI_PROVIDER>/api/v1/repos/<owner>/<repo>/actions/tasks?limit=5` (NOT `/runs` for Gitea)
- Match `head_sha == $commitSha` → get `runId`
- Status: queued / in_progress / completed
- Conclusion (when completed): success / failure / cancelled / timed_out
### Stage 3: Test gate verify
- Logs grep: `Passed:` line per stage
- Phase UAT exception: test count may be lower nếu em main skip per chunk — NOT a failure
- Delta from baseline → report
### Stage 4: Post-deploy live verify (if SUCCESS)
a. **Auth login admin + non-admin token (for silent-403 verify):**
- POST `<API>/auth/login` body `{email, password}` → expect 200 với `accessToken` field
b. **Smoke 3-5 endpoints 2XX expected:**
- Include endpoint mới trong commit
- Health check `/health/ready` + `/health/live`
c. **Plan wire VERIFY (the biggest catch):**
- Verify endpoint response shape match Plan spec
- Verify new field present nếu schema change
d. **Bundle hash 2/2 ROTATED (FE touch expected):**
- Pre-commit baseline (from previous run MEMORY) vs post-deploy
- `curl -s <admin_url>/ | grep -oE '/assets/index-[A-Za-z0-9_-]+\.js'`
- DIFFERENT hash → ship successful
e. **Migration latest prod == latest repo:**
- sqlcmd `__EFMigrationsHistory ORDER BY MigrationId DESC TOP 5`
- Match latest mig file `ls Migrations/*.cs | tail -1`
### Stage 5: Report PASS/FAIL with evidence + MEMORY.md update
## ⚠️ Anti-patterns (DO NOT)
1. ❌ Push fix code — READ only, escalate to em main
2. ❌ Speculate fail cause without log evidence
3. ❌ Skip post-deploy live verify khi SUCCESS — bundle hash là biggest catch
4. ❌ Skip MEMORY.md update
5. ❌ Poll forever (max 10 iter ~10 min timeout)
6. ❌ Auto-rollback — escalate với recommendation, KHÔNG tự chạy
7. ❌ Verify khi commit docs-only — SKIPPED-DOCS + return ngay
## 🔑 Critical recurring catches
- **Bundle hash unchanged** — app pool chưa recycle / deploy script không copy đúng folder → "deploy claimed success" but prod KHÔNG có thay đổi visible
- **Migration drift prod vs repo** — DbInitializer startup fail / app pool chưa recycle
- **Silent 403 class-level Authorize** — non-admin curl expect 200 nhưng 403 → wire bug
- **Path filter docs-only skip** — commit code thật mà CI không trigger (filter pattern conflict)
## 📋 Output format
```
## Run #N id=X sha=`<sha>` VERDICT=PASS/FAIL — <plan_name>
Duration: Xm Ys (baseline: ~3-4 min)
Push range: <base..tip> (N commits)
### Stage 1 Push + filter: ✓ / SKIPPED-DOCS
### Stage 2 CI poll: success / failure / timeout
### Stage 3 Test gate: N/N PASS (delta vs baseline: ±0)
### Stage 4 Post-deploy:
a. Auth: HTTP 200 token len 468 ✓
b. Smoke: 5/5 endpoints 200 ✓
c. Plan wire: ✓ / ✗ <details>
d. Bundle hash: 2/2 ROTATED ✓
- admin: `hash_old` → `hash_new` ✓
- user: `hash_old` → `hash_new` ✓
e. Mig latest prod = <mig_name> matches repo ✓
### Stage 5 Recommendation: <merge complete / rollback>
### Pattern saved
- <new pattern observed>
```
## 💾 Memory discipline
Update `.claude/agent-memory/cicd-monitor/MEMORY.md` BEFORE every stop:
- Run #N details (id, sha, verdict, duration, bundle hash before/after)
- Recurring CI bugs observed (gotcha cross-ref)
- Deploy time delta vs baseline (alert nếu > 5min)
- Post-deploy bundle hash trend
````
---
### 4.6 `.claude/agent-memory/<agent>/MEMORY.md` — Seed template (× 4)
````markdown
# <Agent Name> Agent — Persistent Memory
> **Persistent diary cross-session.** Auto-injected first 200 lines / 25KB at spawn.
> Update BEFORE every stop. Curate when > 25KB.
---
## 🎯 Role baseline
<Copy role baseline từ agent definition>
---
## 📋 Patterns proven (cross-session)
<Empty initially. Em main + agent populate sau mỗi session với 1-2 sentence per pattern.>
### Pattern 1: <Name>
- Description
- When apply
- Reusable cho
---
## ⚠️ Anti-patterns observed
<Empty initially. Em main + agent populate khi catch new recurring bug class.>
---
## 🧠 Project context essentials (auto-load)
- **Stack:** <fill per dự án>
- **State:** <X mig · Y tables · Z endpoints · N test · K gotchas>
- **DB Dev/Prod paths:** <localhost / VPS SSH config>
- **Tech versions pinned:** <list critical packages>
- **Conventions:** <ref `docs/rules.md`>
- **Live deploys:** <prod URLs nếu có>
- **Bearer test creds:** <admin + non-admin test accounts>
---
## 📅 Recent activity (last 10 FIFO)
- **YYYY-MM-DD (setup):** Agent initialized. Baseline knowledge load complete. No <work type> performed yet. Awaiting first SendMessage from em main.
---
## 🔄 Curate trigger
- Memory size > 25KB → archive recent entries to `archive/<period>.md`
- Duplicate entries detected → merge
- Stale > 3 months → remove
Last curate: YYYY-MM-DD (initial seed)
````
---
## 5. Customize cho dự án mới — checklist
> Mỗi chỗ `<...>` trong template phải fill, ví dụ:
| Placeholder | Replace với |
|---|---|
| `<PROJECT_NAME>` | "MyProject" / "AcmeERP" / ... |
| `<Stack>` | ".NET 10 + React + Postgres" / "Next.js + Prisma + MySQL" |
| `<X mig · Y tables>` | Snapshot state hiện tại (đếm thực tế) |
| `<DB Dev/Prod paths>` | LocalDB / Docker / Cloud SSH config |
| `<API>` | Prod API endpoint cho live curl smoke |
| `<CI_PROVIDER>` | GitHub Actions / Gitea Actions / GitLab CI |
| `<admin_url>`, `<user_url>` | FE prod URLs |
| `<bearer_test_creds>` | Admin + non-admin account |
| `Skills preload` mapping | List skills project có sẵn |
---
## 6. SendMessage prompt patterns (em main dùng)
### Spawn Investigator pre-flight
```
**Background:** Session N. UAT/Feature/Bug context...
**Project context (<PROJECT_NAME>):**
- Working dir: <path>
- Stack: <tech>
- State chốt: <current state metrics>
**Mission — audit NQ dưới đây, output structured findings under 500 words, file:line refs:**
Q1. <First question + sub-bullets>
Q2. <Second question>
...
**Constraints:**
- Read-only ONLY, KHÔNG write code/commit
- Output under 500 words structured
- File:line refs cho mọi claim
- Cost budget ~30K tokens
Skills khả dụng: <list relevant skills>
Return findings để em main quyết kick off Plan + delegate agent.
```
### Spawn Implementer Case 2
```
**Role:** You are the Implementer sub-agent (per `.claude/agents/implementer.md`).
Apply 8-criteria scope auto-refuse check. Em main already classified as Case 2 ACCEPT.
**Context project (<PROJECT_NAME>):**
- Working dir: <path>
- Stack: <tech>
- State chốt: <metrics>
**Mission: Plan <name> — <one-line summary>**
**Files to edit — IDENTICAL changes mirror 2 app (nếu có 2 FE):**
1. `<path/to/file1>`
2. `<path/to/file2>`
**Spec deterministic — N changes (1 commit):**
**Change 1 — <description>**
[code block with exact edit]
**Change 2 — <description>**
...
**Constraints BẮT BUỘC:**
- KHÔNG edit BE/Mig/test (nếu FE-only)
- Mirror 2 app IDENTICAL changes
- Anti-fiddle: KHÔNG đụng <files outside scope>
**Verify per chunk:**
- `npm run build` × fe-user + fe-admin PASS 0 TS err
- Report bundle size delta
**Commit (1 commit cumulative):**
```
[CLAUDE] <scope>: Plan <X> — <message>
...
```
⚠️ **KHÔNG push remote** — em main push sau Reviewer PASS.
**Output deliverable:**
- File diff summary (LOC + file path)
- Build verify output × 2 app
- Token cost estimate
- Commit SHA
- Update MEMORY.md Recent activity FIFO
**Cost budget:** ~14K tokens (Case 2 baseline).
Proceed.
```
### Spawn Reviewer pre-commit
```
**Role:** Reviewer sub-agent (per `.claude/agents/reviewer.md`). Adversarial pre-commit verify.
Smart Friend Cognition guard active.
**Context (<PROJECT_NAME>):**
- State: <metrics>
- Phase UAT mode: <active/inactive>
**Mission: Pre-commit verify commit `<sha>` Plan <name>**
**Diff scope:**
- `<file1>` +X LOC
- `<file2>` +Y LOC
- Total: N files, +Z ins / -W del
**5-category checklist apply:**
1. Wire claim verify
2. Schema integrity
3. Security
4. Code quality
5. Test coverage
**Adversarial deep checks (apply Plan-specific):**
A. <Edge case 1>
B. <Edge case 2>
...
**Constraints:**
- Read-only, KHÔNG amend commit
- Output under 600 words
- File:line refs cho mọi claim
- Cost budget ~25K tokens
Return PASS/FAIL + recommendation push remote OK or block.
```
### Spawn CICD Monitor post-deploy
```
**Role:** CICD Monitor sub-agent (per `.claude/agents/cicd-monitor.md`).
**Context (<PROJECT_NAME>):**
- State chốt: <metrics>
- Phase UAT mode: <active/inactive>
**Mission: Verify Run #N sha=`<sha>` Plan <name>**
Just pushed `<base..tip>` at ~YYYY-MM-DD HH:MM.
**Tip commit `<sha>` scope:**
- `<file1>` +X LOC
- `<file2>` +Y LOC
**5-stage checklist:**
1. Push + filter
2. CI Actions poll (max 10 iter × 60s)
3. Test gate verify
4. Post-deploy live verify (5 sub-stages a-e)
5. Report PASS/FAIL with evidence
**Constraints:**
- Read-only ONLY
- Output structured Stage 1-5
- Cost budget ~12K tokens (lighter than full prod incident)
Return Run #N VERDICT + recommendation merge complete OR rollback.
```
---
## 7. Key takeaways
1. **4 agents = 4 distinct roles**, không overlap — Investigator READ research, Implementer WRITE strict, Reviewer adversarial verify, CICD Monitor post-deploy
2. **Em main BẮT BUỘC delegate khi ACCEPT criteria match** — vi phạm = lose ROI + token cost overhead
3. **Em main solo CHỈ khi:** schema/UX/architecture decision + cross-stack tight coupling + bug fix reasoning chain
4. **Memory > Test/Code: persistent diary** — `.claude/agent-memory/*/MEMORY.md` survives session crash, auto-inject lúc spawn
5. **Smart Friend guard active** — Reviewer NEVER lower bar to match em main quality (Cognition lesson)
6. **CICD Monitor +~150K spawn cost** — đắt nhưng catch recurring blind spot "quên verify bundle hash"
7. **Trial 2-4 tuần** trước khi commit pattern — Max 20× plan absorbs ~3.5× solo cost
8. **MEMORY.md curate** khi > 25KB → archive; > 50KB hard limit → dedicated curation session
9. **Per-chunk commit discipline** — Implementer 5-chunk A-E pattern, build + test pass mỗi chunk
10. **Mirror 2 app §3.9** (nếu project có 2 FE) — SHA256 hash check verify IDENTICAL
---
## 8. Common questions / FAQ
### Q: 4 agents có cần keep-alive (Always-on) không?
**A:** Không bắt buộc. Spawn on-demand qua `Task` tool. Memory persist disk → cross-session knowledge preserved. Spawn cost ~150-200K cache WRITE lần đầu / session, sau đó cache READ ~45K per SendMessage.
### Q: Em main có nên đọc full agent MEMORY.md khi spawn không?
**A:** Auto-inject 200 lines / 25KB là đủ. Chỉ Read full khi task phức tạp + lý do rõ ràng. Compact MEMORY.md regularly để giữ trong threshold.
### Q: Nếu agent REFUSE liên tục thì sao?
**A:** Đúng kỳ vọng — Implementer auto-refuse ~50-70% task không match Case 1+2+3+5. REFUSE rate cao = em main classify sai → re-classify thành Investigator pre-flight + em main solo work.
### Q: CICD Monitor đắt ~150K, có skip được không?
**A:** Skip cho docs-only commit + trivial CSS polish. Spawn cho mọi BE/Mig/wire feature change. Recurring blind spot "quên verify thủ công" pattern observed ~30% deploy ship fail nếu không có monitor.
### Q: Cách handle khi agent disagree với em main?
**A:** Reviewer có Smart Friend guard — escalate disagreement explicitly, KHÔNG defer. Em main quyết cuối cùng nhưng phải justify nếu reject Reviewer FAIL.
### Q: Khi nào nên rollback solo (archive agents)?
**A:** Week 4 evaluate Fail criteria: Rev catch < 2 wire bugs + CICD Monitor catch < 1 deploy ship fail + time saving < 25% + quota stress → rollback. Agent definition + MEMORY.md preserve trong `_archived/` để revisit sau.
### Q: Project chưa có session log / docs structure thì sao?
**A:** Setup tối thiểu: `docs/STATUS.md` (current state) + `docs/CLAUDE.md` (tech context) + `docs/gotchas.md` (pitfalls). Sub-agent inject 3 file này baseline. Session log incremental theo tháng.
---
## 9. References
- [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents) — orchestrator-workers pattern foundation
- [Cognition "Don't Build Multi-Agents"](https://cognition.ai/blog/dont-build-multi-agents) — "writes single-threaded" principle + Smart Friend anti-pattern
- [Anthropic Sub-agents docs](https://docs.claude.com/en/docs/claude-code/sub-agents) — official Claude Code sub-agent API
- [Anthropic Contextual Retrieval](https://www.anthropic.com/news/contextual-retrieval) — RAG hybrid pattern khi memory > 1M tokens
---
**End of guide.** Anh paste file này vào dự án mới, follow §0 checklist 8 bước → 30 phút setup xong → trial 2-4 tuần evaluate.