@fontdata/ai-harness 4.2.0 → 4.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +10 -0
- package/dist/atalhos/atalhos.js +59 -0
- package/dist/cli.js +12 -0
- package/dist/comentarios/command.js +7 -1
- package/dist/comentarios/instalar.js +63 -11
- package/dist/contratos/artefatos.js +13 -5
- package/dist/fontes/listar.js +80 -0
- package/dist/mapa/config.js +152 -0
- package/dist/mapa/extratores/csharp.js +33 -0
- package/dist/mapa/extratores/dart.js +31 -0
- package/dist/mapa/extratores/go.js +17 -0
- package/dist/mapa/extratores/index.js +33 -0
- package/dist/mapa/extratores/java.js +7 -0
- package/dist/mapa/extratores/js.js +22 -0
- package/dist/mapa/extratores/kotlin.js +18 -0
- package/dist/mapa/extratores/pascal.js +39 -0
- package/dist/mapa/extratores/php.js +18 -0
- package/dist/mapa/extratores/python.js +19 -0
- package/dist/mapa/extratores/rust.js +19 -0
- package/dist/mapa/extratores/tipos.js +1 -0
- package/dist/mapa/mapa.js +123 -0
- package/dist/update/update.js +14 -2
- package/dist/versao/config.js +1 -1
- package/package.json +1 -1
- package/templates/agents/auditor-plano.md +4 -1
- package/templates/agents/investigador.md +3 -0
- package/templates/agents/qa.md +1 -0
- package/templates/agents/revisor-spec.md +6 -3
- package/templates/agents/revisor-testes.md +3 -1
- package/templates/commands/revisar-pr.md +21 -3
- package/templates/hooks/comentarios/check.mjs +208 -41
- package/templates/rules/comentarios.md +8 -2
- package/templates/skills/auditar-performance/SKILL.md +11 -1
- package/templates/skills/auditar-seguranca/SKILL.md +8 -0
- package/templates/skills/auditar-ui/SKILL.md +8 -0
- package/templates/skills/evoluir-harness/references/code-reviewer.md +16 -5
- package/templates/skills/executar-plan/references/delegacao.md +14 -3
- package/templates/skills/nova-tarefa/references/isso-ja-existe.md +3 -0
- package/templates/skills/resolver-bug/SKILL.md +8 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fontdata",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.1",
|
|
4
4
|
"mcpServers": {
|
|
5
|
-
"banco_dados": { "command": "npx", "args": ["-y", "@fontdata/ai-harness@4.
|
|
5
|
+
"banco_dados": { "command": "npx", "args": ["-y", "@fontdata/ai-harness@4.3.1", "banco-dados-mcp"] }
|
|
6
6
|
},
|
|
7
7
|
"description": "Harness de engenharia com IA da Fontdata para Claude Code",
|
|
8
8
|
"author": { "name": "Fontdata" },
|
package/README.md
CHANGED
|
@@ -167,9 +167,19 @@ projeto, cadastro, limites do filtro, produção, mascaramento e dúvidas freque
|
|
|
167
167
|
| `banco-dados <subcomando>` | Conexões de banco somente leitura: `adicionar`, `listar`, `testar`, `usar`, `remover` |
|
|
168
168
|
| `banco-dados-mcp` | Servidor MCP de leitura do banco, iniciado pelo Claude Code |
|
|
169
169
|
| `comentarios [caminho]` | Instala o hook do padrão de comentários com a catraca do legado (`--yes`) |
|
|
170
|
+
| `mapa [caminho]` | Símbolos públicos por pasta do código-fonte, pastas compartilhadas primeiro (`--limite <n>`, padrão 4000 caracteres) |
|
|
171
|
+
| `atalhos [caminho]` | Lista os `TODO:`/`FIXME:` do código-fonte e marca os sem gatilho (`--sem-gatilho`, `--json`) |
|
|
170
172
|
| `versao detectar\|calcular\|aplicar` | Fontes de versão do projeto, próxima versão e gravação nos arquivos (veja abaixo) |
|
|
171
173
|
| `list` | Lista o catálogo |
|
|
172
174
|
|
|
175
|
+
O `mapa` lê TS/JS, Delphi, Python, C#, Java, Kotlin, Go, PHP, Rust e Dart. Outra linguagem, ou outra regra para uma
|
|
176
|
+
dessas, entra pelo `.ai-harness/mapa.json`, opcional: o primeiro grupo de captura de cada casamento é o nome, e o
|
|
177
|
+
item substitui o extrator embutido da extensão. O formato está em [`docs/contratos/MAPA.md`](docs/contratos/MAPA.md).
|
|
178
|
+
|
|
179
|
+
```json
|
|
180
|
+
{ "extratores": [{ "extensoes": [".rb"], "padrao": "^\\s*def\\s+(\\w+)", "rotina": true }] }
|
|
181
|
+
```
|
|
182
|
+
|
|
173
183
|
### Subcomando `versao`
|
|
174
184
|
|
|
175
185
|
`npx @fontdata/ai-harness versao detectar|calcular|aplicar` é a parte determinística do `/versao`, para qualquer
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { templatesDir } from '../catalog.js';
|
|
4
|
+
import { suggestFlag } from '../install/flags.js';
|
|
5
|
+
import { acharRaiz } from '../raiz.js';
|
|
6
|
+
const FLAGS = ['--sem-gatilho', '--json'];
|
|
7
|
+
/** Atalhos do projeto em `raiz`, pela regra do `check.mjs` do pacote (a única implementação dela). */
|
|
8
|
+
export function listarAtalhos(raiz) {
|
|
9
|
+
const check = join(templatesDir, 'hooks', 'comentarios', 'check.mjs');
|
|
10
|
+
const r = spawnSync(process.execPath, [check, '--atalhos'], {
|
|
11
|
+
env: { ...process.env, CLAUDE_PROJECT_DIR: raiz },
|
|
12
|
+
encoding: 'utf8',
|
|
13
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
14
|
+
});
|
|
15
|
+
if (r.error)
|
|
16
|
+
throw r.error;
|
|
17
|
+
if (r.status !== 0)
|
|
18
|
+
throw new Error(`check.mjs --atalhos saiu com ${r.status}: ${r.stderr.trim()}`);
|
|
19
|
+
return JSON.parse(r.stdout);
|
|
20
|
+
}
|
|
21
|
+
function formatar(a) {
|
|
22
|
+
const fim = a.gatilho === null ? 'sem-gatilho' : `→ ${a.gatilho}`;
|
|
23
|
+
return `${a.arquivo}:${a.linha} ${a.marcador} ${a.limite} ${fim}`;
|
|
24
|
+
}
|
|
25
|
+
/** `atalhos [caminho] [--sem-gatilho] [--json]`: consulta, sai sempre com 0. */
|
|
26
|
+
export function runShortcutsCommand(argv) {
|
|
27
|
+
let caminho;
|
|
28
|
+
let soSemGatilho = false;
|
|
29
|
+
let json = false;
|
|
30
|
+
for (const token of argv) {
|
|
31
|
+
if (!token.startsWith('-')) {
|
|
32
|
+
if (caminho !== undefined)
|
|
33
|
+
throw new Error(`Argumento inesperado: ${token}`);
|
|
34
|
+
caminho = token;
|
|
35
|
+
}
|
|
36
|
+
else if (token === '--sem-gatilho') {
|
|
37
|
+
soSemGatilho = true;
|
|
38
|
+
}
|
|
39
|
+
else if (token === '--json') {
|
|
40
|
+
json = true;
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
const sugestao = suggestFlag(token, FLAGS);
|
|
44
|
+
throw new Error(`Flag desconhecida: ${token}.${sugestao ? ` Você quis dizer ${sugestao}?` : ''}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const raiz = caminho === undefined ? acharRaiz() : resolve(process.cwd(), caminho);
|
|
48
|
+
const todos = listarAtalhos(raiz);
|
|
49
|
+
const semGatilho = todos.filter((a) => a.gatilho === null);
|
|
50
|
+
const exibidos = soSemGatilho ? semGatilho : todos;
|
|
51
|
+
if (json) {
|
|
52
|
+
console.log(JSON.stringify(exibidos, null, 2));
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
for (const a of exibidos)
|
|
56
|
+
console.log(formatar(a));
|
|
57
|
+
console.log(`${todos.length} ${todos.length === 1 ? 'atalho' : 'atalhos'}, ${semGatilho.length} sem gatilho`);
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -22,6 +22,8 @@ const RESERVED = new Set([
|
|
|
22
22
|
'banco-dados-mcp',
|
|
23
23
|
'versao',
|
|
24
24
|
'delphi',
|
|
25
|
+
'mapa',
|
|
26
|
+
'atalhos',
|
|
25
27
|
'list',
|
|
26
28
|
'run',
|
|
27
29
|
'help',
|
|
@@ -70,6 +72,8 @@ Gerenciar:
|
|
|
70
72
|
banco-dados-mcp Servidor MCP de leitura do banco, usado pelo Claude Code (stdio)
|
|
71
73
|
versao detectar|calcular|aplicar Fontes de versão, próxima versão e gravação (--app, --json; aplicar --dry-run)
|
|
72
74
|
delphi classificar|extrair-icone .res de projetos Delphi: classificação e extração do ícone
|
|
75
|
+
mapa [caminho] Símbolos públicos por pasta, compartilhadas primeiro (--limite <n>, padrão 4000 caracteres)
|
|
76
|
+
atalhos [caminho] TODO:/FIXME: do código-fonte, marcando os sem gatilho (--sem-gatilho, --json)
|
|
73
77
|
list Lista todos os comandos disponíveis no catálogo
|
|
74
78
|
|
|
75
79
|
Init sem perguntas (CI):
|
|
@@ -189,6 +193,14 @@ async function main() {
|
|
|
189
193
|
const { runDelphiCommand } = await import('./delphi/command.js');
|
|
190
194
|
process.exit(await runDelphiCommand(argv.slice(1)));
|
|
191
195
|
}
|
|
196
|
+
if (cmd === 'mapa') {
|
|
197
|
+
const { runMapCommand } = await import('./mapa/mapa.js');
|
|
198
|
+
process.exit(runMapCommand(argv.slice(1)));
|
|
199
|
+
}
|
|
200
|
+
if (cmd === 'atalhos') {
|
|
201
|
+
const { runShortcutsCommand } = await import('./atalhos/atalhos.js');
|
|
202
|
+
process.exit(runShortcutsCommand(argv.slice(1)));
|
|
203
|
+
}
|
|
192
204
|
if (cmd === 'run') {
|
|
193
205
|
const id = argv[1];
|
|
194
206
|
if (!id) {
|
|
@@ -8,7 +8,7 @@ import { hashContent } from '../install/lock.js';
|
|
|
8
8
|
import { executePlan, packageInfo } from '../install/plan.js';
|
|
9
9
|
import { mergeSettings } from '../install/settings.js';
|
|
10
10
|
import { acharRaiz } from '../raiz.js';
|
|
11
|
-
import { COMMENTS_BASELINE_PATH, COMMENTS_HOOK_PATH, COMMENTS_RULE_PATH, commentsHooksConfig, ensureCommentsBaseline, hookProprioRegistrado } from './instalar.js';
|
|
11
|
+
import { COMMENTS_BASELINE_PATH, COMMENTS_HOOK_PATH, COMMENTS_RULE_PATH, commentsHooksConfig, completarCommentsBaseline, descreverCompletarBaseline, descreverLimpezaBaseline, ensureCommentsBaseline, hookProprioRegistrado, limparCommentsBaseline } from './instalar.js';
|
|
12
12
|
export { COMMENTS_HOOK_PATH } from './instalar.js';
|
|
13
13
|
const FLAGS = ['--yes', '-y', '--sim'];
|
|
14
14
|
/** `ai-harness comentarios [caminho] [--yes]`: instala a rule, o hook de comentários e a catraca do legado. */
|
|
@@ -76,6 +76,12 @@ export function runCommentsCommand(argv) {
|
|
|
76
76
|
mergeSettings(root, { hooks: commentsHooksConfig() });
|
|
77
77
|
// Instalar pelo comando desfaz uma recusa guardada pelo `--sem-comentarios`.
|
|
78
78
|
gravarInstalarComentarios(root, true);
|
|
79
|
+
const limpeza = descreverLimpezaBaseline(limparCommentsBaseline(root));
|
|
80
|
+
if (limpeza)
|
|
81
|
+
console.log(`${EOL}${limpeza}`);
|
|
82
|
+
const acrescimo = descreverCompletarBaseline(completarCommentsBaseline(root));
|
|
83
|
+
if (acrescimo)
|
|
84
|
+
console.log(`${EOL}${acrescimo}`);
|
|
79
85
|
const legacy = ensureCommentsBaseline(root);
|
|
80
86
|
if (legacy !== null) {
|
|
81
87
|
console.log(`${EOL}Catraca gerada: ${legacy} arquivo(s) legado(s) com violações toleradas. Eles não precisam ser limpos de uma vez, só não podem piorar.`);
|
|
@@ -29,23 +29,75 @@ export function hookProprioRegistrado(root) {
|
|
|
29
29
|
}
|
|
30
30
|
return hookCommands(hooks ?? {}).some((command) => command.includes('.claude/hooks/comentarios/') && normalizarComandoHook(command) !== COMMENTS_HOOK_COMMAND);
|
|
31
31
|
}
|
|
32
|
+
function hookDoPacoteInstalado(root) {
|
|
33
|
+
const hook = join(root, COMMENTS_HOOK_PATH);
|
|
34
|
+
if (!existsSync(hook) || hashContent(readFileSync(hook)) !== hashContent(readFileSync(COMMENTS_HOOK_TEMPLATE)))
|
|
35
|
+
return null;
|
|
36
|
+
return hook;
|
|
37
|
+
}
|
|
38
|
+
function rodarHook(root, hook, modo, falha) {
|
|
39
|
+
const result = spawnSync(process.execPath, [hook, modo], {
|
|
40
|
+
env: { ...process.env, CLAUDE_PROJECT_DIR: root },
|
|
41
|
+
encoding: 'utf8',
|
|
42
|
+
});
|
|
43
|
+
if (result.status !== 0)
|
|
44
|
+
throw new Error(`${falha}: ${result.stderr}`);
|
|
45
|
+
}
|
|
46
|
+
function entradasDoBaseline(root) {
|
|
47
|
+
try {
|
|
48
|
+
return Object.keys(JSON.parse(readFileSync(join(root, COMMENTS_BASELINE_PATH), 'utf8'))).length;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
32
54
|
/**
|
|
33
55
|
* Gera a catraca do legado na primeira instalação e devolve quantos arquivos entraram nela. Devolve `null` quando
|
|
34
56
|
* ela já existe (regerar reabriria tolerâncias que já desceram) ou quando o `check.mjs` do projeto não é o do
|
|
35
57
|
* pacote, que pode não saber gerá-la.
|
|
36
58
|
*/
|
|
37
59
|
export function ensureCommentsBaseline(root) {
|
|
38
|
-
|
|
39
|
-
if (existsSync(join(root, COMMENTS_BASELINE_PATH)) || !existsSync(hook))
|
|
60
|
+
if (existsSync(join(root, COMMENTS_BASELINE_PATH)))
|
|
40
61
|
return null;
|
|
41
|
-
const
|
|
42
|
-
if (
|
|
62
|
+
const hook = hookDoPacoteInstalado(root);
|
|
63
|
+
if (hook === null)
|
|
43
64
|
return null;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
65
|
+
rodarHook(root, hook, '--gerar-baseline', 'Falha ao gerar a catraca do legado');
|
|
66
|
+
return entradasDoBaseline(root);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Tira da catraca existente as entradas de arquivo inexistente ou que não é código-fonte e devolve quantas saíram.
|
|
70
|
+
* Devolve `null` sem tocar nela quando não há baseline, ele não é JSON válido ou o hook do projeto não é o do pacote.
|
|
71
|
+
*/
|
|
72
|
+
export function limparCommentsBaseline(root) {
|
|
73
|
+
const variacao = rodarNoBaselineExistente(root, '--limpar-baseline', 'Falha ao limpar a catraca do legado');
|
|
74
|
+
return variacao === null ? null : -variacao;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Acrescenta à catraca existente os arquivos legados das extensões recém-cobertas e devolve quantos entraram.
|
|
78
|
+
* Devolve `null` nas mesmas condições da limpeza.
|
|
79
|
+
*/
|
|
80
|
+
export function completarCommentsBaseline(root) {
|
|
81
|
+
return rodarNoBaselineExistente(root, '--completar-baseline', 'Falha ao completar a catraca do legado');
|
|
82
|
+
}
|
|
83
|
+
function rodarNoBaselineExistente(root, modo, falha) {
|
|
84
|
+
if (!existsSync(join(root, COMMENTS_BASELINE_PATH)) || hookProprioRegistrado(root))
|
|
85
|
+
return null;
|
|
86
|
+
const hook = hookDoPacoteInstalado(root);
|
|
87
|
+
if (hook === null)
|
|
88
|
+
return null;
|
|
89
|
+
const antes = entradasDoBaseline(root);
|
|
90
|
+
if (antes === null)
|
|
91
|
+
return null;
|
|
92
|
+
rodarHook(root, hook, modo, falha);
|
|
93
|
+
const depois = entradasDoBaseline(root);
|
|
94
|
+
return depois === null ? null : depois - antes;
|
|
95
|
+
}
|
|
96
|
+
/** Linha do relatório para a limpeza da catraca; vazia quando nada saiu. */
|
|
97
|
+
export function descreverLimpezaBaseline(removidas) {
|
|
98
|
+
return removidas ? `${COMMENTS_BASELINE_PATH}: ${removidas} entrada(s) removida(s) do baseline (arquivo inexistente ou que não é código-fonte).` : null;
|
|
99
|
+
}
|
|
100
|
+
/** Linha do relatório para o acréscimo à catraca; vazia quando nada entrou. */
|
|
101
|
+
export function descreverCompletarBaseline(acrescentadas) {
|
|
102
|
+
return acrescentadas ? `${COMMENTS_BASELINE_PATH}: ${acrescentadas} entrada(s) acrescentada(s) ao baseline (legado de extensão recém-coberta).` : null;
|
|
51
103
|
}
|
|
@@ -45,14 +45,22 @@ function isData(value) {
|
|
|
45
45
|
function isStringList(value) {
|
|
46
46
|
return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
|
|
47
47
|
}
|
|
48
|
+
function frontmatterAusente(file, content) {
|
|
49
|
+
const linhas = content.replace(/^/, '').split(/\r?\n/);
|
|
50
|
+
if (linhas[0] !== '---') {
|
|
51
|
+
return { arquivo: file, regra: 'frontmatter-ausente', mensagem: 'O artefato não começa com um frontmatter YAML entre ---.', linha: 1 };
|
|
52
|
+
}
|
|
53
|
+
const colada = linhas.findIndex((linha, i) => i > 0 && linha.trim() !== '---' && linha.trimEnd().endsWith('---'));
|
|
54
|
+
const mensagem = 'O frontmatter abre com --- na linha 1, mas falta o --- de fechamento em linha própria';
|
|
55
|
+
return colada > 0
|
|
56
|
+
? { arquivo: file, regra: 'frontmatter-ausente', mensagem: `${mensagem}: a linha ${colada + 1} termina com --- colado ao texto.`, linha: colada + 1 }
|
|
57
|
+
: { arquivo: file, regra: 'frontmatter-ausente', mensagem: `${mensagem}.`, linha: 1 };
|
|
58
|
+
}
|
|
48
59
|
/** Lê o frontmatter de um artefato; `data` ausente quando há problema de leitura. */
|
|
49
60
|
export function readArtifact(file, content) {
|
|
50
61
|
const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content);
|
|
51
|
-
if (!match)
|
|
52
|
-
return {
|
|
53
|
-
problems: [{ arquivo: file, regra: 'frontmatter-ausente', mensagem: 'O artefato não começa com um frontmatter YAML entre ---.', linha: 1 }],
|
|
54
|
-
};
|
|
55
|
-
}
|
|
62
|
+
if (!match)
|
|
63
|
+
return { problems: [frontmatterAusente(file, content)] };
|
|
56
64
|
let data;
|
|
57
65
|
try {
|
|
58
66
|
data = parse(match[1] ?? '');
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readdirSync, statSync } from 'node:fs';
|
|
3
|
+
import { extname, join } from 'node:path';
|
|
4
|
+
const EXTENSOES = new Set([
|
|
5
|
+
'.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',
|
|
6
|
+
'.py', '.go', '.rs', '.java', '.cs', '.php',
|
|
7
|
+
'.pas', '.dpr', '.dpk', '.lpr', '.sql', '.sh', '.bash', '.zsh',
|
|
8
|
+
'.ps1', '.psm1', '.bat', '.cmd', '.dart', '.kt', '.kts',
|
|
9
|
+
]);
|
|
10
|
+
const PASTAS_EXCLUIDAS = new Set([
|
|
11
|
+
'node_modules', 'docs', 'doc', 'dist', 'build', 'coverage', 'out', 'vendor', 'migrations', 'generated',
|
|
12
|
+
'__generated__', '__history', '__recovery', 'fixtures', 'samples', 'examples', 'exemplos',
|
|
13
|
+
]);
|
|
14
|
+
const ARQUIVO_EXCLUIDO = [
|
|
15
|
+
/\.d\.ts$/, /\.(test|spec)\.[jt]sx?$/, /\.min\.js$/i, /bundle[^/]*\.js$/i,
|
|
16
|
+
/\.(g|freezed|mocks|gr)\.dart$/, /^generated_plugin_registrant\.dart$/,
|
|
17
|
+
];
|
|
18
|
+
function pastaExcluida(nome) {
|
|
19
|
+
return nome.startsWith('.') || PASTAS_EXCLUIDAS.has(nome.toLowerCase());
|
|
20
|
+
}
|
|
21
|
+
function dependenciaBoss(raiz, pastas) {
|
|
22
|
+
return pastas.some((nome, i) => nome.toLowerCase() === 'modules' && existsSync(join(raiz, ...pastas.slice(0, i), 'boss.json')));
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Critério de código-fonte só pelo caminho relativo (aceita `/` ou `\`); não consulta o `.gitignore`.
|
|
26
|
+
* `extensoesExtras` soma extensões às padrão, comparadas com a caixa exata do nome do arquivo.
|
|
27
|
+
*/
|
|
28
|
+
export function ehFonte(raiz, relativo, extensoesExtras = []) {
|
|
29
|
+
const partes = relativo.split(/[\\/]/).filter((p) => p !== '' && p !== '.');
|
|
30
|
+
const nome = partes.pop();
|
|
31
|
+
if (!nome)
|
|
32
|
+
return false;
|
|
33
|
+
const ext = extname(nome);
|
|
34
|
+
if (!EXTENSOES.has(ext) && !extensoesExtras.includes(ext))
|
|
35
|
+
return false;
|
|
36
|
+
if (ARQUIVO_EXCLUIDO.some((re) => re.test(nome)))
|
|
37
|
+
return false;
|
|
38
|
+
if (partes.some(pastaExcluida))
|
|
39
|
+
return false;
|
|
40
|
+
return !dependenciaBoss(raiz, partes);
|
|
41
|
+
}
|
|
42
|
+
function listarPeloGit(raiz) {
|
|
43
|
+
const r = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
|
|
44
|
+
cwd: raiz,
|
|
45
|
+
encoding: 'utf8',
|
|
46
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
47
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
48
|
+
});
|
|
49
|
+
if (r.error || r.status !== 0)
|
|
50
|
+
return null;
|
|
51
|
+
return [...new Set(r.stdout.split('\0').filter((c) => c !== ''))].filter((c) => {
|
|
52
|
+
try {
|
|
53
|
+
return statSync(join(raiz, c)).isFile();
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function varrer(raiz, prefixo, saida) {
|
|
61
|
+
for (const entrada of readdirSync(join(raiz, prefixo), { withFileTypes: true })) {
|
|
62
|
+
const rel = prefixo ? `${prefixo}/${entrada.name}` : entrada.name;
|
|
63
|
+
if (entrada.isDirectory()) {
|
|
64
|
+
if (!pastaExcluida(entrada.name))
|
|
65
|
+
varrer(raiz, rel, saida);
|
|
66
|
+
}
|
|
67
|
+
else if (entrada.isFile()) {
|
|
68
|
+
saida.push(rel);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Arquivos de código-fonte da raiz, relativos e com `/`, em ordem; com git, respeita o `.gitignore`. */
|
|
73
|
+
export function listarFontes(raiz, extensoesExtras = []) {
|
|
74
|
+
let candidatos = listarPeloGit(raiz);
|
|
75
|
+
if (!candidatos) {
|
|
76
|
+
candidatos = [];
|
|
77
|
+
varrer(raiz, '', candidatos);
|
|
78
|
+
}
|
|
79
|
+
return candidatos.filter((c) => ehFonte(raiz, c, extensoesExtras)).sort();
|
|
80
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { contarGrupos } from '../versao/config.js';
|
|
4
|
+
export const MAPA_CONFIG_PATH = join('.ai-harness', 'mapa.json');
|
|
5
|
+
const ORIGEM = MAPA_CONFIG_PATH.split('\\').join('/');
|
|
6
|
+
const CAMPOS_RAIZ = ['$schema', 'extratores'];
|
|
7
|
+
const CAMPOS_EXTRATOR = ['extensoes', 'padrao', 'rotina'];
|
|
8
|
+
const EXTENSAO = /^\.[^.\s/\\]+$/;
|
|
9
|
+
export class MapaConfigErro extends Error {
|
|
10
|
+
problemas;
|
|
11
|
+
constructor(problemas) {
|
|
12
|
+
super(`${ORIGEM} inválido:\n${problemas.map((p) => `- ${p}`).join('\n')}`);
|
|
13
|
+
this.problemas = problemas;
|
|
14
|
+
this.name = 'MapaConfigErro';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function isObject(value) {
|
|
18
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
function extratorRegex(nome, padrao, rotina) {
|
|
21
|
+
return {
|
|
22
|
+
nome,
|
|
23
|
+
extrair(texto) {
|
|
24
|
+
return [...texto.matchAll(new RegExp(padrao, 'gm'))]
|
|
25
|
+
.map((m) => m[1] ?? '')
|
|
26
|
+
.filter((n) => n !== '')
|
|
27
|
+
.map((n) => (rotina ? `${n}()` : n));
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
class Validador {
|
|
32
|
+
problemas = [];
|
|
33
|
+
extratores = new Map();
|
|
34
|
+
origemDa = new Map();
|
|
35
|
+
erro(caminho, mensagem) {
|
|
36
|
+
this.problemas.push(`${caminho}: ${mensagem}`);
|
|
37
|
+
}
|
|
38
|
+
camposDesconhecidos(obj, aceitos, prefixo) {
|
|
39
|
+
for (const chave of Object.keys(obj)) {
|
|
40
|
+
if (!aceitos.includes(chave)) {
|
|
41
|
+
this.erro(prefixo ? `${prefixo}.${chave}` : chave, `campo desconhecido; os aceitos são ${aceitos.filter((c) => c !== '$schema').join(', ')}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
extensoes(valor, prefixo) {
|
|
46
|
+
const caminho = `${prefixo}.extensoes`;
|
|
47
|
+
if (valor === undefined) {
|
|
48
|
+
this.erro(caminho, 'é obrigatório: lista de extensões com ponto, ex.: [".rb"]');
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
if (!Array.isArray(valor)) {
|
|
52
|
+
this.erro(caminho, 'deve ser uma lista de extensões com ponto, ex.: [".rb"]');
|
|
53
|
+
return [];
|
|
54
|
+
}
|
|
55
|
+
if (valor.length === 0)
|
|
56
|
+
this.erro(caminho, 'deve ter ao menos uma extensão');
|
|
57
|
+
return valor.flatMap((item, indice) => {
|
|
58
|
+
const campo = `${caminho}[${indice}]`;
|
|
59
|
+
if (typeof item !== 'string') {
|
|
60
|
+
this.erro(campo, 'deve ser um texto com a extensão, ex.: ".rb"');
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
if (!EXTENSAO.test(item)) {
|
|
64
|
+
this.erro(campo, `deve começar com ponto e ter uma extensão só, ex.: ".rb": "${item}"`);
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
const extensao = item.toLowerCase();
|
|
68
|
+
const anterior = this.origemDa.get(extensao);
|
|
69
|
+
if (anterior !== undefined) {
|
|
70
|
+
this.erro(campo, `a extensão "${extensao}" já aparece em ${anterior}; cada extensão vale em um item só`);
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
this.origemDa.set(extensao, prefixo);
|
|
74
|
+
return [extensao];
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
padrao(valor, caminho) {
|
|
78
|
+
if (typeof valor !== 'string' || valor === '') {
|
|
79
|
+
this.erro(caminho, 'é obrigatório: texto com a expressão regular e um grupo de captura para o nome');
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
let grupos;
|
|
83
|
+
try {
|
|
84
|
+
grupos = contarGrupos(valor);
|
|
85
|
+
}
|
|
86
|
+
catch (erro) {
|
|
87
|
+
this.erro(caminho, `expressão regular inválida: ${erro.message}`);
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
if (grupos < 1) {
|
|
91
|
+
this.erro(caminho, 'a expressão precisa de um grupo de captura com o nome, ex.: ^def\\s+(\\w+)');
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
return valor;
|
|
95
|
+
}
|
|
96
|
+
rotina(valor, caminho) {
|
|
97
|
+
if (valor === undefined)
|
|
98
|
+
return false;
|
|
99
|
+
if (typeof valor !== 'boolean') {
|
|
100
|
+
this.erro(caminho, 'deve ser booleano (true ou false)');
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
return valor;
|
|
104
|
+
}
|
|
105
|
+
lista(valor) {
|
|
106
|
+
if (valor === undefined)
|
|
107
|
+
return;
|
|
108
|
+
if (!Array.isArray(valor)) {
|
|
109
|
+
this.erro('extratores', 'deve ser uma lista de { extensoes, padrao, rotina }');
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
valor.forEach((item, indice) => {
|
|
113
|
+
const prefixo = `extratores[${indice}]`;
|
|
114
|
+
if (!isObject(item)) {
|
|
115
|
+
this.erro(prefixo, 'deve ser um objeto { extensoes, padrao, rotina }');
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
this.camposDesconhecidos(item, CAMPOS_EXTRATOR, prefixo);
|
|
119
|
+
const extensoes = this.extensoes(item.extensoes, prefixo);
|
|
120
|
+
const padrao = this.padrao(item.padrao, `${prefixo}.padrao`);
|
|
121
|
+
const rotina = this.rotina(item.rotina, `${prefixo}.rotina`);
|
|
122
|
+
if (padrao === undefined)
|
|
123
|
+
return;
|
|
124
|
+
for (const extensao of extensoes)
|
|
125
|
+
this.extratores.set(extensao, extratorRegex(`${ORIGEM} ${prefixo}`, padrao, rotina));
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Extratores do `.ai-harness/mapa.json` por extensão em minúsculas; vazio quando o arquivo não existe.
|
|
131
|
+
* Lança `MapaConfigErro` com todos os problemas, cada um com o caminho do campo.
|
|
132
|
+
*/
|
|
133
|
+
export function lerConfigMapa(raiz) {
|
|
134
|
+
const caminho = join(raiz, MAPA_CONFIG_PATH);
|
|
135
|
+
if (!existsSync(caminho))
|
|
136
|
+
return new Map();
|
|
137
|
+
let bruto;
|
|
138
|
+
try {
|
|
139
|
+
bruto = JSON.parse(readFileSync(caminho, 'utf8').replace(/^\uFEFF/, ''));
|
|
140
|
+
}
|
|
141
|
+
catch (erro) {
|
|
142
|
+
throw new MapaConfigErro([`JSON inválido: ${erro.message}`]);
|
|
143
|
+
}
|
|
144
|
+
if (!isObject(bruto))
|
|
145
|
+
throw new MapaConfigErro(['a raiz deve ser um objeto JSON']);
|
|
146
|
+
const v = new Validador();
|
|
147
|
+
v.camposDesconhecidos(bruto, CAMPOS_RAIZ, '');
|
|
148
|
+
v.lista(bruto.extratores);
|
|
149
|
+
if (v.problemas.length > 0)
|
|
150
|
+
throw new MapaConfigErro(v.problemas);
|
|
151
|
+
return v.extratores;
|
|
152
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const NOME = '[\\p{L}_$][\\p{L}\\p{N}_$]*';
|
|
2
|
+
const GENERICO = '<[^=()]*>';
|
|
3
|
+
const TIPO_RETORNO = `(?:\\([^()=]*\\)|[\\p{L}\\p{N}_$.:]+(?:\\s*${GENERICO})?)(?:\\s*\\[[\\s,]*\\])*\\??`;
|
|
4
|
+
/** Extrator de linguagem em que só a linha que começa com `public` é pública (C# e Java). */
|
|
5
|
+
export function criarExtratorPublic(nome, regra) {
|
|
6
|
+
const modsTipo = regra.modificadoresTipo.join('|');
|
|
7
|
+
const modsMetodo = regra.modificadoresMetodo.join('|');
|
|
8
|
+
const tipo = new RegExp(`^\\s*public\\s+(?:(?:${modsTipo})\\s+)*(?:${regra.palavrasTipo.join('|')})\\s+(${NOME})`, 'u');
|
|
9
|
+
// Sem o lookahead, `public static Foo(` casaria com `static` como tipo de retorno e o construtor entraria.
|
|
10
|
+
const metodo = new RegExp(`^\\s*public\\s+(?:(?:${modsMetodo})\\s+)*(?:${GENERICO}\\s+)?(?!(?:${modsMetodo})\\s)${TIPO_RETORNO}\\s+(${NOME})\\s*(?:${GENERICO})?\\s*\\(`, 'u');
|
|
11
|
+
return {
|
|
12
|
+
nome,
|
|
13
|
+
extrair(texto) {
|
|
14
|
+
const simbolos = [];
|
|
15
|
+
for (const linha of texto.split('\n')) {
|
|
16
|
+
const nomeTipo = tipo.exec(linha)?.[1];
|
|
17
|
+
if (nomeTipo) {
|
|
18
|
+
simbolos.push(nomeTipo);
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const nomeMetodo = metodo.exec(linha)?.[1];
|
|
22
|
+
if (nomeMetodo)
|
|
23
|
+
simbolos.push(`${nomeMetodo}()`);
|
|
24
|
+
}
|
|
25
|
+
return simbolos;
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export const extratorCsharp = criarExtratorPublic('csharp', {
|
|
30
|
+
modificadoresTipo: ['static', 'sealed', 'abstract', 'partial', 'readonly'],
|
|
31
|
+
palavrasTipo: ['class', 'interface', 'struct', 'record(?:\\s+(?:struct|class))?', 'enum'],
|
|
32
|
+
modificadoresMetodo: ['static', 'virtual', 'override', 'abstract', 'async', 'sealed', 'new', 'extern'],
|
|
33
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const NOME = '([A-Za-z$][\\w$]*)';
|
|
2
|
+
const TIPO = /^(?:(?:abstract|sealed|base|final|interface|mixin)\s+)*(?:class|mixin|enum)\s+([A-Za-z$_][\w$]*)/;
|
|
3
|
+
const EXTENSAO = /^extension\s+(?!on\b)([A-Za-z$_][\w$]*)/;
|
|
4
|
+
const TYPEDEF = /^typedef\s+(?:[\w$<>?,.\s]+\s+)?([A-Za-z$_][\w$]*)\s*[=<(]/;
|
|
5
|
+
const FUNCAO = new RegExp(`^([A-Za-z$_](?:[\\w$<>?,.\\s]*?[\\w$>?])?)\\s+${NOME}\\s*(?:<[^()]*>\\s*)?\\(`);
|
|
6
|
+
const PALAVRAS_CHAVE = new Set([
|
|
7
|
+
'import', 'export', 'part', 'library', 'return', 'if', 'else', 'for', 'while', 'do', 'switch', 'case',
|
|
8
|
+
'default', 'await', 'yield', 'throw', 'rethrow', 'new', 'const', 'final', 'var', 'late', 'assert', 'try',
|
|
9
|
+
'catch', 'on', 'show', 'hide', 'as', 'is', 'in', 'break', 'continue', 'class', 'enum', 'mixin',
|
|
10
|
+
'extension', 'typedef',
|
|
11
|
+
]);
|
|
12
|
+
function simboloDaLinha(linha) {
|
|
13
|
+
const tipo = TIPO.exec(linha)?.[1] ?? EXTENSAO.exec(linha)?.[1] ?? TYPEDEF.exec(linha)?.[1];
|
|
14
|
+
if (tipo)
|
|
15
|
+
return tipo.startsWith('_') ? undefined : tipo;
|
|
16
|
+
const funcao = FUNCAO.exec(linha);
|
|
17
|
+
if (!funcao)
|
|
18
|
+
return undefined;
|
|
19
|
+
const primeiraPalavra = /^[\w$]+/.exec(funcao[1])?.[0] ?? '';
|
|
20
|
+
return PALAVRAS_CHAVE.has(primeiraPalavra) ? undefined : `${funcao[2]}()`;
|
|
21
|
+
}
|
|
22
|
+
function simbolosDart(texto) {
|
|
23
|
+
const simbolos = [];
|
|
24
|
+
for (const linha of texto.split('\n')) {
|
|
25
|
+
const simbolo = simboloDaLinha(linha);
|
|
26
|
+
if (simbolo)
|
|
27
|
+
simbolos.push(simbolo);
|
|
28
|
+
}
|
|
29
|
+
return simbolos;
|
|
30
|
+
}
|
|
31
|
+
export const extratorDart = { nome: 'dart', extrair: simbolosDart };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const FUNCAO = /^func\s+(?:\([^)]*\)\s*)?(\p{Lu}[\p{L}\p{N}_]*)\s*[[(]/u;
|
|
2
|
+
const TIPO = /^type\s+(\p{Lu}[\p{L}\p{N}_]*)/u;
|
|
3
|
+
function simbolosGo(texto) {
|
|
4
|
+
const simbolos = [];
|
|
5
|
+
for (const linha of texto.split('\n')) {
|
|
6
|
+
const funcao = FUNCAO.exec(linha)?.[1];
|
|
7
|
+
if (funcao) {
|
|
8
|
+
simbolos.push(`${funcao}()`);
|
|
9
|
+
continue;
|
|
10
|
+
}
|
|
11
|
+
const tipo = TIPO.exec(linha)?.[1];
|
|
12
|
+
if (tipo)
|
|
13
|
+
simbolos.push(tipo);
|
|
14
|
+
}
|
|
15
|
+
return simbolos;
|
|
16
|
+
}
|
|
17
|
+
export const extratorGo = { nome: 'go', extrair: simbolosGo };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { extratorCsharp } from './csharp.js';
|
|
2
|
+
import { extratorDart } from './dart.js';
|
|
3
|
+
import { extratorGo } from './go.js';
|
|
4
|
+
import { extratorJava } from './java.js';
|
|
5
|
+
import { extratorJs } from './js.js';
|
|
6
|
+
import { extratorKotlin } from './kotlin.js';
|
|
7
|
+
import { extratorPascal } from './pascal.js';
|
|
8
|
+
import { extratorPhp } from './php.js';
|
|
9
|
+
import { extratorPython } from './python.js';
|
|
10
|
+
import { extratorRust } from './rust.js';
|
|
11
|
+
const POR_EXTENSAO = new Map([
|
|
12
|
+
['.ts', extratorJs],
|
|
13
|
+
['.tsx', extratorJs],
|
|
14
|
+
['.js', extratorJs],
|
|
15
|
+
['.jsx', extratorJs],
|
|
16
|
+
['.mjs', extratorJs],
|
|
17
|
+
['.cjs', extratorJs],
|
|
18
|
+
['.pas', extratorPascal],
|
|
19
|
+
['.py', extratorPython],
|
|
20
|
+
['.cs', extratorCsharp],
|
|
21
|
+
['.java', extratorJava],
|
|
22
|
+
['.kt', extratorKotlin],
|
|
23
|
+
['.kts', extratorKotlin],
|
|
24
|
+
['.go', extratorGo],
|
|
25
|
+
['.php', extratorPhp],
|
|
26
|
+
['.rs', extratorRust],
|
|
27
|
+
['.dart', extratorDart],
|
|
28
|
+
]);
|
|
29
|
+
export const EXTENSOES_MAPA = new Set(POR_EXTENSAO.keys());
|
|
30
|
+
/** Extrator embutido da extensão (com o ponto), comparada em minúsculas; `undefined` se não há. */
|
|
31
|
+
export function extratorPara(extensao) {
|
|
32
|
+
return POR_EXTENSAO.get(extensao.toLowerCase());
|
|
33
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { criarExtratorPublic } from './csharp.js';
|
|
2
|
+
const MODIFICADORES = ['static', 'final', 'abstract', 'sealed', 'non-sealed', 'synchronized', 'default'];
|
|
3
|
+
export const extratorJava = criarExtratorPublic('java', {
|
|
4
|
+
modificadoresTipo: MODIFICADORES,
|
|
5
|
+
palavrasTipo: ['class', 'interface', 'enum', 'record'],
|
|
6
|
+
modificadoresMetodo: MODIFICADORES,
|
|
7
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const NOME = '([A-Za-z_$][\\w$]*)';
|
|
2
|
+
const FORMAS_JS = [
|
|
3
|
+
[new RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${NOME}`), (n) => `${n}()`],
|
|
4
|
+
[new RegExp(`^export\\s+(?:default\\s+)?(?:abstract\\s+)?class\\s+${NOME}`), (n) => n],
|
|
5
|
+
[new RegExp(`^export\\s+(?:const\\s+enum|interface|type|enum)\\s+${NOME}`), (n) => n],
|
|
6
|
+
[new RegExp(`^export\\s+(?:const|let|var)\\s+${NOME}`), (n) => n],
|
|
7
|
+
[new RegExp(`^export\\s+default\\s+(?!(?:async|function|class|abstract)\\b)${NOME}\\s*;?\\s*$`), (n) => `default: ${n}`],
|
|
8
|
+
];
|
|
9
|
+
function simbolosJs(texto) {
|
|
10
|
+
const simbolos = [];
|
|
11
|
+
for (const linha of texto.split('\n')) {
|
|
12
|
+
for (const [forma, formatar] of FORMAS_JS) {
|
|
13
|
+
const nome = forma.exec(linha)?.[1];
|
|
14
|
+
if (nome) {
|
|
15
|
+
simbolos.push(formatar(nome));
|
|
16
|
+
break;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return simbolos;
|
|
21
|
+
}
|
|
22
|
+
export const extratorJs = { nome: 'js', extrair: simbolosJs };
|