@fontdata/ai-harness 4.1.1 → 4.3.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.
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +10 -0
- package/dist/atalhos/atalhos.js +59 -0
- package/dist/cli.js +18 -0
- package/dist/comentarios/command.js +7 -1
- package/dist/comentarios/instalar.js +63 -11
- package/dist/delphi/classificar.js +126 -0
- package/dist/delphi/command.js +76 -0
- package/dist/delphi/icone.js +37 -0
- package/dist/delphi/res.js +47 -0
- package/dist/doctor/checks.js +12 -0
- 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/dist/versao/detectar.js +13 -7
- 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/harness/references/ignores.md +35 -0
- package/templates/skills/nova-tarefa/references/isso-ja-existe.md +3 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fontdata",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.0",
|
|
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.0", "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
|
@@ -21,6 +21,9 @@ const RESERVED = new Set([
|
|
|
21
21
|
'banco-dados',
|
|
22
22
|
'banco-dados-mcp',
|
|
23
23
|
'versao',
|
|
24
|
+
'delphi',
|
|
25
|
+
'mapa',
|
|
26
|
+
'atalhos',
|
|
24
27
|
'list',
|
|
25
28
|
'run',
|
|
26
29
|
'help',
|
|
@@ -68,6 +71,9 @@ Gerenciar:
|
|
|
68
71
|
banco-dados <subcomando> Conexões de banco somente leitura: adicionar, listar, testar, usar, remover
|
|
69
72
|
banco-dados-mcp Servidor MCP de leitura do banco, usado pelo Claude Code (stdio)
|
|
70
73
|
versao detectar|calcular|aplicar Fontes de versão, próxima versão e gravação (--app, --json; aplicar --dry-run)
|
|
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)
|
|
71
77
|
list Lista todos os comandos disponíveis no catálogo
|
|
72
78
|
|
|
73
79
|
Init sem perguntas (CI):
|
|
@@ -183,6 +189,18 @@ async function main() {
|
|
|
183
189
|
const { runVersaoCommand } = await import('./versao/command.js');
|
|
184
190
|
process.exit(runVersaoCommand(argv.slice(1)));
|
|
185
191
|
}
|
|
192
|
+
if (cmd === 'delphi') {
|
|
193
|
+
const { runDelphiCommand } = await import('./delphi/command.js');
|
|
194
|
+
process.exit(await runDelphiCommand(argv.slice(1)));
|
|
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
|
+
}
|
|
186
204
|
if (cmd === 'run') {
|
|
187
205
|
const id = argv[1];
|
|
188
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
|
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, relative, sep } from 'node:path';
|
|
3
|
+
import { git, isVersioned } from '../trabalhos/arquivar.js';
|
|
4
|
+
import { varrerArquivos } from '../versao/detectar.js';
|
|
5
|
+
import { lerRes } from './res.js';
|
|
6
|
+
const RT_ICON = 3;
|
|
7
|
+
const RT_RCDATA = 10;
|
|
8
|
+
const RT_GROUP_ICON = 14;
|
|
9
|
+
const RT_VERSION = 16;
|
|
10
|
+
const RT_MANIFEST = 24;
|
|
11
|
+
export function detectarDelphi(raiz) {
|
|
12
|
+
if (varrerArquivos(raiz, '', 3, /\.(dproj|dpr)$/i).length > 0)
|
|
13
|
+
return true;
|
|
14
|
+
return Boolean(git(raiz, ['ls-files', '--', ':(icase)*.dproj', ':(icase)*.dpr'])?.trim());
|
|
15
|
+
}
|
|
16
|
+
export function emRepositorioGit(raiz) {
|
|
17
|
+
return git(raiz, ['rev-parse', '--is-inside-work-tree'])?.trim() === 'true';
|
|
18
|
+
}
|
|
19
|
+
function mesmoNome(nome, esperado) {
|
|
20
|
+
return typeof nome === 'string' && nome.toUpperCase() === esperado;
|
|
21
|
+
}
|
|
22
|
+
function recursoRegeravel(r) {
|
|
23
|
+
if (r.tipo === RT_VERSION || r.tipo === RT_ICON || r.tipo === RT_MANIFEST)
|
|
24
|
+
return true;
|
|
25
|
+
if (r.tipo === RT_GROUP_ICON)
|
|
26
|
+
return mesmoNome(r.nome, 'MAINICON');
|
|
27
|
+
if (r.tipo === RT_RCDATA)
|
|
28
|
+
return mesmoNome(r.nome, 'PLATFORMTARGETS');
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
function descreverRecurso(r) {
|
|
32
|
+
return `tipo ${r.tipo}, nome ${r.nome}`;
|
|
33
|
+
}
|
|
34
|
+
function vendorizado(raiz, caminho) {
|
|
35
|
+
const saida = git(raiz, ['check-attr', '-z', 'linguist-vendored', '--', caminho]);
|
|
36
|
+
const valor = saida?.split('\0')[2];
|
|
37
|
+
return valor === 'set' || valor === 'true';
|
|
38
|
+
}
|
|
39
|
+
function acharNaPasta(pasta, nome) {
|
|
40
|
+
let entradas;
|
|
41
|
+
try {
|
|
42
|
+
entradas = readdirSync(pasta);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
const alvo = nome.toLowerCase();
|
|
48
|
+
const achado = entradas.find((e) => e.toLowerCase() === alvo);
|
|
49
|
+
return achado === undefined ? null : join(pasta, achado);
|
|
50
|
+
}
|
|
51
|
+
function resolverSemCaixa(pasta, caminho) {
|
|
52
|
+
let atual = pasta;
|
|
53
|
+
for (const segmento of caminho.split(/[\\/]/)) {
|
|
54
|
+
if (atual === null)
|
|
55
|
+
return null;
|
|
56
|
+
if (segmento === '' || segmento === '.')
|
|
57
|
+
continue;
|
|
58
|
+
atual = segmento === '..' ? dirname(atual) : acharNaPasta(atual, segmento);
|
|
59
|
+
}
|
|
60
|
+
return atual;
|
|
61
|
+
}
|
|
62
|
+
function iconesProprios(dproj) {
|
|
63
|
+
const texto = readFileSync(dproj, 'utf8');
|
|
64
|
+
return [...texto.matchAll(/<Icon_MainIcon>([^<]*)<\/Icon_MainIcon>/gi)]
|
|
65
|
+
.map((m) => m[1].trim())
|
|
66
|
+
.filter((valor) => valor !== '' && !valor.toUpperCase().startsWith('$(BDS)'));
|
|
67
|
+
}
|
|
68
|
+
function paraPosix(caminho) {
|
|
69
|
+
return caminho.split(sep).join('/');
|
|
70
|
+
}
|
|
71
|
+
function classificar(raiz, caminho) {
|
|
72
|
+
if (vendorizado(raiz, caminho)) {
|
|
73
|
+
return { classe: 'manter', motivo: 'Pasta marcada como linguist-vendored no .gitattributes (biblioteca de terceiros).' };
|
|
74
|
+
}
|
|
75
|
+
const absoluto = join(raiz, caminho);
|
|
76
|
+
const pasta = dirname(absoluto);
|
|
77
|
+
const projeto = absoluto.slice(pasta.length + 1).replace(/\.res$/i, '');
|
|
78
|
+
const dpr = acharNaPasta(pasta, `${projeto}.dpr`);
|
|
79
|
+
const dproj = acharNaPasta(pasta, `${projeto}.dproj`);
|
|
80
|
+
if (dpr === null || dproj === null) {
|
|
81
|
+
const falta = [dpr === null ? `${projeto}.dpr` : null, dproj === null ? `${projeto}.dproj` : null].filter(Boolean);
|
|
82
|
+
return { classe: 'manter', motivo: `Falta ${falta.join(' e ')} na mesma pasta: a IDE não regera este .res.` };
|
|
83
|
+
}
|
|
84
|
+
let recursos;
|
|
85
|
+
try {
|
|
86
|
+
recursos = lerRes(readFileSync(absoluto));
|
|
87
|
+
}
|
|
88
|
+
catch (erro) {
|
|
89
|
+
return { classe: 'manter', motivo: `O .res não pôde ser lido: ${erro.message}` };
|
|
90
|
+
}
|
|
91
|
+
const proprios = recursos.filter((r) => !recursoRegeravel(r));
|
|
92
|
+
if (proprios.length > 0) {
|
|
93
|
+
return {
|
|
94
|
+
classe: 'manter',
|
|
95
|
+
motivo: `O .res tem recurso que a IDE não regera (${proprios.map(descreverRecurso).join('; ')}).`,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const temMainIcon = recursos.some((r) => r.tipo === RT_GROUP_ICON && mesmoNome(r.nome, 'MAINICON'));
|
|
99
|
+
const icones = iconesProprios(dproj);
|
|
100
|
+
if (temMainIcon && icones.length === 0) {
|
|
101
|
+
return {
|
|
102
|
+
classe: 'icone-so-no-res',
|
|
103
|
+
motivo: 'O .dproj não tem Icon_MainIcon próprio (só $(BDS)): o MAINICON existe só dentro do .res.',
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
for (const icone of icones) {
|
|
107
|
+
const ico = resolverSemCaixa(pasta, icone);
|
|
108
|
+
if (ico === null) {
|
|
109
|
+
return { classe: 'icone-so-no-res', motivo: `O Icon_MainIcon ${icone} não existe no disco: o ícone existe só dentro do .res.` };
|
|
110
|
+
}
|
|
111
|
+
if (!isVersioned(raiz, paraPosix(relative(raiz, ico)))) {
|
|
112
|
+
return { classe: 'icone-so-no-res', motivo: `O Icon_MainIcon ${icone} não está versionado: o ícone existe só dentro do .res.` };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { classe: 'regeravel', motivo: 'Só tem os recursos que a IDE regera a partir do .dproj.' };
|
|
116
|
+
}
|
|
117
|
+
/** Classifica cada `.res` rastreado pelo git, com caminho relativo à raiz e `/`; fora de um repositório, `[]`. */
|
|
118
|
+
export function classificarRes(raiz) {
|
|
119
|
+
if (!emRepositorioGit(raiz))
|
|
120
|
+
return [];
|
|
121
|
+
const saida = git(raiz, ['ls-files', '-z', '--', ':(icase)*.res']) ?? '';
|
|
122
|
+
return saida
|
|
123
|
+
.split('\0')
|
|
124
|
+
.filter((caminho) => caminho !== '')
|
|
125
|
+
.map((caminho) => ({ caminho, ...classificar(raiz, caminho) }));
|
|
126
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
3
|
+
import { acharRaiz } from '../raiz.js';
|
|
4
|
+
import { classificarRes, detectarDelphi, emRepositorioGit } from './classificar.js';
|
|
5
|
+
import { extrairIcone } from './icone.js';
|
|
6
|
+
import { lerRes } from './res.js';
|
|
7
|
+
const USO = `Uso:
|
|
8
|
+
npx @fontdata/ai-harness delphi classificar [raiz] [--json]
|
|
9
|
+
npx @fontdata/ai-harness delphi extrair-icone <arquivo.res> [--saida <arquivo.ico>]`;
|
|
10
|
+
function classificar(args) {
|
|
11
|
+
const json = args.includes('--json');
|
|
12
|
+
const posicionais = args.filter((arg) => arg !== '--json');
|
|
13
|
+
const raiz = posicionais[0] === undefined ? acharRaiz() : resolve(process.cwd(), posicionais[0]);
|
|
14
|
+
if (!emRepositorioGit(raiz)) {
|
|
15
|
+
console.error('Não é um repositório git: a classificação precisa do git ls-files.');
|
|
16
|
+
return 1;
|
|
17
|
+
}
|
|
18
|
+
const delphi = detectarDelphi(raiz);
|
|
19
|
+
const res = classificarRes(raiz);
|
|
20
|
+
if (json) {
|
|
21
|
+
console.log(JSON.stringify({ delphi, res }, null, 2));
|
|
22
|
+
return 0;
|
|
23
|
+
}
|
|
24
|
+
console.log(delphi ? 'Stack Delphi detectada.' : 'Stack Delphi não detectada.');
|
|
25
|
+
if (res.length === 0) {
|
|
26
|
+
console.log('Nenhum .res rastreado pelo git.');
|
|
27
|
+
return 0;
|
|
28
|
+
}
|
|
29
|
+
for (const item of res)
|
|
30
|
+
console.log(` ${item.caminho} ${item.classe} ${item.motivo}`);
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
function extrairIconeDoRes(args) {
|
|
34
|
+
const posicionais = [];
|
|
35
|
+
let saida;
|
|
36
|
+
for (let i = 0; i < args.length; i++) {
|
|
37
|
+
if (args[i] === '--saida')
|
|
38
|
+
saida = args[++i];
|
|
39
|
+
else
|
|
40
|
+
posicionais.push(args[i]);
|
|
41
|
+
}
|
|
42
|
+
const arquivo = posicionais[0];
|
|
43
|
+
if (!arquivo || (args.includes('--saida') && !saida)) {
|
|
44
|
+
console.error(USO);
|
|
45
|
+
return 1;
|
|
46
|
+
}
|
|
47
|
+
const origem = resolve(process.cwd(), arquivo);
|
|
48
|
+
const destino = saida
|
|
49
|
+
? resolve(process.cwd(), saida)
|
|
50
|
+
: join(dirname(origem), `${basename(origem, extname(origem))}_Icon.ico`);
|
|
51
|
+
if (existsSync(destino)) {
|
|
52
|
+
console.error(`O arquivo ${destino} já existe; não foi sobrescrito.`);
|
|
53
|
+
return 1;
|
|
54
|
+
}
|
|
55
|
+
let icone;
|
|
56
|
+
try {
|
|
57
|
+
icone = extrairIcone(lerRes(readFileSync(origem)));
|
|
58
|
+
}
|
|
59
|
+
catch (erro) {
|
|
60
|
+
const mensagem = erro instanceof Error ? erro.message : String(erro);
|
|
61
|
+
console.error(`Não foi possível extrair o ícone de ${origem}: ${mensagem}`);
|
|
62
|
+
return 1;
|
|
63
|
+
}
|
|
64
|
+
writeFileSync(destino, icone, { flag: 'wx' });
|
|
65
|
+
console.log(`Ícone MAINICON gravado em ${destino}.`);
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
export async function runDelphiCommand(args) {
|
|
69
|
+
const [sub, ...resto] = args;
|
|
70
|
+
if (sub === 'classificar')
|
|
71
|
+
return classificar(resto);
|
|
72
|
+
if (sub === 'extrair-icone')
|
|
73
|
+
return extrairIconeDoRes(resto);
|
|
74
|
+
console.error(USO);
|
|
75
|
+
return 1;
|
|
76
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const RT_ICON = 3;
|
|
2
|
+
const RT_GROUP_ICON = 14;
|
|
3
|
+
/**
|
|
4
|
+
* Monta o .ico a partir do RT_GROUP_ICON MAINICON e dos RT_ICON que ele referencia.
|
|
5
|
+
* Com dois RT_ICON de mesmo id, vale o primeiro.
|
|
6
|
+
*/
|
|
7
|
+
export function extrairIcone(recursos) {
|
|
8
|
+
const grupo = recursos.find((r) => r.tipo === RT_GROUP_ICON && typeof r.nome === 'string' && r.nome.toUpperCase() === 'MAINICON');
|
|
9
|
+
if (!grupo)
|
|
10
|
+
throw new Error('O .res não tem o grupo de ícones MAINICON.');
|
|
11
|
+
const dados = grupo.dados;
|
|
12
|
+
if (dados.length < 6)
|
|
13
|
+
throw new Error('Grupo de ícones MAINICON truncado.');
|
|
14
|
+
const count = dados.readUInt16LE(4);
|
|
15
|
+
if (dados.length < 6 + 14 * count)
|
|
16
|
+
throw new Error('Grupo de ícones MAINICON truncado.');
|
|
17
|
+
const blobs = [];
|
|
18
|
+
for (let i = 0; i < count; i++) {
|
|
19
|
+
const id = dados.readUInt16LE(6 + 14 * i + 12);
|
|
20
|
+
const icone = recursos.find((r) => r.tipo === RT_ICON && r.nome === id);
|
|
21
|
+
if (!icone)
|
|
22
|
+
throw new Error(`O grupo MAINICON referencia o RT_ICON ${id}, que não existe no .res.`);
|
|
23
|
+
blobs.push(icone.dados);
|
|
24
|
+
}
|
|
25
|
+
const cabecalho = Buffer.alloc(6 + 16 * count);
|
|
26
|
+
cabecalho.writeUInt16LE(0, 0);
|
|
27
|
+
cabecalho.writeUInt16LE(1, 2);
|
|
28
|
+
cabecalho.writeUInt16LE(count, 4);
|
|
29
|
+
let offsetBlob = cabecalho.length;
|
|
30
|
+
blobs.forEach((blob, i) => {
|
|
31
|
+
const entrada = 6 + 16 * i;
|
|
32
|
+
dados.copy(cabecalho, entrada, 6 + 14 * i, 6 + 14 * i + 12);
|
|
33
|
+
cabecalho.writeUInt32LE(offsetBlob, entrada + 12);
|
|
34
|
+
offsetBlob += blob.length;
|
|
35
|
+
});
|
|
36
|
+
return Buffer.concat([cabecalho, ...blobs]);
|
|
37
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
function alinhar4(valor) {
|
|
2
|
+
return (valor + 3) & ~3;
|
|
3
|
+
}
|
|
4
|
+
function lerIdentificador(buffer, inicio, fim) {
|
|
5
|
+
if (inicio + 2 > fim)
|
|
6
|
+
throw new Error(`Cabeçalho de recurso inválido no offset ${inicio} do .res.`);
|
|
7
|
+
if (buffer.readUInt16LE(inicio) === 0xffff) {
|
|
8
|
+
if (inicio + 4 > fim)
|
|
9
|
+
throw new Error(`Cabeçalho de recurso inválido no offset ${inicio} do .res.`);
|
|
10
|
+
return { valor: buffer.readUInt16LE(inicio + 2), proximo: inicio + 4 };
|
|
11
|
+
}
|
|
12
|
+
for (let i = inicio; i + 2 <= fim; i += 2) {
|
|
13
|
+
if (buffer.readUInt16LE(i) === 0) {
|
|
14
|
+
return { valor: buffer.toString('utf16le', inicio, i), proximo: i + 2 };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
throw new Error(`Cabeçalho de recurso inválido no offset ${inicio} do .res: nome sem terminador.`);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Lê um arquivo de recursos Win32 de 32 bits, ignorando a entrada vazia do início.
|
|
21
|
+
* Lança Error em pt-BR quando o arquivo está truncado ou tem cabeçalho inválido.
|
|
22
|
+
*/
|
|
23
|
+
export function lerRes(buffer) {
|
|
24
|
+
const recursos = [];
|
|
25
|
+
let offset = 0;
|
|
26
|
+
while (offset < buffer.length) {
|
|
27
|
+
if (offset + 8 > buffer.length)
|
|
28
|
+
throw new Error(`Arquivo .res truncado no offset ${offset}.`);
|
|
29
|
+
const dataSize = buffer.readUInt32LE(offset);
|
|
30
|
+
const headerSize = buffer.readUInt32LE(offset + 4);
|
|
31
|
+
if (headerSize < 16) {
|
|
32
|
+
throw new Error(`Cabeçalho de recurso inválido no offset ${offset} do .res: HeaderSize ${headerSize}.`);
|
|
33
|
+
}
|
|
34
|
+
const fimCabecalho = offset + headerSize;
|
|
35
|
+
const fimDados = fimCabecalho + dataSize;
|
|
36
|
+
if (fimDados > buffer.length)
|
|
37
|
+
throw new Error(`Arquivo .res truncado no recurso do offset ${offset}.`);
|
|
38
|
+
const tipo = lerIdentificador(buffer, offset + 8, fimCabecalho);
|
|
39
|
+
const nome = lerIdentificador(buffer, tipo.proximo, fimCabecalho);
|
|
40
|
+
const vazia = offset === 0 && dataSize === 0 && tipo.valor === 0;
|
|
41
|
+
if (!vazia) {
|
|
42
|
+
recursos.push({ tipo: tipo.valor, nome: nome.valor, dados: Buffer.from(buffer.subarray(fimCabecalho, fimDados)) });
|
|
43
|
+
}
|
|
44
|
+
offset = alinhar4(fimDados);
|
|
45
|
+
}
|
|
46
|
+
return recursos;
|
|
47
|
+
}
|
package/dist/doctor/checks.js
CHANGED
|
@@ -8,6 +8,7 @@ import { COMMENTS_HOOK_PATH, hookProprioRegistrado } from '../comentarios/instal
|
|
|
8
8
|
import { CONFIG_PATH, readConfig } from '../config/config.js';
|
|
9
9
|
import { ARCHIVE_DIR_NAME, ARTIFACT_TYPES, listWorkFiles, readArtifact, validateAllWorks, WORKS_DIR } from '../contratos/artefatos.js';
|
|
10
10
|
import { validateEventLog } from '../contratos/eventos.js';
|
|
11
|
+
import { classificarRes } from '../delphi/classificar.js';
|
|
11
12
|
import { hashContent, LOCK_PATH, LOCK_VERSION } from '../install/lock.js';
|
|
12
13
|
import { agentsForaDoLock, itemSources } from '../install/plan.js';
|
|
13
14
|
import { hookCommands, SETTINGS_PATH } from '../install/settings.js';
|
|
@@ -253,6 +254,16 @@ function checkGitIgnore(root) {
|
|
|
253
254
|
},
|
|
254
255
|
];
|
|
255
256
|
}
|
|
257
|
+
function checkDelphiRes(root) {
|
|
258
|
+
return classificarRes(root)
|
|
259
|
+
.filter((res) => res.classe !== 'manter')
|
|
260
|
+
.map((res) => ({
|
|
261
|
+
id: 'delphi-res-versionado',
|
|
262
|
+
severidade: 'aviso',
|
|
263
|
+
mensagem: `${res.caminho} está versionado e é ${res.classe}: ${res.motivo}`,
|
|
264
|
+
correcao: 'Rode a etapa `/harness ignores` para classificar, extrair o ícone se preciso e tirar o .res do versionamento com aprovação.',
|
|
265
|
+
}));
|
|
266
|
+
}
|
|
256
267
|
function checkWorks(root) {
|
|
257
268
|
return validateAllWorks(root).map((problem) => ({
|
|
258
269
|
id: `contrato-${problem.regra}`,
|
|
@@ -650,6 +661,7 @@ export function runDoctor(root, options = {}) {
|
|
|
650
661
|
...checkAgents(root),
|
|
651
662
|
...checkSettings(root),
|
|
652
663
|
...checkGitIgnore(root),
|
|
664
|
+
...checkDelphiRes(root),
|
|
653
665
|
...checkConfig(configProblems),
|
|
654
666
|
...checkBanco(root, config),
|
|
655
667
|
...checkWorks(root),
|
|
@@ -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
|
+
}
|