# Investigator-Codebase 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 soft-cap ~30KB · 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..q4.md` + `archive/2026-06.md`. 🗺️ **Lookup map: `archive/_INDEX.md`** — 1 dòng/bản-ghi + con-trỏ substring (sha-keyed, Ctrl-F fallback); đọc verbatim + `2026-0{5,6}.gist.md` theo nhu cầu. **S80 curate: moved 15 recon entries S65→S76 + 2× 06-20 → archive.**
> **Renamed S39:** investigator → investigator-codebase (internal half; external → investigator-api).

---

## 🎯 Role baseline

Read-only INTERNAL audit SOLUTION_ERP codebase. Tools: Read, Grep, Glob, Bash + 5 RAG MCP. Output: concise findings <500 words + file:line refs. Skills: `contract-workflow` + `permission-matrix` + `ef-core-migration`.

## 🚫 Split boundary (S39)
- ✅ MINE: internal SQL/EF/grep/reference mirror, sqlcmd schema scan, controller audit, migration diff, count grounding
- ❌ NOT: external docs/CVE/lib → `investigator-api` · write → implementer · test → test-specialist · architecture decision → em main

---

## 🆕 Recent invest (S112-S114 stubs — verbatim → git history + `archive/2026-07.md`)
- **S114 (07-12) PE multi-winner PER-HANG-MUC (fable-clone):** Mig58/59 multi-winner = WHOLE-SUPPLIER (`PurchaseEvaluationSupplier.IsWinner`); `Quote.IsSelected` per hang-muc×NCC = latent-hook Mig12 nay LIVE (Mig65 backfill re-key winner-truth IsWinner→IsSelected = CARDINALITY-CHANGE #2). winnerQuoteTotal=SUM(Quote WHERE IsSelected) `PeFeatures.cs:1188`. #1 open: N-win 1 hang-muc split KHOI-LUONG hay full-price (schema thieu per-winner volume). Tag `[s114, pe-multiwinner-per-hangmuc, quote-isselected-live]`.
- **S113 (07-12) Supplier import v2 (5-lane ensemble):** selection consumers qua ListSuppliersQuery (`PeDetailTabs:2222`+`ContractCreatePage:321`+dashboard); chot IsPublic-bool + dedup-MST+Code + fail-closed default. Prod 37 NCC. 1 lane #53-garble→em-main recover. Tag `[s113, supplier-import-v2, ma-ncc=code]`.
- **S112 (07-12) Supplier Excel-import + PE sign-off (fable-clone):** Supplier 27/27 bijective (Mig62 SHIPPED prod); dedup Code CI-collation → normalize-case TRUOC store; PE bypass = go/gate `ApplyDrafterBypassOnSubmitAsync`; EDGE-5 drafter-forge-Reject REACHABLE. Tag `[s112, supplier-mapping, pe-bypass-a1, edge5-reachable]`.

## 📋 Patterns proven (apply confidently)

### Schema scan via sqlcmd
```bash
sqlcmd -S "(localdb)\MSSQLLocalDB" -d SolutionErp_Dev -Q "..."     # runtime API (primary)
sqlcmd -S "(localdb)\MSSQLLocalDB" -d SolutionErp_Design -Q "..."  # ef tooling
ssh vietreport-vps "sqlcmd -S .\SQLEXPRESS -d SolutionErp -U vrapp -P '...' -Q '...'"  # prod
```
Queries: `sys.columns`, `sys.triggers`, `__EFMigrationsHistory`, `COUNT(*)`, `sys.indexes`.
**Gotcha 2 LocalDB distinct** (`feedback_designtime_runtime_db`): `_Dev`=runtime (appsettings.Development), `_Design`=`dotnet ef` default. Prod password fallback `C:\inetpub\solution-erp\api\appsettings.Production.json` khi `$env:PROD_DB_PASSWORD` empty.

### Controller / wire-claim audit
- Grep `\[Route\("api/[a-z]+"\)\]` enumerate controllers · `\[Authorize(Policy = "..."` per-action policy (gotcha #44 silent 403 class-level quá strict)
- Grep `// Mock` / `alert(` / `setEditing(null) // close UI` — wire claim bugs · `IActionResult` vs `ActionResult<T>`

### Smoke verify catalog
Bearer từ `POST api.solutions.com.vn/api/auth/login` → status matrix expected vs actual + file:line evidence.

### Memory cross-reference
30 user-memory tại `C:\Users\pqhuy\.claude\projects\D--...\memory\MEMORY.md` (index). Key: per_chunk_commit · uat_skip_verify · designtime_runtime_db · per_nv_permission_scope · ef_migration_backfill_reorder · workflow_fanout_reliability · canonical_spec_over_broadcast (S79).

### External research → DEFER `investigator-api` (split S39)

---

## ⚠️ Anti-patterns
❌ Skip MEMORY update · ❌ Vague "seems like/probably" · ❌ Missing file:line · ❌ >500 words · ❌ Scope drift to architecture recommendation (em main decides)

---

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

- **DB:** Dev `SolutionErp_Dev` · Design `SolutionErp_Design` (distinct) · Prod `.\SQLEXPRESS`/`SolutionErp`/`vrapp` via SSH `vietreport-vps`
- **Migration path:** `src/Backend/SolutionErp.Infrastructure/Persistence/Migrations/*.cs` (⚠️ NOT root `/Migrations/`). **57 mig**, last `AddPeSuggestedPriceNotes`.
- **Counts S80 (canonical docs/STATUS.md):** 57 mig · **88 SQL tables** (count `.ToTable()` ModelSnapshot NOT DbSet) · ~253 endpoints · 68 FE pages · **54 menu keys** (BE `MenuKeys` const) · **354 test** (45 Domain + 309 Infra) · **71 gotchas** (format `### N.`) · 30 user-memory · 6 skills · **11 sub-agents** (S80-snapshot — roster nay 14 vai + worker-tier-pin S124; số sống đọc STATUS.md)
- **Tech:** .NET 10 Clean Arch (Api→Application←Domain + Infra) + CQRS MediatR + EF Core 10 + 2 React 19 Vite 8 TS 6 (fe-admin :8082 + fe-user :8080) + SQL Server + Gitea CI + IIS
- **Prod:** api/admin/eoffice.solutions.com.vn · Gitea `git.baocaogiaoduc.vn/vietreport-admin/solution-erp` (Actions API `/api/v1/repos/.../actions/tasks` NOT `/runs` 404, cache stale ~2min gotcha #46 — cross-check VPS mtime). Bundle live admin `CsJetgZH`/user `BVS0ApIm` (Run #330).
- **Auth:** `admin@solutions.com.vn/Admin@123456` (full) / `nv.test@solutions.com.vn/TestUser@123456` (Drafter). Response `accessToken`+`refreshToken`+`user`. Password ≥12 chars.

---

## 🔄 Active workflow schemas (V1 + V2 coexist post-S17)

- **V1 Mig 21 flat** — `WorkflowDefinition` pin PE/Contract cũ. Match Dept+PositionLevel.
- **V2 Mig 22-31** — `ApprovalWorkflow` pin PE/Contract mới, match `ApproverUserId` 1-1 OR-of-N cùng Cấp. Steps (Phòng) > Levels (Cấp). PE + Contract đã wire V2 (Mig 32+33 S29). Proposal V2 (Mig 38). WorkflowApps skeleton (Mig 39).
  - Mig 25 IsUserSelectable · Mig 26 PE LevelOpinions UPSERT · Mig 29 Allow* per-NV · Mig 30 F4 AllowApproverEditBudget · Mig 31 SkipToFinal→ApproverLevel · Mig 53 cờ-gấp+CeoApprovalThreshold · Mig 54 giá-đề-xuất PRO/CCM+giá-chốt · Mig 56 ProInitial/ProAdjust · Mig 57 ghi-chú-giá.
- **State machine PE 5 trạng thái:** Nháp / Đã gửi duyệt / **Trả lại (TraLai=98)** / Từ chối (REMOVED-S60 hard-guard) / Đã duyệt
- **Mode Trả lại 4 option per-Level:** OneLevel (lùi 1 Cấp) / OneStep (lùi Bước trước) / Assignee (pick NV đã ký) / Drafter (Phase=TraLai). 3 mode đầu giữ ChoDuyet lùi pointer. Admin bypass `level.Allow*`.

---

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

- **S125 (2026-07-16) adap-review invest-lens [engine:fable-real single deep-pass · vai compound anh gán reviewer+inv-cb · chạy inline-lead]:** probes: auto-memory **50 tracked/0 porcelain** (R6 git-track ĐẠT — còn WRITE-path post-restart) · agents **14/14 `model:opus`+`effort:max`** (file 15=README benign) · 6/6 product-carry còn HANDOFF · H24 counter=4 tick-S125 content-addressed (light@9/deep@18, 0 class-repeat≥3) · Stop-hook wal-flush KHÔNG fire per-turn phiên này (HEAD đứng `3aacdf9` suốt) · residue `all-inherit` floor-sống chỉ 2: `fable-real.md:37` (gap thật — file NGOÀI sync-list S124) + `fable-clone.md:43` (asym trong-file, :57 updated :43 sót) — CẢ 2 vá S125; `session-start.md:52`+`hmw.js` comments = lineage GIỮ. Hub-side: outbox/all=65, `stamp_verify.py` 3-OK / 2-NO-DECLARED-SHA (do-token·h17-bookend) · hub ĐÃ CÓ script-verify s76 `check_email_pull.py` (hub check-email.md:31) — bootstrap-copy sister CHƯA mang. Tag `[s125, adap-review, verifier-suspect-first, worker-tier-pin-residue]`.
- **[→ archive/2026-07.md] 2026-07-13 PE negative-quote 2× LENS (Budget-consumers + edge/precedent/test)** — key giữ: budget-not-mutated-by-quote (architectural) · submit-guard `Sum()<=0` `:206` duy-nhất reject · no-quote-validator · parseVnd strip-minus · giaTri-âm bypass validator · gotcha #81 orthogonal-dấu. Executed S116; anchors sống trong S116/S117 entries.
- **[→ git 07-12 · superseded by S115 entry above] PE per-HANGMUC multi-winner LENS BE-consumer-audit:** 3 cardinality axes — `SelectedSupplierId` single (legacy) · Mig58 `IsWinner`=WHOLE-SUPPLIER liên-danh · `Quote.IsSelected` per hangmuc×supplier (S114 made LIVE). 5 money consumers keyed off IsSelected now (winnerQuoteTotal/submit-guard/ccm-threshold/giaTri/budget-block-B). ~6 test files. Tag `[pe-multiwinner, per-hangmuc, quote-isselected, cardinality]`.
- **[→ git 07-12] Supplier-import-v2 LENS-3 FE-dialog-UX:** SupplierImportDialog+SuppliersPage SHA-identical 2-app; dialog 2-step preview→confirm round-trips `preview.rows` → per-row edit feasible; `ExpectedHeaderTokens` 30-token baked `SupplierExcelImportService.cs:35-68` = template single-source; Mã NCC=Code; import authz-mismatch BE `[Roles=Admin,CatalogManager]` vs FE `Suppliers/Create` open. Tag `[s112, supplier-import-v2, fe-lens3, import-authz-mismatch]`.
- **[→ archive/2026-07.md verbatim + digest @S125] S105 BVAAU auth RCA:** class **"hub+site-tĩnh relative-`/api` chết im prod"** (web.config loại `^/api/` → 404 → anonymous); fix API_BASE-absolute `51c69fb`.
- **[→ archive/2026-07.md verbatim + digest @S125] S104 Supplier 30-field schema-invest:** ClosedXML 0.105.0 chuẩn (KHÔNG OpenXml-raw) · `UpdateSupplierCommand.cs:49-57` blind-set=latent#73 · SupplierDto hand-projected 2-site · chốt Mig 62 +18 nullable.
- **[→ git+session-log 07-03 + adap-reports] S101 H19-adopt Lane-2:** map reviewer=review-gate / investigator=ground-truth-lane; 12-pt tier-checklist ALL✅ (11/11 inherit, C3 no-`[1m]`-in-frontmatter); toggle-marker MUST copy `.gitignore:87` last-match placement; VACUOUS-MET all-inherit+Fable. *(verbatim → archive/2026-07.md)*
- **[→ git+session-log 07-02 + adap-reports] S100 H18-adopt WF1:** ⭐ ghost-wire-class **config-key-defined-but-unread** (`budget.json:54-55` script re-hardcode same-value→no-flag; catch=grep-key-across-scripts); cron=ghost-wire (CronList=0); `_ledger` orphan-catch 0/15-lifetime. *(verbatim → archive/2026-07.md)*
- **[→ git 07-12 · Mig64 IsPublic shipped since] Supplier import-v2 LENS-4 public/visibility recon:** 3 SELECTION consumers ALL hit `GET /suppliers` ListSuppliersQuery (SuppliersPage:83 · PeDetailTabs:2222 · ContractCreatePage:321); DISPLAY-of-existing joins by stored SupplierId MUST NOT filter (ContractFeatures/PeFeatures/Dashboard); write-guard backstops `ContractFeatures.cs:64`+`PurchaseEvaluationSupplierFeatures.cs:49`. Rec fail-closed default + stored `IsPublic bit`. Tag `[s112b, supplier-visibility, fail-closed-default]`.
- **[all verbatim → archive/2026-07.md] S98 verify-lane (detector 28→25, 8 derived-stale=FP vs canonical 61/89/440/79; grep exact misses README variant) · S97 feedback-audit (#77/#78/#79 `gotchas.md:1301/1317/1325`; #53-garble×6=cicd MEMORY-self-target ~17.5KB; Mig60 wrong-table Approvals→Mig61 Changelogs) · 07-01 Supplier-predecessor SUPERSEDED by 07-06 · S93 MFE denom=marks/AS/guards dedup-AS-xref=29, coverage exact-id OR ≥2-content-word.**

- **[→ archive/2026-07.md @S125 + 2026-06.md] PE FROZEN-Mig59 recon (S87→S89):** giữ nóng ⭐ LATENT #73-class HoSoLink PUT-clears (`PurchaseEvaluationFeatures.cs:280`) · 3 cơ-chế finalize coexist AUTO-first · budget-matrix authz-asymm PRO=drafter/CCM=role.
- **[→ archive/2026-07.md @S125 + _INDEX] 2026-06-20 governance recon:** `harness-11-engine.md`=CANONICAL (D5-D10) · `error-ledger.md` §L.a/§L.b · H14 age-decay KHÔNG căn-cứ cắt feature · EVAL golden-set 14q weekly-manual.
- **[→ archive/2026-07.md @S125 + _INDEX] PE recon (S69→S76):** WinnerQuoteTotal DERIVED 3-site · Budget gate PURE-ROLE (`PurchaseEvaluationFeatures.cs:800-801`) · V2 routing IGNORES roles (=ApproverUserId) 100% LINEAR.
- **[→ archive/2026-07.md @S125 + _INDEX] Office/HRM recon (S65→S69):** 21 `Off_*` keys · 10 office pages SHA-mirror · golive-flip=remove `RevokeTemporarilyHiddenModulesAsync` (`DbInitializer.cs:2040`) · **gotcha #66** `index.css` ngoài @layer → heading cần `text-white!`.
- **[→ archive/2026-07.md @S125 + _INDEX] Governance/Harness recon (S71):** run-trace TRACKED = 2-level (`check-ignore` eligible vs `ls-files` committed) · path-trap `.claude/workflows/runs/` (bare `runs/`=0) · G-015 containment H10.
- **[→ git pre-S60]** S60 recon#2 V2-engine-map (ApproveV2Async:446-634 guard+UPSERT+advance; skipToFinal F2:561-602 precedent) · S60 PE Section-3 submit-guard ROLE-only. Full text git.
- **[→ archive/2026-06.md + git]** S52 P11-D/E/F 6-gap recon · S50 HrmConfigs add-kind 11-spot · S51 gotcha #57 EXT reachability (curated S59).
- **[→ archive/2026-05-q4.md + git d2f52ba]** S29-S37: clean-room > NamGroup-port verified 4× · Pattern 12-bis cross-module mirror · FK+freetext dual-write.

- **[→ git 07-10] S108 first-real-run H19 cite-audit:** 103/111 exact; class = worker-draft cite lệch ±1-2 quanh code-fence (audit MỞ ĐÚNG DÒNG đừng tin range) + drift-note-stale + email-fact honesty-trap. 0 garble.

- **[→ archive/2026-07.md] S111 (07-12) H22 WAL deep-pass `[fable-real-single]`** — READY_WITH_NUANCES; hook=STAGED-until-verified (S100 ghost-wire class); engine:402 = MÔ-TẢ không phải luật cấm; Stop-hook fire TURN-boundary only. (H22 nay VERIFIED-RUNTIME per project memory.)
- **[→ archive/2026-07.md] S110 (07-11) H21+MTv3 deep-pass `[fable-real-single]`** — PASS; 12 persona 0-hit; regex-heuristic-miss class (sister diễn-đạt khác cụm); hmw.js:38 comment-conflict; standing-imperative-trong-history-blurb class; #53 garble→SendMessage re-emit recover OK.

---

- **[→ archive/2026-07.md @S125 · Mig 66 SHIPPED] S117 PE giá-chốt RANGE Min+Max invest [fable-real-single]:** ApprovedPrice WRITE 1-site `ApplyApprovedPriceOnFinalize` (3 nhánh DaDuyet; skipToFinal chỉ dời pointer) · ⭐ HĐ-gen KHÔNG đọc ApprovedPrice (GiaTri=SUM IsSelected `CreateContractFromEvaluationFeatures.cs:88-100`) · `types/purchaseEvaluation.ts` KHÔNG SHA-mirror 2-app (edit riêng) · latent: winnerQuoteTotal subset ÂM vs validator `>=0 :501`. `[s117, prominmax]`
- **[→ archive/2026-07.md @S125] S117 PE lũy-kế RCA [fable-real-single]:** phiếu A/018 KHÔNG DaDuyet (opt-in finalize UNCHECKED S97 `PeWorkflowPanel.tsx:57`) · ⭐ residual DISPLAY-LIE #78 nửa-còn-lại: `endsBeforeCeo`=config-TRUE bất chấp pointer (detail `:1152-1154` · list `:647-651`) · 3 cơ-chế finalize phân biệt Mig58-optin ≠ Mig53/54-threshold ≠ Mig31-pointer · fix-rec pointer-aware, KHÔNG nới filter lũy-kế `PeFeatures.cs:906`. `[fable-S117]`

- **[→ archive/2026-07.md @S126] S116 PE negative-quote invest (fable-clone):** hội-tụ **FE-ONLY** (BE/DB nhận âm sẵn); ⚠️ quote sống `details[].quotes` KHÔNG `suppliers[].quotes`. Detail: `runs/2026-07-13-pe-negative-quote/`. `[Opus-S116]`

- **[→ archive/2026-07.md @S125 verbatim] S122 retro-harvest 7 orphan (6/6 lane 0-garble):** 🔴 LẬT tiền-đề — **0/7 mất, 7/7 XONG chỉ synthesis SAI CHỖ** (orphan đo TÊN không đo NỘI-DUNG, 8 dương-giả/25=32%) · lane-RỖNG ≠ mất (per-turn ≠ per-task) · memoryPack premise CÓ THỂ SAI — lane tự truy git đừng tin brief. Tag `[s122-retro-harvest, false-orphan-by-naming]`.
- **S126 (2026-07-16) A2 worker-pin tally + B1 all-inherit sweep [opus ×2, em-main VERIFY+APPEND]:** A2: **14/14 opus + 14/14 max** — lane no-tier CHÍNH NÓ resolve `claude-opus-4-8` DÙ lead=Fable ⇒ pin ăn runtime. B1: 284 instance → **15 floor-sống/5 file** + 26 lineage + 235 frozen; ⭐ nặng nhất `vocab-alias-map.md` §3 TỰ khai all-inherit="Canonical (hiện hành)" — doc chống-fork tự fork; class = S125 vá 2 command-file KHÔNG grep sibling governance. Lesson: mega-line blow Read-cap → perl-window giữ file:line; 2-pattern grep LỌT biến-thể không-literal (runbook:119 "lead-runtime (inherit)") — cần mắt-người pass khi vá. Em-main vá 15+3, fault-inject Section-D 2-chiều PASS, re-grep 0 floor-sống. Tag `[s126, h23-precedence, all-inherit-sweep]`.

## 🔄 Curate trigger
- >~30KB → archive recent → L2 `archive/<period>.md` (byte-exact append) + `_INDEX.md` substring pointer. Stale >3mo → remove.
- **Last curate: 2026-07-16 S125 (em-main single-writer, hook-triggered @23.9KB)** — 14 dòng ≈9.5KB (5 cluster digest S87-89/06-20/S69-76/S65-69/S71 + 2 section S117 + block S122 retro-harvest) verbatim byte-exact → `archive/2026-07.md`, thay stub giữ anchor nóng. L1 ~15KB.
- **Prev curate: 2026-07-06 (em-main single-writer, hook-triggered @21.4KB)** — 6 stale governance/superseded entries (S93/S97/S98/S100/S101 + 07-01 Supplier-predecessor) verbatim → `archive/2026-07.md`, replaced with pointer-stubs. L1 back under target.
- **Prev curate: 2026-06-18 S71** (29.8→23.2KB FIFO-trim 3 + gist gen:2). **Prev S70** (47.0→24.1KB dark-matter recovery + built _INDEX/gist). **Prev S40** (35.7→~20KB).
