# Reviewer Agent — Persistent Memory

> **Persistent diary cross-session.** Auto-injected first ~200 lines at spawn (L1 HOT).
> Update BEFORE every stop. Tiered Memory v1: L1 HOT cap ~17KB (hook 24.4KB read-limit) · L2 `archive/` on-demand · L3 RAG `search_memory` just-in-time. Keep entry ≤ 1.5K chars (gotcha #53).
> Full verbatim history pre-S40 → git `d2f52ba` + `archive/2026-05-q1..q2.md`; S51→S76 detail → `archive/2026-06.md` (S69/S70/S71/**S80** curate). Archive map: `archive/_INDEX.md` + per-period `.gist.md`.

## 📁 Area memory (L2 on-demand — Read khi review vùng tương ứng)
- [S62 PE budget soft-warning](project_s62_pe_budget_soft_warning.md) — PASS: hard-block→soft-warning; submit-guard intact + validator giữ `BudgetPeriodAmount>0`, row8 negative-safe (additive-only). Validator class `PurchaseEvaluationFeatures.cs:317`.
- [Wire/mirror claim verification anchors](feedback_wire_claim_verification_anchors.md) — sha256 twin-file · `git diff -U0` isolate true-adds · `allowNegative` bleed check · guard-still-intact grep.
- [S89 PE budget-sectionB review](project_s89_pe_sectionb_review.md) — 3/3 upheld + CAUGHT MISSED #70 race: Block B PRO row3/row8 share adjustMut + cross-echo stale + NO `||peFetching`. authz-lens ≠ concurrency-lens.
- [S89 PE ends-before-CEO PLAN review](project_s89_pe_endsbeforeceo_plan_review.md) — CONCERN: BE design sound but FE gap — 4 PeUrgentChips render-sites, plan covered only 2 (missed InboxPage:290 + wrong ListPage path).
- [S89 finalize-note PLAN review](project_s89_finalize_note_plan_review.md) — CONCERN: plan ground-truth 100% accurate; gaps = note omits intermediate-approvers-still-sign + skipToFinal-last-level corner + Dev DB 9 migs behind.
- **S101 H18/H19 WF2 governance re-run + LANE-C** — PWC/PASS; detector fault-inject 4/4; 4 hash recompute MATCH (hex→SHA strip/no-strip proves content-hash ≠ commit-SHA); lesson: exact-token sweep misses paraphrased labels → widen concept-phrase khi retire named artifact; #53 garble recovered. → `archive/2026-07.md`.
- [S103 H20+crystallized-backfill review](project_s103_h20_crystallized_backfill_review.md) — WF2 PASS; 6/6 hash recompute MATCH + 4 already-met verified. Lesson: multi-axis warning phải nằm trong OUTPUT của script (reader chạy inline), không chỉ doc.
- [S111 PE sign-off 6-decision design review (schema/history lens)](project_pe_signoff_history_schema_review.md) — GO-WITH-ADJ; D5 opinion-history: append-only table, REJECT version-col (drops UNIQUE + breaks UPSERT).
- [PE multi-NCC per-hạng-mục cardinality#3 review](project_pe_multiwinner_perhangmuc_review.md) — PASS_WITH_ADJ; 2 MUST (giaTri isSingle/detailsSum · seed IsSelected≠IsWinner). Lesson: derived src-of-truth = EVERY write-path re-derive.
- [S113 Supplier import v2 close-review (owner anh Kiệt)](project_s113_supplier_import_v2_review.md) — GO-WITH-ADJ 2 must-fix (consumers không pass published=true → drafts leak). Lesson: "filter added" ≠ "drafts hidden" — grep-all-consumer + create write-path.
- [S114 PE per-hạng-mục BE-financial review](project_s114_pe_multi_ncc_perhangmuc_financial_review.md) — NEEDS-FIX: DeleteQuote/DeleteDetail KHÔNG re-derive IsWinner → phantom HĐ GiaTri=0. Lesson: derived-invariant re-establish MỌI mutation kể cả DELETE.
- [PE per-hạng-mục spec review (winner-truth lần 3)](project_pe_multi_ncc_perhangmuc_specreview.md) — PASS_WITH_ADJ. Lesson: grep write-path field-NGUỒN (IsSelected) không chỉ field-đọc; cite-range bọc branch-decision.
- [S114 PE per-hạng-mục IMPL review (flip lần 3)](project_s114_multi_ncc_perhangmuc_impl_review.md) — NEEDS-FIX; DeleteQuote vỡ invariant. Lesson: cardinality grep-consumer PHẢI gồm Delete-handler field-nguồn; spec-enum writer KHÔNG đáng tin.
- [PE negative-quote FE-only spec review (correctness-wire)](project_pe_negative_quote_correctness_review.md) — PASS_WITH_FIXES; MUST = sign-loss (form.thanhTien read DIRECT at POST). Lesson: defer-parse widget→shared-form dialog = sign phải tới field-chung ở MỌI mutation incl toggle.
- [S118 Procurement master-access seeder review](project_s118_procurement_master_access_review.md) — PASS(cond); MAJOR Reports.Read leaks financials + Suppliers.Update grant ≠ edit. Lesson: menu-flag grant ≠ API capability; bare `[Authorize]` GET = open-to-all.
- [S123 governance 4-change review (backtick-guard + H24-3 + retire dạng-3 + mark)](project_s123_governance_4change_review.md) — PASS_WITH_FIXES; CAUGHT H24-3 thiếu enclosure-guard mà cùng diff vừa chứng cần (gen-2 citation-trap) + greedy `.*` lấy `(S<N>` CUỐI≠MAX + lý-do-retire áp cho dạng-2 thì giết C8. Q5 "HOÀN-THÀNH mark" = nguỵ-biện. Q8 ENDORSE không-bump.

---

## 🎯 Role baseline

Adversarial pre-commit reviewer SOLUTION_ERP. Read-only verify + live curl prod UAT (`*.solutions.com.vn`). Tools: Read, Grep, Glob, Bash (curl + git diff + sqlcmd read) + 5 RAG MCP. Skills: `dependency-audit-erp` + `contract-workflow` + `permission-matrix`. Output: PASS/FAIL + concrete issues file:line. NEVER write code.

---

## 🚨 Recurring bug patterns (catch priority)

- **#44 Silent 403 class-level Authorize quá strict** — Drafter dropdown empty silent (TanStack catch silent → UI empty). Grep `\[Authorize\(Policy=.*\)\]` class-level + curl non-admin expect 200. Fix: class-level `[Authorize]` only (any authenticated); POST/PUT/DELETE giữ `[Authorize(Policy="X.Create")]`.
- **#43 Step.Order ≠ index 0-based** — `Where(s=>s.Order==i)` wrong row. Fix: EF query → in-memory `OrderBy(Order).ToList()` → index.
- **#42 Dual schema V1/V2 — Service phải branch** — `if (entity.ApprovalWorkflowId is Guid awId) ApproveV2Async else V1Legacy`.
- **Wire BE claim** — grep diff `// Mock`/`alert(`/no POST-PUT-DELETE call + live curl expect 2XX. Severity CRITICAL block.
- **#70 FE absolute-set stale-echo race** — N fields cùng-cột share 1 mutation + echo sibling từ server-snapshot (`bs`) + `invalidate()` fire-and-forget (không await) → lưu 2 ô liên-tiếp đè mất. Window mở SAU `isPending=false` (btn re-enable), KHÔNG lúc in-flight. Catch: đếm field-cùng-cột share mutation + check invalidate awaited; fix = `useIsFetching` gate nút Lưu tới khi refetch land.
- **#71 enum proxy-predicate pollution** — thêm enum value vào entity dùng-chung → UI/guard phân-loại theo PROXY-predicate (`supplierId===null`) thay vì enum tường minh → value mới lẫn nhầm phân-loại + false-pass guard. Catch: grep mọi field-proxy predicate, loại value mới tường minh; build-verify TỪNG app.
- **Cross-module security mirror (S29 Smart Friend)** — khi mirror entity/Command cross-module (PE→Contract→Budget V2), focus data-shape MISS security guard. Pattern: `aw.ApplicableType == ExpectedType` validate ON Create BEFORE instantiation (mirror `PurchaseEvaluationFeatures.cs:62-77`). Attack: Drafter forge POST với `approvalWorkflowId` của module khác → FK Restrict chỉ check Id-existence NOT ApplicableType → wrong-scope pin. Re-verify `IsActive`+`IsUserSelectable` server-side. Password ≥12 chars. Severity MAJOR.
- **#17 EF migration 3-file** — `git diff --name-only | grep Migrations/` expect 3 (target + Designer + Snapshot).

---

## 📋 6-category checklist (EVERY review)

- **Cat 1 Wire BE/feature claim:** grep mock markers diff + `await api\.(post|put|delete|patch)\(` + live curl POST/PUT/DELETE if deploy claim + status matrix.
- **Cat 2 Schema integrity:** 3-file rule Mig + column types vs entity def. Reference `docs/gotchas.md` (71 active).
- **Cat 3 Security:** `[Authorize]` class-level ALL new controllers + per-action policy admin-scoped (gotcha #44) + FE PermissionGuard + menuKeys.ts mirror BE MenuKeys.cs + FluentValidation + EF parameterized.
- **Cat 4 Code quality:** `dotnet build SolutionErp.slnx` 0 err + `npm run build` × 2 app (TS6 strict) + tests baseline **354 PASS** (Phase 9 UAT exception OK) + no `--no-verify` + anti-fiddle (scope drift >20% LOC = FAIL) + mirror 2 FE app §3.9.
- **Cat 5 Test coverage:** new helper → xUnit · new endpoint → integration · bug → regression test-before-fix. Phase 9 UAT test-after default OK (`feedback_uat_skip_verify`). Baseline 354.
- **Cat 6 Writing-quality (Harness-7, S64):** outward text (verdict gửi anh / report) = tiếng Việt câu hoàn-chỉnh đủ dấu đúng ngữ-pháp; describe issue + acceptance criteria, NOT code edits. Escalate disagreement explicit.

---

## ⚠️ Anti-patterns + 🛡️ Smart Friend guard

1. ❌ Recommend code edits (only describe issue+criteria) · 2. ❌ Skip live curl if deploy claim · 3. ❌ Accept "wire" without grep proof · 4. ❌ Defer to em main authority (escalate explicit) · 5. ❌ Skip MEMORY · 6. ❌ **Lower bar match em main** (Smart Friend Cognition anti-pattern).

**Smart Friend (Cognition):** NEVER lower bar. Em main code fine → PASS. Em main issues → FAIL with specifics regardless social pressure. "Quality ceiling set by primary, not escalation." Value = raise quality through catch.

---

## 🧠 SOLUTION_ERP review essentials (S80 verified — re-ground từ docs/STATUS.md canonical)

- **Tests baseline:** **354 PASS** (45 Domain + 309 Infra · 0 fail/skip). Must increase khi feature added (§7); Phase 9 UAT exception (`feedback_uat_skip_verify`).
- **Gotchas:** **71 active** (`docs/gotchas.md`, format `### N.`). Latest: #69 bundle-hash non-determ (deploy rebuild-FE-uncond rotate) · #70 FE stale-echo race (useIsFetching gate) · #71 enum proxy-predicate pollution · #66 Tailwind v4 unlayered `h1-h4` color thắng utility · #58 EF read-modify-write lost-update→ExecuteUpdate atomic.
- **Migrations:** **57 latest `AddPeSuggestedPriceNotes`** (path `src/Backend/SolutionErp.Infrastructure/Persistence/Migrations/`). PE-budget: Mig 50 `PeWorkItemBudgets` per-gói-thầu (DROP module Budget cũ) · Mig 54 giá-đề-xuất PRO/CCM + giá-chốt · Mig 55 CcmNote · Mig 56 ProInitial/ProAdjust split · Mig 57 ghi-chú-giá PRO/CCM.
- **Endpoints:** ~253 · **88 SQL tables**.
- **Identity password ≥12 chars** (reject 11-char). Test creds: admin `admin@solutions.com.vn/Admin@123456` (full) · UAT `nv.test@solutions.com.vn/TestUser@123456` (Drafter CCM).
- **Prod:** api/admin/eoffice.solutions.com.vn. Bundle live admin `CsJetgZH` / user `BVS0ApIm` (Run #330). **Pin:** MediatR `12.4.1` (flag `Version="14`) · Swashbuckle `6.9.0` · Node CI `20.x`.
- **Conventions:** `docs/rules.md` (§1.1 outward writing, §3.9 mirror 2 FE, §5.2 commit, §6.5 docs narrative, §7 test timing, §2.8 pin).

---

## 📅 Recent activity (compressed — full verbatim → `archive/2026-06.md` + `archive/2026-07.md` via `archive/_INDEX.md`)

- **S124 L2 fidelity-to-source review, adap-wave plan — PWF (0 misread/1 MAJOR/3m):** 5/6 broadcast-reading traps read-faithful (NOT-adopt→method/spirit · h17 4-floors-KEEP · r6 abs-path). MAJOR = **push-guard "REFINEMENT ahead-of-broadcast" (spec:58) = OVERCLAIM**: SE trailing-K is LOOSER than broadcast ahead-range-all-count, keeps sandwiched wal:→leak; NO dimension strictly ahead. run.md:15 + mark cl.4 already carry honest "noise-accepted no-rewrite" ⇒ spec contradicts own run.md+mark. **Lesson: "ahead/refinement" = verify vs broadcast's ACTUAL requirement (looser≠ahead); spec+adap-report = shipped artifact → reconcile before hub-send.** Verified: adap-reports at `docs/governance/` not `.claude/` (path-trap false-empty). → `archive/2026-07.md`.
- **[→ archive/2026-07.md @S126] S124 adap-wave-reply PLAN L3-lens — PASS_WITH_FIXES (0C/3M/2m):** 🎯 do-token trap bắt WHILE adopting (chunk 26075 mislabeled whole-file 70892, 2.72× under) + M2 meta-count + M3 nấc-verified-on-NEVER-RAN. Lesson: verify do-token = re-Read full + tự đọc truncation-line.
- **[→ archive/2026-07.md @S126] S125 do-token RELABEL (em-main B3):** negative-control 3-probe ⇒ notice-N = **CẬN-TRÊN heuristic, KHÔNG real-token**; dải STATUS [31K byte/4 — 70,9K notice]. Lesson: nhãn "real-N" tự nó = mislabel — negative-control (chuỗi lặp) mới phân-biệt heuristic/tokenizer.
- **[→ archive/2026-07.md @S126] S125 fable-real adap-review — PASS-WITH-SELF-FIXES [engine:fable-real inline-lead]:** 2 near-miss tự bắt: false-TAMPER→RCA **verifier-bệnh** (PS5.1 ANSI-decode; sibling-test 2-CHIỀU: sibling-MATCH⇒file-bệnh · sibling-FAIL⇒verifier-bệnh) · suýt claim-sai nguồn outward→mở ĐÚNG file+dòng trước khi viết; stamp-then-edit = sửa→RE-STAMP `58f5afd8`→re-selftest cùng lượt. Bẫy Edit-tool escape-BOM→build-from-codepoint. Evidence: `runs/2026-07-16-S125-fable-real-adap-review/`.
- **S123 governance 4-change review — PWF (3 must/1 MAJOR/3m):** → [topic](project_s123_governance_4change_review.md). 🔴 **#53 garble tại TAO; đĩa KHÔNG cứu vì chưa ghi diary ⇒ ghi diary TRƯỚC return.** Vá-1-lớp⇒grep MỌI matcher cùng-lớp TRONG diff · đổi-format-cho-trượt-mẫu = Goodhart rời-tập-đo.
- **S117 PE negative-quote FE-only spec-review — PASS.** Lesson: 2-tier guard = compare SUM EXPRESSION not comparator; derived-flag safety = trace what flag KEYED-ON (`IsSelected` sign-agnostic). → `archive/2026-07.md`.
- **S116 outward-email GATE H-22 WAL restart runtime — PASS (3m).** Lesson: persist-claim on git-tracked WAL → verify tracked+0-drift; mechanism-proof lives at Stop-hook run, NOT git property. → `archive/2026-07.md`.
- **S115 presence-not-age spec-review — PWF (0C/2M/5m).** Lesson: verify EACH regex-alt vs EACH target-line by hand; acceptance-grep can't detect its OWN deliverable's miss; skip-on-contiguous-prefix = correctness-inversion. → `archive/2026-07.md`.
- **S101 H19 WF2 Lane-A — PWC (closed @S102):** marker WRITE-ONLY dead — persist-claim cần CẢ reader-side (verify consumer exists). → `archive/2026-07.md`.
- **S100 H18 WF2 synthesis+Lane-B — PWC:** ledger revert-clean + ratio-band; anti-pattern HELD stale WF2 run-id NOT stamped. → `archive/2026-07.md`.
- **S98 3 verify-lane — PASS:** fidelity-gate 3-lớp; Windows byte-verify = .NET ReadAllBytes/`wc -c` (MSYS strip `\r` báo sai). → `archive/2026-07.md`.
- **S97 PE finalize UAT + Mig 60/61 — PASS:** default-flip byte-mirror SHA256 ×2; RUNTIME-flag grep-all + 4-projection. → `archive/2026-07.md`.
- **S93 Harness-16 MFE adopt — PASS:** code-gate re-derived denom; WF1 caught vocab-fork H6.7≠H16. → adap-report + _INDEX.

- **S92 PROD-security hide 5 menu-groups admin-only — PASS (1 note):** → [project_s92_admin_only_modules_revoke.md](project_s92_admin_only_modules_revoke.md).
- **June-2026 digest — LESSON-ONLY (verbatim → `archive/2026-06.md` + `_INDEX`):** merge-distill fabricates false-specificity ⇒ QUALITY gate AFTER presence · sha = self-declared NOT recompute · fail-closed guard BEFORE terminal-state + server-recompute · TRACKED = check-ignore ≠ ls-files · menu-hide ≠ API-lock · single→multi stops at display-layer.

- **S108 first-real-run H19 — FAIL (1C+4M+6m):** email "đã sửa comment" khi hmw.js chưa sửa. Lesson: outward-claim "đã sửa X" phải cat X trước gate; grep stale-claim theo CLASS. → `archive/2026-07.md`.
- **S109 fidelity-gate 2 gist L2 — PWF (3):** gist meta-count 15≠disk 14; delta tự-tính = false-specificity; fact-claim trong N/A verify như content. → `archive/2026-07.md`.
- **S111 H22 WAL adopt — PWF (0C/1M):** CATCH "STAGED" còn khi N.3 nâng VERIFIED-RUNTIME = nâng-nấc-quên-sync cùng-diff; live-witness>forensics. → `archive/2026-07.md`.
- **S110 H21+MTv3 — PWF (0C/5M):** doc "VALID_ROLES 12" code=10 → claim-về-code grep lại kể cả reword; supersede trỏ adap-report chưa tạo = dangling. → `archive/2026-07.md`.
- **S112 fable-real-single close-reviews+FINAL — GO 0-must:** Import btn reuses sibling-menu guard but endpoint=Admin ⇒ derive guard from ENDPOINT authz; EDGE-5 gác FROM-state ở ĐỈNH method KHÔNG per-branch; self-flip token-test = internal NOT external-accept. → [topic](project_s112_supplier_import_review.md).
- **S126 (2026-07-16) A1-H23-probe + email-H23-gate [opus ×2, em-main VERIFY+APPEND] — gate FAIL bắt 3 lỗi thật trước stamp:** (1) 🎯 "Audit 2/2/0" NON-REPRODUCIBLE — audit COUNTS = **session-cumulative**, chính 2 lane review đẩy 2→4. **Lesson: số AGGREGATE cumulative KHÔNG vào outward artifact mời-reproduce — evidence bền = per-lane theo run-id.** (2) "Ba việc nêu ở thư" thực = **2 ASK** — MỞ thư đếm ask thật, đừng gộp courtesy-expectation. (3) "hub 17/17" = SE-self-obs R1-open → hedge+quy-thuộc. Lõi verified độc-lập: lead=Fable **116/116** records · A1 fable · A2 opus. Fixed → stamp `945cf3ad` selftest+stamp_verify+_index CÙNG lượt. Evidence: `runs/2026-07-16-S126-adap-spec-execute/`.
- **S127 (2026-07-16) fable-real #1 gate đầu-vào adap đợt 16-07 [engine: fable-real-single · Fable-S127 · ~62K tok · 0-garble; em-main VERIFY 3/3 spot-check + APPEND] — GO-ADAP, BÁC 1 claim thư điều-phối hub:** "bản 2 = adopt thực chất DUY NHẤT" sai — `rag.json:26 contextual_retrieval: true` override ACTIVE ⇒ bản 5 có việc config THẬT (+ bản 3 ≥2 hằng-số sống bằng nhãn: crystallized-backfill.ps1:117-119 "calibrated" /4.0 /3.0 no-phản-chứng · memory-budget.json:89 measured_token_estimate). **Lesson:** (1) hedge broadcast ("chưa override thì đúng sẵn") phải test bằng MỞ config THẬT — SE là ca override mà thư điều-phối không thấy; (2) "already-aligned" tinh-thần ≠ luật — kiểm-kê vẫn lòi ứng viên; (3) SE GIỮ counter hub vừa gỡ = ĐÚNG (điều-kiện gỡ 1-phiên/ngày + trả-mọi-lượt đo được KHÔNG áp SE: 3 tick/2 ngày `.session-counter.json`). Full verdict + AC 8/8: `runs/2026-07-16-S127-adap-dot-16-07/sub-reviewer-1-verdict.md`.

---

## 🔄 Curate trigger
- Hook-cap **>17.1KB** (24.4KB read-limit — đổi từ ~30KB cũ, S109) → archive recent → L2 `archive/<period>.md` (append additive) + `_INDEX.md` substring pointer. Stale >3mo → remove.
- **S116 curate (self, 2026-07-13, hook 21.4KB→<17.1KB):** moved S115+S116 verbatim → `archive/2026-07.md` (move-not-cut, batch-marker) + digest in L1; MERGED 12 June bullets (S65-S91) → 1 consolidated digest line (detail `archive/2026-06.md`+`_INDEX`); trimmed 4 PE-per-hạng-mục + S89-trio + S111 Area-pointers (detail in topic files on disk).
- **S113 curate (self, 2026-07-12, hook 21.3KB→~16KB):** compressed 4 verbose S112 entries (2 close-review lines→1, BE-close+FINAL→1) + this curate-log in-place; NO file-move (lessons preserved inline). digest kept L1. **+review-lane addendum:** 4 verbatim ALSO moved → `archive/2026-07.md` + 4 `_INDEX` pointer (move-not-cut) + trimmed 2 digest.
- **S109 curate:** moved 4 verbatim S100/S101 → `archive/2026-07.md` +4 pointer.
- **S102 recovery (em-main):** cut-not-moved ×5 @`f229b07` recovered từ git. **Lesson: L1-shrink kèm claim "Detail→archive" = BẮT BUỘC grep moved-not-cut TRƯỚC khi trust digest.**
- **Prev curates:** S80 (moved 13 S65→S76 →archive/2026-06), S71 (moved 10), S70 (built `_INDEX`+`.gist`), S40.
