# Hacker Divergents — Fase 21 — NPC Foundation e NPC Shops

## Status

Documento de checkpoint técnico e funcional da **Fase 21 — NPCs** do projeto Hacker Divergents.

Diretório base do projeto:

```text
C:\Projetos\HackerDivergents
```

Este documento consolida o que já foi validado e o ponto exato de continuidade.

---

# 1. Objetivo da Fase 21

A Fase 21 estabelece a base dos NPCs do Hacker Divergents.

Os NPCs devem integrar:

- mundo;
- missões;
- economia;
- servidores;
- fragmentos;
- software;
- hardware;
- reputação;
- relacionamentos;
- segurança;
- inteligência;
- facções;
- progressão.

A implementação é dividida em blocos progressivos.

---

# 2. Regras funcionais oficiais dos NPCs

## 2.1 NPCs permanentes e procedurais

O sistema poderá possuir:

- NPCs permanentes;
- NPCs procedurais.

Os NPCs permanentes possuem identidade própria e podem ter:

- nome;
- papel;
- facção;
- nível;
- status;
- relacionamento;
- reputação indireta via facção;
- funções específicas no mundo.

## 2.2 Estados de relacionamento

Estados oficiais:

```text
unknown
known
trusted
respected
hostile
blacklisted
```

Relacionamentos podem ser influenciados futuramente por:

- missões;
- reputação;
- pagamentos;
- decisões;
- traições;
- facção;
- eventos.

## 2.3 Estados de NPC

Estados oficiais:

```text
active
offline
hidden
missing
arrested
retired
```

## 2.4 Economia NPC

NPCs não devem criar recursos ou dinheiro sem controle.

Todo sistema econômico NPC deve considerar:

- geração;
- estoque;
- consumo;
- reposição;
- sinks;
- limites.

O objetivo é evitar inflação infinita e escassez artificial permanente.

---

# 3. NPC-1 — Foundation

## 3.1 Estrutura criada

O bloco NPC-1 foi concluído com as seguintes tabelas:

```text
npc_factions
npcs
player_faction_reputation
player_npc_relationships
```

## 3.2 Migrations

```text
000134_create_npc_factions.sql
000135_seed_initial_npc_factions.sql
000136_create_npcs.sql
000137_seed_initial_npcs.sql
000138_create_player_faction_reputation.sql
000139_create_player_npc_relationships.sql
```

---

# 4. Facções iniciais

Seis facções iniciais foram criadas:

1. BlackWire Collective
2. NetCore Industries
3. IronGrid Systems
4. Cipher Labs
5. SafeNet
6. Independent

Public IDs determinísticos:

```text
npcf_00000000000000000000000000000001
npcf_00000000000000000000000000000002
npcf_00000000000000000000000000000003
npcf_00000000000000000000000000000004
npcf_00000000000000000000000000000005
npcf_00000000000000000000000000000006
```

---

# 5. NPCs oficiais iniciais

Doze NPCs iniciais foram criados:

| NPC | Papel | Facção |
|---|---|---|
| ZeroByte | Fixer | BlackWire Collective |
| Cipher | Code Broker | BlackWire Collective |
| Patch | Hardware Dealer | Independent |
| GridMaster | Mission Contractor | IronGrid Systems |
| Volt | Hardware Dealer | IronGrid Systems |
| Nexus | Server Administrator | NetCore Industries |
| Sentinel | Security Analyst | NetCore Industries |
| Hex | Research Specialist | Cipher Labs |
| Vector | Forensic Analyst | Cipher Labs |
| Ghost | Rival Hacker | Independent |
| Null | Rival Hacker | BlackWire Collective |
| Agent Orion | SafeNet Investigator | SafeNet |

Todos foram validados como:

```text
npc_type = permanent
level = 1
status = active
```

---

# 6. Reputação por facção

Tabela:

```text
player_faction_reputation
```

Contrato principal:

- reputação é `INT`;
- valor inicial lógico é `0`;
- pode ser positiva;
- pode ser negativa;
- não há limite mínimo/máximo fixado ainda;
- não foi criado clamp artificial.

A chave lógica é:

```text
player_public_id + faction_public_id
```

---

# 7. Relacionamento jogador ↔ NPC

Tabela:

```text
player_npc_relationships
```

Estados permitidos:

```text
unknown
known
trusted
respected
hostile
blacklisted
```

A chave lógica é:

```text
player_public_id + npc_public_id
```

Quando não existe registro físico, o comportamento lógico inicial é:

```text
unknown
```

---

# 8. Camada PHP do NPC-1

## 8.1 Domain IDs

Criados:

```text
src\NPC\Domain\NpcId.php
src\NPC\Domain\NpcFactionId.php
```

Prefixos:

```text
NpcId         -> npc_
NpcFactionId  -> npcf_
```

## 8.2 NpcCatalogService

Arquivo:

```text
src\NPC\Application\NpcCatalogService.php
```

Operações validadas:

```text
listFactions()
findFactionByCode()
listNpcs()
findNpcByCode()
```

## 8.3 NpcRelationshipService

Arquivo:

```text
src\NPC\Application\NpcRelationshipService.php
```

Operações validadas:

```text
getFactionReputation()
changeFactionReputation()
getNpcRelationship()
setNpcRelationship()
```

O serviço utiliza:

```text
FOR UPDATE
ON DUPLICATE KEY UPDATE
```

Também valida:

- jogador;
- facção;
- NPC;
- estados de relacionamento.

---

# 9. Teste real de reputação e relacionamento

Foi executado teste real no MariaDB utilizando:

```text
Player  : ply_test_phase8_player
Faction : BlackWire Collective
NPC     : ZeroByte
```

Baseline:

```text
reputation   = 0
relationship = unknown
```

Validações realizadas:

```text
+420 reputação........................ PASS
-590 reputação........................ PASS
delta zero............................ PASS
known................................. PASS
trusted............................... PASS
hostile............................... PASS
estado inválido....................... REJECTED
player inexistente.................... REJECTED
facção inexistente.................... REJECTED
NPC inexistente....................... REJECTED
```

Todas as mutações do teste foram executadas dentro de transação controlada e revertidas.

Resultado:

```text
Reputation restored after rollback........ PASS
Relationship restored after rollback...... PASS
Physical state restored exactly........... PASS
```

---

# 10. NPC-1 Regression Suite

Runner:

```text
scripts\phase21c5e-npc-foundation-suite.ps1
```

Resultado consolidado:

```text
Source files............................ 4
Regression tests......................... 6
Tests passed............................. 6

npc_factions............................. PASS
npcs..................................... PASS
player_faction_reputation................ PASS
player_npc_relationships................. PASS
NpcId.................................... PASS
NpcFactionId............................. PASS
NpcCatalogService........................ PASS
NpcRelationshipService................... PASS
test rollback isolation.................. PASS
```

Status:

```text
NPC-1 FOUNDATION: COMPLETE
```

---

# 11. NPC-2 — Shops, Stock e Economia NPC

O próximo bloco da Fase 21 é o NPC-2.

Componentes planejados:

```text
npc_shops
npc_shop_inventory
npc_stock_events
npc_shop_transactions
```

`npc_stock_events` e `npc_shop_transactions` possuem responsabilidades diferentes:

- `npc_stock_events` registra movimentações físicas e reposições de estoque;
- `npc_shop_transactions` deverá registrar compras/vendas comerciais.

---

# 12. Regras oficiais de estoque NPC

Comerciantes possuem estoque limitado.

Cada oferta poderá considerar:

- quantidade;
- condição;
- preço;
- intervalo de reposição;
- raridade;
- reputação mínima.

Quando um item chega a:

```text
estoque = 0
```

o jogador deverá:

- aguardar reposição;
- procurar outro comerciante;
- utilizar marketplace P2P;
- encontrar o item em outra atividade.

Reposição poderá depender de:

- tempo;
- categoria;
- raridade;
- facção;
- região virtual;
- economia.

Itens comuns:

```text
reposição mais frequente
```

Itens raros:

```text
reposição lenta ou condicional
```

Fragmentos raros não podem possuir geração ilimitada por NPC.

---

# 13. Identidades de produtos existentes

A inspeção confirmou que não existe uma única identidade universal para todos os produtos.

## 13.1 Hardware e itens físicos

Catálogo:

```text
item_catalog
```

Identidade:

```text
itm_
```

Exemplos de tipos existentes:

```text
hardware
software_fragment
material
mission_item
consumable
```

Hardware específico utiliza `item_catalog.public_id`.

## 13.2 Inventário do jogador

Tabela:

```text
player_inventory
```

Identidade de instância:

```text
inv_
```

Referência:

```text
item_public_id -> item_catalog.public_id
```

## 13.3 Fragmentos

Catálogo:

```text
code_fragments
```

Identidade:

```text
frg_
```

Raridades:

```text
common
uncommon
rare
epic
legendary
```

## 13.4 Software Blueprints

Catálogo:

```text
software_blueprints
```

Identidade:

```text
sbp_
```

## 13.5 Knowledge / Information

Catálogo existente:

```text
software_knowledge_artifacts
```

Tipos atuais:

```text
research_notes
source_fragment
architecture
protocol_notes
blueprint_clue
other
```

Os artefatos utilizam IDs no formato:

```text
ska_
```

Eles já podem ser concedidos ao jogador através de:

```text
player_software_knowledge
```

---

# 14. Decisão arquitetural do NPC Shop Inventory

O NPC Shop não deverá duplicar os catálogos existentes.

A arquitetura deverá reutilizar:

```text
npc_shop_inventory
    |
    +-- item_catalog
    +-- code_fragments
    +-- software_blueprints
    +-- software_knowledge_artifacts
```

Não será usado um único `item_public_id` universal sem integridade referencial.

Também não será criado um novo catálogo genérico apenas para informação, pois `software_knowledge_artifacts` já atende esse papel.

Serviços abstratos não entram no primeiro schema do NPC Shop.

---

# 15. npc_shops

Migration:

```text
000140_create_npc_shops.sql
```

Tabela criada:

```text
npc_shops
```

Contrato:

```text
id
public_id
npc_public_id
code
name
description
active
created_at
updated_at
```

Restrições:

```text
UNIQUE public_id
UNIQUE code
UNIQUE npc_public_id
```

Assim, no contrato inicial:

**um NPC pode possuir no máximo uma loja principal.**

Foreign key:

```text
npc_public_id -> npcs.public_id
```

Política:

```text
ON UPDATE CASCADE
ON DELETE RESTRICT
```

---

# 16. Validação de npc_shops

A migration `000140_create_npc_shops.sql` foi aplicada com sucesso.

Validação física:

```text
npc_shops table exists.................. PASS
Migration 000140 registered............. PASS
npc_shops columns contract.............. PASS
npc_shops indexes contract.............. PASS
NPC foreign key........................ PASS
npc_shops initially empty............... PASS
```

Status:

```text
PHASE 21D2B NPC SHOPS DATABASE: PASS
```

---

# 17. Comerciantes iniciais confirmados

A inspeção documental e física confirmou:

## Cipher

```text
Papel  : Code Broker
Facção : BlackWire Collective
Código : cipher
ID     : npc_00000000000000000000000000000002
```

Pode negociar futuramente:

- fragmentos;
- blueprints incompletos;
- fragmentos raros;
- localização de código;
- informações sobre servidores;
- pistas sobre pesquisa.

## Patch

```text
Papel  : Hardware Dealer
Facção : Independent
Código : patch
ID     : npc_00000000000000000000000000000003
```

A documentação cita explicitamente a loja:

```text
Patch Hardware
```

## Volt

```text
Papel  : Hardware Dealer
Facção : IronGrid Systems
Código : volt
ID     : npc_00000000000000000000000000000005
```

---

# 18. Seed inicial planejado

O próximo seed será:

```text
000141_seed_initial_npc_shops.sql
```

Lojas planejadas:

```text
Cipher -> Cipher
Patch  -> Patch Hardware
Volt   -> Volt
```

Códigos técnicos planejados:

```text
cipher_shop
patch_hardware
volt_shop
```

Public IDs planejados:

```text
nps_00000000000000000000000000000001
nps_00000000000000000000000000000002
nps_00000000000000000000000000000003
```

## Importante

No momento deste checkpoint:

```text
000141_seed_initial_npc_shops.sql........ PENDENTE
```

A migration ainda não foi confirmada como criada/aplicada.

---

# 19. Próximos passos

Sequência recomendada:

```text
21D2C2
    criar e aplicar 000141_seed_initial_npc_shops.sql
    validar Cipher, Patch e Volt

21D3A
    desenhar npc_shop_inventory

21D3B
    criar migration de npc_shop_inventory

21D3C
    validar catálogo misto:
        item
        fragment
        blueprint
        knowledge

21D4
    stock events e reposição

21D5
    NPC Shop Application Services

21D6
    integração com CreditLedgerService

21D7
    compra de jogador em NPC Shop

21D8
    venda de jogador para NPC

21D9
    preços, reputação e acesso

21D10
    regression suite NPC-2
```

---

# 20. Regra de separação da monetização

A economia NPC utiliza **créditos do jogo**.

Ela não deve utilizar diamantes.

A monetização premium permanece separada:

```text
NPC Shop
    -> créditos
    -> economia do round

Premium Shop
    -> diamantes
    -> economia permanente da conta
```

Diamantes não devem ser integrados ao `CreditLedgerService`.

---

# 21. Round reset

A Fase 21 deve respeitar a regra de round.

Itens competitivos e estado operacional do jogo sofrem reset conforme as regras do round.

Diamantes e ativos permanentes de conta não pertencem a este sistema NPC.

Também existe uma fase reservada para rotação de rede:

```text
PHASE 21R — Round Network Rotation
```

Nela:

- IPs virtuais mudam a cada novo round;
- identidades de servidores/NPCs permanecem;
- descobertas anteriores não revelam automaticamente os novos IPs;
- reconhecimento deve ser realizado novamente.

---

# 22. Checkpoint consolidado

```text
============================================================
 HACKER DIVERGENTS — FASE 21
============================================================

NPC-1 FOUNDATION
npc_factions............................. DONE
npcs..................................... DONE
player_faction_reputation................ DONE
player_npc_relationships................. DONE
NpcId.................................... DONE
NpcFactionId............................. DONE
NpcCatalogService........................ DONE
NpcRelationshipService................... DONE
NPC-1 regression suite................... PASS

NPC-2 SHOPS
NPC Shop contract inspection............. DONE
Product identity inspection.............. DONE
Knowledge identity inspection............ DONE
000140_create_npc_shops.sql.............. APPLIED
npc_shops physical validation............ PASS
Initial merchants inspection............. DONE
000141_seed_initial_npc_shops.sql........ PENDING
npc_shop_inventory....................... PENDING
npc_stock_events......................... PENDING
npc_shop_transactions.................... PENDING

CURRENT CONTINUATION POINT:
PHASE 21D2C2 — INITIAL NPC SHOPS SEED
============================================================
```

---

## Regra de continuidade

Ao retomar o desenvolvimento, continuar diretamente em:

**FASE 21D2C2 — criação, aplicação e validação de `000141_seed_initial_npc_shops.sql`.**
