@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.
Files changed (45) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/README.md +10 -0
  3. package/dist/atalhos/atalhos.js +59 -0
  4. package/dist/cli.js +18 -0
  5. package/dist/comentarios/command.js +7 -1
  6. package/dist/comentarios/instalar.js +63 -11
  7. package/dist/delphi/classificar.js +126 -0
  8. package/dist/delphi/command.js +76 -0
  9. package/dist/delphi/icone.js +37 -0
  10. package/dist/delphi/res.js +47 -0
  11. package/dist/doctor/checks.js +12 -0
  12. package/dist/fontes/listar.js +80 -0
  13. package/dist/mapa/config.js +152 -0
  14. package/dist/mapa/extratores/csharp.js +33 -0
  15. package/dist/mapa/extratores/dart.js +31 -0
  16. package/dist/mapa/extratores/go.js +17 -0
  17. package/dist/mapa/extratores/index.js +33 -0
  18. package/dist/mapa/extratores/java.js +7 -0
  19. package/dist/mapa/extratores/js.js +22 -0
  20. package/dist/mapa/extratores/kotlin.js +18 -0
  21. package/dist/mapa/extratores/pascal.js +39 -0
  22. package/dist/mapa/extratores/php.js +18 -0
  23. package/dist/mapa/extratores/python.js +19 -0
  24. package/dist/mapa/extratores/rust.js +19 -0
  25. package/dist/mapa/extratores/tipos.js +1 -0
  26. package/dist/mapa/mapa.js +123 -0
  27. package/dist/update/update.js +14 -2
  28. package/dist/versao/config.js +1 -1
  29. package/dist/versao/detectar.js +13 -7
  30. package/package.json +1 -1
  31. package/templates/agents/auditor-plano.md +4 -1
  32. package/templates/agents/investigador.md +3 -0
  33. package/templates/agents/qa.md +1 -0
  34. package/templates/agents/revisor-spec.md +6 -3
  35. package/templates/agents/revisor-testes.md +3 -1
  36. package/templates/commands/revisar-pr.md +21 -3
  37. package/templates/hooks/comentarios/check.mjs +208 -41
  38. package/templates/rules/comentarios.md +8 -2
  39. package/templates/skills/auditar-performance/SKILL.md +11 -1
  40. package/templates/skills/auditar-seguranca/SKILL.md +8 -0
  41. package/templates/skills/auditar-ui/SKILL.md +8 -0
  42. package/templates/skills/evoluir-harness/references/code-reviewer.md +16 -5
  43. package/templates/skills/executar-plan/references/delegacao.md +14 -3
  44. package/templates/skills/harness/references/ignores.md +35 -0
  45. package/templates/skills/nova-tarefa/references/isso-ja-existe.md +3 -0
@@ -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 };
@@ -0,0 +1,18 @@
1
+ const ANOTACOES = '(?:@[\\w.:]+(?:\\([^)]*\\))?\\s+)*';
2
+ const MODIFICADORES = '((?:(?:public|private|internal|protected|open|abstract|final|sealed|data|enum|inner|value|annotation|override|inline|suspend|operator|infix|tailrec|external|expect|actual)\\s+)*)';
3
+ const TIPO = new RegExp(`^\\s*${ANOTACOES}${MODIFICADORES}(?:class|interface|object)\\s+([A-Za-z_]\\w*)`);
4
+ const FUNCAO = new RegExp(`^\\s*${ANOTACOES}${MODIFICADORES}fun\\s+(?:<[^>]*>\\s*)?(?:[\\w.<>?,* ]+\\.)?([A-Za-z_]\\w*)\\s*\\(`);
5
+ const RESTRITO = /\b(?:private|internal|protected)\b/;
6
+ function simbolosKotlin(texto) {
7
+ const simbolos = [];
8
+ for (const linha of texto.split('\n')) {
9
+ const tipo = TIPO.exec(linha);
10
+ const funcao = tipo ? null : FUNCAO.exec(linha);
11
+ const casamento = tipo ?? funcao;
12
+ if (!casamento || RESTRITO.test(casamento[1] ?? ''))
13
+ continue;
14
+ simbolos.push(tipo ? casamento[2] : `${casamento[2]}()`);
15
+ }
16
+ return simbolos;
17
+ }
18
+ export const extratorKotlin = { nome: 'kotlin', extrair: simbolosKotlin };
@@ -0,0 +1,39 @@
1
+ function semComentariosPascal(texto) {
2
+ return texto.replace(/\{[^}]*\}|\(\*[\s\S]*?\*\)|\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ' '));
3
+ }
4
+ function simbolosPascal(texto) {
5
+ const limpo = semComentariosPascal(texto);
6
+ const inicio = /^\s*interface\b/im.exec(limpo);
7
+ if (!inicio)
8
+ return [];
9
+ const resto = limpo.slice(inicio.index + inicio[0].length);
10
+ const fim = /^\s*implementation\b/im.exec(resto);
11
+ const secao = fim ? resto.slice(0, fim.index) : resto;
12
+ const simbolos = [];
13
+ let profundidade = 0;
14
+ for (const linha of secao.split('\n')) {
15
+ const tipo = /^\s*([A-Za-z_]\w*)\s*=\s*(?:packed\s+)?(class|record|interface|dispinterface)\b(.*)$/i.exec(linha);
16
+ if (tipo) {
17
+ const depois = tipo[3] ?? '';
18
+ if (/^\s*;/.test(depois) || /^\s*of\b/i.test(depois))
19
+ continue;
20
+ if (profundidade === 0)
21
+ simbolos.push(tipo[1] ?? '');
22
+ if (!/^\s*(\([^)]*\))?\s*;/.test(depois))
23
+ profundidade++;
24
+ continue;
25
+ }
26
+ if (profundidade > 0) {
27
+ if (/:\s*(?:packed\s+)?record\b/i.test(linha))
28
+ profundidade++;
29
+ else if (/^\s*end\s*;/i.test(linha))
30
+ profundidade--;
31
+ continue;
32
+ }
33
+ const rotina = /^\s*(?:function|procedure)\s+([A-Za-z_]\w*)\s*(?![\w.])/i.exec(linha);
34
+ if (rotina)
35
+ simbolos.push(`${rotina[1]}()`);
36
+ }
37
+ return simbolos;
38
+ }
39
+ export const extratorPascal = { nome: 'pascal', extrair: simbolosPascal };
@@ -0,0 +1,18 @@
1
+ const TIPO = /^\s*(?:(?:abstract|final|readonly)\s+)*(?:class|interface|trait|enum)\s+([A-Za-z_]\w*)/;
2
+ const FUNCAO = /^\s*((?:(?:public|private|protected|static|abstract|final)\s+)*)function\s+&?\s*([A-Za-z_]\w*)\s*\(/;
3
+ const RESTRITO = /\b(?:private|protected)\b/;
4
+ function simbolosPhp(texto) {
5
+ const simbolos = [];
6
+ for (const linha of texto.split('\n')) {
7
+ const tipo = TIPO.exec(linha)?.[1];
8
+ if (tipo) {
9
+ simbolos.push(tipo);
10
+ continue;
11
+ }
12
+ const funcao = FUNCAO.exec(linha);
13
+ if (funcao && !RESTRITO.test(funcao[1] ?? ''))
14
+ simbolos.push(`${funcao[2]}()`);
15
+ }
16
+ return simbolos;
17
+ }
18
+ export const extratorPhp = { nome: 'php', extrair: simbolosPhp };
@@ -0,0 +1,19 @@
1
+ const NOME = '(\\p{L}[\\p{L}\\p{N}_]*)';
2
+ const FORMAS_PYTHON = [
3
+ [new RegExp(`^(?:async\\s+)?def\\s+${NOME}`, 'u'), (n) => `${n}()`],
4
+ [new RegExp(`^class\\s+${NOME}`, 'u'), (n) => n],
5
+ ];
6
+ function simbolosPython(texto) {
7
+ const simbolos = [];
8
+ for (const linha of texto.split('\n')) {
9
+ for (const [forma, formatar] of FORMAS_PYTHON) {
10
+ const nome = forma.exec(linha)?.[1];
11
+ if (nome) {
12
+ simbolos.push(formatar(nome));
13
+ break;
14
+ }
15
+ }
16
+ }
17
+ return simbolos;
18
+ }
19
+ export const extratorPython = { nome: 'python', extrair: simbolosPython };
@@ -0,0 +1,19 @@
1
+ const NOME = '([A-Za-z_]\\w*)';
2
+ const FORMAS_RUST = [
3
+ [new RegExp(`^\\s*pub\\s+(?:(?:const|async|unsafe|extern(?:\\s+"[^"]*")?)\\s+)*fn\\s+${NOME}`), (n) => `${n}()`],
4
+ [new RegExp(`^\\s*pub\\s+(?:unsafe\\s+)?(?:struct|enum|trait|type|mod|const)\\s+${NOME}`), (n) => n],
5
+ ];
6
+ function simbolosRust(texto) {
7
+ const simbolos = [];
8
+ for (const linha of texto.split('\n')) {
9
+ for (const [forma, formatar] of FORMAS_RUST) {
10
+ const nome = forma.exec(linha)?.[1];
11
+ if (nome) {
12
+ simbolos.push(formatar(nome));
13
+ break;
14
+ }
15
+ }
16
+ }
17
+ return simbolos;
18
+ }
19
+ export const extratorRust = { nome: 'rust', extrair: simbolosRust };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,123 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { basename, extname, join, posix, relative, resolve } from 'node:path';
3
+ import { listarFontes } from '../fontes/listar.js';
4
+ import { suggestFlag } from '../install/flags.js';
5
+ import { acharRaiz } from '../raiz.js';
6
+ import { lerConfigMapa, MapaConfigErro } from './config.js';
7
+ import { extratorPara } from './extratores/index.js';
8
+ const PASTAS_COMPARTILHADAS = new Set([
9
+ 'lib', 'utils', 'util', 'shared', 'common', 'core', 'comum', 'compartilhado', 'helpers',
10
+ ]);
11
+ const LIMITE_PADRAO = 4000;
12
+ const FLAGS = ['--limite'];
13
+ function simbolosDoArquivo(caminho, doProjeto) {
14
+ const extensao = extname(caminho).toLowerCase();
15
+ const extrator = doProjeto.get(extensao) ?? extratorPara(extensao);
16
+ if (!extrator)
17
+ return [];
18
+ const texto = readFileSync(caminho, 'utf8').replace(/\r\n?/g, '\n');
19
+ return [...new Set(extrator.extrair(texto))];
20
+ }
21
+ function compartilhada(pasta) {
22
+ return PASTAS_COMPARTILHADAS.has(posix.basename(pasta).toLowerCase());
23
+ }
24
+ /**
25
+ * Símbolos públicos por pasta imediata, em texto, com as pastas compartilhadas primeiro e corte por pasta inteira
26
+ * em `limite` caracteres. `pasta` (relativa à raiz, com `/`) restringe a listagem a essa subpasta.
27
+ * O regex do `.ai-harness/mapa.json` substitui o extrator embutido da extensão; config inválida lança `MapaConfigErro`.
28
+ */
29
+ export function gerarMapa(raiz, opcoes) {
30
+ const prefixo = opcoes.pasta ? `${opcoes.pasta.replace(/\/+$/, '')}/` : '';
31
+ const doProjeto = lerConfigMapa(raiz);
32
+ const porPasta = new Map();
33
+ for (const rel of listarFontes(raiz, [...doProjeto.keys()])) {
34
+ if (!rel.startsWith(prefixo))
35
+ continue;
36
+ const simbolos = simbolosDoArquivo(join(raiz, rel), doProjeto);
37
+ if (simbolos.length === 0)
38
+ continue;
39
+ const pasta = posix.dirname(rel);
40
+ const linhas = porPasta.get(pasta) ?? [];
41
+ linhas.push(` ${basename(rel)}: ${simbolos.join(', ')}`);
42
+ porPasta.set(pasta, linhas);
43
+ }
44
+ const blocos = [...porPasta.entries()]
45
+ .map(([pasta, linhas]) => ({ cabecalho: pasta === '.' ? './' : `${pasta}/`, linhas, comum: compartilhada(pasta) }))
46
+ .sort((a, b) => Number(b.comum) - Number(a.comum) || (a.cabecalho < b.cabecalho ? -1 : 1));
47
+ const saida = [];
48
+ let tamanho = -1;
49
+ let exibidas = 0;
50
+ let arquivosCortados = 0;
51
+ for (const bloco of blocos) {
52
+ const texto = [bloco.cabecalho, ...bloco.linhas].join('\n');
53
+ if (exibidas > 0 && tamanho + 1 + texto.length > opcoes.limite)
54
+ break;
55
+ if (exibidas === 0 && texto.length > opcoes.limite) {
56
+ const [primeira, ...demais] = bloco.linhas;
57
+ saida.push(bloco.cabecalho, primeira ?? '');
58
+ tamanho = bloco.cabecalho.length + 1 + (primeira ?? '').length;
59
+ for (const linha of demais) {
60
+ if (tamanho + 1 + linha.length > opcoes.limite) {
61
+ arquivosCortados++;
62
+ continue;
63
+ }
64
+ saida.push(linha);
65
+ tamanho += 1 + linha.length;
66
+ }
67
+ }
68
+ else {
69
+ saida.push(texto);
70
+ tamanho += 1 + texto.length;
71
+ }
72
+ exibidas++;
73
+ }
74
+ const foraPastas = blocos.length - exibidas;
75
+ if (foraPastas > 0 || arquivosCortados > 0) {
76
+ const partes = [];
77
+ if (arquivosCortados > 0)
78
+ partes.push(`${arquivosCortados} arquivo(s) de ${blocos[0]?.cabecalho}`);
79
+ if (foraPastas > 0)
80
+ partes.push(`${foraPastas} ${foraPastas === 1 ? 'pasta' : 'pastas'}`);
81
+ const verbo = foraPastas + arquivosCortados === 1 ? 'ficou' : 'ficaram';
82
+ saida.push(`... ${partes.join(' e ')} ${verbo} de fora (limite de ${opcoes.limite} caracteres); ` +
83
+ 'detalhe com: npx @fontdata/ai-harness mapa <pasta>');
84
+ }
85
+ return saida.join('\n');
86
+ }
87
+ /** `mapa [caminho] [--limite <n>]`: imprime o mapa e sai com 0; com `.ai-harness/mapa.json` inválido, diz o campo e sai com 1. */
88
+ export function runMapCommand(argv) {
89
+ let caminho;
90
+ let limite = LIMITE_PADRAO;
91
+ for (let i = 0; i < argv.length; i++) {
92
+ const token = argv[i] ?? '';
93
+ if (!token.startsWith('-')) {
94
+ if (caminho !== undefined)
95
+ throw new Error(`Argumento inesperado: ${token}`);
96
+ caminho = token;
97
+ continue;
98
+ }
99
+ if (token !== '--limite') {
100
+ const sugestao = suggestFlag(token, FLAGS);
101
+ throw new Error(`Flag desconhecida: ${token}.${sugestao ? ` Você quis dizer ${sugestao}?` : ''}`);
102
+ }
103
+ const valor = Number(argv[++i]);
104
+ if (!Number.isInteger(valor) || valor <= 0)
105
+ throw new Error('--limite precisa de um número inteiro maior que zero.');
106
+ limite = valor;
107
+ }
108
+ const alvo = caminho === undefined ? acharRaiz() : resolve(process.cwd(), caminho);
109
+ const raiz = acharRaiz(alvo);
110
+ const pasta = relative(raiz, alvo).split(/[\\/]/).filter(Boolean).join('/');
111
+ let mapa;
112
+ try {
113
+ mapa = gerarMapa(raiz, { limite, pasta });
114
+ }
115
+ catch (erro) {
116
+ if (!(erro instanceof MapaConfigErro))
117
+ throw erro;
118
+ console.error(erro.message);
119
+ return 1;
120
+ }
121
+ console.log(mapa || 'Nenhum símbolo público encontrado.');
122
+ return 0;
123
+ }
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join, resolve } from 'node:path';
3
3
  import { allCommands, loadCatalog } from '../catalog.js';
4
- import { COMMENTS_HOOK_PATH, COMMENTS_HOOK_TEMPLATE, commentsHooksConfig, ensureCommentsBaseline, hookProprio, hookProprioRegistrado } from '../comentarios/instalar.js';
4
+ import { COMMENTS_HOOK_PATH, COMMENTS_HOOK_TEMPLATE, commentsHooksConfig, completarCommentsBaseline, descreverCompletarBaseline, descreverLimpezaBaseline, ensureCommentsBaseline, hookProprio, hookProprioRegistrado, limparCommentsBaseline } from '../comentarios/instalar.js';
5
5
  import { CONFIG_PATH, gravarInstalarComentarios, gravarRegistrarMcp, migrarSecaoBanco, readConfig, syncGitignore, temSecaoBancoLegada, writeDefaultConfig, } from '../config/config.js';
6
6
  import { applyAtomically } from '../install/atomic.js';
7
7
  import { suggestFlag } from '../install/flags.js';
@@ -218,6 +218,19 @@ export function applyUpdate(root, report, options, pkg, now = new Date()) {
218
218
  const settings = mergeSettings(root, { hooks, allow: harnessPermissions({ banco: report.permissoesBanco }), deny: HARNESS_DENY, removeAllow: BANCO_PERMISSIONS_LEGADAS }, now);
219
219
  if (settings.changed)
220
220
  ajustes.push(`${SETTINGS_PATH} atualizado${settings.backup ? ` (backup em ${settings.backup})` : ''}.`);
221
+ const avisos = [];
222
+ // Uma falha na limpeza ou no acréscimo da catraca nunca deixa o update pela metade, sem lock.
223
+ try {
224
+ const limpeza = write.length ? descreverLimpezaBaseline(limparCommentsBaseline(root)) : null;
225
+ if (limpeza)
226
+ ajustes.push(limpeza);
227
+ const acrescimo = write.length ? descreverCompletarBaseline(completarCommentsBaseline(root)) : null;
228
+ if (acrescimo)
229
+ ajustes.push(acrescimo);
230
+ }
231
+ catch (error) {
232
+ avisos.push(error instanceof Error ? error.message : String(error));
233
+ }
221
234
  if (report.registrarComentarios)
222
235
  ensureCommentsBaseline(root);
223
236
  if (report.adotada) {
@@ -230,7 +243,6 @@ export function applyUpdate(root, report, options, pkg, now = new Date()) {
230
243
  writeFileSync(projectRule, projectRuleContent(renamed.map(({ para }) => para)));
231
244
  }
232
245
  }
233
- const avisos = [];
234
246
  if (report.registrarMcp && report.mudancaMcp === 'invalido')
235
247
  avisos.push(MCP_INVALIDO);
236
248
  else if (report.registrarMcp) {
@@ -59,7 +59,7 @@ export function parseCaminhoJson(texto) {
59
59
  }
60
60
  return chaves.length > 0 ? chaves : null;
61
61
  }
62
- function contarGrupos(padrao) {
62
+ export function contarGrupos(padrao) {
63
63
  return (new RegExp(`${padrao}|`).exec('')?.length ?? 1) - 1;
64
64
  }
65
65
  function contarSegmentosDoFormato(formato) {
@@ -36,7 +36,8 @@ export function extratorParaTexto(cfg) {
36
36
  function juntar(base, nome) {
37
37
  return base ? `${base}/${nome}` : nome;
38
38
  }
39
- function varrer(raiz, base, profundidade) {
39
+ /** Caminhos (com `/`, relativos à raiz) dos arquivos cujo nome casa com `casa`: os do nível antes das subpastas. */
40
+ export function varrerArquivos(raiz, base, profundidade, casa) {
40
41
  let entradas;
41
42
  try {
42
43
  entradas = readdirSync(join(raiz, base), { withFileTypes: true });
@@ -47,21 +48,26 @@ function varrer(raiz, base, profundidade) {
47
48
  entradas.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
48
49
  const achados = [];
49
50
  for (const e of entradas) {
50
- if (e.isFile()) {
51
- const candidato = CANDIDATOS.find((c) => c.casa.test(e.name));
52
- for (const extrator of candidato?.extratores ?? [])
53
- achados.push({ caminho: juntar(base, e.name), extrator });
54
- }
51
+ if (e.isFile() && casa.test(e.name))
52
+ achados.push(juntar(base, e.name));
55
53
  }
56
54
  if (profundidade > 0) {
57
55
  for (const e of entradas) {
58
56
  if (e.isDirectory() && !e.name.startsWith('.') && !PASTAS_IGNORADAS.has(e.name)) {
59
- achados.push(...varrer(raiz, juntar(base, e.name), profundidade - 1));
57
+ achados.push(...varrerArquivos(raiz, juntar(base, e.name), profundidade - 1, casa));
60
58
  }
61
59
  }
62
60
  }
63
61
  return achados;
64
62
  }
63
+ const CASA_CANDIDATO = new RegExp(CANDIDATOS.map((c) => `(?:${c.casa.source})`).join('|'), 'i');
64
+ function varrer(raiz, base, profundidade) {
65
+ return varrerArquivos(raiz, base, profundidade, CASA_CANDIDATO).flatMap((caminho) => {
66
+ const nome = caminho.slice(caminho.lastIndexOf('/') + 1);
67
+ const candidato = CANDIDATOS.find((c) => c.casa.test(nome));
68
+ return (candidato?.extratores ?? []).map((extrator) => ({ caminho, extrator }));
69
+ });
70
+ }
65
71
  function lerFontes(raiz, arquivos, problemas) {
66
72
  return arquivos.map((arquivo) => {
67
73
  const fonte = { caminho: arquivo.caminho, extrator: arquivo.extrator, ocorrencias: [] };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fontdata/ai-harness",
3
- "version": "4.1.1",
3
+ "version": "4.3.0",
4
4
  "description": "Harness de engenharia com IA da Fontdata para Claude Code: roda os slash commands direto na pasta do projeto via npx, sem instalar nada — ou instala-os em .claude/commands.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -32,9 +32,12 @@ Use `Bash` só para rodar o `doctor` e ler o histórico: você é somente leitur
32
32
  ## Saída
33
33
 
34
34
  - **Veredito:** `APROVADO` ou `REPROVADO`.
35
- - **Achados** em BLOQUEANTE, IMPORTANTE e SUGESTÃO, cada um apontando a task (`T-SS.NN`) e a correção esperada.
35
+ - **Achados** em BLOQUEANTE, IMPORTANTE e SUGESTÃO, cada um apontando a task (`T-SS.NN`), o caso concreto (o
36
+ trecho do plano, as duas tasks que tocam o mesmo arquivo, o critério que não dá para responder com sim ou não) e a
37
+ correção esperada. Achado sem caso concreto não entra.
36
38
  - O valor para o orquestrador gravar em `auditoria_plano` no frontmatter do `PLAN.md` (`aprovado` ou
37
39
  `reprovado`).
40
+ - **Não verificado:** o que ficou sem ler, executar ou medir, e por quê; se nada ficou de fora, "nada".
38
41
 
39
42
  Registre o veredito no rastro:
40
43