@fontdata/ai-harness 4.6.0 → 4.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "fontdata",
3
- "version": "4.6.0",
3
+ "version": "4.7.1",
4
4
  "mcpServers": {
5
- "banco_dados": { "command": "npx", "args": ["-y", "@fontdata/ai-harness@4.6.0", "banco-dados-mcp"] }
5
+ "banco_dados": { "command": "npx", "args": ["-y", "@fontdata/ai-harness@4.7.1", "banco-dados-mcp"] }
6
6
  },
7
7
  "description": "Harness de engenharia com IA da Fontdata para Claude Code",
8
8
  "author": { "name": "Fontdata" },
package/README.md CHANGED
@@ -313,6 +313,7 @@ projeto, cadastro, limites do filtro, produção, mascaramento e dúvidas freque
313
313
  | `delphi classificar\|extrair-icone` | Classifica os `.res` versionados de um projeto Delphi e extrai o ícone que só existe no `.res` |
314
314
  | `delphi encoding detectar\|converter\|checar` | Encoding e EOL dos fontes Delphi: diagnóstico, conversão para UTF-8 com BOM e checagem (veja [Comando `delphi encoding`](#comando-delphi-encoding)) |
315
315
  | `delphi catalogo` | Catálogo das units `Fontdata.*.pas` do search path dos `.dproj` (`--pasta <dir>`, `--check`; veja [Comando `delphi catalogo`](#comando-delphi-catalogo)) |
316
+ | `checar-comando "<comando>"` | Diz se o hook `comando-destrutivo` negaria, perguntaria ou liberaria o comando, sem gravar nada (sai com 2, 3 ou 0) |
316
317
  | `list` | Lista o catálogo |
317
318
 
318
319
  O `mapa` lê TS/JS, Delphi, Python, C#, Java, Kotlin, Go, PHP, Rust e Dart. Outra linguagem, ou outra regra para uma
@@ -372,11 +373,18 @@ Os formatos estão em [`docs/contratos/ARTEFATOS.md`](docs/contratos/ARTEFATOS.m
372
373
  | `task-so-fecha-verde` | Task marcada como concluída sem suíte verde no rastro | aviso |
373
374
  | `sem-jargao` | Termo técnico no relatório para o cliente | aviso |
374
375
  | `padroes-proibidos` | `Edit`, `MultiEdit` ou `Write` que introduz um padrão declarado em `.ai-harness/padroes.json` | aviso |
376
+ | `comando-destrutivo` | `Bash` ou `PowerShell` que apaga em massa, descarta mudança do git, roda DDL/DML pelo terminal, joga texto num shell ou lê/envia segredo: nega o catastrófico e pede aprovação para o resto | **bloqueio** |
377
+ | `arquivo-sensivel` | Gravação em `.git/`, em pasta de credenciais ou no lock (nega), fora da raiz ou nos arquivos de config e settings (pergunta) | **bloqueio** |
375
378
 
376
379
  O modo de cada hook (`aviso`, `bloqueio` ou `desligado`) fica em `.ai-harness/config.json`. Hook que falha
377
380
  internamente não atrapalha o trabalho — exceto o de segurança em modo bloqueio. Projetos Delphi recebem também o
378
381
  hook `delphi-encoding`, do [perfil Delphi](#perfil-delphi).
379
382
 
383
+ O `comando-destrutivo` e o `arquivo-sensivel` seguem a rule `.claude/rules/seguranca-harness.md`, instalada com os hooks.
384
+ Para saber antes se um comando seria barrado, rode `npx @fontdata/ai-harness checar-comando "<comando>"`. A seção
385
+ `seguranca` do `.ai-harness/config.json` ajusta as `pastas_descartaveis` que podem ser apagadas sem aprovação, o deny
386
+ de leitura de segredos (`negar_leitura_segredos`, padrão `true`) e o `desligar_bypass` (padrão `false`).
387
+
380
388
  O `padroes-proibidos` vale para qualquer stack e só age no projeto que cria o `.ai-harness/padroes.json`; sem o
381
389
  arquivo, ou com a lista vazia, ele não faz nada. Cada entrada traz as extensões, a regex, os flags e o motivo
382
390
  mostrado ao agente. Só o padrão **introduzido** é acusado: o hook conta as ocorrências no texto antigo e no novo
package/dist/cli.js CHANGED
@@ -24,6 +24,7 @@ const RESERVED = new Set([
24
24
  'delphi',
25
25
  'mapa',
26
26
  'atalhos',
27
+ 'checar-comando',
27
28
  'list',
28
29
  'run',
29
30
  'help',
@@ -75,6 +76,8 @@ Gerenciar:
75
76
  delphi catalogo Catálogo da API das units Fontdata.*.pas do search path (--pasta <dir>, --check)
76
77
  mapa [caminho] Símbolos públicos por pasta, compartilhadas primeiro (--limite <n>, padrão 4000 caracteres)
77
78
  atalhos [caminho] TODO:/FIXME: do código-fonte, marcando os sem gatilho (--sem-gatilho, --json)
79
+ checar-comando "<comando>" Diz se o hook comando-destrutivo negaria, perguntaria ou liberaria, sem executar
80
+ (sai com 0 liberado, 2 negado, 3 pergunta)
78
81
  list Lista todos os comandos disponíveis no catálogo
79
82
 
80
83
  Init sem perguntas (CI):
@@ -202,6 +205,10 @@ async function main() {
202
205
  const { runShortcutsCommand } = await import('./atalhos/atalhos.js');
203
206
  process.exit(runShortcutsCommand(argv.slice(1)));
204
207
  }
208
+ if (cmd === 'checar-comando') {
209
+ const { runCheckCommandCommand } = await import('./seguranca/checar-comando.js');
210
+ process.exit(runCheckCommandCommand(argv.slice(1)));
211
+ }
205
212
  if (cmd === 'run') {
206
213
  const id = argv[1];
207
214
  if (!id) {
@@ -7,6 +7,8 @@ export const HOOK_MODES = ['aviso', 'bloqueio', 'desligado'];
7
7
  export const DEFAULT_HOOK_MODES = {
8
8
  lembrete: 'aviso',
9
9
  'segredo-no-commit': 'bloqueio',
10
+ 'comando-destrutivo': 'bloqueio',
11
+ 'arquivo-sensivel': 'bloqueio',
10
12
  'task-so-fecha-verde': 'aviso',
11
13
  'proteger-contratos': 'aviso',
12
14
  'sem-jargao': 'aviso',
@@ -15,6 +17,21 @@ export const DEFAULT_HOOK_MODES = {
15
17
  export const MODOS_PRODUCAO = ['aviso', 'bloqueio'];
16
18
  export const TIPOS_CONEXAO_PROJETO = ['postgres', 'mariadb', 'sqlite'];
17
19
  export const PERFIS_DO_CONFIG = ['delphi', 'delphi-fiscal'];
20
+ export const PASTAS_DESCARTAVEIS_PADRAO = [
21
+ 'node_modules',
22
+ 'dist',
23
+ 'build',
24
+ 'out',
25
+ 'coverage',
26
+ '.next',
27
+ '.turbo',
28
+ '.cache',
29
+ '.vite',
30
+ 'tmp',
31
+ 'temp',
32
+ '__history',
33
+ '__recovery',
34
+ ];
18
35
  export const DELPHI_IGNORAR_PADRAO = ['**/modules/**', '**/ACBr*/**'];
19
36
  function isObject(value) {
20
37
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -79,6 +96,7 @@ export function defaultConfig() {
79
96
  perfis: { delphi: true, 'delphi-fiscal': true },
80
97
  perfisExplicitos: {},
81
98
  delphi: { ignorar: [...DELPHI_IGNORAR_PADRAO], catalogo: {} },
99
+ seguranca: { pastas_descartaveis: [...PASTAS_DESCARTAVEIS_PADRAO], negar_leitura_segredos: true, desligar_bypass: false },
82
100
  };
83
101
  }
84
102
  function inteiroEntre(value, min, max) {
@@ -202,6 +220,27 @@ function lerBanco(raw, banco, problems) {
202
220
  if ('lgpd' in raw)
203
221
  lerLgpd(raw.lgpd, banco.lgpd, problems);
204
222
  }
223
+ function lerSeguranca(raw, seguranca, problems) {
224
+ if (!isObject(raw)) {
225
+ problems.push(`seguranca deve ser um objeto com pastas_descartaveis, negar_leitura_segredos e desligar_bypass em ${CONFIG_PATH}; valem os padrões.`);
226
+ return;
227
+ }
228
+ if ('pastas_descartaveis' in raw) {
229
+ const pastas = raw.pastas_descartaveis;
230
+ if (Array.isArray(pastas) && pastas.every((pasta) => typeof pasta === 'string' && pasta !== ''))
231
+ seguranca.pastas_descartaveis = pastas;
232
+ else
233
+ problems.push(`seguranca.pastas_descartaveis deve ser uma lista de pastas (texto) em ${CONFIG_PATH}; vale a lista padrão.`);
234
+ }
235
+ for (const chave of ['negar_leitura_segredos', 'desligar_bypass']) {
236
+ if (!(chave in raw))
237
+ continue;
238
+ if (typeof raw[chave] === 'boolean')
239
+ seguranca[chave] = raw[chave];
240
+ else
241
+ problems.push(`seguranca.${chave} deve ser true ou false em ${CONFIG_PATH}; vale o padrão.`);
242
+ }
243
+ }
205
244
  /** Lê a config sobre os padrões; valores inválidos são ignorados e viram problema, nunca erro. */
206
245
  export function readConfig(root) {
207
246
  const config = defaultConfig();
@@ -271,6 +310,8 @@ export function readConfig(root) {
271
310
  else if (pastas !== undefined)
272
311
  problems.push(`delphi.catalogo.pastas deve ser uma lista de pastas (texto) em ${CONFIG_PATH}; vale o search path dos .dproj.`);
273
312
  }
313
+ if ('seguranca' in raw)
314
+ lerSeguranca(raw.seguranca, config.seguranca, problems);
274
315
  const secao = soSecaoLegada(raw) ? raw[BANCO_CHAVE_LEGADA] : raw[BANCO_CHAVE];
275
316
  if (isObject(secao))
276
317
  lerBanco(secao, config.banco_dados, problems);
@@ -282,18 +323,19 @@ export function readConfig(root) {
282
323
  }
283
324
  return { config, problems };
284
325
  }
285
- /** Os padrões que vão para o arquivo: sem as seções banco_dados, comentarios, perfis e delphi, que só entram quando mudam. */
326
+ /** Os padrões que vão para o arquivo: sem as seções banco_dados, comentarios, perfis, delphi e seguranca, que só entram quando mudam. */
286
327
  function configGravada() {
287
- const { banco_dados: _banco, comentarios: _comentarios, perfis: _perfis, perfisExplicitos: _perfisExplicitos, delphi: _delphi, ...gravada } = defaultConfig();
328
+ const { banco_dados: _banco, comentarios: _comentarios, perfis: _perfis, perfisExplicitos: _perfisExplicitos, delphi: _delphi, seguranca: _seguranca, ...gravada } = defaultConfig();
288
329
  return gravada;
289
330
  }
290
- /** Cria a config com os padrões, sem as seções que só entram quando mudam; retorna false se já existia (nunca sobrescreve). */
291
- export function writeDefaultConfig(root) {
331
+ /** Cria a config com os padrões (com `seguranca`, só no `init`, inclui essa seção); retorna false se já existia (nunca sobrescreve). */
332
+ export function writeDefaultConfig(root, { seguranca = false } = {}) {
292
333
  const file = join(root, CONFIG_PATH);
293
334
  if (existsSync(file))
294
335
  return false;
295
336
  mkdirSync(dirname(file), { recursive: true });
296
- writeFileSync(file, `${JSON.stringify(configGravada(), null, 2)}\n`);
337
+ const gravada = seguranca ? { ...configGravada(), seguranca: defaultConfig().seguranca } : configGravada();
338
+ writeFileSync(file, `${JSON.stringify(gravada, null, 2)}\n`);
297
339
  return true;
298
340
  }
299
341
  function lerJsonParaEscrita(file, chave) {
@@ -19,6 +19,7 @@ import { ARCHIVE_DEFAULT_DAYS } from '../trabalhos/command.js';
19
19
  import { ARCHIVE_INDEX, readArchiveIndex } from '../trabalhos/indice-arquivo.js';
20
20
  import { adoptLegacyInstall } from '../update/legado.js';
21
21
  import { checkLegacyDocsCitations, checkMigratedPlansRunning } from './migracao.js';
22
+ import { checkSeguranca } from './seguranca.js';
22
23
  const MIN_NODE_MAJOR = 22;
23
24
  const PLUGIN_ID = 'fontdata@ai-harness';
24
25
  const HARNESS_HOOKS_DIR = '.claude/hooks/ai-harness/';
@@ -713,6 +714,7 @@ export function runDoctor(root, options = {}) {
713
714
  ...checkDelphiRes(root),
714
715
  ...checkConfig(configProblems),
715
716
  ...checkBanco(root, config),
717
+ ...checkSeguranca(root, config),
716
718
  ...checkWorks(root),
717
719
  ...checkArchiveIndex(root),
718
720
  ...checkStaleDraftPlans(root, options.now ?? new Date()),
@@ -0,0 +1,101 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { CONFIG_PATH } from '../config/config.js';
5
+ import { isHarnessPluginEnabled } from '../install/hooks.js';
6
+ import { EVENT_PERMISSION, HARNESS_DENY, SEGREDOS_DENY, SETTINGS_PATH } from '../install/settings.js';
7
+ const ALLOW_PERIGOSO = ['Bash', 'Bash(*)', 'Bash(rm:*)', 'Bash(git reset:*)', 'Bash(git clean:*)', 'Bash(curl:*)'];
8
+ const HOOKS_SEGURANCA = ['comando-destrutivo', 'arquivo-sensivel', 'segredo-no-commit'];
9
+ const HOOKS_DE_SHELL = ['comando-destrutivo', 'segredo-no-commit'];
10
+ const VARIAVEL_POWERSHELL = 'CLAUDE_CODE_USE_POWERSHELL_TOOL';
11
+ const UPDATE = '`npx @fontdata/ai-harness update --yes`';
12
+ const isObjeto = (valor) => typeof valor === 'object' && valor !== null && !Array.isArray(valor);
13
+ const listaDeTexto = (valor) => (Array.isArray(valor) ? valor.filter((item) => typeof item === 'string') : []);
14
+ function lerObjeto(arquivo) {
15
+ try {
16
+ const conteudo = JSON.parse(readFileSync(arquivo, 'utf8'));
17
+ return isObjeto(conteudo) ? conteudo : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ function powershellHabilitado(root, home, settings) {
24
+ const arquivos = [settings, lerObjeto(join(root, '.claude', 'settings.local.json')), lerObjeto(join(home, '.claude', 'settings.json'))];
25
+ return arquivos.some((arquivo) => {
26
+ const valor = isObjeto(arquivo?.env) ? arquivo.env[VARIAVEL_POWERSHELL] : undefined;
27
+ return valor === '1' || valor === 'true' || valor === 1 || valor === true;
28
+ });
29
+ }
30
+ function matcherIncluiPowerShell(matcher) {
31
+ if (matcher === undefined || matcher === '' || matcher === '*')
32
+ return true;
33
+ return typeof matcher === 'string' && matcher.split('|').some((parte) => parte.trim() === 'PowerShell');
34
+ }
35
+ function hooksDeShellSemPowerShell(settings) {
36
+ const grupos = isObjeto(settings.hooks) && Array.isArray(settings.hooks.PreToolUse) ? settings.hooks.PreToolUse : [];
37
+ const nomes = grupos.filter(isObjeto).flatMap((grupo) => {
38
+ if (matcherIncluiPowerShell(grupo.matcher))
39
+ return [];
40
+ const comandos = (Array.isArray(grupo.hooks) ? grupo.hooks : []).map((hook) => (isObjeto(hook) && typeof hook.command === 'string' ? hook.command : ''));
41
+ return HOOKS_DE_SHELL.filter((nome) => comandos.some((comando) => comando.includes(`/${nome}.mjs`)));
42
+ });
43
+ return [...new Set(nomes)];
44
+ }
45
+ /** Avisa quando o settings do projeto ou o config deixam a proteção contra comandos destrutivos fraca ou desligada. */
46
+ export function checkSeguranca(root, config, home = homedir()) {
47
+ const settings = lerObjeto(join(root, SETTINGS_PATH));
48
+ if (!settings)
49
+ return [];
50
+ const permissoes = isObjeto(settings.permissions) ? settings.permissions : {};
51
+ const arquivo = join(root, SETTINGS_PATH);
52
+ const findings = [];
53
+ const allow = listaDeTexto(permissoes.allow);
54
+ const perigosas = allow.filter((regra) => ALLOW_PERIGOSO.includes(regra));
55
+ if (perigosas.length) {
56
+ findings.push({
57
+ id: 'seguranca-allow-perigoso',
58
+ severidade: 'aviso',
59
+ mensagem: `O permissions.allow de ${arquivo} libera sem aprovação comandos que apagam ou baixam código: ${perigosas.join(', ')}.`,
60
+ correcao: `Tire ${perigosas.join(', ')} do permissions.allow e libere só os comandos estreitos de que o projeto precisa.`,
61
+ });
62
+ }
63
+ if (permissoes.defaultMode === 'bypassPermissions') {
64
+ findings.push({
65
+ id: 'seguranca-bypass-padrao',
66
+ severidade: 'aviso',
67
+ mensagem: `O permissions.defaultMode de ${arquivo} é bypassPermissions: toda sessão começa sem pedir aprovação.`,
68
+ correcao: 'Remova o defaultMode ou use um modo que pergunte; o bypass, quando preciso, se liga por sessão.',
69
+ });
70
+ }
71
+ const deny = listaDeTexto(permissoes.deny);
72
+ const esperadas = config.seguranca.negar_leitura_segredos ? [...HARNESS_DENY, ...SEGREDOS_DENY] : HARNESS_DENY;
73
+ // O harness só grava o deny junto da permissão de evento; sem ela, o settings não é dele.
74
+ const ausentes = allow.includes(EVENT_PERMISSION) ? esperadas.filter((regra) => !deny.includes(regra)) : [];
75
+ if (ausentes.length) {
76
+ findings.push({
77
+ id: 'seguranca-deny-ausente',
78
+ severidade: 'aviso',
79
+ mensagem: `Faltam no permissions.deny de ${arquivo} regras do harness: ${ausentes.join(', ')}.`,
80
+ correcao: `Restaure com ${UPDATE}; para não negar a leitura de segredos, use seguranca.negar_leitura_segredos: false em ${CONFIG_PATH}.`,
81
+ });
82
+ }
83
+ for (const nome of HOOKS_SEGURANCA.filter((hook) => config.hooks[hook] === 'desligado')) {
84
+ findings.push({
85
+ id: 'seguranca-hook-desligado',
86
+ severidade: 'aviso',
87
+ mensagem: `O hook ${nome} está desligado em ${join(root, CONFIG_PATH)}.`,
88
+ correcao: `Volte hooks.${nome} para bloqueio (ou aviso, se precisar de uma saída temporária) em ${CONFIG_PATH}.`,
89
+ });
90
+ }
91
+ const semPowerShell = powershellHabilitado(root, home, settings) && !isHarnessPluginEnabled(root, home) ? hooksDeShellSemPowerShell(settings) : [];
92
+ if (semPowerShell.length) {
93
+ findings.push({
94
+ id: 'seguranca-powershell-sem-hook',
95
+ severidade: 'aviso',
96
+ mensagem: `A ferramenta PowerShell está habilitada (${VARIAVEL_POWERSHELL}), mas em ${arquivo} o registro de ${semPowerShell.join(', ')} não inclui PowerShell no matcher.`,
97
+ correcao: `Atualize os registros com ${UPDATE}, que passa o matcher para Bash|PowerShell.`,
98
+ });
99
+ }
100
+ return findings;
101
+ }
package/dist/init.js CHANGED
@@ -104,7 +104,7 @@ async function selectByGroups(catalog, initialIds = new Set()) {
104
104
  }
105
105
  /** Config com os padrões (sem sobrescrever a existente) e o bloco gerenciado do .gitignore. */
106
106
  function prepareProjectFiles(repoPath) {
107
- writeDefaultConfig(repoPath);
107
+ writeDefaultConfig(repoPath, { seguranca: true });
108
108
  syncGitignore(repoPath, readConfig(repoPath).config);
109
109
  }
110
110
  /**
@@ -4,15 +4,17 @@ import { allCommands, recommendedCommands, templatesDir } from '../catalog.js';
4
4
  import { runnableIds, suggestIds } from '../run.js';
5
5
  import { applyAtomically } from './atomic.js';
6
6
  import { buildLockItem, hashContent, LOCK_VERSION, readLock, writeLock } from './lock.js';
7
- import { HOOKS_ITEM_ID, PROJECT_HOOKS_DIR, projectHooksConfig } from './hooks.js';
7
+ import { HOOKS_ITEM_ID, isHarnessPluginEnabled, PROJECT_HOOKS_DIR, projectHooksConfig } from './hooks.js';
8
8
  import { neededSkillsFor, resolveSelection } from './selection.js';
9
9
  import { BANCO_MCP_NOME, bancoMcpServer, MCP_PATH, mergeMcpServers } from './mcp.js';
10
10
  import { gravarInstalarComentarios, gravarRegistrarMcp, readConfig } from '../config/config.js';
11
11
  import { COMMENTS_RULE_PATH, commentsHooksConfig, ensureCommentsBaseline, hookProprio, hookProprioRegistrado } from '../comentarios/instalar.js';
12
12
  import { perfilDelphiHooksConfig, perfisDoProjeto } from './perfis.js';
13
- import { combineHooks, HARNESS_DENY, harnessPermissions, mergeSettings } from './settings.js';
13
+ import { combineHooks, harnessDeny, harnessPermissions, mergeSettings } from './settings.js';
14
14
  /** Rule de convenção com o que é específico do projeto (D-38): é do projeto, então fica fora do lock. */
15
15
  export const PROJECT_RULE_PATH = '.claude/rules/harness-projeto.md';
16
+ export const SECURITY_RULE_ID = 'seguranca-harness';
17
+ const SECURITY_RULE_PATH = '.claude/rules/seguranca-harness.md';
16
18
  /** Esqueleto da rule de projeto; os comandos `-legado` renomeados pelo update entram na última seção. */
17
19
  export function projectRuleContent(legacy) {
18
20
  const template = readFileSync(join(templatesDir, 'rules', 'harness-projeto.md'), 'utf8');
@@ -77,6 +79,9 @@ export function itemSources(catalog, tipo, id) {
77
79
  if (tipo === 'rule' && id === 'comentarios') {
78
80
  return [{ path: COMMENTS_RULE_PATH, source: join(templatesDir, 'rules', 'comentarios.md') }];
79
81
  }
82
+ if (tipo === 'rule' && id === SECURITY_RULE_ID) {
83
+ return [{ path: SECURITY_RULE_PATH, source: join(templatesDir, 'rules', 'seguranca-harness.md') }];
84
+ }
80
85
  if (tipo === 'perfil') {
81
86
  const perfil = catalog.perfis?.find((candidate) => candidate.id === id);
82
87
  if (!perfil)
@@ -178,6 +183,8 @@ export function planInstall(catalog, root, options) {
178
183
  add('skill', skill.id);
179
184
  if (options.hooks)
180
185
  add('hook', HOOKS_ITEM_ID);
186
+ if (options.hooks || isHarnessPluginEnabled(root))
187
+ add('rule', SECURITY_RULE_ID);
181
188
  if (options.agents)
182
189
  for (const agent of catalog.agents ?? [])
183
190
  add('agent', agent.id);
@@ -220,7 +227,13 @@ export function executePlan(root, plan, pkg, now = new Date()) {
220
227
  const permission = needsEventPermission(plan);
221
228
  const hooks = combineHooks(plan.registerHooks ? projectHooksConfig() : {}, plan.registerComments ? commentsHooksConfig() : {}, plan.registerPerfilDelphi ? perfilDelphiHooksConfig() : {});
222
229
  if (Object.keys(hooks).length || permission) {
223
- mergeSettings(root, { hooks, allow: permission ? harnessPermissions({ banco: bancoAtivo(plan) }) : [], deny: permission ? HARNESS_DENY : [] }, now);
230
+ const { seguranca } = readConfig(root).config;
231
+ mergeSettings(root, {
232
+ hooks,
233
+ allow: permission ? harnessPermissions({ banco: bancoAtivo(plan) }) : [],
234
+ deny: permission ? harnessDeny({ negarLeituraSegredos: seguranca.negar_leitura_segredos }) : [],
235
+ disableBypass: permission && seguranca.desligar_bypass,
236
+ }, now);
224
237
  }
225
238
  if (plan.registerComments)
226
239
  ensureCommentsBaseline(root);
@@ -1,5 +1,6 @@
1
1
  import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
+ import { projectHooksConfig } from './hooks.js';
3
4
  export const SETTINGS_PATH = join('.claude', 'settings.json');
4
5
  /** As skills de fluxo e os agents registram o rastro por este comando; sem a regra, cada evento pede aprovação. */
5
6
  export const EVENT_PERMISSION = 'Bash(npx @fontdata/ai-harness evento:*)';
@@ -66,6 +67,25 @@ export const HARNESS_DENY = [
66
67
  'Bash(git push * -f *)',
67
68
  'Bash(git push * +*)',
68
69
  ];
70
+ /** Sem curinga `.env.*`: como `deny` vence `allow`, ele deixaria o `.env.example` ilegível. */
71
+ export const SEGREDOS_DENY = [
72
+ 'Read(**/.env)',
73
+ 'Read(**/.env.local)',
74
+ 'Read(**/.env.*.local)',
75
+ 'Read(**/.env.development)',
76
+ 'Read(**/.env.dev)',
77
+ 'Read(**/.env.test)',
78
+ 'Read(**/.env.staging)',
79
+ 'Read(**/.env.production)',
80
+ 'Read(**/.env.prod)',
81
+ 'Read(**/*.pem)',
82
+ 'Read(**/*.key)',
83
+ 'Read(~/.ssh/**)',
84
+ 'Read(~/.aws/**)',
85
+ ];
86
+ export function harnessDeny({ negarLeituraSegredos }) {
87
+ return negarLeituraSegredos ? [...HARNESS_DENY, ...SEGREDOS_DENY] : HARNESS_DENY;
88
+ }
69
89
  function isPlainObject(value) {
70
90
  return typeof value === 'object' && value !== null && !Array.isArray(value);
71
91
  }
@@ -83,6 +103,18 @@ export function combineHooks(...configs) {
83
103
  }
84
104
  return combined;
85
105
  }
106
+ function lerPermissoes(root) {
107
+ try {
108
+ const settings = JSON.parse(readFileSync(join(root, SETTINGS_PATH), 'utf8'));
109
+ return isPlainObject(settings.permissions) ? settings.permissions : undefined;
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ }
115
+ export function bypassDesligado(root) {
116
+ return lerPermissoes(root)?.disableBypassPermissionsMode === 'disable';
117
+ }
86
118
  /** A regra já está em `permissions.allow` (ou na lista pedida) do `.claude/settings.json` do projeto? */
87
119
  export function hasAllowRule(root, rule, key = 'allow') {
88
120
  try {
@@ -102,6 +134,21 @@ export function hookCommands(hooks) {
102
134
  export function normalizarComandoHook(command) {
103
135
  return command.replace(/\$CLAUDE_PROJECT_DIR\b/g, '${CLAUDE_PROJECT_DIR}');
104
136
  }
137
+ function chaveHook(matcher, hook) {
138
+ const texto = (valor) => (typeof valor === 'string' ? valor : '');
139
+ return JSON.stringify([texto(matcher), normalizarComandoHook(texto(hook.command)), texto(hook.if)]);
140
+ }
141
+ function chavesDoEvento(grupos) {
142
+ return (Array.isArray(grupos) ? grupos : []).flatMap((grupo) => isPlainObject(grupo) && Array.isArray(grupo.hooks) ? grupo.hooks.filter(isPlainObject).map((hook) => chaveHook(grupo.matcher, hook)) : []);
143
+ }
144
+ export function hooksRegistrados(atual, desejado) {
145
+ if (!isPlainObject(atual))
146
+ return false;
147
+ return Object.entries(desejado).every(([evento, grupos]) => {
148
+ const existentes = new Set(chavesDoEvento(atual[evento]));
149
+ return grupos.every((grupo) => grupo.hooks.every((hook) => existentes.has(chaveHook(grupo.matcher, { ...hook }))));
150
+ });
151
+ }
105
152
  /**
106
153
  * Tira de `hooks` as entradas com esses comandos, nas duas grafias de `CLAUDE_PROJECT_DIR`, e apaga os grupos, os
107
154
  * eventos e a chave `hooks` que ficarem vazios. As outras chaves e os valores fora do formato esperado ficam como estão.
@@ -139,10 +186,9 @@ export function mergeHooksIntoSettings(root, hooks, now = new Date()) {
139
186
  }
140
187
  /**
141
188
  * Acrescenta hooks e regras de `permissions.allow` ao `.claude/settings.json` do projeto
142
- * sem perder o que já existe. Um hook é considerado presente quando algum grupo do mesmo
143
- * evento já tem o mesmo `command`, nas duas grafias de `CLAUDE_PROJECT_DIR`, e uma regra quando já está na lista, o que torna a
144
- * operação idempotente. As regras de `removeAllow` saem de `permissions.allow`. Tudo é gravado de uma vez, com um único backup datado do arquivo
145
- * original; JSON inválido é recusado sem tocar em nada. Os hooks de `removeHooks` saem antes dos acréscimos.
189
+ * sem perder o que já existe. Um hook está presente com o mesmo `command` (nas duas grafias de `CLAUDE_PROJECT_DIR`), `matcher`
190
+ * e `if`; o do `hooks.json` com outro `matcher` ou `if` sai do grupo antigo e vai para o do pedido. Uma regra está presente quando já está na lista,
191
+ * o que torna a operação idempotente. `remove*` tiram regras e hooks (`removeHooks` antes dos acréscimos). Tudo é gravado de uma vez, com um único backup datado; JSON inválido é recusado.
146
192
  */
147
193
  export function mergeSettings(root, additions, now = new Date()) {
148
194
  const file = join(root, SETTINGS_PATH);
@@ -180,15 +226,33 @@ export function mergeSettings(root, additions, now = new Date()) {
180
226
  if (hookEntries.length) {
181
227
  const merged = { ...(next.hooks ?? {}) };
182
228
  for (const [event, groups] of hookEntries) {
183
- const eventGroups = [...(merged[event] ?? [])];
184
- const known = new Set(hookCommands({ [event]: eventGroups }).map(normalizarComandoHook));
229
+ const desejadas = new Set(groups.flatMap((group) => group.hooks.map((hook) => chaveHook(group.matcher, { ...hook }))));
230
+ const doNucleo = new Set(hookCommands(projectHooksConfig()).map(normalizarComandoHook));
231
+ const doHarness = new Set(groups.flatMap((group) => group.hooks.map((hook) => normalizarComandoHook(hook.command))).filter((comando) => doNucleo.has(comando)));
232
+ const foraDoLugar = (matcher, hook) => isPlainObject(hook) && typeof hook.command === 'string' && doHarness.has(normalizarComandoHook(hook.command)) && !desejadas.has(chaveHook(matcher, hook));
233
+ const eventGroups = [...(merged[event] ?? [])].flatMap((group) => {
234
+ if (!isPlainObject(group) || !Array.isArray(group.hooks))
235
+ return [group];
236
+ const mantidos = group.hooks.filter((hook) => !foraDoLugar(group.matcher, hook));
237
+ if (mantidos.length === group.hooks.length)
238
+ return [group];
239
+ changed = true;
240
+ return mantidos.length ? [{ ...group, hooks: mantidos }] : [];
241
+ });
242
+ const known = new Set([...chavesDoEvento(eventGroups), ...hookCommands({ [event]: eventGroups }).map(normalizarComandoHook)]);
243
+ const chave = (matcher, hook) => doHarness.has(normalizarComandoHook(hook.command)) ? chaveHook(matcher, { ...hook }) : normalizarComandoHook(hook.command);
185
244
  for (const group of groups) {
186
- const missing = group.hooks.filter((hook) => !known.has(normalizarComandoHook(hook.command)));
245
+ const missing = group.hooks.filter((hook) => !known.has(chave(group.matcher, hook)));
187
246
  if (!missing.length)
188
247
  continue;
189
- eventGroups.push({ ...group, hooks: missing });
248
+ const irmaos = new Set(group.hooks.map((hook) => chaveHook(group.matcher, { ...hook })));
249
+ const destino = eventGroups.findIndex((existente) => chavesDoEvento([existente]).some((chave) => irmaos.has(chave)));
250
+ if (destino >= 0)
251
+ eventGroups[destino] = { ...eventGroups[destino], hooks: [...eventGroups[destino].hooks, ...missing] };
252
+ else
253
+ eventGroups.push({ ...group, hooks: missing });
190
254
  for (const hook of missing)
191
- known.add(normalizarComandoHook(hook.command));
255
+ known.add(chave(group.matcher, hook));
192
256
  changed = true;
193
257
  }
194
258
  merged[event] = eventGroups;
@@ -209,10 +273,16 @@ export function mergeSettings(root, additions, now = new Date()) {
209
273
  }
210
274
  next.permissions = { ...permissions, [key]: list };
211
275
  }
212
- const remove = additions.removeAllow ?? [];
213
- const currentAllow = next.permissions?.allow;
214
- if (remove.length && currentAllow?.some((rule) => remove.includes(rule))) {
215
- next.permissions = { ...next.permissions, allow: currentAllow.filter((rule) => !remove.includes(rule)) };
276
+ for (const [key, remove] of [['allow', additions.removeAllow ?? []], ['deny', additions.removeDeny ?? []]]) {
277
+ const current = next.permissions?.[key];
278
+ if (remove.length && current?.some((rule) => remove.includes(rule))) {
279
+ next.permissions = { ...next.permissions, [key]: current.filter((rule) => !remove.includes(rule)) };
280
+ changed = true;
281
+ }
282
+ }
283
+ const permissions = next.permissions ?? {};
284
+ if (additions.disableBypass && permissions.disableBypassPermissionsMode !== 'disable') {
285
+ next.permissions = { ...permissions, disableBypassPermissionsMode: 'disable' };
216
286
  changed = true;
217
287
  }
218
288
  if (!changed)
@@ -0,0 +1,90 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join, relative } from 'node:path';
4
+ import { templatesDir } from '../catalog.js';
5
+ import { DEFAULT_HOOK_MODES, readConfig } from '../config/config.js';
6
+ import { PROJECT_HOOKS_DIR } from '../install/hooks.js';
7
+ import { acharRaiz } from '../raiz.js';
8
+ const HOOK = 'comando-destrutivo';
9
+ const PREFIXO = `[ai-harness · ${HOOK}] `;
10
+ const USO = 'Uso: npx @fontdata/ai-harness checar-comando "<comando>"';
11
+ export const CODIGO_SAIDA = { LIBERADO: 0, NEGADO: 2, PERGUNTA: 3 };
12
+ /** Erro de execução do hook: sai com 1, como o erro de uso. */
13
+ export class ErroChecagem extends Error {
14
+ }
15
+ function extrairRegra(mensagem) {
16
+ const texto = mensagem.startsWith(PREFIXO) ? mensagem.slice(PREFIXO.length) : mensagem;
17
+ const [, regra, motivo] = /^([a-z0-9]+(?:-[a-z0-9]+)*): ([\s\S]*)$/.exec(texto) ?? [];
18
+ return regra !== undefined && motivo !== undefined ? { regra, motivo } : { motivo: texto };
19
+ }
20
+ /**
21
+ * Roda o hook (a cópia instalada no projeto, senão a do pacote) no modo bloqueio e sem rastro, e devolve a decisão.
22
+ * `inicio` é de onde a raiz é procurada; `env` soma ao ambiente herdado. Lança `ErroChecagem` se o hook falhar.
23
+ */
24
+ export function checarComando(comando, opcoes = {}) {
25
+ const raiz = acharRaiz(opcoes.inicio);
26
+ const instalada = join(raiz, PROJECT_HOOKS_DIR, `${HOOK}.mjs`);
27
+ const hook = existsSync(instalada)
28
+ ? { origem: 'instalada', caminho: instalada }
29
+ : { origem: 'pacote', caminho: join(templatesDir, 'hooks', `${HOOK}.mjs`) };
30
+ const r = spawnSync(process.execPath, [hook.caminho], {
31
+ cwd: raiz,
32
+ input: JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: comando }, cwd: raiz }),
33
+ env: { ...process.env, ...opcoes.env, CLAUDE_PROJECT_DIR: raiz, AI_HARNESS_SEM_RASTRO: '1', AI_HARNESS_MODO_FORCADO: 'bloqueio' },
34
+ encoding: 'utf8',
35
+ });
36
+ const falha = (detalhe) => new ErroChecagem(`Erro ao executar o hook ${hook.caminho}: ${detalhe}`);
37
+ if (r.error)
38
+ throw falha(r.error.message);
39
+ if (r.status !== 0)
40
+ throw falha(`saiu com ${r.status ?? r.signal}.\n${r.stderr.trim()}`);
41
+ const modoConfigurado = readConfig(raiz).config.hooks[HOOK] ?? DEFAULT_HOOK_MODES[HOOK] ?? 'bloqueio';
42
+ const base = { raiz, hook, modoConfigurado };
43
+ if (!r.stdout.trim())
44
+ return { veredito: 'LIBERADO', ...base };
45
+ let saida;
46
+ try {
47
+ saida = JSON.parse(r.stdout);
48
+ }
49
+ catch {
50
+ throw falha(`resposta que não é JSON: ${r.stdout.trim().slice(0, 200)}`);
51
+ }
52
+ const decisao = saida.hookSpecificOutput?.permissionDecision;
53
+ const razao = saida.hookSpecificOutput?.permissionDecisionReason;
54
+ if ((decisao !== 'deny' && decisao !== 'ask') || typeof razao !== 'string') {
55
+ throw falha(`resposta inesperada (a cópia pode não aceitar AI_HARNESS_MODO_FORCADO): ${r.stdout.trim().slice(0, 200)}`);
56
+ }
57
+ return { veredito: decisao === 'deny' ? 'NEGADO' : 'PERGUNTA', ...extrairRegra(razao), ...base };
58
+ }
59
+ export function formatarChecagem(c) {
60
+ const linhas = [c.veredito];
61
+ if (c.veredito !== 'LIBERADO') {
62
+ linhas.push(`regra: ${c.regra ?? '(nenhuma)'}`, `motivo: ${c.motivo ?? ''}`);
63
+ }
64
+ const caminho = c.hook.origem === 'instalada' ? relative(c.raiz, c.hook.caminho) : c.hook.caminho;
65
+ linhas.push(`hook: ${c.hook.origem === 'instalada' ? 'cópia instalada' : 'cópia do pacote'} (${caminho})`);
66
+ if (c.modoConfigurado === 'aviso')
67
+ linhas.push('modo: no modo `aviso` configurado, só avisaria');
68
+ if (c.modoConfigurado === 'desligado')
69
+ linhas.push('modo: desligado: não roda nas sessões');
70
+ return linhas.join('\n');
71
+ }
72
+ /** `checar-comando "<comando>"`: 0 liberado, 2 negado, 3 pergunta, 1 erro de uso ou de execução. */
73
+ export function runCheckCommandCommand(argv) {
74
+ const comando = argv.join(' ');
75
+ if (!comando.trim()) {
76
+ console.error(USO);
77
+ return 1;
78
+ }
79
+ try {
80
+ const checagem = checarComando(comando);
81
+ console.log(formatarChecagem(checagem));
82
+ return CODIGO_SAIDA[checagem.veredito];
83
+ }
84
+ catch (erro) {
85
+ if (!(erro instanceof ErroChecagem))
86
+ throw erro;
87
+ console.error(erro.message);
88
+ return 1;
89
+ }
90
+ }