@semacode/cli 4.2.3 → 4.2.4

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.
@@ -1,10 +1,11 @@
1
+ import { emitirContextoLimitado, ARQUIVOS_CONTEXTO_PROJETO } from "./contextDelivery.js";
1
2
  // SEMA-GOVERNED: sema.governanca_ia_contexto, sema.produto.governanca_ia.drift.cache.modos
2
3
  // Descrição: preserva modos explícitos nas superfícies auxiliares de contexto.
3
4
  import { readFile } from "node:fs/promises";
4
5
  import path from "node:path";
5
6
  import pacoteCli from "../package.json" with { type: "json" };
6
7
  import { compilarCodigo, formatarDiagnosticos, lerArquivoTexto, temErros, } from "@sema/nucleo";
7
- import { carregarProjeto, resolverAlvosVerificacao, } from "./projeto.js";
8
+ import { carregarConfiguracaoProjeto, carregarProjeto, resolverAlvosVerificacao, } from "./projeto.js";
8
9
  import { SCHEMA_CACHE_VERIFICACAO, calcularChaveVerificacao, carregarCacheVerificacao, gravarCacheVerificacao, } from "./verificacaoCache.js";
9
10
  import { erroModoPreservacao, prepararImplementacaoPythonLocal, evidenciaPython } from "./verificacaoPythonLocal.js";
10
11
  const FONTES_POR_ALVO_SUPORTADO = {
@@ -52,10 +53,8 @@ export function avisoEscopoStackVerificacao(fontesLegado, alvosEfetivos) {
52
53
  }
53
54
  return `Alvos fora da stack detectada (${(fontesLegado ?? []).join(", ")}): ${foraDaStack.join(", ")}. Considere reduzir "alvos" no sema.config.json, remover "fontesLegado" auto-declaradas ou usar --alvo unico.`;
54
55
  }
55
- import { criarAgentContextPack } from './agentContextPack.js';
56
- import { criarEntrypointPack } from './entrypointPack.js';
57
56
  import { escreverArquivos, formatarAvisoArtefatosGeradosAcimaDoLimite, } from './fsGovernado.js';
58
- import { obterOpcao, possuiFlag } from './cliArgs.js';
57
+ import { obterOpcao } from './cliArgs.js';
59
58
  import { avaliarDependenciasVerificacao, imprimirFalhaDependenciasVerificacao } from './doctorCommand.js';
60
59
  import { aplicarEstruturaSaida, executarTestesGerados, executarTestesParaVerificacao, gerarArquivosPorAlvo, garantirIr, nomeSubpastaModulo, resolverConfiguracaoVerificacaoPorAlvo, validarCompatibilidadeFramework, } from './geracaoCore.js';
61
60
  import { normalizarModoResumo, normalizarTamanhoResumo } from "./index.part01.js";
@@ -66,6 +65,7 @@ export async function comandoPromptCurto(entrada, args, emJson) {
66
65
  const tamanho = normalizarTamanhoResumo(args);
67
66
  const modo = normalizarModoResumo(obterOpcao(args, "--para"));
68
67
  const alvo = entrada ? path.resolve(process.cwd(), entrada) : process.cwd();
68
+ const baseEntrega = (await carregarConfiguracaoProjeto(alvo))?.baseDiretorio ?? process.cwd();
69
69
  if (entrada && entrada.toLowerCase().endsWith(".sema")) {
70
70
  const contexto = await carregarContextoModuloIa(alvo, {
71
71
  modo: "none",
@@ -76,7 +76,7 @@ export async function comandoPromptCurto(entrada, args, emJson) {
76
76
  const capacidade = tamanho === "micro" ? "fraca" : tamanho === "curto" ? "media" : "forte";
77
77
  const prompt = criarPromptCurtoModulo(resumoSemantico, modo, tamanho, capacidade);
78
78
  if (emJson) {
79
- console.log(JSON.stringify({
79
+ if (!(await emitirContextoLimitado(baseEntrega, {
80
80
  comando: "prompt-curto",
81
81
  modo,
82
82
  tamanho,
@@ -85,47 +85,21 @@ export async function comandoPromptCurto(entrada, args, emJson) {
85
85
  arquivo: contexto.arquivo,
86
86
  modulo: contexto.modulo,
87
87
  prompt,
88
- }, null, 2));
88
+ })))
89
+ return 1;
89
90
  return 0;
90
91
  }
91
- console.log(prompt);
92
+ if (!(await emitirContextoLimitado(baseEntrega, { prompt })))
93
+ return 1;
92
94
  return 0;
93
95
  }
94
96
  const resumoProjeto = await gerarResumoProjetoIa(alvo);
95
- const arquivoResumo = tamanho === "micro"
96
- ? "SEMA_BRIEF.micro.txt"
97
- : tamanho === "curto"
98
- ? "SEMA_BRIEF.curto.txt"
99
- : "SEMA_BRIEF.md";
100
- const contextoProjeto = await readFile(path.join(resumoProjeto.pastaSaida, arquivoResumo), "utf8");
97
+ const arquivoResumo = resumoProjeto.artefatos.find(nome => ARQUIVOS_CONTEXTO_PROJETO.includes(nome));
98
+ const contextoProjeto = arquivoResumo ? await readFile(path.join(resumoProjeto.pastaSaida, arquivoResumo), "utf8") : "Resumo não gerado: confirme o perfil e o orçamento na sessão.";
101
99
  const capacidade = tamanho === "micro" ? "fraca" : tamanho === "curto" ? "media" : "forte";
102
- const prompt = `⚠️ REGRA OBRIGATÓRIA DE GOVERNANÇA:
103
-
104
- ANTES DE QUALQUER AÇÃO (editar, criar, deletar, executar, consultar ou modificar):
105
- 1. Rode \`sema docs-impacto --intencao "<ação>" --json\` com sua intenção declarada.
106
- 2. Aguarde a resposta com as docs obrigatórias.
107
- 3. Leia as docs antes de agir.
108
- 4. Antes de concluir, rode \`sema finalizar-mudanca --intencao "<ação>" --doc-lida <arquivo> --json\` com todas as docs lidas.
109
-
110
- Você está operando Sema em modo IA-first.
111
-
112
- Isto é contexto comprimido para IA operar contrato semântico antes de tocar código vivo.
113
-
114
- Capacidade alvo: ${capacidade}
115
- Modo da tarefa: ${modo}
116
-
117
- Regras:
118
- - ANTES DE TUDO: rode \`sema docs-impacto --intencao "<ação>" --json\`.
119
- - Comece pelo resumo compacto abaixo.
120
- - Se a tarefa pedir mais contexto, abra \`AGENT_CONTEXT_PACK.json\` e depois \`SEMA_INDEX.json\`.
121
- - Não tente ler o repositório inteiro se o resumo já disser onde tocar.
122
- - Preserve contrato, risco, lacuna e checks sugeridos.
123
-
124
- Contexto do projeto:
125
- ${contextoProjeto.trim()}
126
- `;
100
+ const prompt = contextoProjeto.trim();
127
101
  if (emJson) {
128
- console.log(JSON.stringify({
102
+ if (!(await emitirContextoLimitado(baseEntrega, {
129
103
  comando: "prompt-curto",
130
104
  modo,
131
105
  tamanho,
@@ -134,35 +108,25 @@ ${contextoProjeto.trim()}
134
108
  baseProjeto: resumoProjeto.baseProjeto,
135
109
  pastaSaida: resumoProjeto.pastaSaida,
136
110
  prompt,
137
- }, null, 2));
111
+ })))
112
+ return 1;
138
113
  return 0;
139
114
  }
140
- console.log(prompt);
115
+ if (!(await emitirContextoLimitado(baseEntrega, { prompt })))
116
+ return 1;
141
117
  return 0;
142
118
  }
143
119
  export async function comandoContextoIa(arquivo, pastaSaida, emJson, args = []) {
144
120
  const resultado = await gerarContextoIa(arquivo, pastaSaida);
145
- const capacidadeValor = obterOpcao(args, "--capacidade") ?? "media";
146
- const capacidade = capacidadeValor === "fraca" || capacidadeValor === "forte" ? capacidadeValor : "media";
147
- if (possuiFlag(args, "--pacote")) {
148
- const agentContextPack = criarAgentContextPack(resultado.guiaPorCapacidade);
149
- const pacote = criarEntrypointPack({
150
- agentContextPack,
151
- capacity: capacidade,
152
- rawAgentContextChars: JSON.stringify(agentContextPack).length,
153
- });
154
- console.log(JSON.stringify(pacote, null, 2));
155
- return resultado.sucesso ? 0 : 1;
156
- }
157
- if (emJson) {
158
- console.log(JSON.stringify(resultado, null, 2));
159
- return 0;
160
- }
161
- const resumoGerado = await readFile(path.join(resultado.pastaSaida, "README.md"), "utf8");
162
- console.log(`Pacote de contexto gerado em ${resultado.pastaSaida}`);
163
- console.log("");
164
- console.log(resumoGerado);
165
- return 0;
121
+ const base = (await carregarConfiguracaoProjeto(arquivo))?.baseDiretorio ?? process.cwd();
122
+ const resumo = resultado.artefatosCompactos[0];
123
+ const contexto = resumo ? await readFile(path.join(resultado.pastaSaida, resumo), "utf8") : "Resumo não gerado: confirme o perfil e o orçamento na sessão.";
124
+ const entregue = await emitirContextoLimitado(base, {
125
+ comando: "contexto-ia", sucesso: resultado.sucesso, arquivo: resultado.arquivo,
126
+ pastaSaida: resultado.pastaSaida, arquivoContexto: resumo ?? null, contexto,
127
+ evidenciasSobDemanda: ["validar", "diagnosticos", "drift --pacote", "ast", "ir"],
128
+ });
129
+ return entregue && resultado.sucesso ? 0 : 1;
166
130
  }
167
131
  export async function comandoTestar(arquivo, alvo, saida, estrutura, framework) {
168
132
  const incompatibilidade = validarCompatibilidadeFramework(alvo, framework);
@@ -90,7 +90,8 @@ Quando precisar comprovar o código vivo, rode \`sema drift <contrato.sema> --es
90
90
  - \`docs/commands.md\`: catalogo de comandos, pipelines, gates e regra de \`--saida\`.
91
91
  - \`docs/syntax.md\`: referencia curta para escrever \`.sema\`.
92
92
  - \`docs/ai-workflow.md\`: fluxo minimo para agentes.
93
- - \`SEMA_BOOT.md\`, \`SEMA_SMALL_MODEL.md\`, \`AGENT_CONTEXT_PACK.json\` e \`SEMA_INDEX.json\`: contexto IA-first.
93
+ - \`SEMA_BOOT.md\`: regras de operação. A CLI gera somente o resumo correspondente ao perfil e ao orçamento.
94
+ - \`AGENT_CONTEXT_PACK.json\` e \`SEMA_INDEX.json\`: bases internas da CLI, não carregar no contexto da IA.
94
95
 
95
96
  ## Geracao
96
97
 
package/docs/commands.md CHANGED
@@ -18,7 +18,7 @@ Then read every required doc returned by `docs-impacto`.
18
18
 
19
19
  ## Session Opening
20
20
 
21
- - `sema sessao "<intencao>" [--arquivo <contrato-ou-codigo>] [--janela-contexto <tokens>] [--orcamento-contexto <tokens>] [--reserva-saida <tokens>] [--salvar-perfil] --json`: asks for the effective window when absent and stores the profile only on explicit request. The compact response contains workspace identity, artifact freshness, matching contracts and linked files, mandatory document paths, scoped gates and next steps. The index stays inside the CLI. The budget estimates the public JSON size using characters/4; it does not measure the conversation or the model's exact tokenizer. Omitted candidates are counted and require scope refinement; mandatory readings are never silently waived. Treat `frescor.fresco:false` as a pre-action blocker and run the suggested `sema sync-codex --json`. Navigation never authorizes execution.
21
+ - `sema sessao "<intencao>" [--arquivo <contrato-ou-codigo>] [--janela-contexto <tokens>] [--orcamento-contexto <tokens>] [--reserva-saida <tokens>] [--salvar-perfil] --json`: asks for the effective window when absent and stores the profile only on explicit request. The compact response contains workspace identity, artifact freshness, matching contracts and linked files, mandatory document paths, scoped gates and next steps. The index stays inside the CLI. The budget estimates local entry instructions plus the current delivery using characters/4; it does not measure the conversation or the model's exact tokenizer. Omitted candidates are counted and require scope refinement; mandatory readings are never silently waived. Treat `frescor.fresco:false` as a pre-action blocker and run the suggested `sema sync-codex --json`. Navigation never authorizes execution.
22
22
 
23
23
  ## Public JSON output
24
24
 
@@ -91,22 +91,27 @@ Ready UI rule: if the task generates an app, site, dashboard, form, or static HT
91
91
 
92
92
  ## Codex and Context
93
93
 
94
- Session freshness checks the managed `AGENTS.md` block, `SEMA_BOOT.md` and
95
- `SEMA_SMALL_MODEL.md` against the current CLI templates as well as contract
96
- hashes. Older instructions can therefore require `sync-codex` even when no
97
- contract changed. Synchronization preserves manual rules outside the managed
98
- block. The generated workflow uses `drift --cache fresh --pacote --json`; omit
99
- `--pacote` only when full evidence is needed. A session budget limits that
100
- session response, not subsequent commands, file reads or the full conversation.
94
+ The CLI selects context files before generation: micro up to 32,768 tokens,
95
+ short up to 131,072, expanded above that. The budget may lower the selected
96
+ level further. Only the matching summary is materialized; other variants
97
+ are removed from active entry files, with existing edits preserved in
98
+ .sema/contexto-legado/. Internal indexes are not required readings.
99
+ A session already supplying the needed task context does not require another summary.
101
100
 
102
- `validar` and `formatar` require selected `.sema` contracts. An empty scope
103
- returns a nonzero exit code and `SEM_CLI_SEM_CONTRATOS`; it does not validate
104
- an application or adopt the project. Before first-time adoption, the agent
105
- must obtain consent and the effective context window.
101
+ Freshness checks managed instructions, contract hashes and changes to the
102
+ materialized context profile. Synchronization preserves manual AGENTS rules.
103
+ The budget counts AGENTS.md, SEMA_BOOT.md and the current delivery, using
104
+ characters / 4. It does not measure chat history, host instructions or
105
+ cumulative future file reads and tool results. Oversized requests must refine
106
+ the scope; no blocking rule is silently waived.
107
+
108
+ validar and formatar require selected .sema contracts. Empty scope returns
109
+ SEM_CLI_SEM_CONTRATOS and does not validate an application or adopt a project.
110
+ First-time adoption requires consent and the configured context window.
106
111
 
107
112
  - `sema ajuda-ia`: short guidance for Codex.
108
113
  - `sema starter-ia`: operational starter.
109
- - `sema contexto-ia <arquivo.sema> --saida <dir> --json`: AI context package.
114
+ - `sema contexto-ia <arquivo.sema> --saida <dir> --json`: profile-selected context files; raw AST/IR/drift are consulted separately only when needed.
110
115
  - `sema resumo <arquivo-ou-pasta> [--drift <none|cache|fresh>] --json`: compact context; drift is not executed unless requested.
111
116
  - `sema prompt-curto <arquivo-ou-pasta> --json`: compact prompt.
112
117
  - `sema sync-codex --json`: synchronizes the official Codex entrypoint and local support docs.
package/docs/syntax.md CHANGED
@@ -149,9 +149,9 @@ The project can also generate TypeScript, Python, PHP, Dart, Lua, HTML, CSS, C#/
149
149
 
150
150
  - `AGENTS.md`: official Codex repository rules, loaded automatically.
151
151
  - `SEMA_BOOT.md`: first Sema read for Codex.
152
- - `SEMA_SMALL_MODEL.md`: compact guidance for a small context budget.
153
- - `AGENT_CONTEXT_PACK.json`: structured Codex context pack.
154
- - `SEMA_INDEX.json`: project index.
152
+ - Profile-selected summary: the CLI materializes only the matching file within the configured budget. Skip it if the session already supplied the needed context.
153
+ - `AGENT_CONTEXT_PACK.json`: internal CLI policy database, not an initial read.
154
+ - `SEMA_INDEX.json`: internal CLI project index, not an initial read.
155
155
  - `docs/commands.md`: command catalog, gates, and `--saida` rule.
156
156
  - `exemplos/`: official DSL examples.
157
157
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@semacode/cli",
3
- "version": "4.2.3",
3
+ "version": "4.2.4",
4
4
  "description": "Local-first semantic governance CLI for AI agents, proven with Claude, Codex, zCode (GLM) and Kimi: contracts, drift, impact, docs gates, and code generation.",
5
5
  "type": "module",
6
6
  "icon": "logo.png",
@@ -52,7 +52,9 @@ found. If the user corrects a missed Sema workflow, resume it before more writes
52
52
  Read only the selected contract, declared dependencies and blocking docs.
53
53
  `SEMA_INDEX.json` and `AGENT_CONTEXT_PACK.json` are internal CLI databases,
54
54
  not files to preload. Resolve stale indexes or ambiguous targets before editing.
55
- The session budget estimates its response, not the whole chat.
55
+ The profile-selected summary is optional: skip it when the session already supplies the needed context.
56
+ The budget counts local entry instructions plus the current delivery, not the whole chat.
57
+ Do not load multiple summaries or choose context size from labels such as small/strong.
56
58
 
57
59
  ## CLI fallback and results
58
60