cognitivebc 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +70 -0
  2. package/README.md +98 -4
  3. package/SECURITY.md +29 -0
  4. package/TERMS_OF_SERVICE.md +55 -0
  5. package/bin/cbc-cloud-bootstrap.js +108 -0
  6. package/bin/cbc-seed-projects.js +29 -0
  7. package/bin/cbc-server.js +45 -0
  8. package/bin/cognitivebc.js +251 -0
  9. package/docs/ACCESS_CONTROL.md +111 -0
  10. package/docs/ARTIFACT_AUDIT.md +36 -0
  11. package/docs/CONNECT_CLIENTS.md +116 -0
  12. package/docs/DEPLOY_AZURE.md +136 -0
  13. package/docs/INGESTION.md +29 -0
  14. package/docs/OPERATIONS.md +85 -0
  15. package/docs/PROJECT_IDENTITY.md +35 -0
  16. package/docs/RESOLVER.md +86 -0
  17. package/docs/SDK.md +96 -0
  18. package/docs/STORAGE.md +63 -0
  19. package/docs/TECHNICAL_SPECIFICATION.md +365 -0
  20. package/docs/TELEMETRY.md +119 -0
  21. package/index.js +27 -2
  22. package/package.json +45 -5
  23. package/packages/cbc-compiler/index.js +357 -0
  24. package/packages/cbc-compiler/sanitizer.js +43 -0
  25. package/packages/cbc-identity/index.js +92 -0
  26. package/packages/cbc-mcp/http-backend.js +142 -0
  27. package/packages/cbc-mcp/http-route.js +64 -0
  28. package/packages/cbc-mcp/index.js +50 -0
  29. package/packages/cbc-mcp/tools.js +122 -0
  30. package/packages/cbc-resolver/catalog-linker.js +215 -0
  31. package/packages/cbc-resolver/graph-builder.js +533 -0
  32. package/packages/cbc-resolver/index.js +548 -0
  33. package/packages/cbc-resolver/obsidian-bridge.js +564 -0
  34. package/packages/cbc-schema/index.js +194 -0
  35. package/packages/cbc-sdk-js/client.js +162 -0
  36. package/services/cbc-api/access-policy.js +130 -0
  37. package/services/cbc-api/artifact-audit.js +167 -0
  38. package/services/cbc-api/cloud.js +56 -0
  39. package/services/cbc-api/context-service.js +48 -0
  40. package/services/cbc-api/ingestion-service.js +234 -0
  41. package/services/cbc-api/pg-store.js +172 -0
  42. package/services/cbc-api/project-registry.js +343 -0
  43. package/services/cbc-api/public/app.html +123 -0
  44. package/services/cbc-api/public/graph.html +1168 -0
  45. package/services/cbc-api/public/graph2.html +455 -0
  46. package/services/cbc-api/public/graph3.html +503 -0
  47. package/services/cbc-api/public/index.html +78 -0
  48. package/services/cbc-api/public/vendor/cbc-app.js +209 -0
  49. package/services/cbc-api/public/vendor/cbc-auth.js +49 -0
  50. package/services/cbc-api/public/vendor/cbc-site.css +101 -0
  51. package/services/cbc-api/public/vendor/cose-base.js +3214 -0
  52. package/services/cbc-api/public/vendor/cytoscape-dagre.js +397 -0
  53. package/services/cbc-api/public/vendor/cytoscape-fcose.js +1549 -0
  54. package/services/cbc-api/public/vendor/cytoscape.min.js +32 -0
  55. package/services/cbc-api/public/vendor/dagre.min.js +3809 -0
  56. package/services/cbc-api/public/vendor/graphology-library.min.js +2 -0
  57. package/services/cbc-api/public/vendor/graphology.umd.min.js +2 -0
  58. package/services/cbc-api/public/vendor/layout-base.js +5230 -0
  59. package/services/cbc-api/public/vendor/pf-graph.css +86 -0
  60. package/services/cbc-api/public/vendor/pf-telemetry.js +176 -0
  61. package/services/cbc-api/public/vendor/sigma.min.js +1351 -0
  62. package/services/cbc-api/runtime-info.js +39 -0
  63. package/services/cbc-api/server.js +642 -0
  64. package/services/cbc-api/store-loader.js +269 -0
  65. package/services/cbc-api/telemetry.js +148 -0
  66. package/services/cbc-api/token-service.js +61 -0
@@ -0,0 +1,29 @@
1
+ # Ingestão, evidência e publicação
2
+
3
+ A API de ingestão exige `tenant`, `session_id` (ou `sessionId`) e `events`, cada um com `event_id` ou `id` estável e `event_type` explícito. O produtor mantém o mesmo ID, conteúdo e escopo no retry. A identidade autenticada autoriza o tenant antes do processamento. Um nome de cliente de exibição não é inferido como tenant.
4
+
5
+ O serviço `createIngestionService({store})` usa as implementações reais de compiler e CognitiveStore. Seus recibos privados ficam em `<storeDir>/.ingestion`, com arquivos 0600, nomes SHA-256 de tenant/sessão/evento e escrita temporária + fsync + rename. O recibo guarda identidade, hash do evento, qualificação, produtor autenticado, atividade mínima observada e referência de candidato, não a memória operacional inteira. Essa memória continua no runtime proprietário.
6
+
7
+ - Replay idêntico retorna o recibo existente, `newly_accepted: 0` e não cria outro candidato.
8
+ - Mesmo ID com conteúdo diferente recebe 409, inclusive dentro do lote. Todos os conflitos já existentes são verificados antes de aceitar os itens novos.
9
+ - A confirmação só ocorre após salvar candidato e recibo. Falha de recibo pode deixar candidato privado, mas o retry determinístico o reaproveita.
10
+ - Um lote pode ser parcialmente persistido se ocorrer erro de disco durante sua execução. O produtor repete o lote completo com IDs estáveis. Não há promessa de transação única do lote.
11
+ - `ExternalCorrectiveFeedback` precisa de `issue` e `resolution`. `SilentSelfCorrectionCycle` precisa de pelo menos duas versões e resumo de raciocínio. Outros eventos são recebidos, mas não geram ficticiamente uma compilação.
12
+ - Qualificar evidência não comprova sucesso. O compilador marca experiências como `unverified`, sem inventar que a última versão foi adotada ou validada. A publicação exige aprovação separada.
13
+ - Candidatos preservam tenant de origem. O serviço não publica nem gradua automaticamente para conhecimento global. Uma política futura de sanitização global precisa de aceite próprio.
14
+
15
+ `listJobs({allowTenant, tenant, project_id})` projeta os recibos únicos em sessões com atividade observada. O padrão sem predicate não retorna dados. `agent_id`, `role` e `project_id` são registros explícitos do produtor, não papéis inferidos a partir de regras. Uma sessão é identificada por tenant e session_id, que o produtor deve manter único nesse tenant. A projeção preserva identidade de eventos e independe do log opcional de telemetria. Ela faz leitura O(n) dos recibos por consulta, sem prometer um índice escalável ou retenção automática. A autorização de projeto dentro de um tenant ainda precisa de uma política do integrador quando tenants não forem sua fronteira suficiente de acesso.
16
+
17
+ A exclusão mútua é por sessão, em arquivo `.lock`, com identificação do processo. Concorrência retorna 503. Um encerramento abrupto pode deixar lock órfão, deliberadamente fail-closed. A recuperação exige confirmar que nenhum escritor permanece ativo e remover somente esse lock em janela controlada. Não há remoção automática por idade ou PID, pois isso permitiria corrida entre processos. Proteções contra symlinks pressupõem que o diretório de dados e seus pais não são graváveis por outros usuários. fsync de arquivo + rename não promete proteção contra toda falha de energia/filesystem.
18
+
19
+ `ingestStreamEvents` continua disponível como detector puro para compatibilidade, com IDs reproduzíveis e status `detected_not_persisted`. Ele não é fila nem confirmação durável. A API HTTP usa o serviço durável, não esse detector isolado.
20
+
21
+ ## Distribuição e instância
22
+
23
+ O tarball npm distribui código, não `store/`, ledger, vault gerado, candidatos ou recibos operacionais. Configure um store próprio com `COGNITIVEBC_STORE_DIR` ou `createServer({storeDir})`; importar o pacote não instala conhecimento de clientes. O helper launchd local não faz parte da distribuição portátil. O bind padrão do CLI é `127.0.0.1`; exposição remota exige configuração explícita e política de acesso.
24
+
25
+ `runtime-info` captura uma vez o snapshot de fontes observado na criação do servidor e os corpos de funções públicas fornecidos. Informa versão de pacote, PID, início do processo, SHA-256 e HEAD/dirty quando Git existe. Isso não é atestado completo de bytecode V8 nem prova da revisão do daemon antigo. A resposta explicita essa limitação. Arquivos editados depois não alteram retroativamente o fingerprint da instância.
26
+
27
+ ## Verificação
28
+
29
+ `node --test test/ingestion-contract.test.js test/runtime-packaging.test.js` exercita módulos originais, nova instância e novo processo, replay, conflitos, isolamento, ENOSPC no recibo, escopo inválido e manifesto npm real. Os testes de autorização exercitam a integração HTTP; nenhuma observação local comprova implantação em Azure ou reinício dos serviços existentes.
@@ -0,0 +1,85 @@
1
+ # Operação em produção (api.cognitivebc.io)
2
+
3
+ Estado atual e procedimentos do dia a dia. Infraestrutura: ver `DEPLOY_AZURE.md`. Clientes: ver `CONNECT_CLIENTS.md`.
4
+
5
+ ## Recursos
6
+
7
+ | Item | Valor |
8
+ |---|---|
9
+ | Site (landing) | `https://cognitivebc.io` e `https://www.cognitivebc.io` |
10
+ | Área do usuário + grafo | `https://app.cognitivebc.io` |
11
+ | API (somente JSON e MCP) | `https://api.cognitivebc.io` (`/` redireciona para o site, `/app` para o app) |
12
+ | MCP remoto | `https://api.cognitivebc.io/mcp` (Streamable HTTP, `Authorization: Bearer`) |
13
+ | Grupo de recursos | `rg-cognitivebc` (Brazil South), assinatura "Azure subscription 1" |
14
+ | App | Container App `cbc-api`, imagens em `cbcacrujvsks3s5lp22.azurecr.io/cognitivebc:<commit>` |
15
+ | Banco | `cbc-pg-ujvsks3s5lp22` (PostgreSQL 16, banco `cognitivebc`) |
16
+ | DNS | Porkbun: `A @ 4.228.131.224` (IP do ambiente), `CNAME www/app/api` para o FQDN do Container App, `TXT asuid`, `asuid.www`, `asuid.app`, `asuid.api`. Os quatro hosts têm certificado gerenciado pelo Azure. |
17
+ | Separação | Mesmo container, roteado pelo `Host`. Ativada por `COGNITIVEBC_SITE_URL` e `COGNITIVEBC_APP_URL`. O app chama a API por CORS (lista de origens fixa) |
18
+
19
+ ## Segredos (Keychain do macOS do operador)
20
+
21
+ Nada é gravado em arquivo. Leia com `security find-generic-password -a <conta> -s <serviço> -w`.
22
+
23
+ | Serviço | Conta | Uso |
24
+ |---|---|---|
25
+ | `cognitivebc-admin-token` | `fer` | Token admin (`*`): emitir/revogar tokens, aprovar candidatos |
26
+ | `cognitivebc-postgres-admin` | `cognitivebc` | Senha do admin do Postgres |
27
+ | `cognitivebc-token-maquina2` | `fer` | Segunda máquina de desenvolvimento, tenant `profarma` |
28
+ | `cognitivebc-token-bridge-pricefy` | `synapse` | Bridge Synap-se Pricefy, tenant `profarma` |
29
+ | `cognitivebc-token-bridge-mktsquad` | `synapse` | Bridge MktSquad, tenants `diario_glp1`, `cnhsimulado` |
30
+ | `porkbun-api-key` / `porkbun-secret-key` | `porkbun` | API de DNS da Porkbun |
31
+
32
+ No servidor, só o SHA-256 de cada token é armazenado (tabela `cbc_tokens`).
33
+
34
+ ## Tokens
35
+
36
+ ```bash
37
+ ADMIN=$(security find-generic-password -a fer -s cognitivebc-admin-token -w)
38
+
39
+ # Emitir (o segredo aparece uma única vez)
40
+ curl -sS https://api.cognitivebc.io/api/v1/tokens -H "Authorization: Bearer $ADMIN" \
41
+ -H 'content-type: application/json' \
42
+ -d '{"label":"maria notebook","principal":{"id":"maria","tenants":["profarma"],"permissions":["read","ingest"]}}'
43
+
44
+ # Listar e revogar
45
+ curl -sS https://api.cognitivebc.io/api/v1/tokens -H "Authorization: Bearer $ADMIN"
46
+ curl -sS -X POST https://api.cognitivebc.io/api/v1/tokens/<token_id>/revoke -H "Authorization: Bearer $ADMIN"
47
+ ```
48
+
49
+ Permissões: `read`, `ingest`, `compile`, `write`, `export`, `approve`, `*`. Quem emite só delega tenants e permissões que possui. Revogação vale em até 30 s (cache por réplica).
50
+
51
+ ## Projetos
52
+
53
+ ```bash
54
+ curl -sS https://api.cognitivebc.io/api/v1/projects -H "Authorization: Bearer $ADMIN"
55
+ # Cadastrar/atualizar projeto e seus identificadores
56
+ curl -sS https://api.cognitivebc.io/api/v1/projects -H "Authorization: Bearer $ADMIN" -H 'content-type: application/json' \
57
+ -d '{"id":"profarma/novo","tenant":"profarma","name":"Novo","identifiers":{"git_remotes":["github.com/performacia/novo"]}}'
58
+ # Promover projeto candidato (criado por usuário novo) para um tenant real
59
+ curl -sS -X POST https://api.cognitivebc.io/api/v1/projects/user-joao%2Fside-project/promote \
60
+ -H "Authorization: Bearer $ADMIN" -H 'content-type: application/json' -d '{"tenant":"profarma","id":"profarma/side-project"}'
61
+ ```
62
+
63
+ ## Bridges do Synap-se
64
+
65
+ LaunchAgents `io.synapse.bridge-cbc-cloud-azure` e `io.synapse.bridge-cbc-cloud-pricefy` executam `synap-se/bin/run-bridge.sh`, que lê os tokens do Keychain na inicialização. Logs em `synap-se/logs/bridge-cbc-cloud-*.{out,err}` (silenciosos quando tudo vai bem).
66
+
67
+ O bridge antigo (para `localhost:4780`) foi desativado: `~/Library/LaunchAgents/io.synapse.bridge-cbc.plist.disabled-local`.
68
+
69
+ Mapeamento MktSquad → tenant (em `run-bridge.sh`): `diarioglp1 → diario_glp1`, `cnhsimulado → cnhsimulado`. Novo cliente no MktSquad: adicionar ao mapa e ao token do bridge (emitir novo token com o tenant adicional e atualizar o Keychain).
70
+
71
+ ## Publicar nova versão do código
72
+
73
+ ```bash
74
+ T=$(git rev-parse --short HEAD)
75
+ mkdir -p ~/.jcode/scratch/rel-$T && git archive HEAD | tar -x -C ~/.jcode/scratch/rel-$T # só o que está commitado
76
+ az acr build -r cbcacrujvsks3s5lp22 -t cognitivebc:$T -t cognitivebc:latest ~/.jcode/scratch/rel-$T
77
+ az containerapp update -g rg-cognitivebc -n cbc-api --image cbcacrujvsks3s5lp22.azurecr.io/cognitivebc:$T
78
+ curl -fsS https://api.cognitivebc.io/health
79
+ ```
80
+
81
+ Rollback: `az containerapp update ... --image ...:<commit anterior>`.
82
+
83
+ ## Acesso direto ao banco
84
+
85
+ A rede do escritório bloqueia a porta 5432 de saída. Para manutenção, rode um Container Apps Job no ambiente `cbc-env` com a identidade `cbc-id` e o segredo `database-url` do Key Vault (foi assim que a migração inicial foi feita), ou use o Cloud Shell do portal com regra de firewall temporária.
@@ -0,0 +1,35 @@
1
+ # Identidade de projeto entre máquinas
2
+
3
+ O CognitiveBC reconhece o mesmo projeto em máquinas e usuários diferentes usando identificadores estáveis, nunca caminhos absolutos.
4
+
5
+ ## Identificadores (ordem de precedência)
6
+
7
+ 1. **manifest** (forte): `project_id` do arquivo `<raiz>/.cognitivebc.yaml` (`project_id`, `tenant` opcional).
8
+ 2. **git_remote** (forte): remote normalizado `host/owner/repo` em minúsculas. SSH, HTTPS, porta, credenciais e `.git` são removidos. Formas do Azure DevOps (`dev.azure.com`, `ssh.dev.azure.com:v3`, `*.visualstudio.com`) viram `dev.azure.com/org/proj/repo`.
9
+ 3. **root_commit** (fraco): SHA completo de `git rev-list --max-parents=0 HEAD`. Sozinho gera status `probable` e nunca vincula automaticamente.
10
+
11
+ Se um remote aponta para o projeto A e um root commit para o projeto B, vence A e B aparece em `suggestions`.
12
+
13
+ ## Cliente (`packages/cbc-identity`)
14
+
15
+ Sem dependências de servidor: `normalizeGitRemote(url)`, `collectLocalIdentity(cwd)` (usa `git` via `execFileSync`, sem shell; envia apenas `path_hint` = nome da pasta) e `writeManifest(root, {project_id, tenant})`.
16
+
17
+ ## Servidor (`services/cbc-api/project-registry.js`)
18
+
19
+ `createProjectRegistry({ db | dir })`: Postgres (`cbc_projects`, `cbc_project_identifiers`, criadas por `migrate()`) ou JSON em `${dir}/projects.json` (escrita atômica, modo 0600).
20
+
21
+ IDs de projeto: `<tenant>/<slug>`, `[a-z0-9-_]`, até 96 caracteres.
22
+
23
+ | Rota | Permissão | Corpo | Resposta |
24
+ | --- | --- | --- | --- |
25
+ | `POST /api/v1/projects/identify` | read (+ingest p/ candidato) | identidade, `register_candidate?` | `{status: known\|probable\|new\|forbidden, project?, matched_by?, suggestions?}` ou 201 `{status:'candidate', project, created}` |
26
+ | `GET /api/v1/projects` | read | | `{projects:[...]}` filtrado por tenant |
27
+ | `POST /api/v1/projects` | approve | `{id, tenant?, name, stack, squad, identifiers, move?}` | `{project}` (409 com `conflicts` em conflito) |
28
+ | `POST /api/v1/projects/:id/link` | approve | `{identifiers, move?}` | `{project}` |
29
+ | `POST /api/v1/projects/:id/promote` | approve | `{tenant, id?}` | `{project}` |
30
+
31
+ `forbidden` expõe apenas `project.project_id`. Projetos novos viram candidatos no tenant `user-<id do usuário>` até serem promovidos.
32
+
33
+ ## Seed Profarma
34
+
35
+ `node bin/cbc-seed-projects.js --dir <pasta>` ou com `COGNITIVEBC_DATABASE_URL` definido: cadastra `profarma/balanc-linha`, `profarma/pricefy` e `profarma/sal`.
@@ -0,0 +1,86 @@
1
+ # Contrato e desempenho do resolvedor CognitiveBC
2
+
3
+ ## Escopo e contrato
4
+
5
+ `require('../packages/cbc-resolver').resolveContextForRole(options)` é a função pública exercitada pelos testes e pelo benchmark. Não lê store, não abre servidor e não grava vault. Os imports de graph/bridge permanecem compatíveis, mas esses caminhos não são executados pelo harness.
6
+
7
+ - O chamador deve fornecer **dados previamente autorizados**. O filtro interno exige tenant idêntico para bytecodes com `scope.tenant` preenchido e mantém o filtro de stack existente. Isso é defesa adicional, não autenticação nem autorização de projeto/squad/área.
8
+ - Papel novo recebe regras gerais, sem `target_roles`, e regras wildcard `*`. Regras dirigidas somente a outro papel não são fallback. O papel não redefine o escopo autorizado. Evidência mínima, relevância lexical/identificadores, subscopes e prioridades continuam aplicáveis.
9
+ - O orçamento usa, nesta ordem, o primeiro número **finito**: `maxTokens`, `hyperparameters.roleMaxTokens[role]`, orçamento declarativo de bytecode elegível por tenant/stack, `roleMaxTokens.default`, `defaultMaxTokens`, 600. Valores não numéricos, NaN e infinitos são ignorados. O escolhido é arredondado para baixo e limitado a **100..2000**, inclusive zero e negativos, que viram 100.
10
+ - `token_count` é `ceil(push_markdown.length / 3.8)`, não uma contagem de tokenizer de modelo. Cabeçalho anormalmente longo usa `# CBC JIT` para não estourar o limite. O digest SHA-256 passa a corresponder exatamente ao markdown retornado, sem whitespace final invisível.
11
+ - `applied_ids` contém apenas IDs de regras emitidas, **na ordem do texto**, em ambos os packings. MAP não inventa ID de regra. `omitted_ids` contém IDs elegíveis que não couberam. `omissions` descreve `{ section, id, reason: 'budget' }`, incluindo `id: null` para MAP omitido. Regras não autorizadas/inaplicáveis não aparecem nessa lista, evitando divulgar seus IDs.
12
+ - `section_block` inclui uma seção inteira ou a omite e tenta a próxima. `item_granular` preserva os dois passes de relevância e fallback. Regras individuais e MAP agregado não são truncados no meio para caber.
13
+ - MAP preserva preâmbulo e **todas** as seções gerais/relevantes, não apenas a primeira. Anotações `<!-- roles: a, b -->` ou `[roles: a, b]` restringem o bloco do heading ATX e descendentes. Uma anotação em linha própria restringe o mesmo bloco. Uma anotação no preâmbulo restringe o documento. Um filho wildcard não reabre um pai negado. Headings dentro de blocos fenced não encerram uma restrição. Anotações são removidas do texto emitido. Não é um parser Markdown completo: headings setext não definem novos blocos de escopo.
14
+ - A diferenciação é preservada: bytecodes fornecem regras, MAP fornece fatos/regras de tenant, skills continuam disponíveis por referência quando `squad` e `area` existem. O argumento `skills` não é convertido implicitamente em bytecode. `mcp_resources` mantém `cbc://skills/...`, `cbc://bytecode/...`, `cbc://map/.../facts` e `.../verified-claims`.
15
+ - Não existe cache entre chamadas. A mutação de objetos pelo chamador é observada na chamada seguinte. A ordenação não modifica os arrays de entrada.
16
+
17
+ Essas decisões implementam o recorte de §9.1.4 e critérios de orçamento/IDs de §9.2 do dossiê. Autorização HTTP/MCP, persistência e integração de consumidores pertencem às respectivas lanes.
18
+
19
+ ## Reprodução isolada
20
+
21
+ ```sh
22
+ node --test test/resolver-contract.test.js
23
+ node benchmarks/resolver-performance.js > resolver-performance.json
24
+ # Defaults: RUNS=3 WARMUP=30 SAMPLES=100
25
+ RUNS=3 WARMUP=30 SAMPLES=100 node benchmarks/resolver-performance.js
26
+ # Perfil separado, não usar suas latências como benchmark principal:
27
+ node --cpu-prof --cpu-prof-dir="$JCODE_SCRATCH_DIR" benchmarks/resolver-performance.js
28
+ ```
29
+
30
+ Fixtures inteiramente sintéticas e determinísticas: 100/1000/10000 regras, papel novo, regras gerais/wildcard/específicas, tenants A/B, consulta `models/fields.py field_name validate`, orçamento 600 ou tight=100 e variante sem consulta. Cada tamanho inclui mais dois princípios privados A/B. Um cenário não depende de dados reais ou do catálogo. A fixture é construída fora da janela medida; cada chamada pública completa, incluindo seleção, formatação, omissões e SHA-256, é medida. Throughput é número de chamadas/tempo total de suas amostras. Percentis usam o índice empírico `floor(n*p)` no array ordenado.
31
+
32
+ ## Evidência medida em 12/11/2026, UTC−03:00
33
+
34
+ Node **v22.23.0**, macOS **arm64**. Três repetições por cenário no mesmo processo, cada uma com 30 chamadas de warmup e 100 amostras. São 36 blocos e 3600 chamadas medidas por execução. A máquina não estava reservada exclusivamente, portanto não há alegação de significância estatística ou de desempenho de produção.
35
+
36
+ Três checkpoints foram medidos:
37
+
38
+ 1. **Antes**: arquivo original local, incluindo trabalho preexistente, sem alterações desta lane.
39
+ 2. **Corrigido**: invariantes corrigidas, antes das otimizações. Essa comparação evita atribuir ganhos a uma mudança incorreta de seleção.
40
+ 3. **Final**: correções e otimizações. Todos os **36 hashes de markdown + applied_ids** coincidem com o checkpoint corrigido. Mudanças intencionais de MAP, IDs, digest e orçamento não são apresentadas como equivalência com o código defeituoso anterior.
41
+
42
+ Cada célula mostra **mediana das 3 repetições: p50 ms / p95 ms / throughput ops/s**. A mediana do p95 não é um p95 agregado.
43
+
44
+ | Regras | Cenário | Antes | Corrigido | Final |
45
+ |---:|---|---|---|---|
46
+ | 100 | identificadores A | 0.153 / 0.189 / 6312 | 0.155 / 0.171 / 6269 | 0.138 / 0.149 / 7080 |
47
+ | 100 | identificadores B | 0.154 / 0.183 / 6212 | 0.157 / 0.173 / 6238 | 0.135 / 0.152 / 7316 |
48
+ | 100 | tight | 0.151 / 0.180 / 6468 | 0.153 / 0.173 / 6405 | 0.088 / 0.105 / 10946 |
49
+ | 100 | sem consulta | 0.063 / 0.079 / 15143 | 0.067 / 0.076 / 14662 | 0.061 / 0.073 / 15666 |
50
+ | 1000 | identificadores A | 1.592 / 1.794 / 619 | 1.616 / 1.828 / 601 | 1.362 / 1.573 / 720 |
51
+ | 1000 | identificadores B | 1.596 / 1.761 / 619 | 1.599 / 1.762 / 618 | 1.363 / 1.548 / 721 |
52
+ | 1000 | tight | 1.578 / 1.746 / 625 | 1.589 / 1.749 / 622 | 0.951 / 1.080 / 1033 |
53
+ | 1000 | sem consulta | 0.593 / 0.763 / 1630 | 0.592 / 0.766 / 1622 | 0.547 / 0.735 / 1756 |
54
+ | 10000 | identificadores A | 17.971 / 20.514 / 55.1 | 17.992 / 20.208 / 55.1 | 15.263 / 17.585 / 64.1 |
55
+ | 10000 | identificadores B | 17.879 / 20.601 / 55.1 | 18.112 / 20.671 / 53.8 | 15.091 / 17.945 / 64.6 |
56
+ | 10000 | tight | 17.924 / 19.186 / 55.5 | 17.976 / 19.075 / 55.0 | 10.062 / 10.537 / 99.4 |
57
+ | 10000 | sem consulta | 6.615 / 6.907 / 150.8 | 6.947 / 7.856 / 137.4 | 6.022 / 6.667 / 164.1 |
58
+
59
+ **Meta aspiracional atingida somente no cenário tight 1k/10k de forma estável:** redução de p95 contra o checkpoint corrigido de **36.3..39.1%** em 1k e **43.2..46.8%** em 10k, nas três repetições. Contra o original, medianas de p95 tight: 1.746→1.080 ms e 19.186→10.537 ms. Consultas de identificadores com orçamento 600 melhoraram menos e **não sustentam alegação geral de ≥20%**. O cenário sem consulta 100 regras teve uma repetição 28.8% pior no p95, apesar da mediana melhor. Não se deve extrapolar estes números para rede, disco, modelos ou workloads reais.
60
+
61
+ ### Atribuição e alterações de desempenho
62
+
63
+ Perfil CPU anterior: `computeQueryRelevance` 6340 amostras próprias, `compactText` 3953, `getItemScore` 2894 e resolvedor 2056. `parseQueryTokens` teve apenas 10: a consulta **já era parseada uma vez**, então não se inventou esse gargalo. O perfil final reduz trabalho de relevância/compactação, mas contagens absolutas de amostras de execuções com durações diferentes não são uma medição normalizada de ganho.
64
+
65
+ Inspeção estática confirmou: construção repetida de strings de boundaries e soma de pesos por item, formatação/compactação antecipada de todos os candidatos, concatenação redundante de seções no packing granular e IDs candidatos mantidos separadamente sem necessidade. Alterações:
66
+
67
+ - Plano de termos, pesos totais e boundaries preparado uma vez por chamada, sem mudar score.
68
+ - Rendering compartilhado por seção e preguiçoso por item. O packing usa um limite inferior comprovável, tamanho do marcador do ID, para não renderizar itens que não poderiam caber nem com conteúdo vazio.
69
+ - O granular não constrói também o texto completo das seções descartadas. O baseline mantém semântica de bloco.
70
+ - Não aloca cache de scores zero quando não há consulta/subscope. Cache de score continua restrito à chamada. Nenhuma seleção aproximada, top-k limitado, cache persistente ou redução de isolamento foi introduzida.
71
+
72
+ Tradeoff: `omissions`/`omitted_ids` têm tamanho O(n) em candidatos elegíveis e acrescentam alocação/serialização. Isso é deliberado para auditabilidade. Ordenação continua O(n log n), scoring O(n * termos) e packing O(n). O benchmark mede a construção da resposta, não `JSON.stringify` dos milhares de IDs omitidos, que deve ser considerado pelo servidor antes de anunciar ganho HTTP.
73
+
74
+ ## Validação e limites
75
+
76
+ - **6 testes Node** sobre a função pública original: tenant A/B/null, papel novo, wildcard, stack, todos os caminhos de orçamento incluindo NaN/Infinity, header gigante, ambos os packings, IDs exatos na ordem do texto, omissões, MAP geral/específico/descendentes/fenced, evidência, subscopes, referências e mutação entre chamadas.
77
+ - **500 fixtures diferenciais suplementares**: resultado completo idêntico ao checkpoint corrigido pré-otimização, variando consulta, quantidade, evidência, orçamento, packing, tipos de regra e subscopes. Essa comparação não substitui os testes diretos da função pública.
78
+ - `git diff --check` nos arquivos da lane. Não foi executado `npm test` bruto, nem servidor/daemon/cloud, store real, ledger ou vault. Não foram medidos heap, RSS, I/O, concorrência HTTP/MCP, tokenizer real ou tempo de modelo.
79
+
80
+ Artefatos brutos desta sessão: `/Users/fer/.jcode/scratch/resolver-evidence/` contém `before.json`, `corrected.json`, `after-final.json`, perfis `.cpuprofile`, `tests-before.tap`, `tests-after.tap`, `differential.js`/`.json` e snapshots. O snapshot anterior coincide byte a byte com o snapshot autorizado em `remediation-cbc-2026-11-12/before/packages/cbc-resolver/index.js`. SHA-256 das fontes:
81
+
82
+ - Antes: `8d26a6ed6b37494459daea86a7191de8c1b7e89cacaf13631c2a8f89aa5ab3fe`.
83
+ - Corrigido pré-otimização: `a026c879eee5fba50b3f50621871b9321886f65d8a27fd8181cf7be6470abf4b`.
84
+ - Final medido: `8cc093884467ae8afc5eee6476be4a18e0861f5ad68d195848a138e5ce1b9f37`.
85
+
86
+ `packages/cbc-resolver/index.js` já tinha alterações locais extensas e **não é commitado por esta lane**. O coordenador fará staging seletivo. Os novos benchmark/teste/documento podem ser commitados isoladamente. Rollback deve retirar somente os hunks desta lane, nunca restaurar HEAD sobre o trabalho preexistente.
package/docs/SDK.md ADDED
@@ -0,0 +1,96 @@
1
+ # CognitiveBC JavaScript SDK
2
+
3
+ `require('./packages/cbc-sdk-js/client')` exports `CognitiveBCClient` and the additive `CognitiveBCHTTPError` class. Requires Node with native `fetch` and `AbortController`.
4
+
5
+ ```js
6
+ const { CognitiveBCClient } = require('./packages/cbc-sdk-js/client');
7
+ const client = new CognitiveBCClient({
8
+ baseUrl: 'http://127.0.0.1:4780',
9
+ apiKey: process.env.COGNITIVEBC_API_KEY,
10
+ timeoutMs: 10000,
11
+ localFallbackDir: '/absolute/private/cache',
12
+ cacheTtlMs: 300000,
13
+ });
14
+ const context = await client.resolve({
15
+ tenant: 'example', squad: 'research', role: 'writer',
16
+ query: 'What changed?', task: 'summarize', subscopes: ['release'],
17
+ profile: 'baseline', hyperparameters: { profile: 'baseline' },
18
+ maxTokens: 1000,
19
+ });
20
+ if (context._sdk?.degraded) console.warn(context._sdk);
21
+ ```
22
+
23
+ ## Requests and compatibility
24
+
25
+ Existing methods and payload aliases remain: `resolve`, `compile`, `ingestStream`, `verifyGate`, `getArtifact`. There are no automatic retries, including compile and ingest. Timeouts do not imply a mutation was rolled back. Do not retry mutations without application-level idempotency.
26
+
27
+ `resolve` forwards all supplied JSON parameters, including `query`, `task`, `subscopes`, `profile`, `hyperparameters`, scopes and stage. `stacks` still defaults to `[]`. `maxTokens` and `max_tokens` normalize to `max_tokens`. An explicit budget must be a finite number within inclusive 100..2000. Conflicting aliases, numeric strings, NaN and out-of-range numbers reject with `RangeError` before HTTP. Omitted or null budgets are omitted, allowing the server to select role/profile budgets. No implicit 600 is injected. Top-level profile and hyperparameters are forwarded unchanged, with precedence determined by the server.
28
+
29
+ An explicit constructor `baseUrl` takes precedence. Otherwise `COGNITIVEBC_URL` is evaluated for every request, then the historical localhost:4780 default is used. URL normalization removes trailing slashes and uses standard URL origin normalization. Only HTTP(S) is accepted. Embedded credentials, URL query strings and fragments are rejected. Redirects are not followed. Authentication added by the SDK appears only in `Authorization: Bearer ...`, never in cache filenames or cache identity data. API keys are captured at construction, as before. Change `client.apiKey` or construct another client to change identity.
30
+
31
+ `timeoutMs` defaults to 10000, must be finite and positive, and covers response headers plus JSON body consumption. Abort timers are always cleared. HTTP failures throw `CognitiveBCHTTPError` with numeric `status` and `code: 'HTTP_ERROR'`. Network and timeout errors have `status: null`, `code: 'NETWORK_ERROR'` or `'TIMEOUT'`, and native `cause`. Malformed successful JSON has `code: 'INVALID_JSON'`, HTTP status and parsing cause, and never activates fallback. HTTP response bodies are deliberately not copied into error messages, because upstream errors can echo credentials.
32
+
33
+ ## Candidate review and promotion
34
+
35
+ `compile` forwards `evidence` and `options` unchanged along with the existing regime/scope/input aliases. Origin evidence is required by the server. Compilation produces a persisted candidate with `published: false`, not immediately resolvable memory. The SDK HTTP wire test proves both fields are transmitted. The integrated API now validates and forwards `options` to `compileExperience`; original-server regressions verify distinct compact versus standard output and HTTP400 for malformed options. SDK-only lifecycle tests still use default compilation and do not by themselves prove compiler option handling.
36
+
37
+ `ingestStream` also forwards body-level `role`, `stack`, `project_id` and `agent_id`. Camel-case `projectId`/`agentId` are accepted and normalized to snake-case, with non-null camel-case values taking precedence. Event payloads remain unchanged. Body scope/activity is used by the ingestion service for durable receipts and candidate generation, without automatically promoting learned content.
38
+
39
+ ```js
40
+ const compiled = await client.compile({
41
+ regime: 'external_corrective',
42
+ scope: { tenant: 'example', role: 'writer', stack: 'docs' },
43
+ inputPayload: { issue: 'Observed failure', resolution: 'Reviewed correction' },
44
+ evidence: { producer: 'review-session', event_id: 'event-123' },
45
+ options: { compressionLevel: 'compact' },
46
+ });
47
+ const candidate = await client.getCandidate(compiled.candidate.id);
48
+ // A distinct client authenticated with approve permission for this tenant:
49
+ await approverClient.promoteCandidate(candidate.id);
50
+ ```
51
+
52
+ `getCandidate(id)` performs GET `/api/v1/candidates/:id`. `promoteCandidate(id, params = {})` performs POST `/api/v1/candidates/:id/promote`, forwarding the supplied JSON body without inventing approval evidence. IDs are URL-encoded as single path segments. Both operations use normal timeouts and HTTP errors but never retry, cache or activate offline fallback. Promotion authority comes from the authenticated server principal, not caller-supplied `approvedBy`, `permissions` or `principal` body fields. Cross-tenant inspection/promotion and clients lacking approve permission fail with HTTP 403. The server records the real approver identity and prevents publication before approval. These methods require a candidate-capable server and otherwise surface its HTTP errors.
53
+
54
+ ## Resolve-only stale fallback
55
+
56
+ The cache is optional and network-first, not an online response cache. Only successful `POST /api/v1/resolve` responses are stored. Compile, ingest, gates and artifact operations never write or consult it.
57
+
58
+ Cache layout is `localFallbackDir/v2/<namespace hash>/<request hash>.json`. The namespace hashes normalized server URL and a SHA-256 identity fingerprint (including anonymous identity). The request hashes the exact endpoint and recursively sorted JSON object keys. Array ordering is retained. All serialized resolver fields, including query/task, scopes, profile, hyperparameters and explicit budget, participate. Legacy unversioned cache entries are never imported or read.
59
+
60
+ Only network failures, timeouts and HTTP 408, 429, 500, 502, 503, 504 permit fallback. All other statuses fail, including 400 and 404. A 401 or 403 always fails and invalidates the entire current server/identity namespace, not just the requested scope. That client conservatively disables further cache reads/writes in that namespace for its lifetime, even if deletion fails. Other namespaces are unaffected. A successful online request still works after invalidation.
61
+
62
+ `cacheTtlMs` defaults to 300000, must be finite and nonnegative, and setting it to zero disables cache reads and writes. Age is measured from successful cache write time, not last access. Expired, future-dated, malformed or wrong-version entries fail closed. Only object-shaped resolver responses can be returned by fallback. Online success returns the server JSON unchanged. Fallback preserves the server response fields and adds/replaces the reserved `_sdk` field:
63
+
64
+ ```json
65
+ {
66
+ "_sdk": {
67
+ "stale": true,
68
+ "degraded": true,
69
+ "source": "cache",
70
+ "status": 503,
71
+ "reason": "HTTP_ERROR",
72
+ "cachedAt": "2026-11-13T00:00:00.000Z",
73
+ "ageMs": 200
74
+ }
75
+ }
76
+ ```
77
+
78
+ For timeout/network fallback, status is null and reason identifies the cause. Degradation is explicit rather than silently presenting stale context as current. This additive reserved field and stricter input validation are intentional compatibility changes.
79
+
80
+ ## Filesystem safety
81
+
82
+ Use a private, trusted directory. New directories use mode 0700 and cache files 0600. Writes use random exclusive temporary files and atomic same-directory rename with cleanup. Cache write failure never turns successful HTTP into an error. Path components must be real directories, not symlinks. Reads use `O_NOFOLLOW` and require a regular file. Hash-only generated names prevent user scope/path traversal. On macOS, use a canonical path, for example `fs.realpathSync(os.tmpdir())`, rather than the `/var` or `/tmp` symlink aliases when creating a temporary cache.
83
+
84
+ This is not an encrypted or authenticated local store. Responses may contain sensitive context, including any secret echoed by a misconfigured server. Protect the directory against other users and malicious concurrent writers. Component checks do not claim to prevent every directory-swap race by a hostile process with write access. Authentication revocation cannot guarantee persistence across process restart when filesystem deletion is denied, so do not share a read-only stale cache across security contexts.
85
+
86
+ ## Isolated acceptance and timing
87
+
88
+ Run only:
89
+
90
+ ```sh
91
+ node --test test/sdk-contract.test.js
92
+ ```
93
+
94
+ These tests use original Node HTTP servers bound to loopback ephemeral ports and temporary fixtures. Candidate workflow tests additionally instantiate the real API `createServer` with an explicitly temporary `CognitiveStore`, private stores disabled, isolated receipts, and telemetry disabled. They never start the daemon on 4780, use the repository's original store, touch real ledger/vault data or use cloud services. Coverage includes exact wire transmission of compile evidence/options and SDK default compile -> invisible candidate -> authorized promotion -> resolver visibility, persistence reload, negative authority/forged identity/cross-tenant cases, ingest receipt activity and scope, candidate endpoint encoding and no retries/cache. Existing coverage includes two origins and two identities sharing one directory, dynamic environment URL changes, canonical fields, budgets, 401/403 invalidation, 400/404, 500, timeout before headers and during body, network disconnect, TTL, legacy exclusion, malformed JSON, write failure, symlinks and metadata.
95
+
96
+ An initial macOS arm64 local run measured configured 80ms timeout at 80.29ms before headers and 81.60ms during body. Cold online resolve plus cache write was 1.08ms and warm HTTP500 plus fallback was 0.62ms. These are single loopback observations of different paths, not evidence of a throughput improvement or a comparative performance claim. The suite prints fresh measurements on every run.
@@ -0,0 +1,63 @@
1
+ # CognitiveStore persistence contract
2
+
3
+ ## Validated direct writes
4
+
5
+ `saveArtifact(type, id, content)` accepts `bytecode`, `skill`, or `map`. Bytecode is a schema-valid object or YAML document whose embedded ID equals the requested ID. Tenant/role bytecodes require a tenant. Skill and map are nonempty Markdown strings. A map's optional `tenant:` header must equal its requested ID. Unknown types, invalid IDs and invalid content throw before changing disk or memory.
6
+
7
+ New filenames encode the complete UTF-8 ID as lowercase hex with a reserved `__cbc_id_` prefix. Thus `a:b` and `a/b` do not collide, including on case-insensitive filesystems. IDs can include slashes as data, never as paths. IDs are bounded to 96 UTF-8 bytes and reject controls and malformed Unicode. Existing legacy filenames remain supported. Updating a loaded artifact retains its original file and root, including private roots. No automatic rename, deletion, quarantine or migration occurs. Duplicate IDs within a root are reported as integrity errors. Private roots retain their precedence over the public root.
8
+
9
+ Writes use an exclusive temporary file in the destination directory, write all bytes, fsync the file, close it, and atomically rename it over the destination. Only then is the memory entry replaced. Write, fsync and rename failures leave the previous entry and destination intact. File digests derive from persisted bytes. Bytecode inputs are parsed into detached objects, so caller mutation does not change the stored object. Readers should treat returned approved entries as read-only.
10
+
11
+ Existing path components, including configured roots, must not be symlinks. Configure physical paths (for macOS temporary directories, use `fs.realpathSync`). The directories must be owned by the service account and not writable by untrusted processes. Symlink checks do not constitute a sandbox against a malicious local process concurrently replacing directory components.
12
+
13
+ Explicit `storeDir` disables the default private root unless `privateDirs` is supplied. Otherwise the default is `~/.cognitivebc/private-store`; `COGNITIVEBC_PRIVATE_STORE` accepts path-delimited roots or `off`.
14
+
15
+ ## Private candidate API
16
+
17
+ ```js
18
+ const metadata = store.saveCandidate({
19
+ artifacts: {
20
+ bytecode_artifact: tenantScopedBytecode, // object or YAML
21
+ skill_artifact: '# Workflow', // optional, null accepted
22
+ map_artifact: 'tenant: tenant-a\n# Map' // optional, null accepted
23
+ },
24
+ scope: { level: 'tenant', tenant: 'tenant-a' },
25
+ evidence: { source: 'producer', eventId: 'stable-event-1' },
26
+ regime: 'pioneer_discovery'
27
+ });
28
+ store.getCandidate(metadata.id);
29
+ store.promoteCandidate(metadata.id, {
30
+ approvedBy: 'authenticated-reviewer-id',
31
+ scope: { level: 'tenant', tenant: 'tenant-a' }
32
+ });
33
+ ```
34
+
35
+ Compiler wrappers are also accepted: `skill_artifact: {frontmatter, content}` becomes Markdown with YAML frontmatter, and `map_artifact: {tenant, content, ...}` becomes tenant-header Markdown. Skill lookup uses the bytecode ID. Map lookup uses the origin tenant. Wrapper metadata other than skill frontmatter, map tenant and Markdown content is not published. The bytecode must already be scoped to the origin tenant, not a global compiler default. The API layer is responsible for applying the authorized origin scope before calling storage.
36
+
37
+ Origin tenant, a nonempty evidence object/array, and a nonempty regime are mandatory. Storage validates shape and consistency, not truth of evidence. Qualification of evidence and authenticated authorization belong to the caller/service policy. IDs are SHA-256 of canonicalized normalized artifact content, origin scope, evidence and regime, independent of key insertion order and candidate creation time. Replay of the same content and evidence returns the existing record, including an already promoted record. A compiler output that embeds changing timestamps or generated IDs is different content: producers must stabilize those inputs for replay.
38
+
39
+ Records use `cognitivebc/candidate-v1` under `<storeDir>/.candidates/<candidate_id>.json`, with directory mode 0700 when created and file mode 0600. They are private data even when storeDir is the public store. **Do not version, package, export or serve `.candidates`.** Packaging and HTTP authorization must enforce this separately. Records contain inline artifacts, never caller-selected paths. `getCandidate` checks ID grammar, schema, content hash, filename, origin consistency and promotion history. This is integrity checking, not a cryptographic signature against local account compromise.
40
+
41
+ Unapproved candidates are excluded from all approved store collections and therefore from resolver inputs, including after restart. Global/shared promotion is denied by default even with `sanitized: true`: no sanitization/eligibility policy has been established. Cross-tenant promotion is always denied. Promotion requires explicit `approvedBy` and target tenant scope; the service must obtain `approvedBy` from authenticated authority, not trust an arbitrary request field. Successful promotion records version 2 with reviewer, target and timestamp in history. Initial candidates are version 1.
42
+
43
+ ## Atomic bundle publication
44
+
45
+ The private record is the bundle manifest and commit point. Bytecode, skill and map are validated together before the single manifest rename changes status to `promoted`. Approved entries are installed together only after that rename. Restart loads the entire promoted bundle from this manifest. Every published entry carries the origin `scope` metadata, including skills and maps, so authorization can recognize the owning tenant both immediately and after reload. No independent skill/map/bytecode file writes can leave a partially published bundle. Promoted bundle entries remain private and are excluded from public export helpers.
46
+
47
+ Publication refuses any conflict with an existing approved ID, including map tenant keys; it never implicitly replaces approved knowledge. Published bundles are immutable through `saveArtifact`. Supersession of an existing bundle or merge into an existing tenant map needs a separately designed reviewed revision protocol. This conservative rule is intentional, not an automatic migration.
48
+
49
+ Candidate writes and promotions use an exclusive `.candidates/.write-lock`. A concurrent operation fails with `EEXIST` rather than racing. Promotion also checks a fresh disk snapshot for conflicts, preventing a stale in-memory instance from replacing a bundle published by another instance. Direct `saveArtifact` callers must use a single writer; it is a compatibility API, not the reviewed publication path. Do not mix direct artifact mutation concurrently with candidate promotion. A process crash can leave `.write-lock`; stop/verify all writers and inspect the store before manually removing a stale lock. The loader never deletes or quarantines it automatically.
50
+
51
+ Atomic rename guarantees process-failure consistency on a local filesystem. File fsync is used, but parent directory fsync and platform-specific full hardware synchronization are not performed. Power-loss durability across all OS/filesystem combinations and hostile concurrent local filesystem writers are not claimed. Failed pre-rename writes can leave no approved state; crash-orphaned temporary files are ignored, not deleted on reload.
52
+
53
+ ## Readiness and verification
54
+
55
+ `loadAll()` returns counts, `privateRoots`, `integrity`, and `errors: [{file, message, code}]`. `store.loadErrors` exposes the same diagnostics. Syntax, schema, duplicate, permission, symlink and corrupt manifest failures set integrity false while valid entries remain available. A service must not declare readiness merely because loading completed or counts are nonzero. Use `integrity === true` and the service's authorization/configuration checks. Missing optional directories are not integrity failures. No rejected file is removed.
56
+
57
+ Run only the isolated original-module regression file:
58
+
59
+ ```sh
60
+ node --test test/store-integrity.test.js
61
+ ```
62
+
63
+ The tests use synthetic fixtures and temporary physical directories, inject ENOSPC/fsync/rename failures, exercise original store and resolver modules, and cover validation, collisions, traversal, legacy private destinations, replay, approval, cross-tenant/global refusal, conflicts, structured compiler output, visibility and restart. They never start the daemon or touch operational stores. This does not replace deployment, real-consumer, crash/power-loss or multiprocess stress acceptance.