@semacode/cli 2.3.1 → 3.5.0

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 (281) hide show
  1. package/README.md +265 -217
  2. package/dist/agentContextPack.js +14 -10
  3. package/dist/agentEntryPoints.d.ts +5 -0
  4. package/dist/agentEntryPoints.js +592 -568
  5. package/dist/angular-consumer-standalone.js +1 -1
  6. package/dist/bin.d.ts +6 -0
  7. package/dist/bin.js +130 -0
  8. package/dist/cliArgs.js +4 -4
  9. package/dist/cliControlError.d.ts +12 -0
  10. package/dist/cliControlError.js +47 -0
  11. package/dist/cliGrammar.d.ts +11 -0
  12. package/dist/cliGrammar.js +551 -0
  13. package/dist/cliHelp.d.ts +13 -0
  14. package/dist/cliHelp.js +19 -0
  15. package/dist/cliHelpTexto.d.ts +3 -0
  16. package/dist/cliHelpTexto.js +168 -0
  17. package/dist/cliRuntime.d.ts +2 -0
  18. package/dist/cliRuntime.js +31 -0
  19. package/dist/comandos.js +9 -22
  20. package/dist/contexto.js +5 -5
  21. package/dist/dev/index.d.ts +1 -0
  22. package/dist/dev/index.js +51 -9
  23. package/dist/discovery/catalog.js +3 -3
  24. package/dist/distribuicao/filesystemGlobal.d.ts +63 -0
  25. package/dist/distribuicao/filesystemGlobal.js +701 -0
  26. package/dist/distribuicao/index.d.ts +7 -0
  27. package/dist/distribuicao/index.js +227 -0
  28. package/dist/distribuicao/launcherGlobal.d.ts +53 -0
  29. package/dist/distribuicao/launcherGlobal.js +643 -0
  30. package/dist/distribuicao/launcherWindows.d.ts +28 -0
  31. package/dist/distribuicao/launcherWindows.js +326 -0
  32. package/dist/distribuicao/lockContextGlobal.d.ts +10 -0
  33. package/dist/distribuicao/lockContextGlobal.js +17 -0
  34. package/dist/distribuicao/lockGlobal.d.ts +6 -0
  35. package/dist/distribuicao/lockGlobal.js +520 -0
  36. package/dist/distribuicao/skillGlobal.d.ts +48 -0
  37. package/dist/distribuicao/skillGlobal.js +652 -0
  38. package/dist/distribuicao/skillIntentPolicy.d.ts +21 -0
  39. package/dist/distribuicao/skillIntentPolicy.js +115 -0
  40. package/dist/distribuicao/tipos.d.ts +50 -0
  41. package/dist/distribuicao/tipos.js +10 -0
  42. package/dist/distribuicao/versaoSemantica.d.ts +3 -0
  43. package/dist/distribuicao/versaoSemantica.js +62 -0
  44. package/dist/docs.part01.d.ts +4 -1
  45. package/dist/docs.part01.js +8 -0
  46. package/dist/docs.part02.js +9 -1
  47. package/dist/drift.part01.d.ts +33 -25
  48. package/dist/drift.part01.js +2 -1
  49. package/dist/drift.part04.d.ts +26 -5
  50. package/dist/drift.part04.js +123 -19
  51. package/dist/drift.part05.d.ts +2 -2
  52. package/dist/drift.part05.js +8 -6
  53. package/dist/drift.part06.d.ts +2 -2
  54. package/dist/drift.part06.js +113 -26
  55. package/dist/drift.part07.d.ts +11 -11
  56. package/dist/drift.part07.js +261 -265
  57. package/dist/drift.part08.d.ts +2 -2
  58. package/dist/drift.part08.js +35 -26
  59. package/dist/drift.part09.d.ts +2 -2
  60. package/dist/drift.part09.js +10 -3
  61. package/dist/drift.part11.js +261 -58
  62. package/dist/drift.part12.d.ts +1 -1
  63. package/dist/drift.part12.js +193 -21
  64. package/dist/drift.part13.d.ts +20 -39
  65. package/dist/drift.part13.js +601 -647
  66. package/dist/drift.part14.js +23 -7
  67. package/dist/driftCacheCas.d.ts +43 -0
  68. package/dist/driftCacheCas.js +351 -0
  69. package/dist/driftCacheFilesystem.d.ts +64 -0
  70. package/dist/driftCacheFilesystem.js +313 -0
  71. package/dist/driftCacheModes.d.ts +38 -0
  72. package/dist/driftCacheModes.js +147 -0
  73. package/dist/driftCacheStore.d.ts +80 -0
  74. package/dist/driftCacheStore.js +603 -0
  75. package/dist/driftCatalogo.d.ts +2 -28
  76. package/dist/driftCatalogo.js +143 -284
  77. package/dist/driftEscopo.d.ts +1 -3
  78. package/dist/driftEscopo.js +235 -151
  79. package/dist/driftEscopoReferencias.d.ts +5 -1
  80. package/dist/driftEscopoReferencias.js +375 -28
  81. package/dist/driftOrcamento.d.ts +0 -6
  82. package/dist/driftOrcamento.js +2 -1
  83. package/dist/execucoesExternas.js +19 -5
  84. package/dist/exemplosOficiais.d.ts +2 -1
  85. package/dist/exemplosOficiais.js +9 -3
  86. package/dist/geracaoCore.d.ts +1 -0
  87. package/dist/geracaoCore.js +6 -6
  88. package/dist/iaPrompts.d.ts +3 -3
  89. package/dist/iaPrompts.js +312 -313
  90. package/dist/importador.part01.d.ts +1 -1
  91. package/dist/importador.part06.d.ts +2 -0
  92. package/dist/importador.part06.js +87 -1
  93. package/dist/importador.part09.js +7 -1
  94. package/dist/index.d.ts +4 -1
  95. package/dist/index.js +6 -25
  96. package/dist/index.part01.d.ts +20 -28
  97. package/dist/index.part01.js +16 -237
  98. package/dist/index.part02.js +36 -22
  99. package/dist/index.part03.d.ts +24 -2
  100. package/dist/index.part03.js +83 -19
  101. package/dist/index.part04.d.ts +10 -2
  102. package/dist/index.part04.js +152 -123
  103. package/dist/index.part05.js +80 -78
  104. package/dist/index.part06.js +34 -17
  105. package/dist/index.part07.d.ts +8 -2
  106. package/dist/index.part07.js +153 -7
  107. package/dist/index.part08.d.ts +1 -1
  108. package/dist/index.part08.js +25 -30
  109. package/dist/initCommand.d.ts +1 -0
  110. package/dist/initCommand.js +20 -4
  111. package/dist/initTemplatesBase.js +6 -4
  112. package/dist/pipelineConteudo/command.d.ts +1 -0
  113. package/dist/pipelineConteudo/command.js +9 -2
  114. package/dist/pipelineConteudo/help.d.ts +2 -0
  115. package/dist/pipelineConteudo/help.js +33 -0
  116. package/dist/profileAuthorCommand.js +3 -7
  117. package/dist/profileCommand.js +3 -7
  118. package/dist/projetoCarregar.js +35 -17
  119. package/dist/projetoCatalogo.d.ts +1 -0
  120. package/dist/projetoCatalogo.js +64 -25
  121. package/dist/projetoConfig.js +2 -0
  122. package/dist/projetoLegado.js +18 -0
  123. package/dist/projetoOrigens.d.ts +2 -0
  124. package/dist/projetoOrigens.js +65 -9
  125. package/dist/projetoTipos.d.ts +1 -0
  126. package/dist/resultadoCli.d.ts +20 -0
  127. package/dist/resultadoCli.js +57 -0
  128. package/dist/saidaCli.d.ts +35 -0
  129. package/dist/saidaCli.js +118 -0
  130. package/dist/sistemasInterativos/acceptanceEvidence.d.ts +22 -0
  131. package/dist/sistemasInterativos/acceptanceEvidence.js +345 -0
  132. package/dist/sistemasInterativos/engineObservation.d.ts +12 -0
  133. package/dist/sistemasInterativos/engineObservation.js +438 -0
  134. package/dist/sistemasInterativos/jobOrchestration.d.ts +2 -0
  135. package/dist/sistemasInterativos/jobOrchestration.js +204 -0
  136. package/dist/sistemasInterativos/operationPrimitives.d.ts +21 -0
  137. package/dist/sistemasInterativos/operationPrimitives.js +194 -0
  138. package/dist/sistemasInterativos/operations.d.ts +4 -39
  139. package/dist/sistemasInterativos/operations.js +5 -1164
  140. package/dist/skillCommand.d.ts +5 -0
  141. package/dist/skillCommand.js +88 -0
  142. package/dist/tipos.d.ts +1 -1
  143. package/dist/typescript-http-modelos.d.ts +1 -1
  144. package/dist/typescript-http-rotas.d.ts +1 -0
  145. package/dist/typescript-http-rotas.js +93 -0
  146. package/dist/typescript-http.d.ts +1 -1
  147. package/dist/typescript-http.js +1 -1
  148. package/dist/verificacaoCache.d.ts +25 -0
  149. package/dist/verificacaoCache.js +80 -0
  150. package/docs/README.md +34 -30
  151. package/docs/ai-integration.md +25 -12
  152. package/docs/ai-onboarding.md +37 -18
  153. package/docs/ai-workflow.md +9 -7
  154. package/docs/cli.md +125 -7
  155. package/docs/commands.md +41 -20
  156. package/docs/deploy.md +21 -8
  157. package/docs/descoberta-capacidades.md +106 -106
  158. package/docs/documentation.md +49 -39
  159. package/docs/drift-cache.md +108 -0
  160. package/docs/getting-started.md +43 -18
  161. package/docs/pipeline-conteudo.md +246 -246
  162. package/docs/profiles.md +54 -54
  163. package/docs/repositories.md +19 -2
  164. package/docs/rollback.md +15 -8
  165. package/docs/security.md +25 -3
  166. package/docs/sistemas-interativos.md +379 -374
  167. package/docs/syntax.md +14 -0
  168. package/docs/testing.md +139 -40
  169. package/exemplos/express_crud.sema +139 -0
  170. package/exemplos/fastify_crud.sema +146 -0
  171. package/exemplos/pipeline-conteudo/README.md +44 -44
  172. package/exemplos/pipeline-conteudo/alvos.json +23 -23
  173. package/exemplos/pipeline-conteudo/definicao.json +136 -136
  174. package/exemplos/profile_simulation.sema +211 -211
  175. package/exemplos/sistemas-interativos/README.md +100 -100
  176. package/exemplos/sistemas-interativos/advanced/acceptance-context-evaluate-valid.json +5 -5
  177. package/exemplos/sistemas-interativos/advanced/acceptance-lock-valid.json +16 -16
  178. package/exemplos/sistemas-interativos/advanced/asset-provenance-valid.json +32 -32
  179. package/exemplos/sistemas-interativos/advanced/autonomy-repair-valid.json +93 -93
  180. package/exemplos/sistemas-interativos/advanced/control-run-definition-valid.json +78 -78
  181. package/exemplos/sistemas-interativos/advanced/control-run-valid.json +27 -27
  182. package/exemplos/sistemas-interativos/advanced/distributed-workers-valid.json +79 -79
  183. package/exemplos/sistemas-interativos/advanced/editor-state-valid.json +42 -42
  184. package/exemplos/sistemas-interativos/advanced/engine-snapshot-after-valid.json +32 -32
  185. package/exemplos/sistemas-interativos/advanced/engine-snapshot-before-valid.json +23 -23
  186. package/exemplos/sistemas-interativos/advanced/job-orchestration-valid.json +39 -39
  187. package/exemplos/sistemas-interativos/advanced/multimodal-evidence-valid.json +46 -46
  188. package/exemplos/sistemas-interativos/advanced/multiplayer-authority-valid.json +39 -39
  189. package/exemplos/sistemas-interativos/advanced/playtest-fuzz-valid.json +37 -37
  190. package/exemplos/sistemas-interativos/advanced/portability-valid.json +104 -104
  191. package/exemplos/sistemas-interativos/advanced/temporal-evidence-valid.json +27 -27
  192. package/exemplos/sistemas-interativos/advanced/temporal-valid.json +118 -118
  193. package/exemplos/sistemas-interativos/experience-ir-valid.json +459 -459
  194. package/exemplos/sistemas-interativos/game-2d.json +83 -83
  195. package/exemplos/sistemas-interativos/game-3d-human.json +81 -81
  196. package/exemplos/sistemas-interativos/game-pixel-16-bit.json +97 -97
  197. package/exemplos/sistemas-interativos/game-pixel-8-bit.json +94 -94
  198. package/exemplos/sistemas-interativos/game-xr-human.json +80 -80
  199. package/exemplos/sistemas-interativos/hybrid-2-5d.json +108 -108
  200. package/exemplos/sistemas-interativos/protocol-mutating-rollback-valid.json +75 -75
  201. package/exemplos/sistemas-interativos/protocol-read-only-valid.json +58 -58
  202. package/exemplos/sistemas-interativos/simulation-2d-controlled.json +97 -97
  203. package/exemplos/sistemas-interativos/simulation-3d-calibrated-autonomous.json +141 -141
  204. package/exemplos/sistemas-interativos/simulation-headless-autonomous-batch.json +112 -112
  205. package/exemplos/sistemas-interativos/simulation-pixel-16-bit.json +103 -103
  206. package/exemplos/sistemas-interativos/simulation-text-controlled.json +95 -95
  207. package/node_modules/@sema/gerador-cpp/package.json +1 -1
  208. package/node_modules/@sema/gerador-dotnet/package.json +1 -1
  209. package/node_modules/@sema/gerador-lua/dist/index.js +51 -51
  210. package/node_modules/@sema/gerador-php/dist/index.js +113 -113
  211. package/node_modules/@sema/nucleo/dist/ir/conversor.part01.js +37 -38
  212. package/node_modules/@sema/nucleo/dist/ir/modelos.d.ts +1 -0
  213. package/node_modules/@sema/nucleo/dist/semantico/analisador.d.ts +1 -0
  214. package/node_modules/@sema/nucleo/dist/semantico/analisador.js +1 -0
  215. package/node_modules/@sema/nucleo/dist/semantico/analisador.part01.d.ts +7 -0
  216. package/node_modules/@sema/nucleo/dist/semantico/analisador.part01.js +33 -10
  217. package/package.json +9 -4
  218. package/scripts/postinstall.mjs +148 -0
  219. package/skills/sema/SKILL.md +199 -0
  220. package/skills/sema/agents/openai.yaml +4 -0
  221. package/dist/driftCache.d.ts +0 -49
  222. package/dist/driftCache.js +0 -311
  223. package/dist/driftCacheIncremental.d.ts +0 -98
  224. package/dist/driftCacheIncremental.js +0 -596
  225. package/dist/driftCatalogoPersistente.d.ts +0 -8
  226. package/dist/driftCatalogoPersistente.js +0 -77
  227. package/node_modules/@sema/gerador-cpp/dist/index.js.map +0 -1
  228. package/node_modules/@sema/gerador-css/dist/index.js.map +0 -1
  229. package/node_modules/@sema/gerador-css/dist/index.part01.js.map +0 -1
  230. package/node_modules/@sema/gerador-css/dist/index.part02.js.map +0 -1
  231. package/node_modules/@sema/gerador-dart/dist/index.js.map +0 -1
  232. package/node_modules/@sema/gerador-dotnet/dist/index.js.map +0 -1
  233. package/node_modules/@sema/gerador-html/dist/index.js.map +0 -1
  234. package/node_modules/@sema/gerador-javascript/dist/index.js.map +0 -1
  235. package/node_modules/@sema/gerador-lua/dist/index.js.map +0 -1
  236. package/node_modules/@sema/gerador-php/dist/index.js.map +0 -1
  237. package/node_modules/@sema/gerador-python/dist/index.js.map +0 -1
  238. package/node_modules/@sema/gerador-python/dist/index.part01.js.map +0 -1
  239. package/node_modules/@sema/gerador-python/dist/index.part02.js.map +0 -1
  240. package/node_modules/@sema/gerador-typescript/dist/index.js.map +0 -1
  241. package/node_modules/@sema/gerador-typescript/dist/index.part01.js.map +0 -1
  242. package/node_modules/@sema/gerador-typescript/dist/index.part02.js.map +0 -1
  243. package/node_modules/@sema/gerador-typescript/dist/index.part03.js.map +0 -1
  244. package/node_modules/@sema/nucleo/dist/ast/tipos.js.map +0 -1
  245. package/node_modules/@sema/nucleo/dist/diagnosticos/index.js.map +0 -1
  246. package/node_modules/@sema/nucleo/dist/diagnosticos/melhorador.js.map +0 -1
  247. package/node_modules/@sema/nucleo/dist/diagnosticos/snippets.js.map +0 -1
  248. package/node_modules/@sema/nucleo/dist/formatador/index.js.map +0 -1
  249. package/node_modules/@sema/nucleo/dist/formatador/index.part01.js.map +0 -1
  250. package/node_modules/@sema/nucleo/dist/formatador/index.part02.js.map +0 -1
  251. package/node_modules/@sema/nucleo/dist/index.js.map +0 -1
  252. package/node_modules/@sema/nucleo/dist/ir/conversor.js.map +0 -1
  253. package/node_modules/@sema/nucleo/dist/ir/conversor.part01.js.map +0 -1
  254. package/node_modules/@sema/nucleo/dist/ir/conversor.part02.js.map +0 -1
  255. package/node_modules/@sema/nucleo/dist/ir/conversor.part03.js.map +0 -1
  256. package/node_modules/@sema/nucleo/dist/ir/modelos.js.map +0 -1
  257. package/node_modules/@sema/nucleo/dist/lexer/lexer.js.map +0 -1
  258. package/node_modules/@sema/nucleo/dist/lexer/tokens.js.map +0 -1
  259. package/node_modules/@sema/nucleo/dist/parser/parser.declaracoes.js.map +0 -1
  260. package/node_modules/@sema/nucleo/dist/parser/parser.js.map +0 -1
  261. package/node_modules/@sema/nucleo/dist/parser/parser.modulo.js.map +0 -1
  262. package/node_modules/@sema/nucleo/dist/parser/parser.part01.js.map +0 -1
  263. package/node_modules/@sema/nucleo/dist/parser/parser.part02.js.map +0 -1
  264. package/node_modules/@sema/nucleo/dist/parser/parser.part03.js.map +0 -1
  265. package/node_modules/@sema/nucleo/dist/persistencia/contratos.js.map +0 -1
  266. package/node_modules/@sema/nucleo/dist/semantico/analisador.js.map +0 -1
  267. package/node_modules/@sema/nucleo/dist/semantico/analisador.part01.js.map +0 -1
  268. package/node_modules/@sema/nucleo/dist/semantico/analisador.part02.js.map +0 -1
  269. package/node_modules/@sema/nucleo/dist/semantico/analisador.part03.js.map +0 -1
  270. package/node_modules/@sema/nucleo/dist/semantico/analisador.part04.js.map +0 -1
  271. package/node_modules/@sema/nucleo/dist/semantico/analisador.part05.js.map +0 -1
  272. package/node_modules/@sema/nucleo/dist/semantico/analisador.part06.js.map +0 -1
  273. package/node_modules/@sema/nucleo/dist/semantico/analisador.part07.js.map +0 -1
  274. package/node_modules/@sema/nucleo/dist/semantico/analisador.part08.js.map +0 -1
  275. package/node_modules/@sema/nucleo/dist/semantico/estruturas.js.map +0 -1
  276. package/node_modules/@sema/nucleo/dist/semantico/estruturas.part01.js.map +0 -1
  277. package/node_modules/@sema/nucleo/dist/semantico/estruturas.part02.js.map +0 -1
  278. package/node_modules/@sema/nucleo/dist/semantico/orcamentoSemantico.js.map +0 -1
  279. package/node_modules/@sema/nucleo/dist/semantico/seguranca.js.map +0 -1
  280. package/node_modules/@sema/nucleo/dist/util/arquivos.js.map +0 -1
  281. package/node_modules/@sema/padroes/dist/index.js.map +0 -1
@@ -1,15 +1,19 @@
1
1
  // SEMA-GOVERNED: sema.produto.governanca_ia.drift
2
2
  // Descricao: extrai e resolve candidatos exatos de dependencias locais sem caminhada de filesystem.
3
3
  import path from "node:path";
4
+ import ts from "typescript";
4
5
  const EXTENSOES_DEPENDENCIA_CODIGO = [
5
- ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py", ".dart", ".lua", ".cs", ".java",
6
+ ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".py", ".dart", ".lua", ".cs", ".java",
6
7
  ".go", ".rs", ".php", ".cpp", ".cc", ".cxx", ".hpp", ".h",
7
8
  ".sql", ".psql", ".ddl", ".prisma", ".html", ".htm", ".css",
8
9
  ];
9
10
  const EXTENSOES_TYPESCRIPT_DEPENDENCIA = [
10
- ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".html", ".htm", ".css",
11
+ ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".html", ".htm", ".css",
11
12
  ];
12
13
  const PREFIXO_REFERENCIA_PYTHON = "python:";
14
+ const PREFIXO_REFERENCIA_RUST_MODULO = "rust-mod:";
15
+ const PREFIXO_REFERENCIA_RUST_CAMINHO = "rust-path:";
16
+ const REFERENCIA_ALIAS_CONFIG_INCOMPLETA = "alias-config:nao_resolvida";
13
17
  function chaveCaminho(caminho) {
14
18
  const absoluto = path.normalize(path.resolve(caminho));
15
19
  return process.platform === "win32" ? absoluto.toLowerCase() : absoluto;
@@ -20,6 +24,107 @@ function caminhoEstaDentro(raiz, alvo) {
20
24
  && !relativo.startsWith(`..${path.sep}`)
21
25
  && !path.isAbsolute(relativo));
22
26
  }
27
+ function encontrarConfiguracaoTypeScript(contexto, arquivoOrigem) {
28
+ const baseProjeto = path.resolve(contexto.baseProjeto);
29
+ let diretorio = path.dirname(path.resolve(arquivoOrigem));
30
+ if (!caminhoEstaDentro(baseProjeto, diretorio)) {
31
+ return undefined;
32
+ }
33
+ for (;;) {
34
+ for (const nome of ["tsconfig.json", "jsconfig.json"]) {
35
+ const candidato = path.join(diretorio, nome);
36
+ if (ts.sys.fileExists(candidato)) {
37
+ return candidato;
38
+ }
39
+ }
40
+ if (chaveCaminho(diretorio) === chaveCaminho(baseProjeto)) {
41
+ return undefined;
42
+ }
43
+ const pai = path.dirname(diretorio);
44
+ if (pai === diretorio || !caminhoEstaDentro(baseProjeto, pai)) {
45
+ return undefined;
46
+ }
47
+ diretorio = pai;
48
+ }
49
+ }
50
+ function resolverExtendsTypeScript(configuracao, valor) {
51
+ if (!valor.startsWith(".") && !path.isAbsolute(valor)) {
52
+ return undefined;
53
+ }
54
+ const base = path.resolve(path.dirname(configuracao), valor);
55
+ for (const candidato of [base, `${base}.json`, path.join(base, "tsconfig.json")]) {
56
+ if (ts.sys.fileExists(candidato)) {
57
+ return candidato;
58
+ }
59
+ }
60
+ return undefined;
61
+ }
62
+ function carregarConfiguracaoAliasesTypeScript(contexto, arquivoOrigem) {
63
+ const configuracaoInicial = encontrarConfiguracaoTypeScript(contexto, arquivoOrigem);
64
+ if (!configuracaoInicial) {
65
+ return { regras: [], incompleta: false };
66
+ }
67
+ const visitadas = new Set();
68
+ const carregar = (configuracao) => {
69
+ const chave = chaveCaminho(configuracao);
70
+ if (visitadas.has(chave) || visitadas.size >= 8) {
71
+ return { regras: [], incompleta: true };
72
+ }
73
+ visitadas.add(chave);
74
+ const leitura = ts.readConfigFile(configuracao, ts.sys.readFile);
75
+ if (leitura.error || !leitura.config || typeof leitura.config !== "object") {
76
+ return { regras: [], incompleta: true };
77
+ }
78
+ const config = leitura.config;
79
+ const opcoes = config.compilerOptions ?? {};
80
+ const base = path.resolve(path.dirname(configuracao), opcoes.baseUrl ?? ".");
81
+ const regrasAtuais = Object.entries(opcoes.paths ?? {})
82
+ .map(([padrao, alvos]) => {
83
+ if (!Array.isArray(alvos)) {
84
+ return undefined;
85
+ }
86
+ const alvosValidos = alvos.filter((alvo) => typeof alvo === "string" && alvo.length > 0);
87
+ return alvosValidos.length > 0 ? { padrao, alvos: alvosValidos, base } : undefined;
88
+ })
89
+ .filter((regra) => Boolean(regra));
90
+ let incompleta = false;
91
+ const herdadas = [];
92
+ const extensoes = Array.isArray(config.extends)
93
+ ? config.extends
94
+ : config.extends ? [config.extends] : [];
95
+ for (const extensao of extensoes) {
96
+ const caminhoBase = resolverExtendsTypeScript(configuracao, extensao);
97
+ if (!caminhoBase || !caminhoEstaDentro(contexto.baseProjeto, caminhoBase)) {
98
+ incompleta = true;
99
+ continue;
100
+ }
101
+ const resultadoBase = carregar(caminhoBase);
102
+ herdadas.push(...resultadoBase.regras);
103
+ incompleta = incompleta || resultadoBase.incompleta;
104
+ }
105
+ const padroesAtuais = new Set(regrasAtuais.map((regra) => regra.padrao));
106
+ return {
107
+ regras: [...regrasAtuais, ...herdadas.filter((regra) => !padroesAtuais.has(regra.padrao))],
108
+ incompleta,
109
+ };
110
+ };
111
+ return carregar(configuracaoInicial);
112
+ }
113
+ function capturarAliasTypeScript(padrao, referencia) {
114
+ const indiceCoringa = padrao.indexOf("*");
115
+ if (indiceCoringa < 0) {
116
+ return padrao === referencia ? "" : undefined;
117
+ }
118
+ const prefixo = padrao.slice(0, indiceCoringa);
119
+ const sufixo = padrao.slice(indiceCoringa + 1);
120
+ if (!referencia.startsWith(prefixo) || !referencia.endsWith(sufixo)) {
121
+ return undefined;
122
+ }
123
+ return referencia.slice(prefixo.length, referencia.length - sufixo.length);
124
+ }
125
+ function referenciaCorrespondeAliasTypeScript(referencia, configuracao) {
126
+ return configuracao?.regras.some((regra) => capturarAliasTypeScript(regra.padrao, referencia) !== undefined) ?? false;
127
+ }
23
128
  function mascararIntervalo(codigo, saida, inicio, fim) {
24
129
  for (let indice = inicio; indice < fim; indice += 1) {
25
130
  if (codigo[indice] !== "\n" && codigo[indice] !== "\r") {
@@ -27,7 +132,137 @@ function mascararIntervalo(codigo, saida, inicio, fim) {
27
132
  }
28
133
  }
29
134
  }
30
- /** Remove comentarios/docstrings sem alterar offsets ou caminhos em literais de imports reais. */
135
+ function avancarStringEmExpressao(codigo, inicio) {
136
+ const delimitador = codigo[inicio];
137
+ let indice = inicio + 1;
138
+ while (indice < codigo.length) {
139
+ if (codigo[indice] === "\\") {
140
+ indice += 2;
141
+ continue;
142
+ }
143
+ if (codigo[indice] === delimitador) {
144
+ return indice + 1;
145
+ }
146
+ indice += 1;
147
+ }
148
+ return codigo.length;
149
+ }
150
+ function avancarRegexEmExpressao(codigo, inicio) {
151
+ let indice = inicio + 1;
152
+ let classe = false;
153
+ while (indice < codigo.length) {
154
+ if (codigo[indice] === "\\") {
155
+ indice += 2;
156
+ continue;
157
+ }
158
+ if (codigo[indice] === "[") {
159
+ classe = true;
160
+ }
161
+ else if (codigo[indice] === "]") {
162
+ classe = false;
163
+ }
164
+ else if (codigo[indice] === "/" && !classe) {
165
+ indice += 1;
166
+ while (/[A-Za-z]/u.test(codigo[indice] ?? "")) {
167
+ indice += 1;
168
+ }
169
+ return indice;
170
+ }
171
+ indice += 1;
172
+ }
173
+ return codigo.length;
174
+ }
175
+ function barraIniciaRegex(codigo, indice) {
176
+ let anterior = indice - 1;
177
+ while (anterior >= 0 && /\s/u.test(codigo[anterior] ?? "")) {
178
+ anterior -= 1;
179
+ }
180
+ return anterior < 0 || /[([{=,:;!?&|+\-*%^~<>]/u.test(codigo[anterior] ?? "");
181
+ }
182
+ function avancarExpressaoTemplate(codigo, inicio, profundidade) {
183
+ let indice = inicio;
184
+ let nivelChaves = 1;
185
+ while (indice < codigo.length) {
186
+ const atual = codigo[indice];
187
+ const proximo = codigo[indice + 1];
188
+ if (atual === "'" || atual === '"') {
189
+ indice = avancarStringEmExpressao(codigo, indice);
190
+ continue;
191
+ }
192
+ if (atual === "`") {
193
+ indice = avancarTemplateLiteral(codigo, indice, profundidade + 1).fim;
194
+ continue;
195
+ }
196
+ if (atual === "/" && proximo === "/") {
197
+ const fimLinha = codigo.indexOf("\n", indice + 2);
198
+ indice = fimLinha < 0 ? codigo.length : fimLinha;
199
+ continue;
200
+ }
201
+ if (atual === "/" && proximo === "*") {
202
+ const fimComentario = codigo.indexOf("*/", indice + 2);
203
+ indice = fimComentario < 0 ? codigo.length : fimComentario + 2;
204
+ continue;
205
+ }
206
+ if (atual === "/" && barraIniciaRegex(codigo, indice)) {
207
+ indice = avancarRegexEmExpressao(codigo, indice);
208
+ continue;
209
+ }
210
+ if (atual === "{") {
211
+ nivelChaves += 1;
212
+ }
213
+ else if (atual === "}") {
214
+ nivelChaves -= 1;
215
+ if (nivelChaves === 0) {
216
+ return indice + 1;
217
+ }
218
+ }
219
+ indice += 1;
220
+ }
221
+ return codigo.length;
222
+ }
223
+ function avancarTemplateLiteral(codigo, inicio, profundidade = 0) {
224
+ if (profundidade > 64) {
225
+ return { fim: codigo.length, fechado: false, interpolado: true };
226
+ }
227
+ let indice = inicio + 1;
228
+ let interpolado = false;
229
+ while (indice < codigo.length) {
230
+ if (codigo[indice] === "\\") {
231
+ indice += 2;
232
+ continue;
233
+ }
234
+ if (codigo[indice] === "`") {
235
+ return { fim: indice + 1, fechado: true, interpolado };
236
+ }
237
+ if (codigo[indice] === "$" && codigo[indice + 1] === "{") {
238
+ interpolado = true;
239
+ indice = avancarExpressaoTemplate(codigo, indice + 2, profundidade);
240
+ continue;
241
+ }
242
+ indice += 1;
243
+ }
244
+ return { fim: codigo.length, fechado: false, interpolado };
245
+ }
246
+ function literalEhReferenciaEstatica(codigo, inicio, fim, templateLiteral) {
247
+ const conteudo = codigo.slice(inicio + 1, Math.max(inicio + 1, fim - 1));
248
+ if (templateLiteral && conteudo.includes("${")) {
249
+ return false;
250
+ }
251
+ const prefixo = codigo.slice(Math.max(0, inicio - 4_096), inicio);
252
+ const inicioLinha = prefixo.lastIndexOf("\n") + 1;
253
+ const prefixoLinha = prefixo.slice(inicioLinha);
254
+ return /\bstyleUrls\s*:\s*\[[^\]]*$/u.test(prefixo)
255
+ || /\b(?:import|require)\s*\(\s*$/u.test(prefixoLinha)
256
+ || /^\s*import\s*$/u.test(prefixoLinha)
257
+ || /\b(?:import|export)\b[^;]*\bfrom\s*$/u.test(prefixo)
258
+ || /\b(?:templateUrl|styleUrl)\s*:\s*$/u.test(prefixoLinha)
259
+ || /^\s*@import\s+(?:url\(\s*)?$/u.test(prefixoLinha)
260
+ || /^\s*#include\s*$/u.test(prefixoLinha)
261
+ || /\b(?:require|include)(?:_once)?\s*\(?\s*$/u.test(prefixoLinha)
262
+ || /\b(?:include|include_str|include_bytes)!\s*\(\s*$/u.test(prefixoLinha)
263
+ || /^\s*#\[\s*path\s*=\s*$/u.test(prefixoLinha);
264
+ }
265
+ /** Remove comentarios/docstrings sem alterar offsets ou caminhos em imports reais. */
31
266
  function removerComentariosDependencias(codigo) {
32
267
  const saida = [...codigo];
33
268
  let indice = 0;
@@ -44,23 +279,19 @@ function removerComentariosDependencias(codigo) {
44
279
  }
45
280
  if (atual === "`") {
46
281
  const inicio = indice;
47
- indice += 1;
48
- while (indice < codigo.length) {
49
- if (codigo[indice] === "\\") {
50
- indice += 2;
51
- continue;
52
- }
53
- if (codigo[indice] === "`") {
54
- indice += 1;
55
- break;
56
- }
57
- indice += 1;
282
+ const resultado = avancarTemplateLiteral(codigo, inicio);
283
+ indice = resultado.fim;
284
+ if (!resultado.fechado
285
+ || resultado.interpolado
286
+ || !literalEhReferenciaEstatica(codigo, inicio, indice, true)) {
287
+ mascararIntervalo(codigo, saida, inicio, indice);
58
288
  }
59
- mascararIntervalo(codigo, saida, inicio, indice);
60
289
  continue;
61
290
  }
62
291
  if (atual === "'" || atual === '"') {
292
+ const inicio = indice;
63
293
  const delimitador = atual;
294
+ let fechado = false;
64
295
  indice += 1;
65
296
  while (indice < codigo.length) {
66
297
  if (codigo[indice] === "\\") {
@@ -69,10 +300,14 @@ function removerComentariosDependencias(codigo) {
69
300
  }
70
301
  if (codigo[indice] === delimitador) {
71
302
  indice += 1;
303
+ fechado = true;
72
304
  break;
73
305
  }
74
306
  indice += 1;
75
307
  }
308
+ if (!fechado || !literalEhReferenciaEstatica(codigo, inicio, indice, false)) {
309
+ mascararIntervalo(codigo, saida, inicio, indice);
310
+ }
76
311
  continue;
77
312
  }
78
313
  if (atual === "/" && proximo === "/") {
@@ -92,7 +327,8 @@ function removerComentariosDependencias(codigo) {
92
327
  if (atual === "#") {
93
328
  const inicioLinha = codigo.lastIndexOf("\n", indice - 1) + 1;
94
329
  const prefixoLinha = codigo.slice(inicioLinha, indice);
95
- if (/^\s*$/u.test(prefixoLinha) && codigo.slice(indice).startsWith("#include")) {
330
+ if (/^\s*$/u.test(prefixoLinha)
331
+ && (codigo.slice(indice).startsWith("#include") || codigo.slice(indice).startsWith("#[path"))) {
96
332
  indice += 1;
97
333
  continue;
98
334
  }
@@ -106,8 +342,10 @@ function removerComentariosDependencias(codigo) {
106
342
  }
107
343
  return saida.join("");
108
344
  }
109
- function referenciaTypescriptLocal(referencia) {
110
- return referencia.startsWith(".") || referencia.startsWith("@/");
345
+ function referenciaTypescriptLocal(referencia, aliases) {
346
+ return referencia.startsWith(".")
347
+ || referencia.startsWith("@/")
348
+ || referenciaCorrespondeAliasTypeScript(referencia, aliases);
111
349
  }
112
350
  function adicionarImportacoesPython(codigo, referencias) {
113
351
  const adicionarModulo = (modulo) => {
@@ -133,24 +371,67 @@ function adicionarImportacoesPython(codigo, referencias) {
133
371
  }
134
372
  }
135
373
  }
136
- export function extrairReferenciasLocaisDrift(codigo) {
374
+ function adicionarReferenciasRust(codigo, referencias) {
375
+ const padraoModulo = /(?:^\s*#\[\s*path\s*=\s*["'`]([^"'`\r\n]+)["'`]\s*\]\s*(?:\r?\n\s*)?)?^\s*(?:(?:pub(?:\([^)]*\))?)\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;/gmu;
376
+ for (const ocorrencia of codigo.matchAll(padraoModulo)) {
377
+ const caminhoExplicito = ocorrencia[1]?.trim();
378
+ const modulo = ocorrencia[2]?.trim();
379
+ if (caminhoExplicito) {
380
+ const seguro = !path.posix.isAbsolute(caminhoExplicito)
381
+ && !path.win32.isAbsolute(caminhoExplicito)
382
+ && !caminhoExplicito.includes(":");
383
+ referencias.add(`${PREFIXO_REFERENCIA_RUST_CAMINHO}${seguro ? caminhoExplicito : "nao_resolvida"}`);
384
+ }
385
+ else if (modulo) {
386
+ referencias.add(`${PREFIXO_REFERENCIA_RUST_MODULO}${modulo}`);
387
+ }
388
+ }
389
+ for (const ocorrencia of codigo.matchAll(/\b(?:include|include_str|include_bytes)!\s*\(\s*["'`]([^"'`\r\n]+)["'`]\s*\)/gu)) {
390
+ const referencia = ocorrencia[1]?.trim();
391
+ if (referencia && !referencia.includes(":")) {
392
+ referencias.add(referencia);
393
+ }
394
+ }
395
+ }
396
+ export function extrairReferenciasLocaisDrift(codigo, opcoes = {}) {
137
397
  const referencias = new Set();
138
398
  const codigoExecutavel = removerComentariosDependencias(codigo);
399
+ const aliases = opcoes.contexto && opcoes.arquivoOrigem
400
+ ? carregarConfiguracaoAliasesTypeScript(opcoes.contexto, opcoes.arquivoOrigem)
401
+ : undefined;
402
+ let encontrouReferenciaNaoRelativa = false;
403
+ const adicionarReferenciaTypescript = (referenciaBruta) => {
404
+ const referencia = referenciaBruta?.trim();
405
+ if (!referencia) {
406
+ return;
407
+ }
408
+ if (referenciaTypescriptLocal(referencia, aliases)) {
409
+ referencias.add(referencia);
410
+ }
411
+ else if (!referencia.startsWith(".") && aliases?.incompleta) {
412
+ encontrouReferenciaNaoRelativa = true;
413
+ }
414
+ };
139
415
  const padroesTypescript = [
140
416
  /^\s*(?:import|export)\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{[^}]*\}\s+from\s+["'`]([^"'`\r\n]+)["'`]/gmu,
141
417
  /^\s*(?:import|export)\s+(?:type\s+)?(?:[^;"'`\r\n]*?\s+from\s+)?["'`]([^"'`\r\n]+)["'`]/gmu,
142
418
  /\b(?:import|require)\s*\(\s*["'`]([^"'`\r\n]+)["'`]\s*\)/gu,
143
- /\b(?:templateUrl|styleUrls?)\s*:\s*(?:\[\s*)?["'`]([^"'`\r\n]+)["'`]/gu,
419
+ /\b(?:templateUrl|styleUrl)\s*:\s*["'`]([^"'`\r\n]+)["'`]/gu,
144
420
  /^\s*@import\s+(?:url\(\s*)?["'`]([^"'`\r\n]+)["'`]/gmu,
145
421
  ];
146
422
  for (const padrao of padroesTypescript) {
147
423
  for (const ocorrencia of codigoExecutavel.matchAll(padrao)) {
148
- const referencia = ocorrencia[1]?.trim();
149
- if (referencia && referenciaTypescriptLocal(referencia)) {
150
- referencias.add(referencia);
151
- }
424
+ adicionarReferenciaTypescript(ocorrencia[1]);
425
+ }
426
+ }
427
+ for (const ocorrencia of codigoExecutavel.matchAll(/\bstyleUrls\s*:\s*\[([^\]]*)\]/gu)) {
428
+ for (const estilo of (ocorrencia[1] ?? "").matchAll(/["'`]([^"'`\r\n]+)["'`]/gu)) {
429
+ adicionarReferenciaTypescript(estilo[1]);
152
430
  }
153
431
  }
432
+ if (encontrouReferenciaNaoRelativa) {
433
+ referencias.add(REFERENCIA_ALIAS_CONFIG_INCOMPLETA);
434
+ }
154
435
  for (const ocorrencia of codigoExecutavel.matchAll(/^\s*#include\s+["']([^"'\r\n]+)["']/gmu)) {
155
436
  const referencia = ocorrencia[1]?.trim();
156
437
  if (referencia && !referencia.includes(":")) {
@@ -167,6 +448,7 @@ export function extrairReferenciasLocaisDrift(codigo) {
167
448
  }
168
449
  }
169
450
  adicionarImportacoesPython(codigoExecutavel, referencias);
451
+ adicionarReferenciasRust(codigoExecutavel, referencias);
170
452
  return [...referencias];
171
453
  }
172
454
  export function raizesCodigoLogicasDrift(contexto) {
@@ -188,20 +470,61 @@ function adicionarVariantesArquivo(candidatos, base, extensoesPermitidas) {
188
470
  candidatos.set(chave, absoluto);
189
471
  }
190
472
  };
191
- adicionar(base);
192
- if ([".js", ".jsx", ".mjs", ".cjs"].includes(extensao)) {
473
+ const substituicoesNodeNext = {
474
+ ".js": [".ts", ".tsx", ".d.ts", ".js", ".jsx"],
475
+ ".jsx": [".tsx", ".jsx"],
476
+ ".mjs": [".mts", ".d.mts", ".mjs"],
477
+ ".cjs": [".cts", ".d.cts", ".cjs"],
478
+ };
479
+ const substituicoes = substituicoesNodeNext[extensao];
480
+ if (substituicoes) {
193
481
  const semExtensao = base.slice(0, -extensao.length);
194
- for (const alternativa of [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]) {
482
+ for (const alternativa of substituicoes) {
195
483
  adicionar(`${semExtensao}${alternativa}`);
196
484
  }
485
+ return;
197
486
  }
198
- else if (!extensaoConhecida) {
487
+ adicionar(base);
488
+ if (!extensaoConhecida) {
199
489
  for (const alternativa of extensoesPermitidas) {
200
490
  adicionar(`${base}${alternativa}`);
201
491
  adicionar(path.join(base, `index${alternativa}`));
202
492
  }
203
493
  }
204
494
  }
495
+ function adicionarCandidatosAliasTypeScript(candidatos, contexto, arquivoOrigem, referencia) {
496
+ const configuracao = carregarConfiguracaoAliasesTypeScript(contexto, arquivoOrigem);
497
+ const regrasCorrespondentes = configuracao.regras
498
+ .map((regra) => ({ regra, captura: capturarAliasTypeScript(regra.padrao, referencia) }))
499
+ .filter((item) => item.captura !== undefined)
500
+ .sort((a, b) => {
501
+ const especificidadeA = a.regra.padrao.replace("*", "").length;
502
+ const especificidadeB = b.regra.padrao.replace("*", "").length;
503
+ return especificidadeB - especificidadeA;
504
+ });
505
+ const melhorPadrao = regrasCorrespondentes[0]?.regra.padrao;
506
+ if (!melhorPadrao) {
507
+ return false;
508
+ }
509
+ for (const { regra, captura } of regrasCorrespondentes.filter((item) => item.regra.padrao === melhorPadrao)) {
510
+ for (const alvo of regra.alvos) {
511
+ adicionarVariantesArquivo(candidatos, path.resolve(regra.base, alvo.replace("*", captura)), EXTENSOES_TYPESCRIPT_DEPENDENCIA);
512
+ }
513
+ }
514
+ return true;
515
+ }
516
+ function adicionarCandidatosModuloRust(candidatos, arquivoOrigem, modulo) {
517
+ const nomeArquivo = path.basename(arquivoOrigem, path.extname(arquivoOrigem));
518
+ const baseModulo = ["lib", "main", "mod"].includes(nomeArquivo)
519
+ ? path.dirname(arquivoOrigem)
520
+ : path.join(path.dirname(arquivoOrigem), nomeArquivo);
521
+ for (const candidato of [
522
+ path.join(baseModulo, `${modulo}.rs`),
523
+ path.join(baseModulo, modulo, "mod.rs"),
524
+ ]) {
525
+ candidatos.set(chaveCaminho(candidato), path.resolve(candidato));
526
+ }
527
+ }
205
528
  function candidatosModuloPython(contexto, arquivoOrigem, moduloDeclarado) {
206
529
  const candidatos = new Map();
207
530
  const correspondencia = /^(\.*)(.*)$/u.exec(moduloDeclarado);
@@ -239,13 +562,37 @@ function candidatosModuloPython(contexto, arquivoOrigem, moduloDeclarado) {
239
562
  return [...candidatos.values()];
240
563
  }
241
564
  export function candidatosReferenciaLocalDrift(contexto, arquivoOrigem, referencia) {
565
+ if (referencia === REFERENCIA_ALIAS_CONFIG_INCOMPLETA) {
566
+ return [];
567
+ }
242
568
  if (referencia.startsWith(PREFIXO_REFERENCIA_PYTHON)) {
243
569
  if (path.extname(arquivoOrigem).toLowerCase() !== ".py") {
244
570
  return [];
245
571
  }
246
572
  return candidatosModuloPython(contexto, arquivoOrigem, referencia.slice(PREFIXO_REFERENCIA_PYTHON.length));
247
573
  }
574
+ if (referencia.startsWith(PREFIXO_REFERENCIA_RUST_MODULO)) {
575
+ if (path.extname(arquivoOrigem).toLowerCase() !== ".rs") {
576
+ return [];
577
+ }
578
+ const candidatos = new Map();
579
+ adicionarCandidatosModuloRust(candidatos, arquivoOrigem, referencia.slice(PREFIXO_REFERENCIA_RUST_MODULO.length));
580
+ return [...candidatos.values()];
581
+ }
582
+ if (referencia.startsWith(PREFIXO_REFERENCIA_RUST_CAMINHO)) {
583
+ if (path.extname(arquivoOrigem).toLowerCase() !== ".rs") {
584
+ return [];
585
+ }
586
+ const declarado = referencia.slice(PREFIXO_REFERENCIA_RUST_CAMINHO.length);
587
+ if (path.isAbsolute(declarado) || path.win32.isAbsolute(declarado) || declarado.includes(":")) {
588
+ return [];
589
+ }
590
+ return [path.resolve(path.dirname(arquivoOrigem), declarado)];
591
+ }
248
592
  const candidatos = new Map();
593
+ if (adicionarCandidatosAliasTypeScript(candidatos, contexto, arquivoOrigem, referencia)) {
594
+ return [...candidatos.values()];
595
+ }
249
596
  if (referencia.startsWith("@/")) {
250
597
  const relativoAlias = referencia.slice(2);
251
598
  const raizes = raizesCodigoLogicasDrift(contexto).sort((a, b) => {
@@ -36,12 +36,6 @@ export interface DiagnosticoOrcamentoArquivo {
36
36
  limite_aviso_linhas: number;
37
37
  limite_bloqueio_linhas: number;
38
38
  }
39
- /**
40
- * Leitor limitado a um conjunto de arquivos previamente catalogado.
41
- *
42
- * Quando fornecido, o gate de orcamento nao faz fallback para o filesystem:
43
- * um caminho fora do leitor e simplesmente ignorado nesta etapa.
44
- */
45
39
  export interface LeitorArquivosOrcamento {
46
40
  contem(caminho: string): boolean;
47
41
  lerTexto(caminho: string): Promise<string>;
@@ -11,8 +11,9 @@ export const LIMITE_BLOQUEIO_LINHAS_CONTRATO_SEMA = 500;
11
11
  export const LIMITE_AVISO_LINHAS_ORCAMENTO_SEMANTICO = LIMITE_AVISO_LINHAS_CODIGO_GOVERNADO;
12
12
  export const LIMITE_BLOQUEIO_LINHAS_ORCAMENTO_SEMANTICO = LIMITE_BLOQUEIO_LINHAS_CODIGO_GOVERNADO;
13
13
  export async function workspaceExigeCabecalhoCodigoGovernado(baseProjeto, modoEstrito) {
14
- if (!modoEstrito)
14
+ if (!modoEstrito) {
15
15
  return false;
16
+ }
16
17
  try {
17
18
  return (await lstat(path.resolve(baseProjeto, "AGENTS.md"))).isFile();
18
19
  }
@@ -1,7 +1,6 @@
1
- // SEMA-GOVERNED
2
- // M?dulo: sema.produto.orcamento_semantico
3
- // Contrato: contratos/sema/orcamento_semantico.sema
4
- // Descri??o: detec??o de comandos externos usados por doctor, testes gerados e runners opcionais.
1
+ // SEMA-GOVERNED: sema.produto.cli_toolchain_local
2
+ // Contrato: contratos/sema/cli_toolchain_local.sema
3
+ // Descrição: detecção de comandos externos usados por doctor, testes gerados e runners opcionais.
5
4
  import { spawnSync } from "node:child_process";
6
5
  import { createRequire } from "node:module";
7
6
  const requireRuntimeCli = createRequire(import.meta.url);
@@ -16,14 +15,29 @@ function resolverImportadorNodeOpcional(especificador) {
16
15
  export const TSX_IMPORTADOR_CLI = resolverImportadorNodeOpcional("tsx");
17
16
  export const TSX_EXECUTOR_CLI = resolverImportadorNodeOpcional("tsx/cli");
18
17
  const TIMEOUT_CHECAGEM_COMANDO_MS = 5_000;
18
+ const disponibilidadeComandosNoProcesso = new Map();
19
19
  export function comandoDisponivel(comando, argumentos = ["--version"]) {
20
+ const chaveSondagem = JSON.stringify({
21
+ comando,
22
+ argumentos,
23
+ cwd: process.cwd(),
24
+ path: process.env.PATH ?? "",
25
+ pathExt: process.env.PATHEXT ?? "",
26
+ comSpec: process.env.COMSPEC ?? "",
27
+ });
28
+ const resultadoMemorizado = disponibilidadeComandosNoProcesso.get(chaveSondagem);
29
+ if (resultadoMemorizado !== undefined) {
30
+ return resultadoMemorizado;
31
+ }
20
32
  const execucao = spawnSync(comando, argumentos, {
21
33
  stdio: "ignore",
22
34
  shell: process.platform === "win32",
23
35
  timeout: TIMEOUT_CHECAGEM_COMANDO_MS,
24
36
  windowsHide: true,
25
37
  });
26
- return !execucao.error && execucao.signal === null && (execucao.status ?? 1) === 0;
38
+ const disponivel = !execucao.error && execucao.signal === null && (execucao.status ?? 1) === 0;
39
+ disponibilidadeComandosNoProcesso.set(chaveSondagem, disponivel);
40
+ return disponivel;
27
41
  }
28
42
  export function resolverExecucaoPython() {
29
43
  if (comandoDisponivel("python")) {
@@ -17,4 +17,5 @@ export interface PlanoExemplosOficiais {
17
17
  }
18
18
  export declare function localizarDiretorioExemplosOficiais(): Promise<string | undefined>;
19
19
  export declare function planejarExemplosOficiais(): Promise<PlanoExemplosOficiais>;
20
- export declare function materializarExemplosOficiais(baseProjeto?: string, preservarExistentes?: boolean): Promise<ResultadoMaterializacaoExemplos>;
20
+ export declare function normalizarCaminhoExemplo(caminho: string): string;
21
+ export declare function materializarExemplosOficiais(baseProjeto?: string, preservarExistentes?: boolean, somenteCaminhos?: ReadonlySet<string>): Promise<ResultadoMaterializacaoExemplos>;
@@ -56,7 +56,10 @@ export async function planejarExemplosOficiais() {
56
56
  arquivos,
57
57
  };
58
58
  }
59
- export async function materializarExemplosOficiais(baseProjeto = process.cwd(), preservarExistentes = true) {
59
+ export function normalizarCaminhoExemplo(caminho) {
60
+ return caminho.replace(/\\/g, "/");
61
+ }
62
+ export async function materializarExemplosOficiais(baseProjeto = process.cwd(), preservarExistentes = true, somenteCaminhos) {
60
63
  const plano = await planejarExemplosOficiais();
61
64
  const origem = plano.origem;
62
65
  const destino = path.resolve(baseProjeto, "exemplos");
@@ -71,10 +74,13 @@ export async function materializarExemplosOficiais(baseProjeto = process.cwd(),
71
74
  erro: "Diretorio de exemplos oficiais nao foi encontrado no pacote da CLI.",
72
75
  };
73
76
  }
77
+ const arquivosSelecionados = somenteCaminhos
78
+ ? plano.arquivos.filter((arquivo) => somenteCaminhos.has(normalizarCaminhoExemplo(arquivo.caminhoRelativo)))
79
+ : plano.arquivos;
74
80
  const criados = [];
75
81
  const preservados = [];
76
- await validarDestinosEscritaWorkspace(baseProjeto, plano.arquivos.map((arquivo) => arquivo.caminhoRelativo));
77
- for (const arquivo of plano.arquivos) {
82
+ await validarDestinosEscritaWorkspace(baseProjeto, arquivosSelecionados.map((arquivo) => arquivo.caminhoRelativo));
83
+ for (const arquivo of arquivosSelecionados) {
78
84
  const resultado = await escreverArquivoWorkspaceSeguro(baseProjeto, arquivo.caminhoRelativo, await readFile(arquivo.origemArquivo, "utf8"), { sobrescrever: !preservarExistentes });
79
85
  if (resultado.status === "preservado") {
80
86
  preservados.push(arquivo.nome);
@@ -17,6 +17,7 @@ export interface ResumoAlvoVerificacao {
17
17
  framework: FrameworkGeracao;
18
18
  estrutura: EstruturaSaida;
19
19
  testesExecutados: boolean;
20
+ origem?: "executado" | "cache";
20
21
  }
21
22
  export interface ResumoModuloVerificacao {
22
23
  modulo: string;
@@ -1,7 +1,5 @@
1
- // SEMA-GOVERNED
2
- // M?dulo: sema.produto.orcamento_semantico
3
- // Contrato: contratos/sema/orcamento_semantico.sema
4
- // Descri??o: normaliza??o de gera??o, escrita estruturada e execu??o de testes gerados por alvo.
1
+ // SEMA-GOVERNED: sema.produto.geradores_nativos
2
+ // Descricao: normaliza geracao, escrita estruturada e execucao de testes gerados por alvo.
5
3
  import path from "node:path";
6
4
  import { spawnSync } from "node:child_process";
7
5
  import { formatarDiagnosticos } from "@sema/nucleo";
@@ -87,6 +85,8 @@ export function normalizarFonteImportacao(valor) {
87
85
  return "php";
88
86
  }
89
87
  if (valor === "nestjs"
88
+ || valor === "express"
89
+ || valor === "fastify"
90
90
  || valor === "fastapi"
91
91
  || valor === "flask"
92
92
  || valor === "nextjs"
@@ -301,7 +301,7 @@ export function executarTestesGerados(alvo, baseSaida, arquivos, silencioso = fa
301
301
  saidaErro: "Nao foi possivel localizar o runner tsx junto da CLI para executar testes TypeScript.",
302
302
  };
303
303
  }
304
- const execucao = spawnSync("node", [TSX_EXECUTOR_CLI, arquivoTeste], {
304
+ const execucao = spawnSync(process.execPath, [TSX_EXECUTOR_CLI, arquivoTeste], {
305
305
  stdio: silencioso ? "pipe" : "inherit",
306
306
  cwd: baseSaida,
307
307
  encoding: silencioso ? "utf8" : undefined,
@@ -321,7 +321,7 @@ export function executarTestesGerados(alvo, baseSaida, arquivos, silencioso = fa
321
321
  }
322
322
  return { codigoSaida: 0, quantidadeTestes, saidaPadrao: "", saidaErro: "" };
323
323
  }
324
- const execucao = spawnSync("node", ["--test", path.join(baseSaida, arquivoTeste)], {
324
+ const execucao = spawnSync(process.execPath, ["--test", path.join(baseSaida, arquivoTeste)], {
325
325
  stdio: silencioso ? "pipe" : "inherit",
326
326
  encoding: silencioso ? "utf8" : undefined,
327
327
  });