From bf93abd467f5322c131f923723cd7500f2f8c1c7 Mon Sep 17 00:00:00 2001 From: pqhuy1987 Date: Fri, 22 May 2026 02:27:36 +0700 Subject: [PATCH] =?UTF-8?q?[CLAUDE]=20Docs:=20Session=2026=20ch=E1=BB=91t?= =?UTF-8?q?=20cu=E1=BB=91i=20=E2=80=94=206=20Plan=20AG=20series=20PE=20tre?= =?UTF-8?q?e=20view=20+=20Plan=20AI=20RAG=20global=20MCP=20setup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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
/ + Tailwind named groups (group/proj+year+sup) + localStorage Set 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) --- .claude/agent-memory/cicd-monitor/MEMORY.md | 2 + .claude/agent-memory/investigator/MEMORY.md | 4 + .claude/agent-memory/reviewer/MEMORY.md | 2 + .claude/rag.json | 25 + docs/HANDOFF.md | 4 +- docs/STATUS.md | 4 +- .../2026-05-21-s26-pe-tree-view-rag-setup.md | 262 +++++ docs/guides/multi-agent-setup-guide.md | 958 ++++++++++++++++++ 8 files changed, 1259 insertions(+), 2 deletions(-) create mode 100644 .claude/rag.json create mode 100644 docs/changelog/sessions/2026-05-21-s26-pe-tree-view-rag-setup.md create mode 100644 docs/guides/multi-agent-setup-guide.md diff --git a/.claude/agent-memory/cicd-monitor/MEMORY.md b/.claude/agent-memory/cicd-monitor/MEMORY.md index 37f4cbb..02578f5 100644 --- a/.claude/agent-memory/cicd-monitor/MEMORY.md +++ b/.claude/agent-memory/cicd-monitor/MEMORY.md @@ -139,6 +139,8 @@ Flag commit nếu thấy ` 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).** diff --git a/.claude/agent-memory/investigator/MEMORY.md b/.claude/agent-memory/investigator/MEMORY.md index e7944b8..da32c84 100644 --- a/.claude/agent-memory/investigator/MEMORY.md +++ b/.claude/agent-memory/investigator/MEMORY.md @@ -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 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 `
  • ` 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 `
    /` native + inline badge `
    ` (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. + diff --git a/.claude/agent-memory/reviewer/MEMORY.md b/.claude/agent-memory/reviewer/MEMORY.md index c58f7c9..8ea4937 100644 --- a/.claude/agent-memory/reviewer/MEMORY.md +++ b/.claude/agent-memory/reviewer/MEMORY.md @@ -144,6 +144,8 @@ Flag commit nếu thấy ` 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. diff --git a/.claude/rag.json b/.claude/rag.json new file mode 100644 index 0000000..67bb61c --- /dev/null +++ b/.claude/rag.json @@ -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 +} diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 580e15a..04da4c1 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,6 +1,8 @@ # HANDOFF — Brief 5 phút cho session tiếp theo -**Last updated:** 2026-05-19 (Session 25 chốt cuối — **🎯 Plan AB→AF cumulative 7 commits push `e23f51c..506cada` + 7 CICD Runs (#215 FAIL → #216-#221 PASS) — Lịch sử visibility critical fix UAT iteration**. Trigger: Bro UAT 2026-05-19 phát hiện 2 bug critical phiếu PE/2026/A/032: Bug 1 Budget Adjust không show "Lịch sử thay đổi" (BE log OK + FE filter strict TraLai-only loại) + Bug 2 Return Mode 4 mode KHÔNG log Changelog (`ApplyReturnModeAsync` miss `db.PurchaseEvaluationChangelogs.Add()`). **Plan AB Chunk A** (`cdfd542`, 🟨 Implementer Case 1 spawn ~12K): BE refactor `ApplyReturnModeAsync` Drafter early return → common path + single `Changelog.Add()` cover 4 mode uniform với `modeName` switch enum + `actorName` resolve via `userManager.FindByIdAsync` mirror `LogTransitionAsync` pattern. FE `PeDetailTabs.tsx` × 2 app `HistoryTab` filter extend (PE_ENTITY_HEADER=1 + summary 'ngân sách' + Workflow summary 'Trả lại'). 🟥 Reviewer pre-commit verify ~22K PASS 0 critical/major/minor (1 minor V1 legacy fallback non-block). Run #215 FAIL test_infra 2/53 — Plan M edge case tests SQLite frozen-clock tie-break (gotcha #48 NEW): 2 Changelog rows cùng `CreatedAt` → `OrderByDescending.FirstAsync()` pick wrong → ContextNote null. **Plan AB Chunk A2** (`8c05947`, em main solo): Test filter `Where(Summary.Contains("Chuyển phase"))` pick đúng LogTransition entry. 111/111 PASS. Run #216 PASS. **Plan AC** (`a734bf2`, em main solo): BE capture pre-call Step/Level → Reject branch add `PurchaseEvaluationApprovals.Add()` với Decision=Reject + Comment from-pos + mode summary. BE line 472 enrich Approve comment prefix `[Duyệt vượt cấp tới Cấp cuối]` khi skipToFinal=true. FE × 2 app ApprovalsTab thêm `decisionBadge(decision, toPhase)` helper (Duyệt emerald / Trả lại amber / Từ chối rose). Run #217 PASS, bundle rotate × 2 app. **Plan AC2** (`25837b6`, em main solo, Option 2A bro chốt): FE merge view ApprovalsTab fetch changelogs + reconstruct synthetic Reject rows từ Workflow+Reject Changelog (filter EntityType=5 + Summary "→ TraLai"/"→ TuChoi" OR ContextNote "Trả về"/"không lùi được") + dedupe `approverUserId + timestamp 5s bucket` cùng real Reject rows + merge sort by approvedAt. KHÔNG DB write, reversible historical recovery. Run #218 PASS, 8 Workflow entries verified, bundle rotate × 2 app. **Plan AD** (`0aaf2df`, em main solo, Option A bro chốt): Drop fromPhase→toPhase badges (visual confusion 3/4 mode Reject giữ ChoDuyet — gotcha #49 NEW) + add `extractNextTargetHint(decision, toPhase, comment)` helper regex parse `Chuyển phase X → Y` + keyword detect "Trả về"/"vượt cấp"/"Cấp cuối" → "→ Cấp Y" / "→ Trả về Người chỉ định (Bước X Cấp Y)" / "→ Vượt cấp tới Cấp cuối" / "→ Đã duyệt hoàn tất". Cleanup unused `PurchaseEvaluationPhaseColor` import. Mirror × 2 app §3.9. Run #219 PASS, bundle rotate × 2 app. **Plan AE** (`9ea62be`, em main solo, preventive batch fix): BE 9 `Changelog.Add()` sites add `UserName = currentUser.FullName ?? currentUser.Email` (Budget Adjust + Create PE + Update PE Header + Detail Insert/Update/Delete + Quote Insert/Update/Delete + Select Winner). ICurrentUser đã có FullName/Email từ JWT — KHÔNG inject userManager mới. `replace_all=true` 1 pass cover 8 sites cùng indent + 1 site manual fix indent 16 spaces inside if block. 111/111 PASS local. Run #220 PASS, bundle UNCHANGED (BE-only commit). **Plan AF** (`506cada`, em main solo, Option A bro chốt): FE ApprovalsTab + HistoryTab build `userMap useMemo` từ embedded PeDetailBundle data: `drafterUserId+drafterName + approvals[].approverUserId+approverName + approvalFlow.steps[].levels[].approvers[].userId+fullName + levelOpinions[].signedByUserId+signedByFullName + departmentOpinions[].userId+userName` — no extra `/api/users` fetch (admin permission). `resolveActorName(a) / resolveUserName(l)` helper: trust entry.userName non-empty → userMap.get(entry.userId) → 'Hệ thống' fallback. Mirror × 2 app §3.9. Run #221 PASS, bundle rotate × 2 app. **Multi-agent ROI S25:** 🟦 Investigator 1 spawn (~28K Bug 1+2 audit) + 🟨 Implementer 1 spawn (~12K Plan AB Chunk A Case 1) + 🟥 Reviewer 1 spawn (~22K Plan AB pre-commit) + 🟩 CICD Monitor 7 spawns (Run #215 catch test gate fail + Run #216-#221 PASS verify, ~70K cumulative). Em main solo 5 plans AC→AF cross-stack reasoning + UAT iteration. Total cumulative agent cost ~132K · em main ~210K. **State chốt S25:** 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 + feedback_fe_usermap_fallback)** · 6 skills · 4 sub-agents active. **Memory CRITICAL FLAG:** cicd-monitor MEMORY ~72KB strongly over 50KB hard threshold — DEDICATED CURATION SESSION REQUIRED next (archive Run #186-#210 + S22-S24 verbose entries to `archive/2026-05-runs-186-210.md`). Investigator 32KB / Implementer 35.7KB / Reviewer 32.3KB cũng over 25KB threshold — recommend curate cùng session với cicd-monitor. **8 patterns reusable saved S25:** (1) Multi-Changelog SQLite tie-break (gotcha #48) → test discriminator, (2) CICD catch UAT skip test risk → resumed local verify 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 (Plan AC2), (6) Drop misleading dual-phase badges + semantic next-target hint (Plan AD), (7) Changelog UserName preventive systemic batch fix 9 sites (Plan AE), (8) FE userMap fallback từ embedded domain data no extra API (Plan AF). Bro UAT verify cumulative deploy live PE/2026/A/032 — historical entries pre-Plan AE nay resolve user names qua userMap fallback.) +**Last updated:** 2026-05-21 (Session 26 chốt cuối — **🎯 Plan AG/AG2/AG3/AG4/AG5/AG6 cumulative 6 commits Plan AG series `0bf6c7e..d99069a` push remote + Plan AI RAG global MCP infrastructure setup**. **Trigger:** Bro UAT 2026-05-21 screenshot phàn nàn UI Duyệt NCC PE List "đám rừng" flat list + đề xuất Outlook-style folder tree theo dự án + dưới năm + NCC. 6 plan UI iteration cumulative: **Plan AG** Phase 1 PE List tree view 2-level Project > Gói thầu > PE (🟦 Investigator audit 5Q ~30K + 🟨 Implementer Case 2 cookie-cutter mirror 2 app ~16K commit `0bf6c7e` 2 file +346/-116 LOC SHA256 IDENTICAL + 🟥 Reviewer pre-commit ~25K PASS 0 blocker + 🟩 CICD Monitor Run #222 ~12K bundle hash 2 app rotate verified `C8TvDy7r→CWHIdoFo` admin + `BvcWrq2z→Bg2FNeIz` user). **Plan AG2** (`c5429c0`) simplify 1-level (drop tầng gói thầu per bro feedback "gói thầu thì ko cần thiết phải treedow") + widen Panel 1 340px → 400px. **Plan AG3** (`fbad4a9`) drop single-PE flat branch consistent UI (mọi dự án dù 1/N phiếu đều render `
    `). **Plan AG4** (`2bf0118`) bổ sung Người tạo + Phòng ban tạo PE card — BE+FE cross-stack 8 file (DTO `PurchaseEvaluationListItemDto` +4 fields DrafterUserId/DrafterName/DepartmentId/DepartmentName + 3 projection JOIN Users+Departments LEFT (ListHandler/InboxHandler/ApprovedHandler) + FE PeListItem type +4 + UI card 👤 Drafter · Phòng ban inline) + dotnet test 111/111 PASS unchanged. **Plan AG5** (`083b601`) extend tree 3-level Project > Năm > NCC > PE (selectedSupplierName fallback "(Chưa chọn NCC)" cho PE chưa DaDuyet, sort vi locale + năm DESC + PE createdAt DESC). **Plan AG6** (`d99069a`) compact card 3-row gọn đẹp (drop Type "Duyệt NCC" label redundant + combine mã phiếu/time + Drafter/Dept/HĐ inline + py-2.5 → py-2). Tất cả 6 commit verified IDENTICAL SHA256 hash mirror 2 app §3.9 + npm build × 2 PASS 0 TS err. **Plan AI RAG global MCP setup** (User-level Approach A — 1 dev 5 dự án cùng máy localhost share infrastructure): Phase 0 pre-flight (Python 3.11.3 + Voyage API key set User scope length 46 + 5 project paths detected Claude Desktop config epitaxy: SOLUTION + NAMGROUP + DAI_Y_DUOC + ASHICO + VIPIX_MULTISITE) + Phase 1 Qdrant v1.18.0 Windows native binary running PID 67240 port 6333 (KHÔNG Docker, anh chốt no Docker) + Phase 2 FastMCP server ~1100 LOC Python 9 file (server.py 6 tool handlers + lib/embed.py Voyage wrapper + lib/retrieval.py 3-layer pipeline + lib/projects.py auto-detect cwd + lib/chunking.py Anthropic Contextual Retrieval prepend + lib/watcher.py + bootstrap.py CLI + README.md) + Phase 3 register MCP user-level (`claude mcp add -s user -e VOYAGE_API_KEY=$VK -- rag-unified python ...` — trick `--` separator để terminate variadic `-e` flag) — "rag-unified: ✓ Connected" + Phase 4 bootstrap SOLUTION_ERP corpus 126 files → **2,392 chunks indexed 60.9s** (~484K Voyage tokens = 0.24% free tier 200M/month) + verify search 4 query thực tế recall 0.641-0.879 rerank score. **Stack final RAG:** Voyage-4-large embedding (1024-dim) + Voyage rerank-2.5 cross-encoder + Qdrant Windows native + SQLite FTS5 BM25 (unicode61 + diacritics remove) + Reciprocal Rank Fusion (k=60) + FastMCP 3.3.1 stdio + Anthropic Contextual Retrieval prepend "From > :" + git-sync embeddings snapshot pattern (Cursor lesson). 6 MCP tools exposed: search_memory · cross_project_search · search_code · store_memory · promote_to_shared · list_projects. **+1 file MD onboarding** `docs/guides/multi-agent-setup-guide.md` xuất cho 4 dự án future áp dụng pattern 1 em main + 4 sub-agent + RAG share infrastructure. Multi-agent ROI S26: 🟦 Investigator 2 spawn (Plan AG audit 5Q + Plan AI RAG distribution research 4 study cases Cursor/Cline/Continue/Sourcegraph) ~70K + 🟨 Implementer 1 spawn (Plan AG Case 2) ~16K + 🟥 Reviewer 1 spawn (Plan AG pre-commit) ~25K + 🟩 CICD Monitor 1 spawn (Run #222) ~12K. Em main solo Plan AG2-AG6 (5 plan polish UAT iteration) + Plan AI Phase 0-4 (RAG infra setup ~1.5h). **State chốt S26:** 31 mig (no schema) · 59 tables · ~146 endpoints · 35 FE pages · **111 test pass unchanged** (UAT defer test-after per §7) · 49 gotcha unchanged · 23 memory user-level unchanged · 6 skills · 4 sub-agents · **+1 docs/guides/multi-agent-setup-guide.md** + **+1 RAG infrastructure** `D:\.claude-rag\` ready 5 project. 3 patterns reusable cross-project (S26 NEW): (1) Pattern 19 Implementer — HTML native `
    /` + Tailwind named groups `group/proj`+`group/year`+`group/sup` + localStorage Set cho hierarchical 3-level tree UI no Accordion lib, (2) RAG User-level Global MCP — 1 server localhost serve N project + per-project `.claude/rag.json` config (Approach A — 1 dev solo scenario), (3) Qdrant Windows native binary deployment — no Docker overhead, appropriate cho solo dev không enterprise scale. **Memory FLAG continued S26:** cicd-monitor MEMORY ~74KB (+2KB từ S25), critical curate session URGENT next (archive Run #186-#221 verbose → `archive/2026-05-runs.md`). **Pending follow-up Plan AI:** Phase 5 bootstrap 4 project còn lại (NamGroup/DH Y Dược/Ashico/Vipix) ~30 phút mỗi project + Phase 6 file watcher + Windows Task Scheduler auto-start Qdrant. Tests baseline 111 preserve cross 6 commit (test debt cumulative S22+1 + S25 + S26 bug fix not added — UAT mode defer per §7).) + +**Last updated S25:** 2026-05-19 (Session 25 chốt cuối — **🎯 Plan AB→AF cumulative 7 commits push `e23f51c..506cada` + 7 CICD Runs (#215 FAIL → #216-#221 PASS) — Lịch sử visibility critical fix UAT iteration**. Trigger: Bro UAT 2026-05-19 phát hiện 2 bug critical phiếu PE/2026/A/032: Bug 1 Budget Adjust không show "Lịch sử thay đổi" (BE log OK + FE filter strict TraLai-only loại) + Bug 2 Return Mode 4 mode KHÔNG log Changelog (`ApplyReturnModeAsync` miss `db.PurchaseEvaluationChangelogs.Add()`). **Plan AB Chunk A** (`cdfd542`, 🟨 Implementer Case 1 spawn ~12K): BE refactor `ApplyReturnModeAsync` Drafter early return → common path + single `Changelog.Add()` cover 4 mode uniform với `modeName` switch enum + `actorName` resolve via `userManager.FindByIdAsync` mirror `LogTransitionAsync` pattern. FE `PeDetailTabs.tsx` × 2 app `HistoryTab` filter extend (PE_ENTITY_HEADER=1 + summary 'ngân sách' + Workflow summary 'Trả lại'). 🟥 Reviewer pre-commit verify ~22K PASS 0 critical/major/minor (1 minor V1 legacy fallback non-block). Run #215 FAIL test_infra 2/53 — Plan M edge case tests SQLite frozen-clock tie-break (gotcha #48 NEW): 2 Changelog rows cùng `CreatedAt` → `OrderByDescending.FirstAsync()` pick wrong → ContextNote null. **Plan AB Chunk A2** (`8c05947`, em main solo): Test filter `Where(Summary.Contains("Chuyển phase"))` pick đúng LogTransition entry. 111/111 PASS. Run #216 PASS. **Plan AC** (`a734bf2`, em main solo): BE capture pre-call Step/Level → Reject branch add `PurchaseEvaluationApprovals.Add()` với Decision=Reject + Comment from-pos + mode summary. BE line 472 enrich Approve comment prefix `[Duyệt vượt cấp tới Cấp cuối]` khi skipToFinal=true. FE × 2 app ApprovalsTab thêm `decisionBadge(decision, toPhase)` helper (Duyệt emerald / Trả lại amber / Từ chối rose). Run #217 PASS, bundle rotate × 2 app. **Plan AC2** (`25837b6`, em main solo, Option 2A bro chốt): FE merge view ApprovalsTab fetch changelogs + reconstruct synthetic Reject rows từ Workflow+Reject Changelog (filter EntityType=5 + Summary "→ TraLai"/"→ TuChoi" OR ContextNote "Trả về"/"không lùi được") + dedupe `approverUserId + timestamp 5s bucket` cùng real Reject rows + merge sort by approvedAt. KHÔNG DB write, reversible historical recovery. Run #218 PASS, 8 Workflow entries verified, bundle rotate × 2 app. **Plan AD** (`0aaf2df`, em main solo, Option A bro chốt): Drop fromPhase→toPhase badges (visual confusion 3/4 mode Reject giữ ChoDuyet — gotcha #49 NEW) + add `extractNextTargetHint(decision, toPhase, comment)` helper regex parse `Chuyển phase X → Y` + keyword detect "Trả về"/"vượt cấp"/"Cấp cuối" → "→ Cấp Y" / "→ Trả về Người chỉ định (Bước X Cấp Y)" / "→ Vượt cấp tới Cấp cuối" / "→ Đã duyệt hoàn tất". Cleanup unused `PurchaseEvaluationPhaseColor` import. Mirror × 2 app §3.9. Run #219 PASS, bundle rotate × 2 app. **Plan AE** (`9ea62be`, em main solo, preventive batch fix): BE 9 `Changelog.Add()` sites add `UserName = currentUser.FullName ?? currentUser.Email` (Budget Adjust + Create PE + Update PE Header + Detail Insert/Update/Delete + Quote Insert/Update/Delete + Select Winner). ICurrentUser đã có FullName/Email từ JWT — KHÔNG inject userManager mới. `replace_all=true` 1 pass cover 8 sites cùng indent + 1 site manual fix indent 16 spaces inside if block. 111/111 PASS local. Run #220 PASS, bundle UNCHANGED (BE-only commit). **Plan AF** (`506cada`, em main solo, Option A bro chốt): FE ApprovalsTab + HistoryTab build `userMap useMemo` từ embedded PeDetailBundle data: `drafterUserId+drafterName + approvals[].approverUserId+approverName + approvalFlow.steps[].levels[].approvers[].userId+fullName + levelOpinions[].signedByUserId+signedByFullName + departmentOpinions[].userId+userName` — no extra `/api/users` fetch (admin permission). `resolveActorName(a) / resolveUserName(l)` helper: trust entry.userName non-empty → userMap.get(entry.userId) → 'Hệ thống' fallback. Mirror × 2 app §3.9. Run #221 PASS, bundle rotate × 2 app. **Multi-agent ROI S25:** 🟦 Investigator 1 spawn (~28K Bug 1+2 audit) + 🟨 Implementer 1 spawn (~12K Plan AB Chunk A Case 1) + 🟥 Reviewer 1 spawn (~22K Plan AB pre-commit) + 🟩 CICD Monitor 7 spawns (Run #215 catch test gate fail + Run #216-#221 PASS verify, ~70K cumulative). Em main solo 5 plans AC→AF cross-stack reasoning + UAT iteration. Total cumulative agent cost ~132K · em main ~210K. **State chốt S25:** 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 + feedback_fe_usermap_fallback)** · 6 skills · 4 sub-agents active. **Memory CRITICAL FLAG:** cicd-monitor MEMORY ~72KB strongly over 50KB hard threshold — DEDICATED CURATION SESSION REQUIRED next (archive Run #186-#210 + S22-S24 verbose entries to `archive/2026-05-runs-186-210.md`). Investigator 32KB / Implementer 35.7KB / Reviewer 32.3KB cũng over 25KB threshold — recommend curate cùng session với cicd-monitor. **8 patterns reusable saved S25:** (1) Multi-Changelog SQLite tie-break (gotcha #48) → test discriminator, (2) CICD catch UAT skip test risk → resumed local verify 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 (Plan AC2), (6) Drop misleading dual-phase badges + semantic next-target hint (Plan AD), (7) Changelog UserName preventive systemic batch fix 9 sites (Plan AE), (8) FE userMap fallback từ embedded domain data no extra API (Plan AF). Bro UAT verify cumulative deploy live PE/2026/A/032 — historical entries pre-Plan AE nay resolve user names qua userMap fallback.) **Last updated S24:** 2026-05-15 (Session 24 chốt cuối — **🎯 Plan AA cumulative 7 commits push `a1a910f..ee0902a`** — User Workflow Matrix view + Sidebar widen + 4 polish iteration UAT feedback. Phase 1 Plan AA core (3 commit `ee776d5..ac2c859`): 🟦 Investigator Pre-A 5Q audit (~32K) + 👤 Chủ trì Chunk A BE+Layout solo (gotcha #44 đã fix permanent từ S18 → chỉ ADD `IsUserSelectable bool?` filter + DbInitializer INSERT-OR-UPDATE-Order idempotent shift existing prod rows + MenuKeys `Pe_DuyetNcc_WfView` helper + sidebar widen `w-72 xl:w-80` × 2 app + revert Plan U truncate × 5 sites) + 🟨 Implementer Case 2 Chunk B FE (~14K, WorkflowMatrixViewPage + types + App.tsx route ~270 LOC) + 🟥 Reviewer cumulative pre-commit (~25K, PASS 0 blocker + fe-admin build bonus 1926 modules) + 🟩 CICD Monitor Run #210 verify (4/4 wire end-to-end: filter live + menu Order shift + bundle hash rotate 2 app + Mig 31 unchanged). Phase 2 polish iteration UAT feedback (4 commit `da218f1..ee0902a`): 👤 Chủ trì Solo 4× CSS/UX polish — (1) `da218f1` hotfix container px-6→px-2 (content sát sidebar) + (2) `4d60598` redesign v1 panel-per-NV mirror admin Designer color coding (drop table 11 cột symbol khó hiểu) + (3) `fbbd361` redesign v2 HTML table rowSpan tận dụng full width (4 cột: Bước/Cấp/NV/Quyền duyệt grid 2-col 7 label) + (4) `ee0902a` wrap fix label dài về đầu hàng pattern hanging-indent reverse CSS (flex→block + inline-block icon + inline text + absolute ChevronDown) + text smaller text-[12px] leading-snug. Patterns reusable cross-project: (a) gotcha #44 relax pattern PROVEN cross-stack reuse, (b) DbInitializer INSERT-OR-UPDATE-Order idempotent re-deploy, (c) Tailwind JIT palette array (STEP_PALETTE 5 màu + LEVEL_PALETTE 5 màu cycle), (d) HTML table rowSpan flat row builder helper, (e) hanging-indent reverse via inline-block icon. Stats: 31 mig · 59 tables · **~146 endpoints (+1 GET filter param)** · **35 FE pages (+1 WorkflowMatrixViewPage)** · **111 test** (no change, baseline confirmed post-Plan AA) · 47 gotcha · 21 memory · 6 skills · 4 sub-agents. Multi-agent ROI S24: ~175K total (Inv 32K + Imp 14K + Rev 25K + CICD 12K + 3 flush agents ~12K + em main ~80K) = ~28% solo equiv. CICD verify Run #210 PASS. **Implementer MEMORY ~31.5KB > 25KB threshold** → recommend curate next session archive S20-S22 old entries.) diff --git a/docs/STATUS.md b/docs/STATUS.md index 90793b7..7e7c788 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -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`. -**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 `
    `). **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 `
    /` + Tailwind named groups `group/proj` + localStorage Set 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 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("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.) diff --git a/docs/changelog/sessions/2026-05-21-s26-pe-tree-view-rag-setup.md b/docs/changelog/sessions/2026-05-21-s26-pe-tree-view-rag-setup.md new file mode 100644 index 0000000..1488251 --- /dev/null +++ b/docs/changelog/sessions/2026-05-21-s26-pe-tree-view-rag-setup.md @@ -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 `
    /` 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 `
    /` HTML native 2-level + Tailwind named groups `group/proj` + `group/gt` chevron rotation + `[&::-webkit-details-marker]:hidden` +- Chunk C localStorage Set 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` +- Panel 1 widen `lg:grid-cols-[340px_1fr_360px]` → `[400px_1fr_360px]` +- Single PE project → flat card (no `
    `); 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 `
    ` 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 `
    ` 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 > :" + ├── 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 `` để 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 `` để 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 | diff --git a/docs/guides/multi-agent-setup-guide.md b/docs/guides/multi-agent-setup-guide.md new file mode 100644 index 0000000..8dab552 --- /dev/null +++ b/docs/guides/multi-agent-setup-guide.md @@ -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//` × 4 +□ 2. Paste 5 file template từ §4 — customize + 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 — 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//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:** + +**Current state:** + +**Skills preload mỗi sub-agent:** +- **Investigator:** +- **Implementer:** +- **Reviewer:** +- **CI/CD Monitor:** + +**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 `` + +→ 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 . 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: + + +## Q2 [topic] +... + +## Recommendations +- +- + +## Surprises / Edge cases +- + +## Cross-ref memory +- ... +``` + +## 💾 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/.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 . 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] : Chunk ` +7. Update MEMORY.md với pattern applied + ambiguities + token cost +8. Return deliverable report + +## 📝 Commit message format + +``` +[CLAUDE] : Chunk + + +Verify: +- Build pass (X warning, 0 error) +- N test pass (...) + +Pending Chunk : + +Co-Authored-By: Claude Opus 4.7 (1M context) +``` + +## ⚠️ 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 . 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 `` +- 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 + +### Verdict: PASS / FAIL — + +### 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. ✓/✗ +B. ✓/✗ +... + +### Issues +- CRITICAL: at + acceptance criteria +- MAJOR: +- MINOR: + +### Recommendations defer +- +``` + +## 💾 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 . 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: `/api/v1/repos///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 `/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 / | 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=`` VERDICT=PASS/FAIL — + +Duration: Xm Ys (baseline: ~3-4 min) +Push range: (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: ✓ / ✗
    + d. Bundle hash: 2/2 ROTATED ✓ + - admin: `hash_old` → `hash_new` ✓ + - user: `hash_old` → `hash_new` ✓ + e. Mig latest prod = matches repo ✓ +### Stage 5 Recommendation: + +### Pattern saved +- +``` + +## 💾 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//MEMORY.md` — Seed template (× 4) + +````markdown +# Agent — Persistent Memory + +> **Persistent diary cross-session.** Auto-injected first 200 lines / 25KB at spawn. +> Update BEFORE every stop. Curate when > 25KB. + +--- + +## 🎯 Role baseline + + + +--- + +## 📋 Patterns proven (cross-session) + + + +### Pattern 1: +- Description +- When apply +- Reusable cho + +--- + +## ⚠️ Anti-patterns observed + + + +--- + +## 🧠 Project context essentials (auto-load) + +- **Stack:** +- **State:** +- **DB Dev/Prod paths:** +- **Tech versions pinned:** +- **Conventions:** +- **Live deploys:** +- **Bearer test creds:** + +--- + +## 📅 Recent activity (last 10 FIFO) + +- **YYYY-MM-DD (setup):** Agent initialized. Baseline knowledge load complete. No performed yet. Awaiting first SendMessage from em main. + +--- + +## 🔄 Curate trigger + +- Memory size > 25KB → archive recent entries to `archive/.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 | +|---|---| +| `` | "MyProject" / "AcmeERP" / ... | +| `` | ".NET 10 + React + Postgres" / "Next.js + Prisma + MySQL" | +| `` | Snapshot state hiện tại (đếm thực tế) | +| `` | LocalDB / Docker / Cloud SSH config | +| `` | Prod API endpoint cho live curl smoke | +| `` | GitHub Actions / Gitea Actions / GitLab CI | +| ``, `` | FE prod URLs | +| `` | 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 ():** +- Working dir: +- Stack: +- State chốt: + +**Mission — audit NQ dưới đây, output structured findings under 500 words, file:line refs:** + +Q1. +Q2. +... + +**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: + +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 ():** +- Working dir: +- Stack: +- State chốt: + +**Mission: Plan ** + +**Files to edit — IDENTICAL changes mirror 2 app (nếu có 2 FE):** +1. `` +2. `` + +**Spec deterministic — N changes (1 commit):** + +**Change 1 — ** +[code block with exact edit] + +**Change 2 — ** +... + +**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 + +**Verify per chunk:** +- `npm run build` × fe-user + fe-admin PASS 0 TS err +- Report bundle size delta + +**Commit (1 commit cumulative):** +``` +[CLAUDE] : Plan +... +``` + +⚠️ **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 ():** +- State: +- Phase UAT mode: + +**Mission: Pre-commit verify commit `` Plan ** + +**Diff scope:** +- `` +X LOC +- `` +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. +B. +... + +**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 ():** +- State chốt: +- Phase UAT mode: + +**Mission: Verify Run #N sha=`` Plan ** + +Just pushed `` at ~YYYY-MM-DD HH:MM. + +**Tip commit `` scope:** +- `` +X LOC +- `` +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.