@semacode/cli 2.3.0 → 2.3.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 (177) hide show
  1. package/LICENSE +39 -39
  2. package/README.md +251 -228
  3. package/dist/agentEntryPoints.js +551 -550
  4. package/dist/angular-consumer-standalone.d.ts +3 -1
  5. package/dist/angular-consumer-standalone.js +12 -8
  6. package/dist/drift.part01.d.ts +32 -2
  7. package/dist/drift.part01.js +2 -0
  8. package/dist/drift.part04.d.ts +3 -2
  9. package/dist/drift.part04.js +6 -3
  10. package/dist/drift.part05.d.ts +2 -1
  11. package/dist/drift.part05.js +4 -3
  12. package/dist/drift.part06.d.ts +2 -1
  13. package/dist/drift.part06.js +9 -5
  14. package/dist/drift.part07.d.ts +11 -10
  15. package/dist/drift.part07.js +40 -30
  16. package/dist/drift.part08.d.ts +2 -1
  17. package/dist/drift.part08.js +4 -3
  18. package/dist/drift.part11.js +71 -6
  19. package/dist/drift.part12.js +14 -1
  20. package/dist/drift.part13.d.ts +42 -7
  21. package/dist/drift.part13.js +660 -36
  22. package/dist/driftCache.d.ts +49 -0
  23. package/dist/driftCache.js +311 -0
  24. package/dist/driftCacheIncremental.d.ts +98 -0
  25. package/dist/driftCacheIncremental.js +596 -0
  26. package/dist/driftCatalogo.d.ts +91 -0
  27. package/dist/driftCatalogo.js +657 -0
  28. package/dist/driftCatalogoPersistente.d.ts +8 -0
  29. package/dist/driftCatalogoPersistente.js +77 -0
  30. package/dist/driftEscopo.d.ts +23 -0
  31. package/dist/driftEscopo.js +563 -0
  32. package/dist/driftEscopoReferencias.d.ts +4 -0
  33. package/dist/driftEscopoReferencias.js +265 -0
  34. package/dist/driftOrcamento.d.ts +12 -0
  35. package/dist/driftOrcamento.js +19 -3
  36. package/dist/execucoesExternas.js +5 -19
  37. package/dist/iaPrompts.js +310 -310
  38. package/dist/index.part01.d.ts +16 -1
  39. package/dist/index.part01.js +80 -4
  40. package/dist/index.part02.js +21 -21
  41. package/dist/index.part03.d.ts +2 -2
  42. package/dist/index.part03.js +14 -3
  43. package/dist/index.part04.d.ts +2 -2
  44. package/dist/index.part04.js +113 -101
  45. package/dist/index.part05.d.ts +1 -1
  46. package/dist/index.part05.js +99 -22
  47. package/dist/index.part06.js +3 -2
  48. package/dist/index.part07.js +24 -24
  49. package/dist/index.part08.js +1 -1
  50. package/dist/init/templates.part01.js +393 -393
  51. package/dist/init/templates.part02.js +189 -189
  52. package/dist/initTemplatesBackend.js +73 -73
  53. package/dist/initTemplatesBase.js +81 -81
  54. package/dist/initTemplatesFlutter.js +137 -137
  55. package/dist/initTemplatesRuntime.js +350 -350
  56. package/dist/initTemplatesWeb.js +309 -309
  57. package/dist/pipelineConteudo/command.js +1 -36
  58. package/dist/projeto.d.ts +1 -1
  59. package/dist/projetoCarregar.d.ts +2 -2
  60. package/dist/projetoCarregar.js +47 -24
  61. package/dist/projetoCatalogo.d.ts +7 -0
  62. package/dist/projetoCatalogo.js +125 -0
  63. package/dist/projetoTipos.d.ts +14 -5
  64. package/dist/sync/index.js +35 -35
  65. package/docs/README.md +34 -34
  66. package/docs/ai-integration.md +1 -7
  67. package/docs/ai-onboarding.md +62 -62
  68. package/docs/ai-workflow.md +4 -0
  69. package/docs/auth.md +26 -26
  70. package/docs/cli.md +79 -79
  71. package/docs/commands.md +16 -13
  72. package/docs/database.md +15 -15
  73. package/docs/deploy.md +41 -41
  74. package/docs/descoberta-capacidades.md +106 -106
  75. package/docs/documentation.md +37 -46
  76. package/docs/env.md +16 -16
  77. package/docs/frontend.md +41 -41
  78. package/docs/getting-started.md +57 -57
  79. package/docs/i18n.md +15 -15
  80. package/docs/pipeline-conteudo.md +246 -246
  81. package/docs/profiles.md +54 -54
  82. package/docs/repositories.md +43 -43
  83. package/docs/rollback.md +31 -31
  84. package/docs/security.md +32 -32
  85. package/docs/sistemas-interativos.md +373 -378
  86. package/docs/support.md +8 -8
  87. package/docs/testing.md +51 -44
  88. package/docs/vocabulary.md +29 -29
  89. package/exemplos/agendamento.sema +1 -1
  90. package/exemplos/assinatura.sema +1 -1
  91. package/exemplos/auditoria.sema +1 -1
  92. package/exemplos/autenticacao.sema +1 -1
  93. package/exemplos/author_obra_comum.sema +1 -1
  94. package/exemplos/author_tema_sensivel.sema +1 -1
  95. package/exemplos/automacao.sema +1 -1
  96. package/exemplos/cadastro_usuario.sema +1 -1
  97. package/exemplos/calculadora.sema +1 -1
  98. package/exemplos/crud_simples.sema +1 -1
  99. package/exemplos/estoque.sema +1 -1
  100. package/exemplos/exportacao.sema +1 -1
  101. package/exemplos/fila.sema +1 -1
  102. package/exemplos/integracao_externa.sema +1 -1
  103. package/exemplos/multi_tenant.sema +1 -1
  104. package/exemplos/notificacao.sema +1 -1
  105. package/exemplos/operacao_estrategia.sema +132 -132
  106. package/exemplos/operacao_estrategia_discovery.sema +220 -220
  107. package/exemplos/operacao_estrategia_fluxo.sema +114 -114
  108. package/exemplos/operacao_estrategia_gates.sema +106 -106
  109. package/exemplos/operacao_estrategia_quarentena.sema +133 -133
  110. package/exemplos/operacao_estrategia_rollout.sema +124 -124
  111. package/exemplos/pagamento.sema +1 -1
  112. package/exemplos/pagamento_dominio.sema +1 -1
  113. package/exemplos/pedido.sema +1 -1
  114. package/exemplos/permissao.sema +1 -1
  115. package/exemplos/persistencia_vendor_first.sema +1 -1
  116. package/exemplos/pipeline-conteudo/README.md +44 -44
  117. package/exemplos/pipeline-conteudo/alvos.json +23 -23
  118. package/exemplos/pipeline-conteudo/definicao.json +136 -136
  119. package/exemplos/profile_conversas.sema +165 -165
  120. package/exemplos/profile_game.sema +1 -1
  121. package/exemplos/profile_legal.sema +1 -1
  122. package/exemplos/profile_ops.sema +1 -1
  123. package/exemplos/profile_research.sema +1 -1
  124. package/exemplos/profile_simulation.sema +211 -211
  125. package/exemplos/profile_software.sema +1 -1
  126. package/exemplos/profile_workflow_n8n.sema +1 -1
  127. package/exemplos/relatorio.sema +1 -1
  128. package/exemplos/replica_analitica_erp.sema +1 -1
  129. package/exemplos/sistemas-interativos/README.md +100 -100
  130. package/exemplos/sistemas-interativos/advanced/acceptance-context-evaluate-valid.json +5 -5
  131. package/exemplos/sistemas-interativos/advanced/acceptance-lock-valid.json +16 -16
  132. package/exemplos/sistemas-interativos/advanced/asset-provenance-valid.json +32 -32
  133. package/exemplos/sistemas-interativos/advanced/autonomy-repair-valid.json +93 -93
  134. package/exemplos/sistemas-interativos/advanced/control-run-definition-valid.json +78 -78
  135. package/exemplos/sistemas-interativos/advanced/control-run-valid.json +27 -27
  136. package/exemplos/sistemas-interativos/advanced/distributed-workers-valid.json +79 -79
  137. package/exemplos/sistemas-interativos/advanced/editor-state-valid.json +42 -42
  138. package/exemplos/sistemas-interativos/advanced/engine-snapshot-after-valid.json +32 -32
  139. package/exemplos/sistemas-interativos/advanced/engine-snapshot-before-valid.json +23 -23
  140. package/exemplos/sistemas-interativos/advanced/job-orchestration-valid.json +39 -39
  141. package/exemplos/sistemas-interativos/advanced/multimodal-evidence-valid.json +46 -46
  142. package/exemplos/sistemas-interativos/advanced/multiplayer-authority-valid.json +39 -39
  143. package/exemplos/sistemas-interativos/advanced/playtest-fuzz-valid.json +37 -37
  144. package/exemplos/sistemas-interativos/advanced/portability-valid.json +104 -104
  145. package/exemplos/sistemas-interativos/advanced/temporal-evidence-valid.json +27 -27
  146. package/exemplos/sistemas-interativos/advanced/temporal-valid.json +118 -118
  147. package/exemplos/sistemas-interativos/experience-ir-valid.json +459 -459
  148. package/exemplos/sistemas-interativos/game-2d.json +83 -83
  149. package/exemplos/sistemas-interativos/game-3d-human.json +81 -81
  150. package/exemplos/sistemas-interativos/game-pixel-16-bit.json +97 -97
  151. package/exemplos/sistemas-interativos/game-pixel-8-bit.json +94 -94
  152. package/exemplos/sistemas-interativos/game-xr-human.json +80 -80
  153. package/exemplos/sistemas-interativos/hybrid-2-5d.json +108 -108
  154. package/exemplos/sistemas-interativos/protocol-mutating-rollback-valid.json +75 -75
  155. package/exemplos/sistemas-interativos/protocol-read-only-valid.json +58 -58
  156. package/exemplos/sistemas-interativos/simulation-2d-controlled.json +97 -97
  157. package/exemplos/sistemas-interativos/simulation-3d-calibrated-autonomous.json +141 -141
  158. package/exemplos/sistemas-interativos/simulation-headless-autonomous-batch.json +112 -112
  159. package/exemplos/sistemas-interativos/simulation-pixel-16-bit.json +103 -103
  160. package/exemplos/sistemas-interativos/simulation-text-controlled.json +95 -95
  161. package/exemplos/testes_embutidos.sema +1 -1
  162. package/exemplos/tratamento_erro.sema +1 -1
  163. package/exemplos/upload_arquivo.sema +1 -1
  164. package/exemplos/webhook.sema +1 -1
  165. package/node_modules/@sema/gerador-cpp/dist/index.js +176 -176
  166. package/node_modules/@sema/gerador-cpp/package.json +1 -1
  167. package/node_modules/@sema/gerador-css/dist/index.part01.js +10 -10
  168. package/node_modules/@sema/gerador-css/dist/index.part02.js +460 -460
  169. package/node_modules/@sema/gerador-dotnet/dist/index.js +169 -169
  170. package/node_modules/@sema/gerador-dotnet/package.json +1 -1
  171. package/node_modules/@sema/gerador-html/dist/index.js +17 -17
  172. package/node_modules/@sema/gerador-lua/dist/index.js +51 -51
  173. package/node_modules/@sema/gerador-php/dist/index.js +113 -113
  174. package/node_modules/@sema/gerador-python/dist/index.part02.js +3 -3
  175. package/node_modules/@sema/gerador-typescript/dist/index.part02.js +11 -11
  176. package/node_modules/@sema/nucleo/dist/diagnosticos/melhorador.js +42 -42
  177. package/package.json +3 -3
@@ -26,7 +26,6 @@ const OPCOES_COM_VALOR_CONTEUDO = new Set([
26
26
  "--revocation-digest",
27
27
  ]);
28
28
  const SUBCOMANDOS_CONTEUDO = new Set([
29
- "ajuda",
30
29
  "capabilities",
31
30
  "validar",
32
31
  "planejar",
@@ -35,36 +34,6 @@ const SUBCOMANDOS_CONTEUDO = new Set([
35
34
  "status",
36
35
  "projetar",
37
36
  ]);
38
- const USOS_PIPELINE_CONTEUDO = [
39
- "sema conteudo capabilities --json",
40
- "sema conteudo validar <definition.json> --json",
41
- "sema conteudo planejar <definition.json> --alvos-arquivo <targets.json> --json",
42
- "sema conteudo validar-envelope --envelope-arquivo <envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --payload-type <type> --json",
43
- "sema conteudo registrar <ledger.ndjson> --envelope-arquivo <envelope.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-id <id> --expected-head <sha256:...> --json",
44
- "sema conteudo status <definition.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-arquivo <ledger.ndjson> --expected-head <sha256:...> --json",
45
- "sema conteudo projetar <definition.json> --politica-arquivo <policy-envelope.json> --confianca-arquivo <trust.json> --trust-root-digest <sha256:...> --revocation-digest <sha256:...> --ledger-arquivo <ledger.ndjson> --expected-head <sha256:...> --saida <manifest.json> --json",
46
- ];
47
- function ajudaPipelineConteudo() {
48
- const mensagem = [
49
- "Sema Content Pipeline — controle AI-native multicanal e multiformato.",
50
- "",
51
- "Uso:",
52
- ...USOS_PIPELINE_CONTEUDO.map((uso) => ` ${uso}`),
53
- "",
54
- "O runner é externo e avança somente pelos nextActions derivados pelo Sema.",
55
- "Evidências entram como envelopes assinados; vereditos e transições não são escritos manualmente.",
56
- "Não existe revisão humana nativa. Chaves privadas permanecem nos processos signatários independentes.",
57
- ].join("\n");
58
- return {
59
- sucesso: true,
60
- comando: "ajuda",
61
- mensagem,
62
- usos: USOS_PIPELINE_CONTEUDO,
63
- nativeHumanReview: false,
64
- runner: "external",
65
- canonicalState: "signed_hash_chained_ledger",
66
- };
67
- }
68
37
  const CAUSAS_PUBLICAS_CONTEUDO = [
69
38
  "expected_head_divergente",
70
39
  "trust_root_digest_divergente",
@@ -394,15 +363,11 @@ async function registrarEnvelopeLocal(args, ledgerArquivo) {
394
363
  }
395
364
  export async function comandoPipelineConteudo(_posicionaisGlobais, args, emJson) {
396
365
  const posicionais = posicionaisConteudo(args);
397
- const solicitouAjuda = args.includes("--help") || args.includes("-h") || posicionais[0] === "help" || posicionais[0] === "ajuda";
398
- const subcomando = solicitouAjuda ? "ajuda" : posicionais[0] ?? "capabilities";
366
+ const subcomando = posicionais[0] ?? "capabilities";
399
367
  const comandoPublico = SUBCOMANDOS_CONTEUDO.has(subcomando) ? subcomando : "desconhecido";
400
368
  try {
401
369
  let payload;
402
370
  switch (subcomando) {
403
- case "ajuda":
404
- payload = ajudaPipelineConteudo();
405
- break;
406
371
  case "capabilities":
407
372
  payload = {
408
373
  sucesso: true,
package/dist/projeto.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { ConfiguracaoPersistenciaProjeto, ConfiguracaoProjetoCarregada, ContextoProjetoCarregado, SemaConfigProjeto, } from './projetoTipos.js';
1
+ export type { ConfiguracaoPersistenciaProjeto, ConfiguracaoProjetoCarregada, ContextoProjetoCarregado, EscopoCarregamentoProjeto, ModuloProjetoCarregado, OpcoesCarregarProjeto, SemaConfigProjeto, } from './projetoTipos.js';
2
2
  export { carregarConfiguracaoProjeto, localizarConfiguracaoProjeto, normalizarEstruturaSaida, normalizarFrameworkGeracao, } from './projetoConfig.js';
3
3
  export { carregarProjeto } from './projetoCarregar.js';
4
4
  export { resolverAlvoPadrao, resolverAlvosVerificacao, resolverEstruturaSaidaPadrao, resolverFrameworkPadrao, resolverSaidaPadrao, } from './projetoResolucao.js';
@@ -1,2 +1,2 @@
1
- import type { ContextoProjetoCarregado } from './projetoTipos.js';
2
- export declare function carregarProjeto(entrada: string | undefined, cwd: string): Promise<ContextoProjetoCarregado>;
1
+ import type { ContextoProjetoCarregado, OpcoesCarregarProjeto } from './projetoTipos.js';
2
+ export declare function carregarProjeto(entrada: string | undefined, cwd: string, opcoes?: OpcoesCarregarProjeto): Promise<ContextoProjetoCarregado>;
@@ -2,49 +2,72 @@
2
2
  // Descrição: orquestra leitura de contratos, compila??o e sele??o de m?dulos do projeto.
3
3
  import { stat } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
- import { compilarProjeto, lerArquivoTexto, listarArquivosSema } from '@sema/nucleo';
5
+ import { compilarProjeto, listarArquivosSema } from '@sema/nucleo';
6
+ import { carregarFechamentoContratosSema, carregarFontesContratos } from './projetoCatalogo.js';
6
7
  import { carregarConfiguracaoProjeto, normalizarModoAdocao } from './projetoConfig.js';
7
8
  import { inferirFontesLegado } from './projetoLegado.js';
8
9
  import { inferirDiretoriosCodigo, listarArquivosDeOrigens, resolverBaseProjeto, resolverEntradaPadrao, resolverOrigensProjeto, } from './projetoOrigens.js';
9
- export async function carregarProjeto(entrada, cwd) {
10
+ export async function carregarProjeto(entrada, cwd, opcoes = {}) {
10
11
  const entradaBase = entrada ? path.resolve(cwd, entrada) : cwd;
11
12
  const configCarregada = await carregarConfiguracaoProjeto(entradaBase);
12
13
  const entradaResolvida = entrada ? path.resolve(cwd, entrada) : await resolverEntradaPadrao(cwd, configCarregada);
13
14
  const baseProjeto = await resolverBaseProjeto(entradaResolvida, configCarregada);
14
15
  const infoEntrada = await stat(entradaResolvida);
15
- const origensProjeto = await resolverOrigensProjeto(baseProjeto, entradaResolvida, configCarregada);
16
- const arquivosProjeto = await listarArquivosDeOrigens(origensProjeto);
17
- const diretoriosCodigo = await inferirDiretoriosCodigo(baseProjeto, configCarregada);
18
- const fontesLegado = await inferirFontesLegado(diretoriosCodigo, baseProjeto, configCarregada);
19
- const modoAdocao = normalizarModoAdocao(configCarregada?.config.modoAdocao);
20
- const arquivosSelecionados = infoEntrada.isFile()
21
- ? new Set([path.resolve(entradaResolvida)])
22
- : new Set((configCarregada && path.resolve(entradaResolvida) === path.resolve(configCarregada.baseDiretorio)
23
- ? arquivosProjeto
24
- : await listarArquivosSema(entradaResolvida)).map((arquivo) => path.resolve(arquivo)));
25
- const fontes = [];
26
- for (const arquivo of arquivosProjeto) {
27
- const codigo = await lerArquivoTexto(arquivo);
28
- fontes.push({ caminho: arquivo, codigo });
16
+ const escopo = opcoes.escopo ?? (infoEntrada.isFile() ? "modulo" : "projeto");
17
+ const carregarProjetoCompleto = !infoEntrada.isFile() || escopo === "projeto";
18
+ const origensBase = infoEntrada.isFile()
19
+ ? await resolverOrigensProjeto(baseProjeto, baseProjeto, configCarregada)
20
+ : await resolverOrigensProjeto(baseProjeto, entradaResolvida, configCarregada);
21
+ const origensProjeto = [...new Set([
22
+ ...origensBase,
23
+ ...(infoEntrada.isFile() ? [path.dirname(entradaResolvida)] : []),
24
+ ].map((origem) => path.resolve(origem)))]
25
+ .sort((a, b) => a.localeCompare(b, "pt-BR"));
26
+ const arquivosDescobertosSet = new Set(await listarArquivosDeOrigens(origensProjeto));
27
+ if (infoEntrada.isFile()) {
28
+ arquivosDescobertosSet.add(path.resolve(entradaResolvida));
29
29
  }
30
+ const arquivosDescobertos = [...arquivosDescobertosSet]
31
+ .sort((a, b) => a.localeCompare(b, "pt-BR"));
32
+ const possuiDiretoriosCodigoExplicitos = Boolean(configCarregada?.config.diretoriosCodigo?.length);
33
+ const possuiFontesLegadoExplicitas = Boolean(configCarregada?.config.fontesLegado?.length);
34
+ const diretoriosCodigo = carregarProjetoCompleto || possuiDiretoriosCodigoExplicitos
35
+ ? await inferirDiretoriosCodigo(baseProjeto, configCarregada)
36
+ : [];
37
+ const fontesLegado = carregarProjetoCompleto || possuiFontesLegadoExplicitas
38
+ ? await inferirFontesLegado(diretoriosCodigo, baseProjeto, configCarregada)
39
+ : [];
40
+ const modoAdocao = normalizarModoAdocao(configCarregada?.config.modoAdocao);
41
+ const arquivosSelecionados = carregarProjetoCompleto && escopo === "projeto"
42
+ ? new Set(arquivosDescobertos.map((arquivo) => path.resolve(arquivo)))
43
+ : infoEntrada.isFile()
44
+ ? new Set([path.resolve(entradaResolvida)])
45
+ : new Set((configCarregada && path.resolve(entradaResolvida) === path.resolve(configCarregada.baseDiretorio)
46
+ ? arquivosDescobertos
47
+ : await listarArquivosSema(entradaResolvida)).map((arquivo) => path.resolve(arquivo)));
48
+ const fontes = carregarProjetoCompleto
49
+ ? await carregarFontesContratos(arquivosDescobertos)
50
+ : (await carregarFechamentoContratosSema([entradaResolvida], arquivosDescobertos)).fontes;
30
51
  const resultadoProjeto = compilarProjeto(fontes);
31
52
  const resultados = new Map(resultadoProjeto.modulos.map((modulo) => [path.resolve(modulo.caminho), modulo]));
53
+ const modulosCarregados = fontes.map((fonte) => ({
54
+ caminho: fonte.caminho,
55
+ codigo: fonte.codigo,
56
+ resultado: resultados.get(path.resolve(fonte.caminho)),
57
+ }));
32
58
  return {
33
59
  entradaResolvida,
34
60
  baseProjeto,
35
61
  configCarregada,
36
- arquivosProjeto,
62
+ arquivosProjeto: fontes.map((fonte) => fonte.caminho),
63
+ arquivosDescobertos,
37
64
  origensProjeto,
38
65
  diretoriosCodigo,
39
66
  fontesLegado,
40
67
  modoAdocao,
41
- modulosSelecionados: fontes
42
- .filter((fonte) => arquivosSelecionados.has(path.resolve(fonte.caminho)))
43
- .map((fonte) => ({
44
- caminho: fonte.caminho,
45
- codigo: fonte.codigo,
46
- resultado: resultados.get(path.resolve(fonte.caminho)),
47
- })),
68
+ modulosCarregados,
69
+ modulosSelecionados: modulosCarregados
70
+ .filter((modulo) => arquivosSelecionados.has(path.resolve(modulo.caminho))),
48
71
  };
49
72
  }
50
73
  //# sourceMappingURL=projetoCarregar.js.map
@@ -0,0 +1,7 @@
1
+ import { type FonteProjeto } from "@sema/nucleo";
2
+ export interface FechamentoContratosSema {
3
+ fontes: FonteProjeto[];
4
+ dependenciasNaoResolvidas: string[];
5
+ }
6
+ export declare function carregarFontesContratos(arquivos: string[]): Promise<FonteProjeto[]>;
7
+ export declare function carregarFechamentoContratosSema(arquivosAlvo: string[], arquivosDescobertos: string[]): Promise<FechamentoContratosSema>;
@@ -0,0 +1,125 @@
1
+ // SEMA-GOVERNED: sema.produto.governanca_ia.contexto
2
+ // Descricao: descobre contratos por caminho e carrega apenas o fechamento transitivo de uses do alvo.
3
+ import path from "node:path";
4
+ import { lerArquivoTexto, parsear, tokenizar, } from "@sema/nucleo";
5
+ function normalizarChaveArquivo(valor) {
6
+ return valor
7
+ .normalize("NFD")
8
+ .replace(/[\u0300-\u036f]/g, "")
9
+ .toLowerCase()
10
+ .replace(/[^a-z0-9]+/g, "_")
11
+ .replace(/^_+|_+$/g, "");
12
+ }
13
+ function chavesSufixoModulo(nomeModulo) {
14
+ const partes = nomeModulo.split(".").map(normalizarChaveArquivo).filter(Boolean);
15
+ return partes.map((_, indice) => partes.slice(indice).join("_"));
16
+ }
17
+ function criarIndiceSufixos(arquivos) {
18
+ const indice = new Map();
19
+ for (const arquivo of arquivos) {
20
+ const chave = normalizarChaveArquivo(path.basename(arquivo, path.extname(arquivo)));
21
+ const atuais = indice.get(chave) ?? [];
22
+ atuais.push(path.resolve(arquivo));
23
+ indice.set(chave, atuais);
24
+ }
25
+ for (const caminhos of indice.values()) {
26
+ caminhos.sort((a, b) => a.localeCompare(b, "pt-BR"));
27
+ }
28
+ return indice;
29
+ }
30
+ export async function carregarFontesContratos(arquivos) {
31
+ const fontes = [];
32
+ for (const arquivo of arquivos) {
33
+ const caminho = path.resolve(arquivo);
34
+ fontes.push({ caminho, codigo: await lerArquivoTexto(caminho) });
35
+ }
36
+ return fontes;
37
+ }
38
+ export async function carregarFechamentoContratosSema(arquivosAlvo, arquivosDescobertos) {
39
+ const descobertos = [...new Set(arquivosDescobertos.map((arquivo) => path.resolve(arquivo)))]
40
+ .sort((a, b) => a.localeCompare(b, "pt-BR"));
41
+ const indiceSufixos = criarIndiceSufixos(descobertos);
42
+ const leituras = new Map();
43
+ const caminhoPorModulo = new Map();
44
+ const lerContrato = (arquivo) => {
45
+ const caminho = path.resolve(arquivo);
46
+ const existente = leituras.get(caminho);
47
+ if (existente) {
48
+ return existente;
49
+ }
50
+ const leitura = (async () => {
51
+ const codigo = await lerArquivoTexto(caminho);
52
+ const resultadoLexer = tokenizar(codigo, caminho);
53
+ const resultadoParser = parsear(resultadoLexer.tokens);
54
+ if (resultadoParser.modulo) {
55
+ caminhoPorModulo.set(resultadoParser.modulo.nome, caminho);
56
+ }
57
+ return {
58
+ fonte: { caminho, codigo },
59
+ modulo: resultadoParser.modulo,
60
+ };
61
+ })();
62
+ leituras.set(caminho, leitura);
63
+ return leitura;
64
+ };
65
+ const resolverArquivoModulo = async (nomeModulo) => {
66
+ const jaConhecido = caminhoPorModulo.get(nomeModulo);
67
+ if (jaConhecido) {
68
+ return jaConhecido;
69
+ }
70
+ const tentados = new Set();
71
+ for (const chave of chavesSufixoModulo(nomeModulo)) {
72
+ for (const candidato of indiceSufixos.get(chave) ?? []) {
73
+ tentados.add(candidato);
74
+ const contrato = await lerContrato(candidato);
75
+ if (contrato.modulo?.nome === nomeModulo) {
76
+ return candidato;
77
+ }
78
+ }
79
+ }
80
+ // Fallback raro para workspaces que nao seguem a convencao modulo -> nome do arquivo.
81
+ // Ele so acontece depois que todos os sufixos deterministas falharam.
82
+ for (const candidato of descobertos) {
83
+ if (tentados.has(candidato)) {
84
+ continue;
85
+ }
86
+ const contrato = await lerContrato(candidato);
87
+ if (contrato.modulo?.nome === nomeModulo) {
88
+ return candidato;
89
+ }
90
+ }
91
+ return undefined;
92
+ };
93
+ const fila = arquivosAlvo.map((arquivo) => path.resolve(arquivo));
94
+ const carregados = new Set();
95
+ const fontes = [];
96
+ const dependenciasNaoResolvidas = new Set();
97
+ while (fila.length > 0) {
98
+ const arquivo = fila.shift();
99
+ if (carregados.has(arquivo)) {
100
+ continue;
101
+ }
102
+ carregados.add(arquivo);
103
+ const contrato = await lerContrato(arquivo);
104
+ fontes.push(contrato.fonte);
105
+ const usesSema = contrato.modulo?.uses
106
+ .filter((use) => use.origem === "sema")
107
+ .map((use) => use.caminho) ?? [];
108
+ for (const use of usesSema) {
109
+ const dependencia = await resolverArquivoModulo(use);
110
+ if (!dependencia) {
111
+ dependenciasNaoResolvidas.add(use);
112
+ continue;
113
+ }
114
+ if (!carregados.has(dependencia)) {
115
+ fila.push(dependencia);
116
+ }
117
+ }
118
+ }
119
+ return {
120
+ fontes,
121
+ dependenciasNaoResolvidas: [...dependenciasNaoResolvidas]
122
+ .sort((a, b) => a.localeCompare(b, "pt-BR")),
123
+ };
124
+ }
125
+ //# sourceMappingURL=projetoCatalogo.js.map
@@ -1,6 +1,10 @@
1
1
  import type { EngineBanco, ResultadoCompilacaoProjetoModulo } from '@sema/nucleo';
2
2
  import type { AlvoGeracao, FrameworkGeracao } from '@sema/padroes';
3
3
  import type { EstruturaSaida, FonteLegado, ModoAdocao } from './tipos.js';
4
+ export type EscopoCarregamentoProjeto = "arquivo" | "modulo" | "projeto";
5
+ export interface OpcoesCarregarProjeto {
6
+ escopo?: EscopoCarregamentoProjeto;
7
+ }
4
8
  export interface ConfiguracaoPersistenciaProjeto {
5
9
  enginesHabilitados?: EngineBanco[];
6
10
  adaptersPorEngine?: Partial<Record<EngineBanco, string>>;
@@ -30,18 +34,23 @@ export interface ConfiguracaoProjetoCarregada {
30
34
  baseDiretorio: string;
31
35
  config: SemaConfigProjeto;
32
36
  }
37
+ export interface ModuloProjetoCarregado {
38
+ caminho: string;
39
+ codigo: string;
40
+ resultado: ResultadoCompilacaoProjetoModulo;
41
+ }
33
42
  export interface ContextoProjetoCarregado {
34
43
  entradaResolvida: string;
35
44
  baseProjeto: string;
36
45
  configCarregada?: ConfiguracaoProjetoCarregada;
46
+ /** Contratos efetivamente lidos e compilados nesta execucao. */
37
47
  arquivosProjeto: string[];
48
+ /** Contratos encontrados nas origens, inclusive os que ficaram fora do escopo carregado. */
49
+ arquivosDescobertos: string[];
38
50
  origensProjeto: string[];
39
51
  diretoriosCodigo: string[];
40
52
  fontesLegado: FonteLegado[];
41
53
  modoAdocao: ModoAdocao;
42
- modulosSelecionados: Array<{
43
- caminho: string;
44
- codigo: string;
45
- resultado: ResultadoCompilacaoProjetoModulo;
46
- }>;
54
+ modulosCarregados: ModuloProjetoCarregado[];
55
+ modulosSelecionados: ModuloProjetoCarregado[];
47
56
  }
@@ -46,25 +46,25 @@ export async function gerarSchemaPrisma(pastaContratos, saidaSchema, datasourceP
46
46
  for (const contrato of contratos) {
47
47
  const nomeModel = path.basename(contrato, '.sema').replace(/\./g, '_');
48
48
  // Schema simplificado - em producao, fazer parsing real do contrato
49
- models += `\nmodel ${nomeModel.charAt(0).toUpperCase() + nomeModel.slice(1)} {
50
- id String @id @default(uuid())
51
- criadoEm DateTime @default(now())
52
- // Gerado a partir de: ${contrato}
53
- // TODO: Adicionar campos do contrato Sema
49
+ models += `\nmodel ${nomeModel.charAt(0).toUpperCase() + nomeModel.slice(1)} {
50
+ id String @id @default(uuid())
51
+ criadoEm DateTime @default(now())
52
+ // Gerado a partir de: ${contrato}
53
+ // TODO: Adicionar campos do contrato Sema
54
54
  }\n`;
55
55
  modelCount++;
56
56
  }
57
- const schema = `// Gerado automaticamente pelo Sema
58
- // Fonte: ${pastaContratos}
59
-
60
- generator client {
61
- provider = "prisma-client-js"
62
- }
63
-
64
- datasource db {
65
- provider = "${datasourceProvider}"
66
- url = env("SEMA_PRISMA_URL")
67
- }
57
+ const schema = `// Gerado automaticamente pelo Sema
58
+ // Fonte: ${pastaContratos}
59
+
60
+ generator client {
61
+ provider = "prisma-client-js"
62
+ }
63
+
64
+ datasource db {
65
+ provider = "${datasourceProvider}"
66
+ url = env("SEMA_PRISMA_URL")
67
+ }
68
68
  ${models}`;
69
69
  // Salvar
70
70
  fs.writeFileSync(saidaSchema, schema, 'utf-8');
@@ -90,25 +90,25 @@ export async function importarSchemaPrisma(caminhoSchema, pastaSaida, nomeModulo
90
90
  const nomeContrato = `${nomeModel.toLowerCase()}.sema`;
91
91
  const caminhoContrato = path.join(pastaSaida, nomeContrato);
92
92
  // Gerar contrato basico
93
- const conteudo = `module ${nomeModulo}.${nomeModel.toLowerCase()} {
94
- entity ${nomeModel} {
95
- fields {
96
- id: Id
97
- // TODO: Mapear campos do schema Prisma
98
- }
99
- }
100
-
101
- task criar_${nomeModel.toLowerCase()} {
102
- input {
103
- // TODO: Definir inputs
104
- }
105
- output {
106
- ${nomeModel.toLowerCase()}: ${nomeModel}
107
- }
108
- effects {
109
- persistencia ${nomeModel}
110
- }
111
- }
93
+ const conteudo = `module ${nomeModulo}.${nomeModel.toLowerCase()} {
94
+ entity ${nomeModel} {
95
+ fields {
96
+ id: Id
97
+ // TODO: Mapear campos do schema Prisma
98
+ }
99
+ }
100
+
101
+ task criar_${nomeModel.toLowerCase()} {
102
+ input {
103
+ // TODO: Definir inputs
104
+ }
105
+ output {
106
+ ${nomeModel.toLowerCase()}: ${nomeModel}
107
+ }
108
+ effects {
109
+ persistencia ${nomeModel}
110
+ }
111
+ }
112
112
  }`;
113
113
  fs.writeFileSync(caminhoContrato, conteudo, 'utf-8');
114
114
  contratos.push(caminhoContrato);
package/docs/README.md CHANGED
@@ -1,34 +1,34 @@
1
- # Sema Documentation
2
-
3
- These docs describe the public Codex-native local CLI distribution of Sema.
4
-
5
- Sema is local-first: Codex runs the CLI inside a project folder, reads `.sema`
6
- contracts, checks drift, maps impact, and closes changes with documentation
7
- evidence. `AGENTS.md` is the official Codex entrypoint. Public docs are written
8
- in English.
9
-
10
- Sema is an independent product and is not affiliated with or endorsed by
11
- OpenAI. Codex-native describes Sema's product direction, not an official OpenAI
12
- program or submission.
13
-
14
- Start here:
15
-
16
- - [CLI](./cli.md)
17
- - [Commands](./commands.md)
18
- - [Syntax](./syntax.md)
19
- - [Profiles](./profiles.md)
20
- - [Capability Discovery](./descoberta-capacidades.md) — one explainable catalog
21
- for governance flows, profiles, specialized workflows, pipelines, generators,
22
- capability tokens, and adapters.
23
- - [AI-native Interactive Systems](./sistemas-interativos.md) — declarative
24
- control plane for games, simulations, and hybrids across 3D, 2D, retro,
25
- text, XR, and headless execution.
26
- - [AI-native Content Pipeline](./pipeline-conteudo.md) — signed-policy,
27
- multi-channel and multi-format orchestration for external AI runners, with
28
- canonical ledger replay and no native human-review path.
29
- - [Documentation Governance](./documentation.md)
30
- - [Repository Boundary](./repositories.md)
31
- - [Security](./security.md)
32
- - [Codex Integration](./ai-integration.md)
33
-
34
- Official support: [suporte@otimitare.online](mailto:suporte@otimitare.online)
1
+ # Sema Documentation
2
+
3
+ These docs describe the public Codex-native local CLI distribution of Sema.
4
+
5
+ Sema is local-first: Codex runs the CLI inside a project folder, reads `.sema`
6
+ contracts, checks drift, maps impact, and closes changes with documentation
7
+ evidence. `AGENTS.md` is the official Codex entrypoint. Public docs are written
8
+ in English.
9
+
10
+ Sema is an independent product and is not affiliated with or endorsed by
11
+ OpenAI. Codex-native describes Sema's product direction, not an official OpenAI
12
+ program or submission.
13
+
14
+ Start here:
15
+
16
+ - [CLI](./cli.md)
17
+ - [Commands](./commands.md)
18
+ - [Syntax](./syntax.md)
19
+ - [Profiles](./profiles.md)
20
+ - [Capability Discovery](./descoberta-capacidades.md) — one explainable catalog
21
+ for governance flows, profiles, specialized workflows, pipelines, generators,
22
+ capability tokens, and adapters.
23
+ - [AI-native Interactive Systems](./sistemas-interativos.md) — declarative
24
+ control plane for games, simulations, and hybrids across 3D, 2D, retro,
25
+ text, XR, and headless execution.
26
+ - [AI-native Content Pipeline](./pipeline-conteudo.md) — signed-policy,
27
+ multi-channel and multi-format orchestration for external AI runners, with
28
+ canonical ledger replay and no native human-review path.
29
+ - [Documentation Governance](./documentation.md)
30
+ - [Repository Boundary](./repositories.md)
31
+ - [Security](./security.md)
32
+ - [Codex Integration](./ai-integration.md)
33
+
34
+ Official support: [suporte@otimitare.online](mailto:suporte@otimitare.online)
@@ -73,12 +73,6 @@ Generated or governed code should keep a short `SEMA-GOVERNED` marker that
73
73
  points back to the applicable contract. The marker is not a substitute for
74
74
  validation, drift, impact, or finalization gates.
75
75
 
76
- Generated Lua tests preserve the contract's failure shape. A case whose only
77
- expectation is `sucesso: falso` may terminate without an output, while a case
78
- that also declares observable output fields must return a structured failure
79
- result. The generator keeps these paths distinct instead of forcing every
80
- failure into one representation.
81
-
82
76
  Governed code above 1000 lines requires a
83
77
  split plan. Governed code above 2000
84
78
  lines blocks closure. Markdown documentation is not counted as governed code
@@ -112,4 +106,4 @@ user-facing experience, closure requires evidence:
112
106
  ## Platform Policy
113
107
 
114
108
  Sema governs contract, scope, drift, evidence, and quality. It does not bypass
115
- platform policies, terms of use, permissions, security controls, or laws.
109
+ platform policies, terms of use, permissions, security controls, or laws.
@@ -1,62 +1,62 @@
1
- # Codex Onboarding
2
-
3
- The official Sema skill is required for Codex to recognize and initialize Sema
4
- before a project has its own protocol:
5
-
6
- ```bash
7
- codex plugin marketplace add gerlanss/Sema
8
- codex plugin add sema@sema
9
- ```
10
-
11
- Open a new Codex task in the target repository after installation. Codex loads
12
- the plugin/skill catalog at task start, so `$sema` is not added retroactively to
13
- an already-open task. Invoke `$sema` in the new task; it bootstraps the project,
14
- reads the generated `AGENTS.md`, and later tasks load that protocol
15
- automatically.
16
-
17
- `AGENTS.md` is the official Sema entrypoint for Codex. It gives Codex the durable
18
- repository rule that contracts come first and the local CLI is the source of
19
- truth. Once the file exists, the skill delegates to it instead of carrying a
20
- second copy of the governed workflow.
21
-
22
- Create or refresh the entrypoint with:
23
-
24
- ```bash
25
- sema sync-codex --json
26
- ```
27
-
28
- ## Minimal Prompt
29
-
30
- ```text
31
- This workspace is governed by Sema. Before editing code, contracts, docs,
32
- workflows, profiles, or release scripts, run:
33
-
34
- 1. sema --version
35
- 2. sema resumo
36
- 3. sema docs-impacto --intencao "<change>" --json
37
- 4. sema inspecionar on the applicable .sema contract
38
- 5. sema drift before editing existing code
39
- 6. sema impacto before changing behavior
40
- 7. sema finalizar-mudanca before closing
41
-
42
- If the CLI is unavailable, stop and install or repair @semacode/cli. There is
43
- no separate Sema login, license activation, or authorization gate. Do not
44
- replace Sema with manual search or guessed contracts.
45
- ```
46
-
47
- ## What Codex Should Not Do
48
-
49
- - Do not invent `.sema` contracts.
50
- - Do not implement code without an applicable contract.
51
- - Do not ignore severity 4+ warnings.
52
- - Do not publish private or sensitive operational material.
53
- - Do not replace the local CLI when the local workspace is available.
54
-
55
- Other AI clients can invoke the public CLI manually, but Sema does not ship or
56
- manage an official repository entrypoint for them. The supported product path
57
- is Codex plus `AGENTS.md`.
58
-
59
- Sema is an independent product and is not affiliated with or endorsed by
60
- OpenAI.
61
-
62
- Support: suporte@otimitare.online
1
+ # Codex Onboarding
2
+
3
+ The official Sema skill is required for Codex to recognize and initialize Sema
4
+ before a project has its own protocol:
5
+
6
+ ```bash
7
+ codex plugin marketplace add gerlanss/Sema
8
+ codex plugin add sema@sema
9
+ ```
10
+
11
+ Open a new Codex task in the target repository after installation. Codex loads
12
+ the plugin/skill catalog at task start, so `$sema` is not added retroactively to
13
+ an already-open task. Invoke `$sema` in the new task; it bootstraps the project,
14
+ reads the generated `AGENTS.md`, and later tasks load that protocol
15
+ automatically.
16
+
17
+ `AGENTS.md` is the official Sema entrypoint for Codex. It gives Codex the durable
18
+ repository rule that contracts come first and the local CLI is the source of
19
+ truth. Once the file exists, the skill delegates to it instead of carrying a
20
+ second copy of the governed workflow.
21
+
22
+ Create or refresh the entrypoint with:
23
+
24
+ ```bash
25
+ sema sync-codex --json
26
+ ```
27
+
28
+ ## Minimal Prompt
29
+
30
+ ```text
31
+ This workspace is governed by Sema. Before editing code, contracts, docs,
32
+ workflows, profiles, or release scripts, run:
33
+
34
+ 1. sema --version
35
+ 2. sema resumo
36
+ 3. sema docs-impacto --intencao "<change>" --json
37
+ 4. sema inspecionar on the applicable .sema contract
38
+ 5. sema drift before editing existing code
39
+ 6. sema impacto before changing behavior
40
+ 7. sema finalizar-mudanca before closing
41
+
42
+ If the CLI is unavailable, stop and install or repair @semacode/cli. There is
43
+ no separate Sema login, license activation, or authorization gate. Do not
44
+ replace Sema with manual search or guessed contracts.
45
+ ```
46
+
47
+ ## What Codex Should Not Do
48
+
49
+ - Do not invent `.sema` contracts.
50
+ - Do not implement code without an applicable contract.
51
+ - Do not ignore severity 4+ warnings.
52
+ - Do not publish private or sensitive operational material.
53
+ - Do not replace the local CLI when the local workspace is available.
54
+
55
+ Other AI clients can invoke the public CLI manually, but Sema does not ship or
56
+ manage an official repository entrypoint for them. The supported product path
57
+ is Codex plus `AGENTS.md`.
58
+
59
+ Sema is an independent product and is not affiliated with or endorsed by
60
+ OpenAI.
61
+
62
+ Support: suporte@otimitare.online