@semacode/cli 4.1.3 → 4.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agentBootstrap.d.ts +4 -0
- package/dist/agentBootstrap.js +45 -0
- package/dist/agentContext.d.ts +1 -1
- package/dist/agentContext.js +5 -5
- package/dist/agentContextPack.js +22 -31
- package/dist/agentEntryPoints.d.ts +1 -3
- package/dist/agentEntryPoints.js +16 -262
- package/dist/agentProtocol.d.ts +1 -0
- package/dist/agentProtocol.js +41 -0
- package/dist/cliArgs.js +1 -0
- package/dist/cliGrammar.js +7 -3
- package/dist/cliHelpTexto.js +2 -2
- package/dist/comandoSessao.d.ts +0 -33
- package/dist/comandoSessao.js +71 -70
- package/dist/contextBudget.d.ts +15 -0
- package/dist/contextBudget.js +64 -0
- package/dist/distribuicao/skillIntentPolicy.d.ts +1 -1
- package/dist/distribuicao/skillIntentPolicy.js +1 -0
- package/dist/docs.part01.js +0 -1
- package/dist/docs.part02.js +11 -23
- package/dist/docsRelations.d.ts +2 -0
- package/dist/docsRelations.js +83 -0
- package/dist/driftPack.js +19 -6
- package/dist/entradaContratos.d.ts +2 -0
- package/dist/entradaContratos.js +20 -0
- package/dist/index.part04.d.ts +2 -0
- package/dist/index.part04.js +13 -5
- package/dist/index.part05.js +1 -1
- package/dist/index.part06.js +15 -0
- package/dist/index.part08.js +1 -1
- package/dist/indexPack.d.ts +1 -0
- package/dist/indexPack.js +1 -1
- package/dist/initCommand.d.ts +1 -0
- package/dist/initCommand.js +10 -1
- package/dist/sessionContext.d.ts +13 -0
- package/dist/sessionContext.js +41 -0
- package/docs/ai-integration.md +5 -13
- package/docs/ai-workflow.md +8 -6
- package/docs/commands.md +14 -1
- package/docs/documentation.md +33 -0
- package/docs/drift-cache.md +7 -0
- package/exemplos/python_verificacao.sema +68 -68
- package/node_modules/@sema/gerador-python/dist/runtime.js +65 -65
- package/package.json +1 -1
- package/skills/sema/SKILL.md +57 -182
- package/skills/sema/agents/openai.yaml +4 -2
- package/skills/sema/references/distribution.md +70 -0
package/dist/index.part04.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// SEMA-GOVERNED: sema.governanca_ia_contexto, sema.produto.escrita_segura_workspace, sema.produto.governanca_ia.drift.cache.modos
|
|
2
2
|
// Descrição: gera contexto local e grava artefatos somente dentro da base validada.
|
|
3
3
|
import { mkdir, readFile } from "node:fs/promises";
|
|
4
|
+
import { diagnosticarEntradaContratos } from "./entradaContratos.js";
|
|
5
|
+
import { arquivosProtocoloDesatualizados } from "./agentProtocol.js";
|
|
4
6
|
import { createHash } from "node:crypto";
|
|
5
7
|
import path from "node:path";
|
|
6
8
|
import { formatarDiagnosticos, gerarRespostaValidacao, temErros, } from "@sema/nucleo";
|
|
@@ -82,13 +84,17 @@ export async function verificarFrescorArtefatos(baseProjeto) {
|
|
|
82
84
|
const { listarArquivosDeOrigens } = await import("./projetoOrigens.js");
|
|
83
85
|
const contratos = await listarArquivosDeOrigens(origens);
|
|
84
86
|
const hashAtual = await calcularHashContratos(contratos, baseProjeto);
|
|
85
|
-
const
|
|
87
|
+
const protocoloPendente = await arquivosProtocoloDesatualizados(baseProjeto);
|
|
88
|
+
const contratosMudaram = hashArtefato !== hashAtual;
|
|
89
|
+
const fresco = !contratosMudaram && protocoloPendente.length === 0;
|
|
86
90
|
return {
|
|
87
91
|
fresco,
|
|
88
92
|
hashArtefato,
|
|
89
93
|
hashAtual,
|
|
90
|
-
contratosMudaram
|
|
91
|
-
|
|
94
|
+
contratosMudaram,
|
|
95
|
+
protocoloAtualizado: protocoloPendente.length === 0,
|
|
96
|
+
arquivosProtocoloDesatualizados: protocoloPendente,
|
|
97
|
+
sugestao: fresco ? "" : "Índice ou protocolo de entrada desatualizado; rode sema sync-codex --json para atualizar o bloco gerenciado e preservar as regras manuais.",
|
|
92
98
|
};
|
|
93
99
|
}
|
|
94
100
|
export async function gerarResumoProjetoIa(entrada, pastaSaidaOpcional, escreverNaRaiz = false, analiseDrift = { modo: "none", executar: false, avisos: [] }) {
|
|
@@ -490,13 +496,15 @@ export async function comandoFinalizarMudanca(posicionais, args, emJson) {
|
|
|
490
496
|
}
|
|
491
497
|
export async function comandoValidar(entrada) {
|
|
492
498
|
const modulos = await carregarModulos(entrada);
|
|
493
|
-
const diagnosticos = modulos.
|
|
499
|
+
const diagnosticos = [...diagnosticarEntradaContratos(modulos.map((item) => item.caminho)),
|
|
500
|
+
...modulos.flatMap((item) => item.resultado.diagnosticos)];
|
|
494
501
|
console.log(formatarDiagnosticos(diagnosticos));
|
|
495
502
|
return temErros(diagnosticos) ? 1 : 0;
|
|
496
503
|
}
|
|
497
504
|
export async function comandoValidarJson(entrada) {
|
|
498
505
|
const modulos = await carregarModulos(entrada);
|
|
499
|
-
const diagnosticos = modulos.
|
|
506
|
+
const diagnosticos = [...diagnosticarEntradaContratos(modulos.map((item) => item.caminho)),
|
|
507
|
+
...modulos.flatMap((item) => item.resultado.diagnosticos)];
|
|
500
508
|
const resultado = gerarRespostaValidacao(diagnosticos);
|
|
501
509
|
console.log(JSON.stringify(resultado, null, 2));
|
|
502
510
|
return resultado.valido ? 0 : 1;
|
package/dist/index.part05.js
CHANGED
|
@@ -137,7 +137,7 @@ export async function comandoDrift(entrada, args, emJson, cwd = process.cwd()) {
|
|
|
137
137
|
});
|
|
138
138
|
const resultado = await analisarDriftLegado(contextoProjeto, opcoes);
|
|
139
139
|
if (possuiFlag(args, "--pacote")) {
|
|
140
|
-
const pacote = criarDriftPack(resultado, { rawDriftChars: JSON.stringify(resultado).length });
|
|
140
|
+
const pacote = criarDriftPack(resultado, { rawDriftChars: JSON.stringify(resultado, null, 2).length });
|
|
141
141
|
console.log(JSON.stringify(pacote, null, 2));
|
|
142
142
|
return resultado.sucesso ? 0 : 1;
|
|
143
143
|
}
|
package/dist/index.part06.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// SEMA-GOVERNED: sema.governanca_ia_contexto, sema.produto.governanca_ia.drift.cache.modos
|
|
2
2
|
// Descrição: resume contrato ou projeto com política explícita de análise de drift.
|
|
3
3
|
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { diagnosticarEntradaContratos } from "./entradaContratos.js";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import { compilarCodigo, formatarCodigo, formatarDiagnosticos, lerArquivoTexto, temErros, } from "@sema/nucleo";
|
|
6
7
|
import { carregarProjeto, } from "./projeto.js";
|
|
@@ -63,6 +64,20 @@ export async function comandoFormatar(entrada, verificarApenas, emJson) {
|
|
|
63
64
|
const arquivos = estatisticas.isFile()
|
|
64
65
|
? [entradaResolvida]
|
|
65
66
|
: contextoProjeto.arquivosProjeto.filter((arquivo) => arquivo.startsWith(path.resolve(entradaResolvida)));
|
|
67
|
+
const errosEntrada = diagnosticarEntradaContratos(arquivos);
|
|
68
|
+
if (errosEntrada.length > 0) {
|
|
69
|
+
if (emJson) {
|
|
70
|
+
console.log(JSON.stringify({
|
|
71
|
+
comando: "formatar", sucesso: false, modo: verificarApenas ? "check" : "write",
|
|
72
|
+
arquivos: [], totais: { arquivos: 0, alterados: 0, erros: errosEntrada.length },
|
|
73
|
+
diagnosticos: errosEntrada,
|
|
74
|
+
}, null, 2));
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
console.error(formatarDiagnosticos(errosEntrada));
|
|
78
|
+
}
|
|
79
|
+
return 1;
|
|
80
|
+
}
|
|
66
81
|
const resultados = [];
|
|
67
82
|
for (const arquivo of arquivos) {
|
|
68
83
|
const codigo = await lerArquivoTexto(arquivo);
|
package/dist/index.part08.js
CHANGED
|
@@ -34,7 +34,7 @@ export async function principal() {
|
|
|
34
34
|
let codigoSaida = 0;
|
|
35
35
|
switch (comando) {
|
|
36
36
|
case "iniciar":
|
|
37
|
-
codigoSaida = await comandoIniciar(cwd, normalizarTemplateIniciar(obterOpcao(resto, "--template")), { force: possuiFlag(resto, "--force"), exemplosCompletos: possuiFlag(resto, "--com-exemplos") });
|
|
37
|
+
codigoSaida = await comandoIniciar(cwd, normalizarTemplateIniciar(obterOpcao(resto, "--template")), { force: possuiFlag(resto, "--force"), exemplosCompletos: possuiFlag(resto, "--com-exemplos"), contextoArgs: resto });
|
|
38
38
|
break;
|
|
39
39
|
case "sessao": {
|
|
40
40
|
const { comandoSessao } = await import("./comandoSessao.js");
|
package/dist/indexPack.d.ts
CHANGED
package/dist/indexPack.js
CHANGED
|
@@ -84,7 +84,7 @@ export function selecionarIndiceContexto(input) {
|
|
|
84
84
|
.map((modulo) => compactarModulo(modulo, requestTokens, projetarResumoInteiro))
|
|
85
85
|
.filter((item) => item !== null)
|
|
86
86
|
.sort((a, b) => b.relevanceScore - a.relevanceScore || a.module.localeCompare(b.module, "pt-BR"))
|
|
87
|
-
.slice(0, projetarResumoInteiro ? input.modulos.length : 8);
|
|
87
|
+
.slice(0, input.maximoModulos ?? (projetarResumoInteiro ? input.modulos.length : 8));
|
|
88
88
|
const base = {
|
|
89
89
|
schema: "sema.ai.index-pack/v1",
|
|
90
90
|
selection,
|
package/dist/initCommand.d.ts
CHANGED
|
@@ -2,5 +2,6 @@ import { type TemplateIniciar } from "./initTemplatesBase.js";
|
|
|
2
2
|
export declare function comandoIniciar(cwd: string, template: TemplateIniciar, opcoes?: {
|
|
3
3
|
force?: boolean;
|
|
4
4
|
exemplosCompletos?: boolean;
|
|
5
|
+
contextoArgs?: string[];
|
|
5
6
|
}): Promise<number>;
|
|
6
7
|
export declare function comandoInstalarExemplos(emJson: boolean): Promise<number>;
|
package/dist/initCommand.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// SEMA-GOVERNED: sema.produto.cli_init_templates, sema.produto.escrita_segura_workspace
|
|
2
2
|
// Descrição: inicializa projetos preservando arquivos existentes e bloqueando escapes do workspace.
|
|
3
|
+
import { resolverPerfilContexto, salvarPerfilContexto, ARQUIVO_PERFIL_CONTEXTO, PERGUNTA_CONTEXTO } from "./contextBudget.js";
|
|
3
4
|
import * as fs from "node:fs";
|
|
4
5
|
import { readFile } from "node:fs/promises";
|
|
5
6
|
import path from "node:path";
|
|
@@ -57,8 +58,14 @@ const EXEMPLOS_STARTER_INICIAR = new Set([
|
|
|
57
58
|
"exemplos/autenticacao.sema",
|
|
58
59
|
]);
|
|
59
60
|
export async function comandoIniciar(cwd, template, opcoes = {}) {
|
|
60
|
-
const arquivosCompletos = arquivosTemplateIniciar(template);
|
|
61
61
|
const configAncestral = await carregarConfiguracaoProjeto(cwd);
|
|
62
|
+
const basePerfil = configAncestral?.baseDiretorio ?? cwd;
|
|
63
|
+
const perfilContexto = await resolverPerfilContexto(basePerfil, opcoes.contextoArgs ?? []);
|
|
64
|
+
if (!perfilContexto) {
|
|
65
|
+
console.log(JSON.stringify({ comando: "iniciar", sucesso: false, status: "configuracao_necessaria", pergunta: PERGUNTA_CONTEXTO, proximoPasso: "Repita iniciar com --janela-contexto <tokens>; nenhum arquivo foi criado." }));
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
const arquivosCompletos = arquivosTemplateIniciar(template);
|
|
62
69
|
const subpastaGovernada = Boolean(configAncestral
|
|
63
70
|
&& path.resolve(configAncestral.baseDiretorio) !== path.resolve(cwd));
|
|
64
71
|
// Em subpasta de workspace ja governado o config do template e omitido: a
|
|
@@ -84,6 +91,7 @@ export async function comandoIniciar(cwd, template, opcoes = {}) {
|
|
|
84
91
|
]);
|
|
85
92
|
const caminhosTemplate = new Set(arquivos.map((arquivo) => arquivo.caminhoRelativo));
|
|
86
93
|
const destinos = await validarDestinosEscritaWorkspace(cwd, [
|
|
94
|
+
...(basePerfil === cwd ? [ARQUIVO_PERFIL_CONTEXTO] : []),
|
|
87
95
|
...caminhosTemplate,
|
|
88
96
|
...exemplosIniciar.map((arquivo) => arquivo.caminhoRelativo),
|
|
89
97
|
...ARQUIVOS_RESUMO_PROJETO_IA,
|
|
@@ -95,6 +103,7 @@ export async function comandoIniciar(cwd, template, opcoes = {}) {
|
|
|
95
103
|
const arquivosParaEscrever = opcoes.force
|
|
96
104
|
? arquivos
|
|
97
105
|
: arquivos.filter((arquivo) => !existentes.has(arquivo.caminhoRelativo));
|
|
106
|
+
await salvarPerfilContexto(basePerfil, perfilContexto);
|
|
98
107
|
await escreverArquivos(cwd, arquivosParaEscrever, { inserirCabecalhoGovernado: true });
|
|
99
108
|
const exemplos = await materializarExemplosOficiais(cwd, true, opcoes.exemplosCompletos ? undefined : EXEMPLOS_STARTER_INICIAR);
|
|
100
109
|
if (!exemplos.sucesso) {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare function navegarContextoSessao(base: string, pedido: string, arquivo?: string): Promise<{
|
|
2
|
+
totalModulos: number;
|
|
3
|
+
indiceCaracteres: number;
|
|
4
|
+
candidatos: {
|
|
5
|
+
modulo: any;
|
|
6
|
+
contrato: string;
|
|
7
|
+
motivo: string;
|
|
8
|
+
resumo: any;
|
|
9
|
+
arquivos: any;
|
|
10
|
+
}[];
|
|
11
|
+
status: string;
|
|
12
|
+
execucaoAutorizada: boolean;
|
|
13
|
+
}>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// SEMA-GOVERNED: sema.produto.cli_sessao
|
|
2
|
+
// Descrição: consulta o índice local internamente e retorna candidatos rastreáveis, sem autorização de edição.
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { selecionarIndiceContexto } from "./indexPack.js";
|
|
6
|
+
import { validarDestinosEscritaWorkspace } from "./workspaceWrite.js";
|
|
7
|
+
export async function navegarContextoSessao(base, pedido, arquivo) {
|
|
8
|
+
await validarDestinosEscritaWorkspace(base, ["SEMA_INDEX.json"]);
|
|
9
|
+
const texto = await readFile(path.join(base, "SEMA_INDEX.json"), "utf8");
|
|
10
|
+
const indice = JSON.parse(texto);
|
|
11
|
+
if (!Array.isArray(indice.modulos))
|
|
12
|
+
throw new Error("Índice sem módulos; rode sema sync-codex --json.");
|
|
13
|
+
const relativo = (valor) => {
|
|
14
|
+
const absoluto = path.resolve(base, valor);
|
|
15
|
+
const rel = path.relative(base, absoluto);
|
|
16
|
+
if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
|
|
17
|
+
throw new Error("Referência de contexto fora do workspace.");
|
|
18
|
+
return rel.replace(/\\/g, "/");
|
|
19
|
+
};
|
|
20
|
+
const alvo = arquivo ? relativo(arquivo) : undefined;
|
|
21
|
+
const exatos = alvo ? indice.modulos.filter((m) => relativo(m.arquivo) === alvo
|
|
22
|
+
|| m.arquivosProvaveis?.some((p) => relativo(p) === alvo)) : [];
|
|
23
|
+
const pack = selecionarIndiceContexto({ modulos: indice.modulos, request: pedido, baseProject: base, sourceIndexChars: texto.length, maximoModulos: indice.modulos.length });
|
|
24
|
+
const encontrados = alvo ? exatos.map((m) => ({
|
|
25
|
+
module: m.modulo, contract: m.arquivo, purpose: m.faz, likelyFiles: m.arquivosProvaveis,
|
|
26
|
+
})) : pack.matches;
|
|
27
|
+
return {
|
|
28
|
+
totalModulos: indice.modulos.length,
|
|
29
|
+
indiceCaracteres: texto.length,
|
|
30
|
+
candidatos: encontrados.map((m) => ({
|
|
31
|
+
modulo: m.module,
|
|
32
|
+
contrato: relativo(m.contract),
|
|
33
|
+
motivo: alvo ? `Referência exata: ${alvo}` : "Correspondência de intenção; confirme no contrato antes de editar.",
|
|
34
|
+
resumo: m.purpose,
|
|
35
|
+
arquivos: (m.likelyFiles ?? []).map(relativo),
|
|
36
|
+
})),
|
|
37
|
+
status: encontrados.length === 0 ? "sem_correspondencia" : encontrados.length === 1 ? "contrato_localizado" : "selecionar_contrato",
|
|
38
|
+
execucaoAutorizada: false,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=sessionContext.js.map
|
package/docs/ai-integration.md
CHANGED
|
@@ -60,19 +60,11 @@ while contract-only queries keep unobserved implementation fields null inside th
|
|
|
60
60
|
|
|
61
61
|
## Codex Context Tiers
|
|
62
62
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
Codex with a medium context budget should start with `SEMA_BOOT.md`,
|
|
69
|
-
`AGENT_CONTEXT_PACK.json`, `SEMA_BRIEF.curto.txt`,
|
|
70
|
-
`SEMA_INDEX.json`, and `AGENTS.md`. They must run docs-impact, drift, and
|
|
71
|
-
impact before edits.
|
|
72
|
-
|
|
73
|
-
Codex with a large context budget may consume `AGENT_CONTEXT_PACK.json`, `SEMA_BRIEF.md`,
|
|
74
|
-
`SEMA_INDEX.json`, AST, IR, drift, and impact outputs, but larger context does
|
|
75
|
-
not remove the contract-first rule.
|
|
63
|
+
All context capacities start with AGENTS.md, SEMA_BOOT.md and sema sessao.
|
|
64
|
+
The first session asks for the effective window in tokens. Declare --janela-contexto
|
|
65
|
+
and use --salvar-perfil to remember it; --orcamento-contexto and --reserva-saida are adjustable.
|
|
66
|
+
SEMA_INDEX.json and AGENT_CONTEXT_PACK.json are internal CLI data, never mandatory full reads.
|
|
67
|
+
Read the selected contract and its declared dependencies, then the linked code. Ambiguity requires refinement.
|
|
76
68
|
|
|
77
69
|
## Governed Code
|
|
78
70
|
|
package/docs/ai-workflow.md
CHANGED
|
@@ -5,10 +5,10 @@ This is the minimum workflow for Codex in a local workspace.
|
|
|
5
5
|
|
|
6
6
|
1. Read `SEMA_BOOT.md`.
|
|
7
7
|
2. Run `sema --version`. If the shell cannot find it, use `$HOME/.sema/bin/sema` on macOS/Linux. On Windows, PowerShell resolves `sema.ps1` from PATH and cmd.exe resolves `sema.cmd`; use `& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$HOME\.sema\bin\sema-managed.ps1" --version` as the absolute fallback. Only then declare the CLI unavailable.
|
|
8
|
-
3. Run `sema
|
|
9
|
-
4. Run `sema docs-impacto --intencao "<change>" --json`.
|
|
8
|
+
3. Run `sema sessao "<intenção>" --json`; then `sema resumo <contrato> --micro --drift none --json` only for the selected contract.
|
|
9
|
+
4. Run `sema docs-impacto --intencao "<change>" --arquivo <contract> --json`.
|
|
10
10
|
5. Read every required document returned by the command.
|
|
11
|
-
6.
|
|
11
|
+
6. Consult command help or the relevant section of `docs/commands.md` when syntax, a gate or `--saida` is unclear.
|
|
12
12
|
7. If the right capability is unclear, run `sema descobrir recomendar --intencao "<goal>" --json`; do not auto-run ambiguous recommendations.
|
|
13
13
|
8. Use `exemplos/` and `docs/syntax.md` before creating or editing a contract.
|
|
14
14
|
9. Run `sema drift --cache fresh` and `sema impacto` before editing existing code.
|
|
@@ -30,9 +30,11 @@ UI rule: if the task involves an interface, minimum evidence includes desktop an
|
|
|
30
30
|
|
|
31
31
|
## Codex Context Capacity
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
-
|
|
33
|
+
All capacities use AGENTS.md -> SEMA_BOOT.md -> the contract returned by `sema sessao`.
|
|
34
|
+
The first session asks for the configured token window; declare `--janela-contexto <tokens> --salvar-perfil`.
|
|
35
|
+
Use `--orcamento-contexto` and `--reserva-saida` to allocate space. Counts use characters / 4, not the model tokenizer.
|
|
36
|
+
The CLI reads SEMA_INDEX.json internally. Do not load the full index, global pack, or unrelated modules.
|
|
37
|
+
An explicit `--arquivo` selects its contract and declared dependencies. Word matches are optional references.
|
|
36
38
|
|
|
37
39
|
## When to Generate Code
|
|
38
40
|
|
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>" --json`:
|
|
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.
|
|
22
22
|
|
|
23
23
|
## Public JSON output
|
|
24
24
|
|
|
@@ -91,6 +91,19 @@ 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.
|
|
101
|
+
|
|
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.
|
|
106
|
+
|
|
94
107
|
- `sema ajuda-ia`: short guidance for Codex.
|
|
95
108
|
- `sema starter-ia`: operational starter.
|
|
96
109
|
- `sema contexto-ia <arquivo.sema> --saida <dir> --json`: AI context package.
|
package/docs/documentation.md
CHANGED
|
@@ -47,3 +47,36 @@ same rule applies to drift and semantic-budget governance: keep a cohesive
|
|
|
47
47
|
primary capability in the root contract and move secondary responsibilities to
|
|
48
48
|
named children. Preserve task names, guarantees, implementations, and
|
|
49
49
|
`vinculos`; never create numbered part files.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
## Progressive AI Context
|
|
53
|
+
|
|
54
|
+
The mandatory entry is AGENTS.md and SEMA_BOOT.md. SEMA_INDEX.json and
|
|
55
|
+
AGENT_CONTEXT_PACK.json are internal CLI sources, not required full readings.
|
|
56
|
+
The session asks for the effective context window when it is unknown. The local
|
|
57
|
+
`.sema/contexto-ia.json` profile is saved only by `--salvar-perfil` or by `iniciar`
|
|
58
|
+
with a declared window. Reconfigure it after switching models.
|
|
59
|
+
|
|
60
|
+
`sema sessao "<intent>" --janela-contexto 32768 --salvar-perfil --json`
|
|
61
|
+
configures a 32K window. Defaults allocate 4096 estimated tokens to the session
|
|
62
|
+
response and reserve 4096 for output. Other instructions, tools, conversation
|
|
63
|
+
and code need the remaining space. `--orcamento-contexto` and `--reserva-saida`
|
|
64
|
+
adjust this split. The characters/4 estimate includes the public envelope and
|
|
65
|
+
a margin; it is not an exact tokenizer or a measurement of the client's used
|
|
66
|
+
context. The limit applies to the session response, not every legacy command
|
|
67
|
+
or the cumulative conversation. The output reserve does not configure the model.
|
|
68
|
+
|
|
69
|
+
In docs-impacto and finalizar-mudanca, `--arquivo` fixes the target. Explicit
|
|
70
|
+
contracts are included even beyond the 80th catalog entry. Source files resolve
|
|
71
|
+
through `vinculos.arquivo`. Required expansion follows declared `use` dependencies,
|
|
72
|
+
with reasons and originating contracts. Missing or ambiguous dependencies block.
|
|
73
|
+
`docs.arquivo` references are recommendations and do not expand the dependency
|
|
74
|
+
graph. Intent suggestions stay in `leituraRecomendada`, distinct from
|
|
75
|
+
`leituraObrigatoria`, and do not block closure. Pass the same target at closure
|
|
76
|
+
and confirm the selected contracts before editing code.
|
|
77
|
+
|
|
78
|
+
The context-budget and docs-relevancia tests measure actual CLI output, prove
|
|
79
|
+
that the raw index is absent, verify hash invalidation and configuration before
|
|
80
|
+
writes, and cover WhatsApp alongside 85 unrelated contracts. Drift, contract
|
|
81
|
+
and behavioral gates remain required. To roll back, restore the prior generators
|
|
82
|
+
and resolvers and run sync-codex; preserve manual blocks and the local profile.
|
package/docs/drift-cache.md
CHANGED
|
@@ -15,6 +15,13 @@ Use `--cache none` when a direct analysis must leave no persistent cache access.
|
|
|
15
15
|
Use `--drift none` when a summary or inspection should not perform drift at all.
|
|
16
16
|
The two forms are not interchangeable.
|
|
17
17
|
|
|
18
|
+
For agent workflows, use `sema drift <contract> --cache fresh --pacote --json`.
|
|
19
|
+
The compact packet preserves blockers, diagnostics and task gaps, while
|
|
20
|
+
consolidating repeated file paths and suggested checks under `guidance`.
|
|
21
|
+
Remove `--pacote` for the complete evidence. Packet telemetry estimates the
|
|
22
|
+
pretty-printed packet, including its own telemetry, using characters/4; the
|
|
23
|
+
outer CLI envelope and other conversation content are not part of that count.
|
|
24
|
+
|
|
18
25
|
## Honest Query Evidence
|
|
19
26
|
|
|
20
27
|
`sema resumo` and `sema inspecionar` default to `--drift none`. Their JSON
|
|
@@ -1,68 +1,68 @@
|
|
|
1
|
-
module exemplos.python_verificacao {
|
|
2
|
-
docs {
|
|
3
|
-
resumo: "Regressao executavel Python para garantias numericas, formulario tipado, status e metadados aninhados."
|
|
4
|
-
}
|
|
5
|
-
entity FormularioEntrega {
|
|
6
|
-
fields {
|
|
7
|
-
tipo: Texto
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
entity MetaTemplate {
|
|
11
|
-
fields {
|
|
12
|
-
original_campaign_id: Texto
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
entity Template {
|
|
16
|
-
fields {
|
|
17
|
-
_template_meta: MetaTemplate
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
entity Status {
|
|
21
|
-
fields {
|
|
22
|
-
desired_action: Texto
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
task preparar {
|
|
26
|
-
input {
|
|
27
|
-
formulario: FormularioEntrega required
|
|
28
|
-
}
|
|
29
|
-
output {
|
|
30
|
-
poolSize: Inteiro
|
|
31
|
-
workersAplicados: Inteiro
|
|
32
|
-
template: Template
|
|
33
|
-
status: Status
|
|
34
|
-
}
|
|
35
|
-
rules {
|
|
36
|
-
formulario.tipo existe
|
|
37
|
-
}
|
|
38
|
-
guarantees {
|
|
39
|
-
poolSize > 0
|
|
40
|
-
workersAplicados >= 2
|
|
41
|
-
template._template_meta existe
|
|
42
|
-
template._template_meta.original_campaign_id em ["campanha_1"]
|
|
43
|
-
status.desired_action em ["iniciar", "parar"]
|
|
44
|
-
}
|
|
45
|
-
tests {
|
|
46
|
-
caso "verifica cada saida" {
|
|
47
|
-
given {
|
|
48
|
-
formulario {
|
|
49
|
-
tipo: "entrega"
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
expect {
|
|
53
|
-
sucesso: verdadeiro
|
|
54
|
-
poolSize: 1
|
|
55
|
-
workersAplicados: 2
|
|
56
|
-
template {
|
|
57
|
-
_template_meta {
|
|
58
|
-
original_campaign_id: "campanha_1"
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
status {
|
|
62
|
-
desired_action: "iniciar"
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
1
|
+
module exemplos.python_verificacao {
|
|
2
|
+
docs {
|
|
3
|
+
resumo: "Regressao executavel Python para garantias numericas, formulario tipado, status e metadados aninhados."
|
|
4
|
+
}
|
|
5
|
+
entity FormularioEntrega {
|
|
6
|
+
fields {
|
|
7
|
+
tipo: Texto
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
entity MetaTemplate {
|
|
11
|
+
fields {
|
|
12
|
+
original_campaign_id: Texto
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
entity Template {
|
|
16
|
+
fields {
|
|
17
|
+
_template_meta: MetaTemplate
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
entity Status {
|
|
21
|
+
fields {
|
|
22
|
+
desired_action: Texto
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
task preparar {
|
|
26
|
+
input {
|
|
27
|
+
formulario: FormularioEntrega required
|
|
28
|
+
}
|
|
29
|
+
output {
|
|
30
|
+
poolSize: Inteiro
|
|
31
|
+
workersAplicados: Inteiro
|
|
32
|
+
template: Template
|
|
33
|
+
status: Status
|
|
34
|
+
}
|
|
35
|
+
rules {
|
|
36
|
+
formulario.tipo existe
|
|
37
|
+
}
|
|
38
|
+
guarantees {
|
|
39
|
+
poolSize > 0
|
|
40
|
+
workersAplicados >= 2
|
|
41
|
+
template._template_meta existe
|
|
42
|
+
template._template_meta.original_campaign_id em ["campanha_1"]
|
|
43
|
+
status.desired_action em ["iniciar", "parar"]
|
|
44
|
+
}
|
|
45
|
+
tests {
|
|
46
|
+
caso "verifica cada saida" {
|
|
47
|
+
given {
|
|
48
|
+
formulario {
|
|
49
|
+
tipo: "entrega"
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
expect {
|
|
53
|
+
sucesso: verdadeiro
|
|
54
|
+
poolSize: 1
|
|
55
|
+
workersAplicados: 2
|
|
56
|
+
template {
|
|
57
|
+
_template_meta {
|
|
58
|
+
original_campaign_id: "campanha_1"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
status {
|
|
62
|
+
desired_action: "iniciar"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -1,70 +1,70 @@
|
|
|
1
1
|
// SEMA-GOVERNED: sema.produto.gerador_python_verificacao
|
|
2
2
|
// Contrato: contratos/sema/gerador_python_verificacao.sema
|
|
3
3
|
// Descrição: acesso uniforme a mapas e entidades e síntese demonstrativa de garantias.
|
|
4
|
-
export const RUNTIME_PYTHON = `
|
|
5
|
-
import math
|
|
6
|
-
|
|
7
|
-
def sema_get(objeto, caminho):
|
|
8
|
-
for campo in caminho:
|
|
9
|
-
if objeto is None:
|
|
10
|
-
return None
|
|
11
|
-
objeto = objeto.get(campo) if isinstance(objeto, dict) else getattr(objeto, campo, None)
|
|
12
|
-
return objeto
|
|
13
|
-
|
|
14
|
-
def sema_set(objeto, caminho, valor):
|
|
15
|
-
for campo in caminho[:-1]:
|
|
16
|
-
filho = sema_get(objeto, [campo])
|
|
17
|
-
if filho is None:
|
|
18
|
-
filho = {} if isinstance(objeto, dict) else SimpleNamespace()
|
|
19
|
-
if isinstance(objeto, dict):
|
|
20
|
-
objeto[campo] = filho
|
|
21
|
-
else:
|
|
22
|
-
setattr(objeto, campo, filho)
|
|
23
|
-
if not isinstance(filho, dict) and not hasattr(filho, "__dict__"):
|
|
24
|
-
raise ValueError(f"Caminho de objeto incompatível: {campo}")
|
|
25
|
-
objeto = filho
|
|
26
|
-
if isinstance(objeto, dict):
|
|
27
|
-
objeto[caminho[-1]] = valor
|
|
28
|
-
else:
|
|
29
|
-
setattr(objeto, caminho[-1], valor)
|
|
30
|
-
|
|
31
|
-
def sema_sintetizar(atual, restricoes, inteiro=False):
|
|
32
|
-
# Apenas valores demonstrativos: expect nunca participa desta síntese.
|
|
33
|
-
def aceita(valor):
|
|
34
|
-
for operador, limite in restricoes:
|
|
35
|
-
if operador == "existe" and valor is None:
|
|
36
|
-
return False
|
|
37
|
-
if operador == "in" and valor not in limite:
|
|
38
|
-
return False
|
|
39
|
-
try:
|
|
40
|
-
if operador == "==" and valor != limite: return False
|
|
41
|
-
if operador == "!=" and valor == limite: return False
|
|
42
|
-
if operador == ">" and not valor > limite: return False
|
|
43
|
-
if operador == ">=" and not valor >= limite: return False
|
|
44
|
-
if operador == "<" and not valor < limite: return False
|
|
45
|
-
if operador == "<=" and not valor <= limite: return False
|
|
46
|
-
except TypeError:
|
|
47
|
-
return False
|
|
48
|
-
return True
|
|
49
|
-
|
|
50
|
-
candidatos = [atual]
|
|
51
|
-
numeros = []
|
|
52
|
-
for operador, limite in restricoes:
|
|
53
|
-
if operador == "in":
|
|
54
|
-
candidatos.extend(limite)
|
|
55
|
-
elif operador != "existe":
|
|
56
|
-
candidatos.append(limite)
|
|
57
|
-
if isinstance(limite, (int, float)) and not isinstance(limite, bool):
|
|
58
|
-
numeros.append(limite)
|
|
59
|
-
candidatos.extend([limite - 1, limite + 1, math.floor(limite), math.ceil(limite)])
|
|
60
|
-
numeros.sort()
|
|
61
|
-
candidatos.extend((a + b) / 2 for a, b in zip(numeros, numeros[1:]))
|
|
62
|
-
candidatos.extend([1, 0, -1, True, False, "valor_garantido", "outro_valor"])
|
|
63
|
-
for candidato in candidatos:
|
|
64
|
-
if inteiro and (not isinstance(candidato, int) or isinstance(candidato, bool)):
|
|
65
|
-
continue
|
|
66
|
-
if aceita(candidato):
|
|
67
|
-
return candidato
|
|
68
|
-
raise ValueError("Não foi possível sintetizar saída demonstrativa compatível com as garantias; forneça implementação real.")
|
|
4
|
+
export const RUNTIME_PYTHON = `
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
def sema_get(objeto, caminho):
|
|
8
|
+
for campo in caminho:
|
|
9
|
+
if objeto is None:
|
|
10
|
+
return None
|
|
11
|
+
objeto = objeto.get(campo) if isinstance(objeto, dict) else getattr(objeto, campo, None)
|
|
12
|
+
return objeto
|
|
13
|
+
|
|
14
|
+
def sema_set(objeto, caminho, valor):
|
|
15
|
+
for campo in caminho[:-1]:
|
|
16
|
+
filho = sema_get(objeto, [campo])
|
|
17
|
+
if filho is None:
|
|
18
|
+
filho = {} if isinstance(objeto, dict) else SimpleNamespace()
|
|
19
|
+
if isinstance(objeto, dict):
|
|
20
|
+
objeto[campo] = filho
|
|
21
|
+
else:
|
|
22
|
+
setattr(objeto, campo, filho)
|
|
23
|
+
if not isinstance(filho, dict) and not hasattr(filho, "__dict__"):
|
|
24
|
+
raise ValueError(f"Caminho de objeto incompatível: {campo}")
|
|
25
|
+
objeto = filho
|
|
26
|
+
if isinstance(objeto, dict):
|
|
27
|
+
objeto[caminho[-1]] = valor
|
|
28
|
+
else:
|
|
29
|
+
setattr(objeto, caminho[-1], valor)
|
|
30
|
+
|
|
31
|
+
def sema_sintetizar(atual, restricoes, inteiro=False):
|
|
32
|
+
# Apenas valores demonstrativos: expect nunca participa desta síntese.
|
|
33
|
+
def aceita(valor):
|
|
34
|
+
for operador, limite in restricoes:
|
|
35
|
+
if operador == "existe" and valor is None:
|
|
36
|
+
return False
|
|
37
|
+
if operador == "in" and valor not in limite:
|
|
38
|
+
return False
|
|
39
|
+
try:
|
|
40
|
+
if operador == "==" and valor != limite: return False
|
|
41
|
+
if operador == "!=" and valor == limite: return False
|
|
42
|
+
if operador == ">" and not valor > limite: return False
|
|
43
|
+
if operador == ">=" and not valor >= limite: return False
|
|
44
|
+
if operador == "<" and not valor < limite: return False
|
|
45
|
+
if operador == "<=" and not valor <= limite: return False
|
|
46
|
+
except TypeError:
|
|
47
|
+
return False
|
|
48
|
+
return True
|
|
49
|
+
|
|
50
|
+
candidatos = [atual]
|
|
51
|
+
numeros = []
|
|
52
|
+
for operador, limite in restricoes:
|
|
53
|
+
if operador == "in":
|
|
54
|
+
candidatos.extend(limite)
|
|
55
|
+
elif operador != "existe":
|
|
56
|
+
candidatos.append(limite)
|
|
57
|
+
if isinstance(limite, (int, float)) and not isinstance(limite, bool):
|
|
58
|
+
numeros.append(limite)
|
|
59
|
+
candidatos.extend([limite - 1, limite + 1, math.floor(limite), math.ceil(limite)])
|
|
60
|
+
numeros.sort()
|
|
61
|
+
candidatos.extend((a + b) / 2 for a, b in zip(numeros, numeros[1:]))
|
|
62
|
+
candidatos.extend([1, 0, -1, True, False, "valor_garantido", "outro_valor"])
|
|
63
|
+
for candidato in candidatos:
|
|
64
|
+
if inteiro and (not isinstance(candidato, int) or isinstance(candidato, bool)):
|
|
65
|
+
continue
|
|
66
|
+
if aceita(candidato):
|
|
67
|
+
return candidato
|
|
68
|
+
raise ValueError("Não foi possível sintetizar saída demonstrativa compatível com as garantias; forneça implementação real.")
|
|
69
69
|
`;
|
|
70
70
|
//# sourceMappingURL=runtime.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@semacode/cli",
|
|
3
|
-
"version": "4.1
|
|
3
|
+
"version": "4.2.1",
|
|
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",
|