← Về Portal

⚡ V4 Prompts Playbook

Tất cả prompts Claude Code để triển khai V4 Migration từng bước. Copy → paste → chạy.

Copy-paste ready Step-by-step 4 phases
Cách dùng: Mỗi prompt copy-paste vào Claude Code. Claude sẽ tự thực hiện steps (install, write code, test). Không cần chạy git commands — Claude làm tự động khi được yêu cầu.
1

Unlock 4 BOD decisions (tuần 1)

KHÔNG code gì cho tới khi 4 câu hỏi sau được BOD ký. Dùng prompt dưới để Claude tạo deck thuyết trình cho BOD.

/ck:brainstorm "Tạo BOD decision workshop cho VIỆC XANH X V4 migration:

Q1. Tenant model: row-level tenant_id (stancl/tenancy) vs schema-per-tenant
Q2. Ứng lương: tự cho vay (cần license NHNN) vs partner fintech
Q3. Tenant type: factory/supplier/hybrid schema
Q4. Chat-service rename: downtime 4h vs dual-run 1 tháng

Output:
- 1 file HTML slide deck thuyết trình cho BOD
- 1 decision-matrix.md chi tiết pros/cons mỗi option
- Recommend option nào + lý do
- Ước lượng cost + timeline impact mỗi lựa chọn

Work context: /Users/trungnguyen/Sites/viecxanh
Save to: plans/{timestamp}-bod-decision-workshop/"
Sau workshop: yêu cầu Claude lưu quyết định vào docs_v4/decisions-{date}-locked.md
2

Deep planning 3 plans song song (tuần 2)

Sau khi BOD lock, tạo 3 plan thực thi song song. Mỗi prompt chạy 1 lượt riêng.

Plan A — P1 Foundation chi tiết:

/ck:plan "P1 Foundation detailed — breakdown 12 tuần thành phase files.

Context: V4 migration plan đã có ở plans/260414-2143-v4-techstack-brief/ và plans/260414-2209-v4-evaluation-framework/.
Decisions đã lock trong docs_v4/decisions-*-locked.md.

Scope P1:
- Audit libraries (spatie/activitylog, owen-it/auditing)
- Permission DB migration (358 hardcoded → DB)
- Trust Layer 5 tables
- Observability (OpenTelemetry + Grafana + Sentry)
- JWT unify backend ↔ chat-service
- Horizon queue dashboard

Output: plans/{timestamp}-p1-foundation-detailed/
Include mỗi phase file: context, requirements, related files, implementation steps, todo checklist, success criteria, risk matrix, rollback plan, test plan.
Follow docs/code-standards.md + .claude/enforcement/memory-gate.md."

Plan B — Permission DB migration (CRITICAL):

/ck:plan "Permission DB migration — 358 hardcoded permissions → spatie/laravel-permission DB.

Critical risk: regression break existing RBAC trong backend (17 domains) và backend-admin (9 domains).

Cần chuẩn bị:
1. Mapping script: extract 358 permission names từ config/permissions.php → seed DB
2. Shadow mode: config vẫn còn, nhưng check DB trước (feature flag FEATURE_PERMISSION_DB=shadow|db|config)
3. Canary rollout: 5% → 50% → 100% tenant
4. Rollback: DB snapshot + feature flag → config
5. Regression test plan: 161 backend tests + 34 admin tests + 100 custom permission scenarios

Output: plans/{timestamp}-permission-db-migration/
Include: risk matrix, scenario tests với /ck:scenario, step-by-step migration timeline."

Plan C — Trust Layer design (P1 MUST):

/ck:plan "Trust Layer detailed design — 5 tables + services cho backend.

Tables:
1. activity_log (spatie/laravel-activitylog) — user actions
2. audits (owen-it/laravel-auditing) — column-level change tracking
3. policy_snapshots — JSON versioned policy (payroll rules, commission rates...)
4. ai_actions — AI call log with prompt hash, tokens, cost, scope
5. disputes + dispute_evidences — case management with file upload

Services:
- PolicySnapshotService::freeze(Model, policyType): void
- PolicySnapshotService::at(Model, Carbon): array
- AiActionLogger::log(user, tenant, agent, prompt, model, tokens, result)
- DisputeService::openCase(), addEvidence(), resolve()

Integration: 17 backend domains + 9 backend-admin domains.
Tests: Feature tests cho mỗi service + integration flow.

Output: plans/{timestamp}-trust-layer-detailed/
Follow DDD structure backend/app/Domains/Trust/."

Review 3 plans trước khi start code:

/ck:code-review "Review 3 plans vừa tạo:
- plans/*-p1-foundation-detailed/
- plans/*-permission-db-migration/
- plans/*-trust-layer-detailed/

Check:
- Completeness (có đủ requirements, tests, risk, rollback)
- Realistic effort estimates
- Dependency giữa 3 plans (order execute)
- Alignment với V4 spec (docs_v4/viec-xanh-x-nen-tang-viec-lam.md)

Output: plans/reports/review-3-plans-p1.md với verdict PASS/REVISE/FAIL mỗi plan."

Phase 1 — Foundation (3 tháng)

Target: 45% compliance

Trust + Permission + Observability. Không touch tenancy.

1.1 — Install audit libraries (Week 1)
/ck:cook "Install audit libraries cho backend + backend-admin:

1. composer require spatie/laravel-activitylog vào cả 2 projects
2. composer require owen-it/laravel-auditing vào cả 2 projects
3. Publish config + chạy migrations
4. Add LogsActivity trait + Auditable interface vào 10 model trọng yếu:
   Worker, Employer, Job, Application, Attendance, Payroll, Leave, Incentive, Housing, Commission
5. Mỗi model:
   - use LogsActivity từ spatie/activitylog
   - implements Auditable từ owen-it/auditing
   - \$logAttributes = ['*'] trừ timestamps
   - \$auditInclude theo nghiệp vụ
6. Test: Feature test mỗi model có activity log + audit entry khi update
7. Commit theo từng model riêng biệt với conventional commit message

Work context: /Users/trungnguyen/Sites/viecxanh
Read docs/code-standards.md + .claude/enforcement/memory-gate.md trước khi code."
1.2 — Permission DB migration (Week 2-3) 🔴 CRITICAL
/ck:cook "Task: Migrate 358 permissions hardcoded từ config/permissions.php → DB table permissions (spatie/laravel-permission).

Steps:
1. Install spatie/laravel-permission + publish config + migrate
2. Read config/permissions.php — extract all permission names + roles
3. Create seeder MigrateHardcodedPermissionsToDb (idempotent):
   - Foreach permission: Permission::firstOrCreate(['name' => \$name, 'guard_name' => 'web'])
   - Map existing roles → permissions
4. Shadow mode strategy:
   - Keep config/permissions.php
   - New service PermissionChecker::check() với feature flag FEATURE_PERMISSION_DB
   - flag=config: dùng config (default)
   - flag=shadow: check cả config + DB, log mismatch
   - flag=db: dùng DB (target)
5. Canary rollout plan: 5% tenant → 50% → 100% (1 tuần mỗi step)
6. Rollback: DB snapshot tagged v3-before-perm + feature flag → config tức thì

Test:
- Regression test 100% existing permission checks (backend 161 tests + admin 34)
- Feature test: shadow mode log 0 mismatch sau 3 ngày
- Load test: check DB performance không degrade > 10%

Output: PR riêng biệt, docs/permission-migration-runbook.md, migration rollback procedure.

Memory gate: docs/code-standards.md. Tests BẮT BUỘC pass trước merge."
1.3 — Trust Layer custom tables (Week 4-6)
/ck:cook "Tạo Trust Layer cho backend.

Table schemas:
1. policy_snapshots: id, subject_type, subject_id, policy_type, policy_version, snapshot_json, applied_at, applied_by, tenant_id
2. ai_actions: id, user_id, tenant_id, agent_name, prompt_hash, model, tokens_in, tokens_out, cost_vnd, permission_scope_json, result_summary, created_at
3. disputes: id, case_code, worker_id, tenant_id, category, description, status (enum), resolved_at, resolved_by, resolution_note
4. dispute_evidences: id, dispute_id, file_path, mime, size_bytes, uploaded_by, uploaded_at

Services trong backend/app/Domains/Trust/Services/:
- PolicySnapshotService:
  - freeze(Model \$subject, string \$policyType): PolicySnapshot
  - at(Model \$subject, Carbon \$time): ?array
  - diff(PolicySnapshot \$a, PolicySnapshot \$b): array
- AiActionLogger:
  - log(User \$user, string \$agent, string \$prompt, ...): AiAction
- DisputeService:
  - openCase(Worker, category, description): Dispute
  - addEvidence(Dispute, UploadedFile): DisputeEvidence
  - resolve(Dispute, User \$resolver, string \$note): void

Tests: backend/tests/Feature/Trust/ — 15+ tests covering happy path + edge cases.
API endpoints: /api/v1/trust/policy-snapshots, /api/v1/trust/disputes (admin only).

Follow DDD pattern đã có trong backend/app/Domains/. Memory gate: docs/code-standards.md."
1.4 — Observability stack (Week 7-8)
/ck:cook "Setup observability cho 3 services: backend (Laravel), chat-service (NestJS), frontend (Next.js).

1. Install:
   - backend: sentry/sentry-laravel + open-telemetry/opentelemetry + laravel/horizon
   - chat-service: @sentry/node + @opentelemetry/api + @opentelemetry/sdk-node
   - frontend: @sentry/nextjs

2. Config OpenTelemetry auto-instrument:
   - backend: capture request/response + DB queries + queue jobs
   - chat-service: capture LLM calls với token count + cost
   - frontend: capture page load + API calls + web vitals

3. Export to OTLP endpoint (env OTEL_EXPORTER_OTLP_ENDPOINT).
   Dashboard: Grafana Cloud free tier (khuyến nghị) hoặc SigNoz self-host.

4. Setup Horizon dashboard cho queue monitoring.

5. 5 key metrics baseline cần track và alert:
   - API p95 latency (alert > 500ms)
   - DB query p95 (alert > 200ms)
   - Queue depth (alert > 1000)
   - Error rate 5xx (alert > 1%)
   - LLM cost per tenant per day (alert > budget)

6. Runbook: docs/observability-runbook.md — cách read dashboard + respond alerts.

Test: Manual smoke test + load test 1000 req → verify metrics xuất hiện trong dashboard."
1.5 — JWT unify backend ↔ chat-service (Week 9-10)
/ck:cook "Unify JWT giữa Laravel backend và NestJS chat-service.

Current state: 2 token riêng biệt (Sanctum backend + custom chat-service).
Target: 1 JWT với claims:
{
  sub: user_id,
  tenant_id: string|null,
  role: string,
  permissions: string[],
  aud: ['backend', 'chat'],
  iat, exp
}

Steps:
1. Laravel: extend Sanctum để generate JWT (dùng tymon/jwt-auth hoặc custom provider)
2. chat-service (NestJS): verify JWT using shared secret (env JWT_SHARED_SECRET)
3. NestJS middleware AuthGuard: kiểm permissions từ claims thay vì re-query backend /auth/me
4. Deprecate cross-service /auth/me HTTP call sau 2 tuần transition
5. Key rotation: support dual-key 24h window (no downtime rotate)

Test:
- Integration test: login backend → token dùng chat-service OK
- Rotation test: rotate secret không gây downtime
- Revocation test: logout backend → token invalidated in chat-service trong 1 phút

Docs: docs/auth-jwt-unified.md."
1.X — P1 Exit Review (Week 11-12)
/ck:code-review "Final review Phase 1 Foundation trước khi đóng phase.

Checklist theo plans/260414-2209-v4-evaluation-framework/02-phase-exit-criteria.md Phase 1:
- Compliance score ≥ 45%
- Audit libraries installed + 10 models configured
- 358 permissions migrated to DB (flag=db)
- Trust Layer 5 tables + services ship
- Observability 3 services có metric dashboard
- JWT unified
- Horizon dashboard live

Checks:
- 0 architecture violations (.claude/enforcement/)
- Code coverage ≥ 75% cho new domains (Trust)
- No regression: 161 backend + 34 admin tests vẫn pass
- Security scan: 0 critical, ≤ 3 high findings
- Performance: p95 latency delta ≤ +20% vs baseline pre-P1

Output: plans/reports/p1-exit-review-{date}.md theo template plans/260414-2209-v4-evaluation-framework/templates/phase-exit-review.md.

Verdict: PASS / PASS_WITH_CONDITIONS / FAIL."

Phase 2 — Multi-Tenant SaaS (4 tháng)

Target: 65% compliance
/ck:cook "Phase 2.1 — Implement multi-tenant SaaS với stancl/tenancy.

Context: Decision Q1 locked = row-level tenant_id (không phải schema-per-tenant).

Critical steps:
1. composer require stancl/tenancy vào backend và backend-admin
2. php artisan tenancy:install + publish config
3. Generate migration add_tenant_id_to_{table} cho 71 tables (script loop, KHÔNG manual)
4. Backfill: default tenant 'xanhvina-main' cho tất cả rows hiện tại
5. Global scope TenantScope trên tất cả tenant-aware models
6. Tenant resolver: subdomain ({tenant}.xanhvina.com.vn) + JWT claim fallback
7. Super-admin bypass middleware (xem cross-tenant data)

Rules cứng:
- KHÔNG drop/rename column. Chỉ ADD.
- Mỗi migration có down() để rollback.
- Existing queries không break — dùng default tenant.

Test plan BẮT BUỘC:
- Cross-tenant penetration test với 50 attack vectors (external audit nếu budget cho phép)
- Regression: 161 backend + 34 admin + 50 mobile tests
- EXPLAIN ANALYZE mọi query mới có index hit
- Load test 10K concurrent connections

Output: PR riêng + docs/tenant-onboarding-playbook.md + DR runbook.

Work context: /Users/trungnguyen/Sites/viecxanh. Memory gate: .claude/enforcement/memory-gate.md."
/ck:cook "Phase 2.2 — State machines cho 3 object trọng yếu.

Install: composer require spatie/laravel-model-states.

Implement state machines:
1. Application:
   draft → submitted → interviewing → hired → onboarding → active
   rejected (from any step)
   withdrawn (by worker)

2. Job:
   draft → open → filling → closed
   paused (from open)

3. Payroll:
   draft → calculating → pending_approval → approved → paid
   void (admin only, with reason)

Each transition:
- Guard (who can transition)
- Action (side effects: notify, log, snapshot policy)
- Audit log entry

Test: Feature tests cho mỗi transition + invalid transition throws exception.

Output: backend/app/Domains/{Application,Job,Payroll}/States/."
/ck:cook "Phase 2.3 — Search (Meilisearch) + Real-time (Reverb).

Install:
- backend: laravel/scout + meilisearch/meilisearch-php + laravel/reverb
- Deploy Meilisearch self-host qua Docker
- php artisan reverb:install

Search setup:
- Index 3 models: Worker, Job, Employer
- Tenant-scoped indexes (index name: workers_tenant_{id})
- Real-time sync qua Scout observer
- Search API endpoint /api/v1/search/{type}

Reverb setup:
- 5 notification channels:
  1. worker.{id} — personal notifications
  2. tenant.{id} — tenant broadcasts
  3. job.{id} — application updates
  4. attendance.{tenant_id} — realtime attendance push
  5. admin.broadcasts — system announcements
- Test concurrent 10K connections

Mobile integration: update xanhvina-mobile để subscribe channels qua Laravel Echo."

Phase 3 — V4 Core (3 tháng)

Target: 80% compliance
/ck:cook "Phase 3.1 — AI Orchestrator (rename chat-service + expand).

Context: Decision Q4 locked = dual-run blue-green 6 tuần.

Steps:
1. Clone chat-service → ai-orchestrator (keep chat endpoints backward-compat trong period transition)
2. Add LangChain.js abstraction:
   - ai-orchestrator/src/orchestrator/router.ts — route by intent
   - ai-orchestrator/src/agents/recruitment-agent.ts
   - ai-orchestrator/src/agents/worker-management-agent.ts
   - ai-orchestrator/src/agents/payroll-agent.ts
3. AI Permission Boundary middleware (ai-orchestrator/src/middleware/permission-boundary.ts):
   - Read JWT claims (tenant, role, permissions)
   - Inject into LLM system prompt: 'You can only access data user has permission for'
   - Tool calling → backend REST API (read-only default)
   - Block actions outside permission scope
4. Langfuse integration:
   - Self-host qua Docker
   - Prompt versioning
   - Cost tracking per tenant + per agent
5. Per-tenant cost cap:
   - env TENANT_COST_CAP_VND_MONTHLY=500000 (default)
   - Table ai_cost_ledger track realtime
   - Hard stop khi exceeded (return 429 with message)

Blue-green cutover schedule (6 tuần):
- Week 1-2: Deploy ai-orchestrator side-by-side, 0% traffic
- Week 3: 5% chat traffic
- Week 4: 50%
- Week 5: 100%
- Week 6: Decommission chat-service

Test:
- Permission boundary: user A query AI → không access tenant B data
- Cost cap: exceed budget → 429 clear message
- 3 agents respond correct prompts
- Blue-green rollback trong 60s

Output: PR + docs/ai-orchestrator-architecture.md + cost-cap runbook."
/ck:cook "Phase 3.2 — Integration Hub.

Install: composer require laravel-workflow/laravel-workflow + deploy n8n self-host (Docker).

Components:
1. n8n deployment: infra/n8n/docker-compose.yml
2. Laravel migrations:
   - webhook_subscriptions (tenant_id, event_name, url, secret, retry_count, is_active)
   - integration_logs (tenant_id, direction, payload_json, status, error)
   - field_mappings (tenant_id, source, target, mapping_json)
3. Services:
   - app/Domains/Integration/Services/WebhookDispatcher.php — outbound với retry queue
   - app/Domains/Integration/Services/FieldMappingApplier.php
   - app/Domains/Integration/Services/WebhookVerifier.php — verify HMAC inbound
4. Admin SPA UI: /admin/integrations
   - List subscriptions, CRUD
   - Test fire webhook
   - View logs with filter
5. Outbound retry policy:
   - 3 attempts, exponential backoff (1s, 8s, 60s)
   - Dead letter queue after 3 failures
6. Inbound verify: HMAC signature header X-Signature

Test: E2E 3 integration scenarios:
- Import Excel chunked queue
- Outbound webhook with retry + DLQ
- 2-way sync với field mapping

Output: PR + docs/integration-hub-operator-manual.md."
/ck:cook "Phase 3.3 — Workflow Engine deploy 5 core workflows.

Use laravel-workflow (đã install Phase 3.2).

5 workflows:
1. RecruitmentWorkflow:
   Lead → Screening → Interview → Offer → Accepted → Onboarding
   SLA: mỗi bước 48h, escalate to supervisor nếu vượt
2. AttendanceApprovalWorkflow:
   Clock-in bất thường → Auto-detect anomaly → Notify manager → Approve/Reject
3. PayrollCloseWorkflow:
   Draft → Calculate → Review → Approve (multi-step if > 100M VND) → Disburse
4. LeaveRequestWorkflow:
   Submit → Manager approve → HR notify → Auto-adjust balance
5. DisputeWorkflow:
   Open → Investigate (7 days) → Resolve → Notify worker → Close

Each workflow:
- State machine (đã có từ Phase 2)
- Saga compensation trên failure
- SLA tracking + escalation job
- Audit log mỗi transition

Output: backend/app/Workflows/ + tests cho mỗi workflow."

Phase 4 — VIỆC XANH 247 (3 tháng)

Target: 95% compliance
/ck:cook "Phase 4.1 — Ứng lương (Earned Wage Access) E2E production.

Context: Decision Q2 locked = partner fintech giai đoạn 1. Partner chọn: [điền sau khi BOD quyết].

Backend domain: backend/app/Domains/EarnedWageAccess/

Migrations:
- earned_wage_requests (id, worker_id, tenant_id, amount_vnd, status, disbursed_at, partner_ref)
- kyc_records (id, worker_id, provider (vnpt_ekyc|onfido), status, verified_at, raw_response_json)

Services:
- EligibilityService::check(Worker): { eligible: bool, max_amount: int, reason: string }
  Rules: active worker ≥ 30 days, retention_score ≥ 0.7, no open dispute, no existing active advance
- KycService::initiate(Worker) + verify(session_token)
- DisbursementService::disburse(Request) → partner fintech API
- AutoDeductionService: listener PayrollCreated event → deduct advance từ lương kỳ sau

Mobile screens (xanhvina-mobile/app/(worker)/earned-wage-access/):
- index.tsx — dashboard: max amount + history
- request.tsx — form nhập amount
- kyc.tsx — webview VNPT eKYC hoặc Onfido
- confirm.tsx — review + consent + submit
- success.tsx — status + estimated arrival time
- history.tsx — past advances

Test:
- Stress test 100 concurrent requests, 0 double-disburse (idempotency key required)
- KYC edge cases (fail, retry, timeout)
- E2E happy path với partner sandbox
- Rollback: cancel request → refund idempotent

Compliance: legal review bắt buộc trước go-live.

Output: PR + docs/earned-wage-access-runbook.md."
/ck:cook "Phase 4.2 — Ví quyền lợi (Wallet double-entry ledger).

Critical: ledger bugs = tiền lệch → audit trail + reconciliation bắt buộc.

Migration wallet_ledger:
- id, tenant_id, worker_id
- amount_vnd (signed int, positive = credit, negative = debit)
- direction (enum: credit|debit)
- balance_after (snapshot balance sau transaction)
- tx_type (enum: earned_wage_disburse|earned_wage_deduct|bonus|penalty|manual_adjust)
- reference_type, reference_id (polymorphic)
- created_at, created_by

Service LedgerService:
- credit(worker_id, amount, tx_type, reference): Entry
- debit(worker_id, amount, tx_type, reference): Entry
- balance(worker_id): int
- history(worker_id, limit, offset): array
- reconcile(Carbon \$at): ReconcileReport

Rules cứng:
- Every transaction ATOMIC: BEGIN + SELECT FOR UPDATE + INSERT + COMMIT
- balance_after tính sau INSERT (lock row)
- Không cho update/delete entry sau khi commit (append-only)

Daily reconciliation job:
- Chạy 00:05 mỗi ngày
- Compute: sum(credit) - sum(debit) per worker
- Compare với current balance snapshot
- Drift > 0 → alert SEV-1 + freeze wallet

Mobile: app/(worker)/wallet/index.tsx + history.tsx.

Test:
- 1000 random concurrent transactions → balance consistency 100%
- Reconciliation catch manual DB drift (test intentional corruption)
- Edge: insufficient balance → reject

Output: PR + docs/wallet-ledger-invariants.md."

📅 Weekly Evaluation

Mỗi Monday — monitor progress + detect slippage sớm.

/ck:watzup "Weekly wrap-up V4 migration.

Tasks:
1. Run compliance scanner: bash plans/260414-2209-v4-evaluation-framework/scripts/check-v4-compliance.sh
2. Run traceability generator: bash plans/260414-2209-v4-evaluation-framework/scripts/generate-traceability.sh
3. Compare current compliance score vs last week
4. List capabilities newly completed tuần này
5. Flag slipping items (tasks delayed > 3 ngày)
6. Risk update: new risks, mitigated risks
7. Next week focus

Output: plans/reports/weekly-{date}.md
Tone: concise, data-driven, actionable."
/ck:project-manager "Monthly review V4 migration progress.

Tasks:
1. Read plans/reports/weekly-*.md last 4 tuần
2. Calculate velocity: PW consumed vs PW estimated
3. Update project-roadmap.md status từng phase
4. Stakeholder update: 1-page summary cho BOD
5. Burn rate: compare budget consumed vs forecast

Output: plans/reports/monthly-{month}.md + update docs/project-roadmap.md."