@fontdata/ai-harness 4.3.1 → 4.4.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 (55) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/README.md +80 -2
  3. package/dist/config/config.js +37 -3
  4. package/dist/delphi/command.js +102 -1
  5. package/dist/delphi/encoding.js +112 -0
  6. package/dist/init.js +8 -2
  7. package/dist/install/perfis.js +14 -0
  8. package/dist/install/plan.js +29 -2
  9. package/dist/install/settings.js +40 -3
  10. package/dist/update/update.js +69 -7
  11. package/package.json +1 -1
  12. package/templates/catalog.json +3 -0
  13. package/templates/perfis/delphi/hooks/encoding.mjs +317 -0
  14. package/templates/perfis/delphi/rules/build-e-verificacao.md +59 -0
  15. package/templates/perfis/delphi/rules/dados/cnpj-alfanumerico-nao-extrair-so-numeros.md +65 -0
  16. package/templates/perfis/delphi/rules/dados/data-hora-sql-nunca-round-trip-textual.md +78 -0
  17. package/templates/perfis/delphi/rules/dados/datestyle-sessao-firedac-postgres.md +60 -0
  18. package/templates/perfis/delphi/rules/dados/ddl-tabela-nova-exige-trigger-de-log.md +68 -0
  19. package/templates/perfis/delphi/rules/dados/divisao-e-conversao-numerica.md +53 -0
  20. package/templates/perfis/delphi/rules/dados/fieldbyname-value-variant-cru-em-aritmetica.md +73 -0
  21. package/templates/perfis/delphi/rules/dados/filtro-condicional-sql-par-add-parambyname.md +72 -0
  22. package/templates/perfis/delphi/rules/dados/firedac.md +51 -0
  23. package/templates/perfis/delphi/rules/dados/macro-firedac-exige-entrada-macrodata.md +96 -0
  24. package/templates/perfis/delphi/rules/dados/sql-qualificacao-colunas.md +36 -0
  25. package/templates/perfis/delphi/rules/dados/tmeminifile-getstrings-nao-limpa-destino.md +89 -0
  26. package/templates/perfis/delphi/rules/encoding-eol.md +130 -0
  27. package/templates/perfis/delphi/rules/linguagem/dataset-nao-se-le-depois-do-laco-eof.md +56 -0
  28. package/templates/perfis/delphi/rules/linguagem/existencia-nunca-se-testa-por-campo-formatado.md +60 -0
  29. package/templates/perfis/delphi/rules/linguagem/float-nunca-comparado-por-igualdade-com-literal.md +55 -0
  30. package/templates/perfis/delphi/rules/linguagem/literal-enum-de-dfm-exige-unit-no-uses.md +84 -0
  31. package/templates/perfis/delphi/rules/linguagem/reaproveitar-funcao-existente-antes-de-criar.md +172 -0
  32. package/templates/perfis/delphi/rules/linguagem/sem-clipboard-debug.md +43 -0
  33. package/templates/perfis/delphi/rules/linguagem/validacao-em-onexit-nao-protege-a-gravacao.md +65 -0
  34. package/templates/perfis/delphi/rules/linguagem/variavel-inline-sai-de-escopo-ao-envolver-bloco.md +69 -0
  35. package/templates/perfis/delphi/rules/telas/foco-decisao-por-canfocus-nao-tabstop.md +40 -0
  36. package/templates/perfis/delphi/rules/telas/form-dinamico-liberar-em-toda-saida.md +80 -0
  37. package/templates/perfis/delphi/rules/telas/heranca-de-form-e-grade-de-selecao.md +58 -0
  38. package/templates/perfis/delphi/rules/threads-e-timers.md +131 -0
  39. package/templates/perfis/delphi/rules/try-finally-e-vazamento.md +109 -0
  40. package/templates/perfis/delphi/skills/conhecimento-delphi/SKILL.md +64 -0
  41. package/templates/perfis/delphi/skills/conhecimento-delphi/references/ATRIBUICAO.md +29 -0
  42. package/templates/perfis/delphi/skills/conhecimento-delphi/references/acbr-nfce-integracao.md +60 -0
  43. package/templates/perfis/delphi/skills/conhecimento-delphi/references/build-via-bat-com-log.md +86 -0
  44. package/templates/perfis/delphi/skills/conhecimento-delphi/references/class-var-vaza-para-campos-de-instancia.md +73 -0
  45. package/templates/perfis/delphi/skills/conhecimento-delphi/references/componentes-designer-vs-runtime.md +47 -0
  46. package/templates/perfis/delphi/skills/conhecimento-delphi/references/console-writeln-sem-flush-nao-loga.md +47 -0
  47. package/templates/perfis/delphi/skills/conhecimento-delphi/references/conversao-numerica-locale.md +47 -0
  48. package/templates/perfis/delphi/skills/conhecimento-delphi/references/delphi13-breaking-changes.md +41 -0
  49. package/templates/perfis/delphi/skills/conhecimento-delphi/references/dpr-uses-project-manager.md +62 -0
  50. package/templates/perfis/delphi/skills/conhecimento-delphi/references/dproj-dcc-debuginformation-nao-booleano.md +78 -0
  51. package/templates/perfis/delphi/skills/conhecimento-delphi/references/dproj-projectguid-valido.md +38 -0
  52. package/templates/perfis/delphi/skills/conhecimento-delphi/references/firedac-registro-drivers.md +94 -0
  53. package/templates/perfis/delphi/skills/conhecimento-delphi/references/horse-gbswagger-rotas-jwt.md +61 -0
  54. package/templates/perfis/delphi/skills/conhecimento-delphi/references/msb6003-command-line-too-long.md +52 -0
  55. package/templates/perfis/delphi/skills/conhecimento-delphi/references/recursos-rcdata.md +67 -0
@@ -9,9 +9,30 @@ import { HOOKS_ITEM_ID, isHarnessPluginEnabled, projectHooksConfig } from '../in
9
9
  import { BANCO_MCP_NOME, BANCO_MCP_NOME_LEGADO, bancoMcpServer, ehEntradaGerenciada, MCP_PATH, mergeMcpServers } from '../install/mcp.js';
10
10
  import { hashContent, LOCK_PATH, LOCK_VERSION, readLock, writeLock } from '../install/lock.js';
11
11
  import { agentsForaDoLock, itemSources, packageInfo, PROJECT_RULE_PATH, projectRuleContent } from '../install/plan.js';
12
+ import { PERFIL_DELPHI_HOOK_COMMAND, perfilDelphiHooksConfig, perfisDoProjeto } from '../install/perfis.js';
12
13
  import { neededSkillsFor } from '../install/selection.js';
13
- import { BANCO_PERMISSIONS_LEGADAS, combineHooks, HARNESS_DENY, harnessPermissions, hasAllowRule, mergeSettings, SETTINGS_PATH, } from '../install/settings.js';
14
+ import { BANCO_PERMISSIONS_LEGADAS, combineHooks, HARNESS_DENY, harnessPermissions, hasAllowRule, hookCommands, mergeSettings, normalizarComandoHook, SETTINGS_PATH, } from '../install/settings.js';
14
15
  import { adoptLegacyInstall } from './legado.js';
16
+ const PERFIL_DELPHI_ITEM = 'perfil:delphi';
17
+ /** Pastas que os arquivos do item ocupam no projeto (`.claude/<tipo>/<nome>/`), as que ainda existem. */
18
+ function pastasDoItem(root, item) {
19
+ const pastas = new Set(item.arquivos.map((entry) => `${entry.caminho.split('/').slice(0, 3).join('/')}/`));
20
+ return [...pastas].filter((pasta) => existsSync(join(root, pasta))).sort();
21
+ }
22
+ /** O settings do projeto já registra o hook do perfil em todos os eventos dele. */
23
+ function perfilDelphiRegistrado(root) {
24
+ let hooks;
25
+ try {
26
+ hooks = JSON.parse(readFileSync(join(root, SETTINGS_PATH), 'utf8')).hooks ?? {};
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ if (!isPlainObject(hooks))
32
+ return false;
33
+ const comando = normalizarComandoHook(PERFIL_DELPHI_HOOK_COMMAND);
34
+ return Object.keys(perfilDelphiHooksConfig()).every((evento) => hookCommands({ [evento]: hooks[evento] ?? [] }).map(normalizarComandoHook).includes(comando));
35
+ }
15
36
  function isPlainObject(value) {
16
37
  return typeof value === 'object' && value !== null && !Array.isArray(value);
17
38
  }
@@ -58,8 +79,13 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
58
79
  }
59
80
  const changes = [];
60
81
  const stale = [];
82
+ const { config } = readConfig(root);
83
+ const itemPerfil = lock.itens.find((item) => `${item.tipo}:${item.id}` === PERFIL_DELPHI_ITEM);
84
+ const perfilRecusado = itemPerfil && !config.perfis.delphi ? { pastas: pastasDoItem(root, itemPerfil) } : null;
61
85
  for (const item of lock.itens) {
62
86
  const key = `${item.tipo}:${item.id}`;
87
+ if (perfilRecusado && key === PERFIL_DELPHI_ITEM)
88
+ continue;
63
89
  const sources = itemSources(catalog, item.tipo, item.id) ?? [];
64
90
  const sourceByPath = new Map(sources.map((entry) => [entry.path, entry.source]));
65
91
  for (const entry of item.arquivos) {
@@ -99,6 +125,9 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
99
125
  continue;
100
126
  const target = join(root, path);
101
127
  const same = existsSync(target) && hashContent(readFileSync(target)) === hashContent(readFileSync(source));
128
+ // O perfil entrou sem este arquivo porque ele já era do projeto: continua do projeto, mesmo com --forcar.
129
+ if (!same && existsSync(target) && item.tipo === 'perfil')
130
+ continue;
102
131
  changes.push({ tipo: !existsSync(target) || same ? 'novo' : 'conflito', caminho: path, item: key, source });
103
132
  }
104
133
  }
@@ -129,7 +158,6 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
129
158
  addItem('skill', skill.id, false);
130
159
  }
131
160
  }
132
- const { config } = readConfig(root);
133
161
  // Na adoção, a instalação antiga ganha o que a 2.1 instala e ela não tinha.
134
162
  const adotada = !recorded;
135
163
  const pluginHooks = adotada && isHarnessPluginEnabled(root, home);
@@ -151,6 +179,10 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
151
179
  addItem('rule', 'comentarios', true);
152
180
  addItem('hook', 'comentarios', true);
153
181
  }
182
+ const instalarPerfilDelphi = !itemPerfil && perfisDoProjeto(root, config).includes('delphi');
183
+ if (instalarPerfilDelphi)
184
+ addItem('perfil', 'delphi', true);
185
+ const registrarPerfilDelphi = instalarPerfilDelphi || (!!itemPerfil && !perfilRecusado && !perfilDelphiRegistrado(root));
154
186
  const registrarMcpConfig = config.banco_dados.registrar_mcp;
155
187
  const permissoesBanco = !semBanco && registrarMcpConfig;
156
188
  const permissoesFaltando = [
@@ -176,6 +208,9 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
176
208
  mudancaMcp: registrarMcp ? mcpChange(root, packageInfo().versao) : null,
177
209
  recusarMcp: semBanco && registrarMcpConfig,
178
210
  renomearSecaoBanco: temSecaoBancoLegada(root),
211
+ registrarPerfilDelphi,
212
+ instalarPerfilDelphi,
213
+ perfilRecusado,
179
214
  };
180
215
  }
181
216
  /**
@@ -213,9 +248,15 @@ export function applyUpdate(root, report, options, pkg, now = new Date()) {
213
248
  renameSync(join(root, path), join(root, para));
214
249
  return { de: path, para };
215
250
  });
216
- const hooks = combineHooks(report.registrarHooks ? projectHooksConfig() : {}, report.registrarComentarios ? commentsHooksConfig() : {});
251
+ const hooks = combineHooks(report.registrarHooks ? projectHooksConfig() : {}, report.registrarComentarios ? commentsHooksConfig() : {}, report.registrarPerfilDelphi ? perfilDelphiHooksConfig() : {});
217
252
  const ajustes = [];
218
- const settings = mergeSettings(root, { hooks, allow: harnessPermissions({ banco: report.permissoesBanco }), deny: HARNESS_DENY, removeAllow: BANCO_PERMISSIONS_LEGADAS }, now);
253
+ const settings = mergeSettings(root, {
254
+ hooks,
255
+ allow: harnessPermissions({ banco: report.permissoesBanco }),
256
+ deny: HARNESS_DENY,
257
+ removeAllow: BANCO_PERMISSIONS_LEGADAS,
258
+ removeHooks: report.perfilRecusado ? [PERFIL_DELPHI_HOOK_COMMAND] : [],
259
+ }, now);
219
260
  if (settings.changed)
220
261
  ajustes.push(`${SETTINGS_PATH} atualizado${settings.backup ? ` (backup em ${settings.backup})` : ''}.`);
221
262
  const avisos = [];
@@ -275,6 +316,8 @@ export function applyUpdate(root, report, options, pkg, now = new Date()) {
275
316
  const itens = [];
276
317
  for (const item of report.lock.itens) {
277
318
  const key = `${item.tipo}:${item.id}`;
319
+ if (report.perfilRecusado && key === PERFIL_DELPHI_ITEM)
320
+ continue;
278
321
  const entries = new Map(item.arquivos.map((entry) => [entry.caminho, entry]));
279
322
  for (const [path, sha256] of writtenHash) {
280
323
  if (itemOf.get(path) === key)
@@ -365,15 +408,34 @@ export function describeUpdate(report) {
365
408
  ...(report.renomearSecaoBanco ? [`A seção banco de ${CONFIG_PATH} agora se chama banco_dados; o --yes a renomeia.`] : []),
366
409
  ...(report.recusarMcp ? [`--sem-banco-dados: o --yes grava banco_dados.registrar_mcp: false em ${CONFIG_PATH} e não registra o MCP.`] : []),
367
410
  ];
411
+ const perfil = [
412
+ ...(report.instalarPerfilDelphi
413
+ ? [
414
+ 'Projeto Delphi sem o perfil delphi: o --yes grava as rules em .claude/rules/delphi/, a skill conhecimento-delphi e o hook ' +
415
+ `.claude/hooks/delphi/encoding.mjs, registrado em ${SETTINGS_PATH}. Para recusar, grave perfis.delphi: false em ${CONFIG_PATH}.`,
416
+ ]
417
+ : report.registrarPerfilDelphi
418
+ ? [`O hook do perfil delphi não está registrado em ${SETTINGS_PATH}; o --yes o registra.`]
419
+ : []),
420
+ ...(report.perfilRecusado
421
+ ? [
422
+ `perfis.delphi: false em ${CONFIG_PATH}: o --yes tira o perfil delphi do ${LOCK_PATH} e o registro do hook de ${SETTINGS_PATH}. ` +
423
+ (report.perfilRecusado.pastas.length
424
+ ? `Os arquivos do perfil são mantidos e podem ser apagados à mão: ${report.perfilRecusado.pastas.join(', ')}.`
425
+ : 'Os arquivos do perfil já foram apagados.'),
426
+ ]
427
+ : []),
428
+ ];
368
429
  if (!report.changes.length) {
369
- const status = adopted.length || comentarios.length || permission.length || legadas.length || mcp.length
430
+ const status = adopted.length || comentarios.length || perfil.length || permission.length || legadas.length || mcp.length
370
431
  ? 'Nenhum arquivo a atualizar.'
371
432
  : 'A instalação está em dia: nenhum arquivo a atualizar.';
372
- return [...adopted, ...comentarios, ...permission, ...legadas, ...mcp, status].join('\n');
433
+ return [...adopted, ...comentarios, ...perfil, ...permission, ...legadas, ...mcp, status].join('\n');
373
434
  }
374
435
  return [
375
436
  ...adopted,
376
437
  ...comentarios,
438
+ ...perfil,
377
439
  ...permission,
378
440
  ...legadas,
379
441
  ...mcp,
@@ -416,7 +478,7 @@ export function runUpdateCommand(argv) {
416
478
  const report = checkUpdate(root, undefined, undefined, undefined, { semBanco: args.semBanco, semComentarios: args.semComentarios });
417
479
  console.log(describeUpdate(report));
418
480
  // Sem arquivo a atualizar, a adoção ainda grava o lock, e a permissão e o MCP ainda são acrescentados.
419
- const pendente = report.adotada || report.permissaoAusente || report.permissoesLegadas.length > 0 || report.mudancaMcp !== null || report.recusarMcp || report.recusarComentarios || report.registrarHookComentarios || report.renomearSecaoBanco;
481
+ const pendente = report.adotada || report.permissaoAusente || report.permissoesLegadas.length > 0 || report.mudancaMcp !== null || report.recusarMcp || report.recusarComentarios || report.registrarHookComentarios || report.renomearSecaoBanco || report.registrarPerfilDelphi || report.perfilRecusado !== null;
420
482
  if (args.check || (!report.changes.length && !pendente))
421
483
  return 0;
422
484
  if (!args.yes) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fontdata/ai-harness",
3
- "version": "4.3.1",
3
+ "version": "4.4.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": {
@@ -23,6 +23,9 @@
23
23
  "skills": [
24
24
  { "id": "lgpd-checker", "dir": "skills/lgpd-checker", "title": "Skill lgpd-checker", "description": "Conformidade com a LGPD (Lei nº 13.709/2018) em 11 categorias, com checklist e template de relatório. Vendorizada de bittencourtthulio/lgpd-checker." }
25
25
  ],
26
+ "perfis": [
27
+ { "id": "delphi", "dir": "perfis/delphi", "title": "Perfil Delphi", "description": "Rules de Delphi, a skill conhecimento-delphi e o hook de encoding, instalados quando o projeto tem .dpr ou .dproj." }
28
+ ],
26
29
  "groups": [
27
30
  {
28
31
  "id": "setup",
@@ -0,0 +1,317 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ /** @typedef {'aviso' | 'bloqueio' | 'desligado'} Modo */
9
+ /** @typedef {'utf8-bom' | 'utf8-sem-bom' | 'cp1252' | 'dfm-binario'} Encoding */
10
+ /** @typedef {'crlf' | 'lf' | 'misto' | 'nenhum'} Eol */
11
+ /** @typedef {{ linha: number, mensagem: string, texto: string }} Problema */
12
+
13
+ const NOME = 'delphi-encoding';
14
+ /** @type {Modo} */
15
+ const MODO_PADRAO = 'bloqueio';
16
+ /** @type {Modo[]} */
17
+ const MODOS = ['aviso', 'bloqueio', 'desligado'];
18
+ const IGNORAR_PADRAO = ['**/modules/**', '**/ACBr*/**'];
19
+ const EXTENSOES_CONVERTER = ['.pas', '.dpr', '.dpk', '.inc'];
20
+ const MAX_LINHAS_NO_AVISO = 10;
21
+
22
+ /** @param {Buffer} bytes */
23
+ function temBom(bytes) {
24
+ return bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
25
+ }
26
+
27
+ /** @param {Buffer} bytes */
28
+ function utf8Valido(bytes) {
29
+ try {
30
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * @param {Buffer} bytes
39
+ * @returns {Encoding}
40
+ */
41
+ export function detectarEncoding(bytes) {
42
+ if (bytes.subarray(0, 3).equals(Buffer.from([0xff, 0x0a, 0x00])) || bytes.subarray(0, 4).toString('latin1') === 'TPF0') {
43
+ return 'dfm-binario';
44
+ }
45
+ if (temBom(bytes)) return 'utf8-bom';
46
+ return utf8Valido(bytes) ? 'utf8-sem-bom' : 'cp1252';
47
+ }
48
+
49
+ /** @param {string} texto */
50
+ function contarEol(texto) {
51
+ const crlf = texto.match(/\r\n/g)?.length ?? 0;
52
+ const lf = (texto.match(/\n/g)?.length ?? 0) - crlf;
53
+ return { crlf, lf };
54
+ }
55
+
56
+ /**
57
+ * @param {Buffer} bytes
58
+ * @returns {Eol}
59
+ */
60
+ export function detectarEol(bytes) {
61
+ const { crlf, lf } = contarEol(bytes.toString('latin1'));
62
+ if (crlf && lf) return 'misto';
63
+ if (crlf) return 'crlf';
64
+ return lf ? 'lf' : 'nenhum';
65
+ }
66
+
67
+ /** @param {Buffer} bytes */
68
+ export function decodificar(bytes) {
69
+ const corpo = temBom(bytes) ? bytes.subarray(3) : bytes;
70
+ return utf8Valido(corpo) ? corpo.toString('utf8') : new TextDecoder('windows-1252').decode(corpo);
71
+ }
72
+
73
+ const SEGUNDO_BYTE_UTF8 = new TextDecoder('windows-1252').decode(Uint8Array.from({ length: 0x40 }, (_, i) => 0x80 + i));
74
+ const DUPLA_CODIFICACAO = new RegExp(`[ÃÂ][${SEGUNDO_BYTE_UTF8.replace(/[\\\]^-]/g, '\\$&')}]|â€`);
75
+
76
+ /** @param {string} caminho */
77
+ function extensao(caminho) {
78
+ const ponto = caminho.lastIndexOf('.');
79
+ return ponto < 0 ? '' : caminho.slice(ponto).toLowerCase();
80
+ }
81
+
82
+ /**
83
+ * Problemas do arquivo com a linha (1 em diante) e o texto dela, que identifica o problema na comparação com o HEAD.
84
+ * @param {string} caminho
85
+ * @param {Buffer} bytes
86
+ * @returns {Problema[]}
87
+ */
88
+ export function checarArquivo(caminho, bytes) {
89
+ const encoding = detectarEncoding(bytes);
90
+ if (encoding === 'dfm-binario') return [];
91
+ /** @type {Problema[]} */
92
+ const problemas = [];
93
+ if (encoding !== 'utf8-bom' && EXTENSOES_CONVERTER.includes(extensao(caminho))) {
94
+ problemas.push({ linha: 1, mensagem: `BOM ausente (${encoding})`, texto: '' });
95
+ }
96
+ const texto = decodificar(bytes);
97
+ const linhas = texto.split('\n');
98
+ const eol = detectarEol(bytes);
99
+ const { crlf, lf } = contarEol(texto);
100
+ const eolMaioria = lf > crlf ? 'lf' : 'crlf';
101
+ linhas.forEach((linha, i) => {
102
+ const numero = i + 1;
103
+ const conteudo = linha.replace(/\r$/, '');
104
+ if (linha.includes('�')) problemas.push({ linha: numero, mensagem: 'caractere U+FFFD', texto: conteudo });
105
+ const dupla = linha.match(DUPLA_CODIFICACAO);
106
+ if (dupla) problemas.push({ linha: numero, mensagem: `dupla codificação ('${dupla[0]}')`, texto: conteudo });
107
+ if (eol === 'misto' && i < linhas.length - 1 && (linha.endsWith('\r') ? 'crlf' : 'lf') !== eolMaioria) {
108
+ const mensagem = `EOL misto (${eolMaioria === 'crlf' ? 'LF' : 'CRLF'} num arquivo ${eolMaioria.toUpperCase()})`;
109
+ problemas.push({ linha: numero, mensagem, texto: conteudo });
110
+ }
111
+ });
112
+ return problemas;
113
+ }
114
+
115
+ /** @param {string} glob */
116
+ function globParaRegex(glob) {
117
+ let fonte = '';
118
+ for (let i = 0; i < glob.length; i++) {
119
+ if (glob.startsWith('**/', i)) {
120
+ fonte += '(?:.*/)?';
121
+ i += 2;
122
+ } else if (glob.startsWith('**', i)) {
123
+ fonte += '.*';
124
+ i += 1;
125
+ } else if (glob[i] === '*') fonte += '[^/]*';
126
+ else fonte += (glob[i] ?? '').replace(/[.+?^${}()|[\]\\]/g, '\\$&');
127
+ }
128
+ return new RegExp(`^${fonte}$`, 'i');
129
+ }
130
+
131
+ /**
132
+ * @param {string} caminho
133
+ * @param {string[]} padroes
134
+ */
135
+ export function casaGlob(caminho, padroes) {
136
+ const normalizado = caminho.replace(/\\/g, '/').replace(/^\.\//, '');
137
+ return padroes.some((padrao) => globParaRegex(padrao.replace(/\\/g, '/')).test(normalizado));
138
+ }
139
+
140
+ /**
141
+ * Config ausente, ilegível ou com valor inválido cai nos padrões, campo a campo.
142
+ * @param {string} raiz
143
+ * @returns {{ modo: Modo, ignorar: string[] }}
144
+ */
145
+ function lerConfig(raiz) {
146
+ /** @type {any} */
147
+ let config = {};
148
+ try {
149
+ const arquivo = join(raiz, '.ai-harness', 'config.json');
150
+ if (existsSync(arquivo)) config = JSON.parse(readFileSync(arquivo, 'utf8')) ?? {};
151
+ } catch {
152
+ config = {};
153
+ }
154
+ const modo = config?.hooks?.[NOME];
155
+ const ignorar = config?.delphi?.ignorar;
156
+ return {
157
+ modo: MODOS.includes(modo) ? modo : MODO_PADRAO,
158
+ ignorar: Array.isArray(ignorar) && ignorar.every((glob) => typeof glob === 'string') ? ignorar : IGNORAR_PADRAO,
159
+ };
160
+ }
161
+
162
+ /**
163
+ * Bytes do arquivo no HEAD, ou null quando não há repositório ou versão. `HEAD:./nome` resolve contra o cwd, o que
164
+ * funciona mesmo com o projeto numa subpasta do repositório.
165
+ * @param {string} arquivo
166
+ * @returns {Buffer | null}
167
+ */
168
+ function versaoNoHead(arquivo) {
169
+ const r = spawnSync('git', ['show', `HEAD:./${basename(arquivo)}`], { cwd: dirname(arquivo), maxBuffer: 256 * 1024 * 1024 });
170
+ return r.status === 0 && Buffer.isBuffer(r.stdout) ? r.stdout : null;
171
+ }
172
+
173
+ /** @param {string} caminho */
174
+ const comandoConverter = (caminho) =>
175
+ `npx @fontdata/ai-harness delphi encoding converter ${/\s/.test(caminho) ? `"${caminho}"` : caminho}`;
176
+
177
+ /**
178
+ * @param {Problema[]} problemas
179
+ * @param {string} rel
180
+ */
181
+ function listar(problemas, rel) {
182
+ const linhas = problemas.slice(0, MAX_LINHAS_NO_AVISO).map((p) => `- ${rel}, linha ${p.linha}: ${p.mensagem}`);
183
+ if (problemas.length > MAX_LINHAS_NO_AVISO) linhas.push(`- e mais ${problemas.length - MAX_LINHAS_NO_AVISO}`);
184
+ return linhas.join('\n');
185
+ }
186
+
187
+ /**
188
+ * @param {string} rel
189
+ * @param {Buffer} bytes
190
+ * @returns {{ bloqueia: boolean, mensagem: string } | null}
191
+ */
192
+ function antesDeEditar(rel, bytes) {
193
+ if (!EXTENSOES_CONVERTER.includes(extensao(rel))) return null;
194
+ const encoding = detectarEncoding(bytes);
195
+ if (encoding === 'cp1252') {
196
+ return {
197
+ bloqueia: true,
198
+ mensagem:
199
+ `${rel} não está em UTF-8 (parece CP1252/ANSI); editar assim corrompe os acentos. ` +
200
+ `Converta para UTF-8 com BOM antes de editar: ${comandoConverter(rel)}`,
201
+ };
202
+ }
203
+ if (encoding === 'utf8-sem-bom') {
204
+ return {
205
+ bloqueia: false,
206
+ mensagem: `${rel} está em UTF-8 sem BOM; o Delphi pode lê-lo como ANSI. Para acrescentar o BOM: ${comandoConverter(rel)}`,
207
+ };
208
+ }
209
+ return null;
210
+ }
211
+
212
+ /** @param {Eol} eol */
213
+ const nomeEol = (eol) => (eol === 'nenhum' ? 'sem quebra de linha' : eol.toUpperCase());
214
+
215
+ /**
216
+ * Problemas que o HEAD não tinha; sem HEAD, todos contam como novos.
217
+ * @param {string} rel
218
+ * @param {Buffer} bytes
219
+ * @param {Buffer | null} head
220
+ * @returns {string | null}
221
+ */
222
+ function depoisDeGravar(rel, bytes, head) {
223
+ const ext = extensao(rel);
224
+ const ehDfm = ext === '.dfm';
225
+ if (!ehDfm && !EXTENSOES_CONVERTER.includes(ext)) return null;
226
+ if (detectarEncoding(bytes) === 'dfm-binario') return null;
227
+ const anterior = head && detectarEncoding(head) !== 'dfm-binario' ? head : null;
228
+
229
+ const atuais = checarArquivo(rel, bytes);
230
+ const antigos = anterior ? checarArquivo(rel, anterior) : [];
231
+ const chave = (/** @type {Problema} */ p) => `${p.mensagem.replace(/ \(.*$/, '')}\0${p.texto}`;
232
+ const jaExistiam = new Set(antigos.map(chave));
233
+ const eolMistoAntes = anterior !== null && detectarEol(anterior) === 'misto';
234
+
235
+ const novos = atuais.filter((p) => {
236
+ if (p.mensagem.startsWith('BOM ausente')) return !ehDfm && (anterior === null || temBom(anterior));
237
+ if (p.mensagem.startsWith('EOL misto')) return !ehDfm && !eolMistoAntes;
238
+ if (ehDfm && !p.mensagem.startsWith('caractere U+FFFD')) return false;
239
+ return !jaExistiam.has(chave(p));
240
+ });
241
+
242
+ const partes = [];
243
+ if (novos.length) partes.push(`Regressão de encoding em ${rel}:\n${listar(novos, rel)}`);
244
+ if (ehDfm && anterior) {
245
+ const antes = detectarEol(anterior);
246
+ const depois = detectarEol(bytes);
247
+ if (antes !== depois) {
248
+ partes.push(`${rel}: o EOL mudou de ${nomeEol(antes)} para ${nomeEol(depois)}; o .dfm deve manter o EOL do HEAD.`);
249
+ }
250
+ }
251
+ return partes.length ? partes.join('\n') : null;
252
+ }
253
+
254
+ /**
255
+ * @param {string} evento
256
+ * @param {string} mensagem
257
+ */
258
+ function avisar(evento, mensagem) {
259
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: evento, additionalContext: `[ai-harness · ${NOME}] ${mensagem}` } }));
260
+ }
261
+
262
+ async function lerStdin() {
263
+ let dados = '';
264
+ for await (const pedaco of process.stdin) dados += pedaco;
265
+ return dados;
266
+ }
267
+
268
+ async function main() {
269
+ /** @type {any} */
270
+ let evento;
271
+ try {
272
+ evento = JSON.parse(await lerStdin());
273
+ } catch {
274
+ return;
275
+ }
276
+ const caminho = evento?.tool_input?.file_path;
277
+ if (typeof caminho !== 'string' || !caminho) return;
278
+ const nomeEvento = String(evento.hook_event_name ?? '');
279
+ const ferramenta = String(evento.tool_name ?? '');
280
+ const pre = nomeEvento === 'PreToolUse' && ['Edit', 'MultiEdit'].includes(ferramenta);
281
+ const pos = nomeEvento === 'PostToolUse' && ['Write', 'Edit', 'MultiEdit'].includes(ferramenta);
282
+ if (!pre && !pos) return;
283
+
284
+ const raiz = process.env.CLAUDE_PROJECT_DIR || (typeof evento.cwd === 'string' && evento.cwd) || process.cwd();
285
+ const { modo, ignorar } = lerConfig(raiz);
286
+ if (modo === 'desligado') return;
287
+
288
+ const arquivo = isAbsolute(caminho) ? caminho : resolve(raiz, caminho);
289
+ const rel = relative(raiz, arquivo).replace(/\\/g, '/');
290
+ if (casaGlob(rel, ignorar)) return;
291
+
292
+ /** @type {Buffer} */
293
+ let bytes;
294
+ try {
295
+ bytes = readFileSync(arquivo);
296
+ } catch {
297
+ return;
298
+ }
299
+
300
+ if (pre) {
301
+ const resultado = antesDeEditar(rel, bytes);
302
+ if (!resultado) return;
303
+ if (resultado.bloqueia && modo === 'bloqueio') {
304
+ process.stderr.write(`[ai-harness · ${NOME}] ${resultado.mensagem}\n`);
305
+ process.exitCode = 2;
306
+ return;
307
+ }
308
+ avisar(nomeEvento, resultado.mensagem);
309
+ return;
310
+ }
311
+
312
+ const mensagem = depoisDeGravar(rel, bytes, versaoNoHead(arquivo));
313
+ if (mensagem) avisar(nomeEvento, mensagem);
314
+ }
315
+
316
+ const entrypoint = process.argv[1] ? realpathSync(process.argv[1]) : '';
317
+ if (entrypoint === realpathSync(fileURLToPath(import.meta.url))) await main();
@@ -0,0 +1,59 @@
1
+ ---
2
+ paths:
3
+ - "**/*.pas"
4
+ - "**/*.dpr"
5
+ - "**/*.dpk"
6
+ - "**/*.inc"
7
+ - "**/*.dfm"
8
+ - "**/*.dproj"
9
+ ---
10
+
11
+ # Build e verificação em projeto Delphi
12
+
13
+ ## Quem compila é o usuário
14
+
15
+ A compilação é manual: no macOS, pela IDE do Delphi dentro da VM do Parallels; no Windows, pela IDE direto. O
16
+ agente **não compila**: não procura o compilador (`dcc32`, `dcc64`, `msbuild`, `rsvars.bat`), não monta linha de
17
+ comando de build e não tenta rodar a IDE.
18
+
19
+ Por quê: o compilador não está no ambiente do agente (no macOS ele só existe na VM), e uma tentativa de achar ou
20
+ chamar o build gasta tempo e induz a afirmar que algo compilou quando não compilou.
21
+
22
+ ## Unit nova entra no `uses` do `.dpr`
23
+
24
+ Toda unit criada pelo agente entra no `uses` do `.dpr` do projeto, com o caminho relativo e, se for form, o nome
25
+ do form no comentário que a IDE usa:
26
+
27
+ ```pascal
28
+ uses
29
+ Vcl.Forms,
30
+ uPrincipal in 'uPrincipal.pas' {FrmPrincipal},
31
+ uRelatorioVendas in 'Relatorios\uRelatorioVendas.pas' {FrmRelatorioVendas};
32
+ ```
33
+
34
+ Por quê: a IDE acha a unit pelo search path no build incremental, mas o build "limpo" (o do deploy, ou um
35
+ *Build* depois de apagar os `.dcu`) só compila o que o `.dpr` lista. Unit fora do `uses` passa na máquina do dev e
36
+ quebra no build limpo. O `.dproj` também lista a unit (`<DCCReference>`); se a unit não aparecer no Project
37
+ Manager, avise o usuário para adicioná-la pela IDE, que atualiza os dois arquivos.
38
+
39
+ ## Entrega sem compilação diz "não compilado"
40
+
41
+ Como o agente não compila, toda entrega que mexe em fonte Delphi termina dizendo **"não compilado"** e lista:
42
+
43
+ - as units e forms alterados ou criados;
44
+ - o projeto (`.dpr`/`.dproj`) que o usuário deve compilar;
45
+ - o que testar na aplicação depois de compilar (tela, rotina, caso de borda).
46
+
47
+ Errado: "a alteração está pronta e funcionando". Certo: "não compilado; compile `Vendas.dproj` e teste o
48
+ fechamento de pedido com desconto zerado".
49
+
50
+ ## `DelphiBuildRelease` não é ferramenta do agente
51
+
52
+ O `DelphiBuildRelease` só roda no pipeline de deploy. O agente não o chama, não
53
+ o usa para "validar" a alteração e não pede ao usuário que dispare o deploy para testar o build.
54
+
55
+ ## Suíte própria do projeto prevalece
56
+
57
+ Se o projeto declara uma suíte de testes automatizados em `.claude/rules/harness-projeto.md` (seção "Suíte de
58
+ testes"), ela prevalece sobre esta rule: o agente roda a suíte do projeto como ela está descrita lá, inclusive
59
+ quando ela compila. Sem suíte declarada, vale o "não compilado" acima.
@@ -0,0 +1,65 @@
1
+ ---
2
+ paths:
3
+ - "**/*.pas"
4
+ - "**/*.dfm"
5
+ - "**/*.dpr"
6
+ - "**/*.inc"
7
+ - "**/*.sql"
8
+ ---
9
+
10
+ # Regra (camada de dados/fiscal): CNPJ alfanumérico, nunca extrair só os números
11
+
12
+ Aplica-se a todo código que manipula CNPJ ou CPF/CNPJ para **gravar** no banco, **comparar** ("o CNPJ
13
+ mudou?"), **decidir** o ramo de validação (CNPJ x CPF) ou **transmitir** em documento fiscal.
14
+
15
+ ## O CNPJ passou a ser alfanumérico, e "extrair números" o destrói
16
+
17
+ O CNPJ admite letras nas 12 primeiras posições (ex.: `12.ABC.345/01DE-35`); só os 2 dígitos
18
+ verificadores continuam numéricos. Uma função que mantém **só dígitos** (`ExtrairNumeros`, um helper
19
+ `ExtractNumbers` de edit, `OnlyNumbers` e parecidas), aplicada a um CNPJ alfanumérico, **descarta as
20
+ letras em silêncio**: nada estoura na compilação, o campo aceita a digitação, a validação passa e o valor
21
+ chega mutilado ao banco.
22
+
23
+ ## Padrão obrigatório
24
+
25
+ Use uma função que remova só a pontuação da máscara (`.`, `/`, `-`, espaço) e preserve letras e dígitos.
26
+ Procure primeiro a que o projeto ou suas bibliotecas já têm (ver
27
+ `linguagem/reaproveitar-funcao-existente-antes-de-criar.md`) antes de escrever uma.
28
+
29
+ ```pascal
30
+ // ERRADO: perde as letras do CNPJ alfanumérico
31
+ ParamByName('cnpj').AsString := ExtrairNumeros(EditCnpj.Text);
32
+
33
+ // CERTO
34
+ ParamByName('cnpj').AsString := ExtrairLetrasENumeros(EditCnpj.Text);
35
+ ```
36
+
37
+ Extrair só números **continua correto** para CPF, CEP, telefone, CFOP, agência e outros valores de fato
38
+ numéricos. O critério não é "é documento", é **"este valor pode conter letra?"**.
39
+
40
+ ## Três armadilhas irmãs: corrija as três juntas
41
+
42
+ 1. **Gravação** (`ParamByName`/`FieldByName`): o caso óbvio.
43
+ 2. **Comparação de "mudou?"**: as duas pontas têm de usar a **mesma** extração. Se a carga do valor
44
+ original usa uma função e a comparação usa outra, uma troca só de letras passa despercebida e a trava
45
+ que dependia dela não dispara.
46
+ 3. **Decisão CNPJ x CPF por tamanho**: nunca conte **dígitos** para escolher o ramo.
47
+
48
+ ```pascal
49
+ // ERRADO: CNPJ alfanumérico tem menos de 14 dígitos, cai no ramo CPF e acusa "CPF inválido"
50
+ if ExtrairNumeros(MskDocumento.Text).Length >= 14 then
51
+
52
+ // CERTO: conta caracteres alfanuméricos
53
+ if ExtrairLetrasENumeros(MskDocumento.Text).Length >= 14 then
54
+ ```
55
+
56
+ ## Validação e gravação são irmãs: nunca corrija só uma
57
+
58
+ A correção pela metade é o caminho mais comum para este defeito: a **validação** da tela é ajustada para
59
+ aceitar letras, e o **ponto de gravação** da mesma tela continua extraindo só números. Resultado: valida
60
+ com letras e grava sem letras.
61
+
62
+ Ao ajustar a validação de um campo fiscal, ajuste na mesma passagem o ponto de gravação correspondente, e
63
+ vice-versa. Antes de fechar, faça `grep` pelas funções de extração de números na unit inteira e
64
+ classifique **cada** ocorrência: valor numérico (mantém) ou alfanumérico (troca). Inclua na busca as
65
+ rotinas que montam documentos fiscais e arquivos para o fisco, que também transmitem o CNPJ.