@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.
@@ -0,0 +1,386 @@
1
+ // @ts-check
2
+
3
+ /** @typedef {{ valor: string, inicio: number, fim: number, heredoc: boolean, subs: string[] }} Palavra */
4
+ /** @typedef {{ palavras: Palavra[], corpos: Array<[number, number]>, inicio: number, fim: number, separador: string }} Segmento */
5
+ /** @typedef {{ pastas_descartaveis: string[], negar_leitura_segredos: boolean, desligar_bypass: boolean }} Seguranca */
6
+ /** @typedef {{ comando: string, segmentos: string[], raiz: string, seguranca: Seguranca, readonly trabalhosAtivos: string[] }} ContextoComando */
7
+ /** @typedef {{ id: string, decisao: 'negar' | 'perguntar', motivo: string, testar: (ctx: ContextoComando) => boolean }} Regra */
8
+
9
+ export const INTERPRETADORES_SHELL = new Set([
10
+ 'sh', 'bash', 'zsh', 'dash', 'ksh', 'fish', 'csh', 'tcsh', 'pwsh', 'powershell', 'cmd', 'iex', 'invoke-expression', 'source',
11
+ ]);
12
+
13
+ const ESCAPAVEIS = '\'"\\$`()';
14
+ const FIM_DE_DELIMITADOR = /[\s;|&<>()]/;
15
+
16
+ /** @type {Record<string, string[]>} */
17
+ const PREFIXOS = {
18
+ sudo: ['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U', '-T'],
19
+ doas: ['-u', '-C'],
20
+ env: ['-u', '-C'],
21
+ command: [],
22
+ builtin: [],
23
+ exec: ['-a'],
24
+ nohup: [],
25
+ time: ['-f', '-o'],
26
+ nice: ['-n'],
27
+ npx: ['-p', '--package'],
28
+ bunx: ['-p', '--package'],
29
+ pnpx: [],
30
+ '&': [],
31
+ '{': [],
32
+ '}': [],
33
+ '!': [],
34
+ if: [],
35
+ then: [],
36
+ else: [],
37
+ elif: [],
38
+ do: [],
39
+ while: [],
40
+ until: [],
41
+ };
42
+
43
+ export function nomeBase(/** @type {string} */ palavra) {
44
+ return (palavra.split(/[\\/]/).pop() ?? '').toLowerCase().replace(/\.(exe|cmd|bat|com)$/, '');
45
+ }
46
+
47
+ /** @param {string} texto @param {number} j posição do `<<` */
48
+ function lerHeredoc(texto, j) {
49
+ let k = j + 2;
50
+ if (texto[k] === '-') k++;
51
+ while (texto[k] === ' ' || texto[k] === '\t') k++;
52
+ const inicio = k;
53
+ let quote = '';
54
+ while (k < texto.length) {
55
+ const c = texto[k] ?? '';
56
+ if (quote) {
57
+ if (c === quote) quote = '';
58
+ } else if (c === '"' || c === "'") quote = c;
59
+ else if (FIM_DE_DELIMITADOR.test(c)) break;
60
+ k++;
61
+ }
62
+ return { delimitador: texto.slice(inicio, k).replace(/["'\\]/g, ''), fim: k };
63
+ }
64
+
65
+ /** Delimitador ausente vai até o fim. @param {string} texto @param {number} inicio @param {string[]} delimitadores */
66
+ function lerCorpos(texto, inicio, delimitadores) {
67
+ /** @type {Array<[number, number]>} */
68
+ const trechos = [];
69
+ let pos = inicio;
70
+ for (const delimitador of delimitadores) {
71
+ const comeco = pos;
72
+ for (;;) {
73
+ const eol = texto.indexOf('\n', pos);
74
+ const linha = texto.slice(pos, eol === -1 ? texto.length : eol);
75
+ if (linha.trim() === delimitador || eol === -1) {
76
+ trechos.push([comeco, pos + linha.length]);
77
+ pos = eol === -1 ? texto.length : eol + 1;
78
+ break;
79
+ }
80
+ pos = eol + 1;
81
+ }
82
+ }
83
+ return { trechos, fim: pos };
84
+ }
85
+
86
+ /** Fim do `$(...)` aberto antes de `j`. @param {string} texto @param {number} j */
87
+ function fimSubshell(texto, j) {
88
+ let profundidade = 1;
89
+ /** @type {string[]} */
90
+ let pendentes = [];
91
+ while (j < texto.length) {
92
+ const c = texto[j];
93
+ if (c === '\\') j += 2;
94
+ else if (c === "'") {
95
+ const f = texto.indexOf("'", j + 1);
96
+ j = f === -1 ? texto.length : f + 1;
97
+ } else if (c === '"') j = lerAspasDuplas(texto, j).fim;
98
+ else if (c === '`') {
99
+ const f = texto.indexOf('`', j + 1);
100
+ j = f === -1 ? j + 1 : f + 1;
101
+ } else if (texto.startsWith('<<<', j)) j += 3;
102
+ else if (texto.startsWith('<<', j)) {
103
+ const heredoc = lerHeredoc(texto, j);
104
+ if (heredoc.delimitador) pendentes.push(heredoc.delimitador);
105
+ j = heredoc.fim;
106
+ } else if (c === '\n' && pendentes.length) {
107
+ j = lerCorpos(texto, j + 1, pendentes).fim;
108
+ pendentes = [];
109
+ } else {
110
+ if (c === '(') profundidade++;
111
+ if (c === ')' && --profundidade === 0) return j + 1;
112
+ j++;
113
+ }
114
+ }
115
+ return texto.length;
116
+ }
117
+
118
+ /**
119
+ * Sem a aspa de fechamento pelo bash, relê sem escape de barra como o PowerShell em `"C:\"`: o bash o recusaria.
120
+ * @param {string} texto @param {number} i @returns {{ valor: string, fim: number, subs: string[] }} */
121
+ function lerAspasDuplas(texto, i) {
122
+ let valor = '';
123
+ /** @type {string[]} */
124
+ const subs = [];
125
+ let j = i + 1;
126
+ while (j < texto.length) {
127
+ const c = texto[j];
128
+ if (c === '"') return { valor, fim: j + 1, subs };
129
+ if (c === '\\' && '"\\$`\n'.includes(texto[j + 1] ?? '')) {
130
+ if (texto[j + 1] !== '\n') valor += texto[j + 1];
131
+ j += 2;
132
+ } else if (c === '$' && texto[j + 1] === '(') {
133
+ const fim = fimSubshell(texto, j + 2);
134
+ subs.push(texto.slice(j + 2, fim - 1));
135
+ valor += texto.slice(j, fim);
136
+ j = fim;
137
+ } else if (c === '`' && texto.indexOf('`', j + 1) !== -1) {
138
+ const fim = texto.indexOf('`', j + 1);
139
+ subs.push(texto.slice(j + 1, fim));
140
+ valor += texto.slice(j, fim + 1);
141
+ j = fim + 1;
142
+ } else {
143
+ valor += c;
144
+ j++;
145
+ }
146
+ }
147
+ const fecha = texto.indexOf('"', i + 1);
148
+ return fecha === -1 ? { valor: texto.slice(i + 1), fim: texto.length, subs } : { valor: texto.slice(i + 1, fecha), fim: fecha + 1, subs };
149
+ }
150
+
151
+ /** @param {string} texto @returns {Segmento[]} */
152
+ function analisar(texto) {
153
+ /** @type {Segmento[]} */
154
+ const segmentos = [];
155
+ /** @type {(inicio: number) => Segmento} */
156
+ const novo = (inicio) => ({ palavras: [], corpos: [], inicio, fim: inicio, separador: '' });
157
+ let seg = novo(0);
158
+ /** @type {{ valor: string, inicio: number, subs: string[], heredoc?: boolean } | null} */
159
+ let atual = null;
160
+ /** @type {Array<{ delimitador: string, seg: Segmento }>} */
161
+ let pendentes = [];
162
+ let i = 0;
163
+
164
+ const palavra = () => (atual ??= { valor: '', inicio: i, subs: [] });
165
+ const fechar = (/** @type {number} */ fim) => {
166
+ if (atual) seg.palavras.push({ valor: atual.valor, inicio: atual.inicio, fim, heredoc: Boolean(atual.heredoc), subs: atual.subs });
167
+ atual = null;
168
+ };
169
+ const separar = (/** @type {string} */ separador, /** @type {number} */ tamanho) => {
170
+ fechar(i);
171
+ seg.fim = i;
172
+ seg.separador = separador;
173
+ segmentos.push(seg);
174
+ i += tamanho;
175
+ if (separador === '\n' && pendentes.length) {
176
+ const { trechos, fim } = lerCorpos(texto, i, pendentes.map((p) => p.delimitador));
177
+ trechos.forEach((trecho, k) => pendentes[k]?.seg.corpos.push(trecho));
178
+ pendentes = [];
179
+ i = fim;
180
+ }
181
+ seg = novo(i);
182
+ };
183
+
184
+ while (i < texto.length) {
185
+ const c = texto[i];
186
+ const prox = texto[i + 1];
187
+ if (c === "'") {
188
+ const p = palavra();
189
+ const fim = texto.indexOf("'", i + 1);
190
+ p.valor += texto.slice(i + 1, fim === -1 ? texto.length : fim);
191
+ i = fim === -1 ? texto.length : fim + 1;
192
+ } else if (c === '"') {
193
+ const p = palavra();
194
+ const lido = lerAspasDuplas(texto, i);
195
+ p.valor += lido.valor;
196
+ p.subs.push(...lido.subs);
197
+ i = lido.fim;
198
+ } else if (c === '$' && prox === '(') {
199
+ const p = palavra();
200
+ const fim = fimSubshell(texto, i + 2);
201
+ p.subs.push(texto.slice(i + 2, fim - 1));
202
+ p.valor += texto.slice(i, fim);
203
+ i = fim;
204
+ } else if (c === '`' && texto.indexOf('`', i + 1) !== -1) {
205
+ const p = palavra();
206
+ const fim = texto.indexOf('`', i + 1);
207
+ p.subs.push(texto.slice(i + 1, fim));
208
+ p.valor += texto.slice(i, fim + 1);
209
+ i = fim + 1;
210
+ } else if (c === '\\' && prox === '\n') {
211
+ i += 2;
212
+ } else if (c === '\\' && prox !== undefined && ESCAPAVEIS.includes(prox)) {
213
+ palavra().valor += prox;
214
+ i += 2;
215
+ } else if (c === ' ' || c === '\t' || c === '\r') {
216
+ fechar(i);
217
+ i++;
218
+ } else if (c === '#' && !atual) {
219
+ const eol = texto.indexOf('\n', i);
220
+ i = eol === -1 ? texto.length : eol;
221
+ } else if (c === '\n') separar('\n', 1);
222
+ else if (c === ';') separar(';', 1);
223
+ else if (c === '(' || c === ')') separar(c, 1);
224
+ else if (c === '&' && prox === '&') separar('&&', 2);
225
+ else if (c === '|' && prox === '|') separar('||', 2);
226
+ else if (c === '|' && prox === '&') separar('|&', 2);
227
+ else if (c === '|') separar('|', 1);
228
+ else if (c === '&' && prox !== '>' && !/[<>]$/.test(atual?.valor ?? '')) separar('&', 1);
229
+ else if (texto.startsWith('<<<', i)) {
230
+ palavra().valor += '<<<';
231
+ i += 3;
232
+ } else if (c === '<' && prox === '<') {
233
+ fechar(i);
234
+ const heredoc = lerHeredoc(texto, i);
235
+ if (heredoc.delimitador) pendentes.push({ delimitador: heredoc.delimitador, seg });
236
+ atual = { valor: `<<${heredoc.delimitador}`, inicio: i, subs: [], heredoc: true };
237
+ i = heredoc.fim;
238
+ fechar(i);
239
+ } else {
240
+ palavra().valor += c;
241
+ i++;
242
+ }
243
+ }
244
+ fechar(i);
245
+ seg.fim = i;
246
+ segmentos.push(seg);
247
+ return segmentos;
248
+ }
249
+
250
+ /** @param {string} texto @param {Segmento} seg */
251
+ function textoDoSegmento(texto, seg) {
252
+ return [texto.slice(seg.inicio, seg.fim).trim(), ...seg.corpos.map(([a, b]) => texto.slice(a, b))].join('\n').trim();
253
+ }
254
+
255
+ /** Trechos fora de aspas; o corpo do heredoc fica no trecho que o abre. @param {string} comando */
256
+ export function segmentos(comando) {
257
+ return analisar(comando)
258
+ .map((seg) => textoDoSegmento(comando, seg))
259
+ .filter(Boolean);
260
+ }
261
+
262
+ /** Palavras sem aspas e sem os operadores de heredoc. @param {string} segmento */
263
+ export function palavras(segmento) {
264
+ return analisar(segmento).flatMap((seg) => seg.palavras.filter((p) => !p.heredoc).map((p) => p.valor));
265
+ }
266
+
267
+ /** @param {string[]} lista */
268
+ function inicioDoComando(lista) {
269
+ let k = 0;
270
+ while (k < lista.length) {
271
+ const atual = lista[k] ?? '';
272
+ const nome = nomeBase(atual);
273
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(atual)) {
274
+ k++;
275
+ } else if (Object.hasOwn(PREFIXOS, nome)) {
276
+ const comValor = PREFIXOS[nome] ?? [];
277
+ k++;
278
+ while ((lista[k] ?? '').startsWith('-')) k += comValor.includes(lista[k] ?? '') ? 2 : 1;
279
+ } else if (['npm', 'pnpm', 'yarn'].includes(nome) && ['exec', 'dlx', 'x'].includes(lista[k + 1] ?? '')) {
280
+ k += 2;
281
+ while ((lista[k] ?? '').startsWith('-')) k++;
282
+ } else break;
283
+ }
284
+ return k;
285
+ }
286
+
287
+ /** @param {string[]} lista */
288
+ function semRedirecoes(lista) {
289
+ /** @type {string[]} */
290
+ const saida = [];
291
+ for (let k = 0; k < lista.length; k++) {
292
+ const atual = lista[k] ?? '';
293
+ if (/^(\d+|&)?(>>?|<|>\||<<<)$/.test(atual)) k++;
294
+ else if (!/^(\d+|&)?(>>?|<)/.test(atual)) saida.push(atual);
295
+ }
296
+ return saida;
297
+ }
298
+
299
+ /** Programa depois de atribuições, `sudo`, `env`, `npx` e afins; args sem redirecionamentos. @param {string[]} lista */
300
+ export function invocacao(lista) {
301
+ const limpa = semRedirecoes(lista);
302
+ const k = inicioDoComando(limpa);
303
+ return { nome: nomeBase(limpa[k] ?? ''), args: limpa.slice(k + 1) };
304
+ }
305
+
306
+ /** @param {Segmento[]} segs @param {number} k */
307
+ function saidaVaiParaShell(segs, k) {
308
+ for (let m = k; segs[m]?.separador === '|' || segs[m]?.separador === '|&'; m++) {
309
+ const seguinte = segs[m + 1];
310
+ if (seguinte && INTERPRETADORES_SHELL.has(invocacao(seguinte.palavras.filter((p) => !p.heredoc).map((p) => p.valor)).nome)) return true;
311
+ }
312
+ return false;
313
+ }
314
+
315
+ /** @param {Segmento} seg @returns {{ palavras: Palavra[], corpos: boolean }} */
316
+ function textoLivreDo(seg) {
317
+ const normais = seg.palavras.filter((p) => !p.heredoc);
318
+ const valores = normais.map((p) => p.valor);
319
+ const k = inicioDoComando(valores);
320
+ const nome = nomeBase(valores[k] ?? '');
321
+ const heredocs = seg.palavras.filter((p) => p.heredoc);
322
+ if (['grep', 'egrep', 'fgrep', 'rg', 'echo'].includes(nome)) return { palavras: [...normais.slice(k + 1), ...heredocs], corpos: true };
323
+ if (nome !== 'git') return { palavras: [], corpos: false };
324
+
325
+ let j = k + 1;
326
+ while ((valores[j] ?? '').startsWith('-')) j += ['-C', '-c', '--git-dir', '--work-tree', '--namespace'].includes(valores[j] ?? '') ? 2 : 1;
327
+ const sub = valores[j];
328
+ if (sub === 'grep') return { palavras: [...normais.slice(j + 1), ...heredocs], corpos: true };
329
+ /** @type {Palavra[]} */
330
+ const livres = [];
331
+ for (let m = j + 1; m < normais.length; m++) {
332
+ const atual = valores[m] ?? '';
333
+ const p = normais[m];
334
+ const seguinte = normais[m + 1];
335
+ if (!p) continue;
336
+ if (sub === 'log' && (/^-[SG]$/.test(atual) || atual === '--grep')) {
337
+ livres.push(p);
338
+ if (seguinte) livres.push(seguinte);
339
+ m++;
340
+ } else if (sub === 'log' && (/^-[SG]./.test(atual) || atual.startsWith('--grep='))) livres.push(p);
341
+ else if (sub === 'commit' && (/^-[A-Za-z]*m$/.test(atual) || atual === '--message')) {
342
+ if (seguinte) livres.push(seguinte);
343
+ m++;
344
+ } else if (sub === 'commit' && (/^-[A-Za-z]*m./.test(atual) || atual.startsWith('--message='))) {
345
+ const corte = atual.startsWith('--') ? 0 : atual.indexOf('m') + 1;
346
+ livres.push({ ...p, inicio: p.inicio + corte });
347
+ }
348
+ }
349
+ return sub === 'commit' ? { palavras: [...livres, ...heredocs], corpos: true } : { palavras: livres, corpos: false };
350
+ }
351
+
352
+ /** `$(cat <<'EOF' … EOF)`: só texto, o idioma da mensagem de commit e do corpo de PR. */
353
+ function soHeredocDoCat(/** @type {string} */ sub) {
354
+ const segs = analisar(sub).filter((seg) => seg.palavras.length);
355
+ const unico = segs[0];
356
+ if (segs.length !== 1 || !unico || !unico.corpos.length) return false;
357
+ const { nome, args } = invocacao(unico.palavras.filter((p) => !p.heredoc).map((p) => p.valor));
358
+ return nome === 'cat' && args.length === 0;
359
+ }
360
+
361
+ /**
362
+ * Tira o texto livre (mensagem de commit, args de grep, rg, echo e git log -S/-G), salvo se a saída vai para shell.
363
+ * As substituições `$(...)` e crases voltam no fim, uma por linha, porque rodam. @param {string} comando @returns {string} */
364
+ export function semTextoLivre(comando) {
365
+ const segs = analisar(comando);
366
+ /** @type {Array<[number, number]>} */
367
+ const cortes = [];
368
+ /** @type {string[]} */
369
+ const extras = [];
370
+ segs.forEach((seg, k) => {
371
+ for (const p of seg.palavras) for (const sub of p.subs) if (!soHeredocDoCat(sub)) extras.push(semTextoLivre(sub));
372
+ if (saidaVaiParaShell(segs, k)) return;
373
+ const livre = textoLivreDo(seg);
374
+ for (const p of livre.palavras) cortes.push([p.inicio, p.fim]);
375
+ if (livre.corpos) cortes.push(...seg.corpos);
376
+ });
377
+
378
+ let saida = '';
379
+ let pos = 0;
380
+ for (const [a, b] of cortes.sort((x, y) => x[0] - y[0])) {
381
+ if (a > pos) saida += comando.slice(pos, a);
382
+ pos = Math.max(pos, b);
383
+ }
384
+ saida += comando.slice(pos);
385
+ return [saida, ...extras].join('\n');
386
+ }
@@ -13,6 +13,8 @@ import { join } from 'node:path';
13
13
  export const DEFAULT_HOOK_MODES = {
14
14
  lembrete: 'aviso',
15
15
  'segredo-no-commit': 'bloqueio',
16
+ 'comando-destrutivo': 'bloqueio',
17
+ 'arquivo-sensivel': 'bloqueio',
16
18
  'task-so-fecha-verde': 'aviso',
17
19
  'proteger-contratos': 'aviso',
18
20
  'sem-jargao': 'aviso',
@@ -39,3 +41,44 @@ export function hookMode(root, hook) {
39
41
  return fallback;
40
42
  }
41
43
  }
44
+
45
+ /** Mesmos padrões de `seguranca` em src/config/config.ts. */
46
+ export const PASTAS_DESCARTAVEIS_PADRAO = [
47
+ 'node_modules',
48
+ 'dist',
49
+ 'build',
50
+ 'out',
51
+ 'coverage',
52
+ '.next',
53
+ '.turbo',
54
+ '.cache',
55
+ '.vite',
56
+ 'tmp',
57
+ 'temp',
58
+ '__history',
59
+ '__recovery',
60
+ ];
61
+
62
+ /**
63
+ * Seção `seguranca` da config; config ausente, ilegível ou valor inválido cai no padrão daquela chave.
64
+ * @param {string} root
65
+ * @returns {{ pastas_descartaveis: string[], negar_leitura_segredos: boolean, desligar_bypass: boolean }}
66
+ */
67
+ export function segurancaConfig(root) {
68
+ const seguranca = { pastas_descartaveis: [...PASTAS_DESCARTAVEIS_PADRAO], negar_leitura_segredos: true, desligar_bypass: false };
69
+ const file = join(root, '.ai-harness', 'config.json');
70
+ if (!existsSync(file)) return seguranca;
71
+ /** @type {any} */
72
+ let raw;
73
+ try {
74
+ raw = JSON.parse(readFileSync(file, 'utf8'))?.seguranca;
75
+ } catch {
76
+ return seguranca;
77
+ }
78
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return seguranca;
79
+ const pastas = raw.pastas_descartaveis;
80
+ if (Array.isArray(pastas) && pastas.every((pasta) => typeof pasta === 'string' && pasta !== '')) seguranca.pastas_descartaveis = pastas;
81
+ if (typeof raw.negar_leitura_segredos === 'boolean') seguranca.negar_leitura_segredos = raw.negar_leitura_segredos;
82
+ if (typeof raw.desligar_bypass === 'boolean') seguranca.desligar_bypass = raw.desligar_bypass;
83
+ return seguranca;
84
+ }
@@ -5,7 +5,7 @@ import { DEFAULT_HOOK_MODES, hookMode } from './config.mjs';
5
5
  import { recordEvent } from './rastro.mjs';
6
6
 
7
7
  /**
8
- * @typedef {{ motivo: string }} Violation
8
+ * @typedef {{ motivo: string, decisao?: 'negar' | 'perguntar' }} Violation
9
9
  * @typedef {{ root: string, mode: 'aviso' | 'bloqueio' }} HookContext
10
10
  * @callback Handler
11
11
  * @param {Record<string, any>} input
@@ -19,17 +19,20 @@ async function readStdin() {
19
19
  return data;
20
20
  }
21
21
 
22
+ /** @type {readonly string[]} */
23
+ const MODOS_FORCADOS = ['aviso', 'bloqueio'];
24
+
22
25
  /**
23
- * Resposta no formato de cada evento: em `PreToolUse` o bloqueio nega a permissão e o aviso só
24
- * acrescenta contexto; nos demais eventos o bloqueio usa `decision: "block"`.
26
+ * Fora de `PreToolUse`, o bloqueio responde `decision: "block"`, mesmo quando a decisão é perguntar.
25
27
  * @param {string} event
26
28
  * @param {'aviso' | 'bloqueio'} mode
29
+ * @param {boolean} pergunta
27
30
  * @param {string} message
28
31
  */
29
- function response(event, mode, message) {
32
+ function response(event, mode, pergunta, message) {
30
33
  if (event === 'PreToolUse') {
31
34
  return mode === 'bloqueio'
32
- ? { hookSpecificOutput: { hookEventName: event, permissionDecision: 'deny', permissionDecisionReason: message } }
35
+ ? { hookSpecificOutput: { hookEventName: event, permissionDecision: pergunta ? 'ask' : 'deny', permissionDecisionReason: message } }
33
36
  : { hookSpecificOutput: { hookEventName: event, additionalContext: message } };
34
37
  }
35
38
  if (mode === 'bloqueio') return { decision: 'block', reason: message };
@@ -37,8 +40,9 @@ function response(event, mode, message) {
37
40
  }
38
41
 
39
42
  /**
40
- * Executa um hook. O handler devolve `{ motivo }` quando há algo a avisar ou bloquear, ou null.
41
- * Erros falham abertos (não atrapalham o usuário), exceto em hook de segurança no modo bloqueio.
43
+ * Executa um hook; o handler devolve `{ motivo, decisao? }` ou null. `perguntar` pede aprovação só em
44
+ * `PreToolUse` no modo bloqueio. Erros falham abertos, exceto em hook de segurança no modo bloqueio.
45
+ * `AI_HARNESS_MODO_FORCADO` troca o modo da config; `AI_HARNESS_SEM_RASTRO=1` não grava evento.
42
46
  * @param {string} name
43
47
  * @param {Handler} handler
44
48
  */
@@ -53,7 +57,8 @@ export async function runHook(name, handler) {
53
57
  if (typeof input !== 'object' || input === null) return;
54
58
 
55
59
  const root = process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();
56
- const mode = hookMode(root, name);
60
+ const forcado = process.env.AI_HARNESS_MODO_FORCADO;
61
+ const mode = forcado && MODOS_FORCADOS.includes(forcado) ? /** @type {'aviso' | 'bloqueio'} */ (forcado) : hookMode(root, name);
57
62
  if (mode === 'desligado') return;
58
63
 
59
64
  /** @type {Violation | null} */
@@ -67,17 +72,22 @@ export async function runHook(name, handler) {
67
72
  }
68
73
  if (!violation) return;
69
74
 
75
+ const event = String(input.hook_event_name ?? '');
76
+ const pergunta = mode === 'bloqueio' && event === 'PreToolUse' && violation.decisao === 'perguntar';
70
77
  const message = `[ai-harness · ${name}] ${violation.motivo}`;
71
- process.stdout.write(JSON.stringify(response(String(input.hook_event_name ?? ''), mode, message)));
78
+ process.stdout.write(JSON.stringify(response(event, mode, pergunta, message)));
79
+ if (process.env.AI_HARNESS_SEM_RASTRO === '1') return;
72
80
 
81
+ const bloqueou = mode === 'bloqueio' && !pergunta;
82
+ const motivo = violation.motivo.slice(0, 1000);
73
83
  try {
74
84
  recordEvent(root, {
75
- evento: mode === 'bloqueio' ? 'hook_bloqueio' : 'hook_aviso',
85
+ evento: bloqueou ? 'hook_bloqueio' : 'hook_aviso',
76
86
  origem: 'hook',
77
87
  nome: name,
78
88
  modo: mode,
79
- resultado: mode,
80
- dados: { motivo: violation.motivo.slice(0, 1000) },
89
+ resultado: bloqueou ? 'bloqueio' : 'aviso',
90
+ dados: pergunta ? { motivo, decisao: 'perguntar' } : { motivo },
81
91
  });
82
92
  } catch {
83
93
  // o rastro nunca impede a resposta do hook.
@@ -0,0 +1,100 @@
1
+ // @ts-check
2
+ import { posix, win32 } from 'node:path';
3
+ import { invocacao, nomeBase, palavras } from '../comando-texto.mjs';
4
+
5
+ const RECURSE_PS = /^-r(e(c(u(r(s(e)?)?)?)?)?)?$/i;
6
+ const FLAG_CMD = /^\/[a-z](:\S*)?$/i;
7
+ const API_DE_APAGAR = /\b(?:rmSync|rmdirSync)\b|\bfs(?:\.promises)?\.rm(?:dir)?\s*\(|\bshutil\.rmtree\b|\[(?:System\.)?IO\.Directory\]::Delete\b/i;
8
+ const APAGADORES = ['rm', 'rimraf'];
9
+
10
+ /**
11
+ * `literal` só em rm, rimraf, Remove-Item, rd, del e aliases: só eles aceitam a exceção das pastas descartáveis.
12
+ * @param {string} segmento @returns {{ literal: boolean, alvos: string[] } | null} */
13
+ function apagarRecursivo(segmento) {
14
+ const { nome, args } = invocacao(palavras(segmento));
15
+ if (nome === 'rm') {
16
+ const fim = args.indexOf('--');
17
+ const opcoes = fim === -1 ? args : args.slice(0, fim);
18
+ if (!opcoes.some((a) => a === '--recursive' || (/^-[a-z]+$/i.test(a) && /r/i.test(a)))) return null;
19
+ return { literal: true, alvos: [...opcoes.filter((a) => !a.startsWith('-')), ...(fim === -1 ? [] : args.slice(fim + 1))] };
20
+ }
21
+ if (nome === 'rimraf') return { literal: true, alvos: args.filter((a) => !a.startsWith('-')) };
22
+ if (['remove-item', 'ri', 'rd', 'rmdir', 'del', 'erase'].includes(nome)) {
23
+ if (!args.some((a) => RECURSE_PS.test(a) || /^\/s$/i.test(a))) return null;
24
+ const cmd = !['remove-item', 'ri'].includes(nome);
25
+ const alvos = args.filter((a) => !a.startsWith('-') && !(cmd && FLAG_CMD.test(a))).flatMap((a) => a.split(','));
26
+ return { literal: true, alvos: alvos.filter(Boolean) };
27
+ }
28
+ if (nome === 'find') {
29
+ const exec = args.some((a, k) => /^-(exec|execdir|ok|okdir)$/.test(a) && APAGADORES.includes(nomeBase(args[k + 1] ?? '')));
30
+ if (!exec && !args.includes('-delete')) return null;
31
+ const expressao = args.findIndex((a) => /^[-(!]/.test(a));
32
+ const caminhos = expressao === -1 ? args : args.slice(0, expressao);
33
+ return { literal: false, alvos: caminhos.length ? caminhos : ['.'] };
34
+ }
35
+ if (nome === 'xargs' && args.some((a) => APAGADORES.includes(nomeBase(a)))) return { literal: false, alvos: [] };
36
+ if (nome === 'robocopy' && args.some((a) => /^\/(mir|purge)$/i.test(a))) {
37
+ return { literal: false, alvos: args.filter((a) => !a.startsWith('/')).slice(1, 2) };
38
+ }
39
+ const interpretador = /^(node|deno|bun|tsx|ts-node|python(\d(\.\d+)?)?|py|pwsh|powershell|ruby|perl)$|^[[$]/.test(nome);
40
+ if (interpretador && API_DE_APAGAR.test(segmento)) return { literal: false, alvos: [] };
41
+ return null;
42
+ }
43
+
44
+ /** @param {string} alvo */
45
+ function alvoProtegido(alvo) {
46
+ if (alvo.startsWith('~') || /[$`]|%[^%\s]+%|~\d/.test(alvo)) return true;
47
+ if (/^\/[a-z](\/|$)/i.test(alvo)) return true;
48
+ const semCuringa = alvo.replace(/[\\/]\*$/, '/');
49
+ if (/^[a-z]:$/i.test(semCuringa)) return true;
50
+ if (/^[a-z]:/i.test(semCuringa)) return /^[a-z]:\\$/i.test(win32.normalize(semCuringa));
51
+ if (/^[\\/]/.test(semCuringa)) return posix.normalize(semCuringa.replace(/\\/g, '/')) === '/';
52
+ return false;
53
+ }
54
+
55
+ /** @param {string} alvo @param {string[]} pastas */
56
+ function descartavel(alvo, pastas) {
57
+ const caminho = alvo.replace(/^\.[\\/]/, '').replace(/[\\/]$/, '');
58
+ if (!caminho || /^[\\/~]|^[a-z]:/i.test(caminho) || caminho.includes('..') || /[$%*?`]|~\d/.test(caminho)) return false;
59
+ const ultimo = (caminho.split(/[\\/]/).pop() ?? '').toLowerCase();
60
+ return pastas.some((pasta) => pasta.toLowerCase() === ultimo);
61
+ }
62
+
63
+ /** @param {string} segmento */
64
+ function formataDisco(segmento) {
65
+ const { nome, args } = invocacao(palavras(segmento));
66
+ if (['format-volume', 'clear-disk', 'diskpart'].includes(nome) || /^mkfs(\..+)?$/.test(nome)) return true;
67
+ if (nome === 'format') return args.some((a) => /^[a-z]:\\?$/i.test(a));
68
+ if (nome === 'cipher') return args.some((a) => /^\/w(:|$)/i.test(a));
69
+ if (nome === 'dd') return args.some((a) => /^of=\/dev\//.test(a) && !/^of=\/dev\/(null|zero|stdout|stderr|tty|fd\/)/.test(a));
70
+ return false;
71
+ }
72
+
73
+ /** @type {import('../comando-texto.mjs').Regra[]} */
74
+ export const REGRAS = [
75
+ {
76
+ id: 'apagar-alvo-protegido',
77
+ decisao: 'negar',
78
+ motivo: 'apagar recursivo com alvo na raiz do disco, em /, na home, num caminho com variável, num nome curto 8.3 ou num caminho /c/ do Git Bash',
79
+ testar: (ctx) => ctx.segmentos.some((s) => apagarRecursivo(s)?.alvos.some(alvoProtegido)),
80
+ },
81
+ {
82
+ id: 'formatar-disco',
83
+ decisao: 'negar',
84
+ motivo: 'formatar ou limpar disco (Format-Volume, Clear-Disk, diskpart, format, cipher /w, mkfs, dd para /dev/…)',
85
+ testar: (ctx) => ctx.segmentos.some(formataDisco),
86
+ },
87
+ {
88
+ id: 'apagar-recursivo',
89
+ decisao: 'perguntar',
90
+ motivo:
91
+ 'apagar recursivo fora das pastas descartáveis (seguranca.pastas_descartaveis do .ai-harness/config.json); confira os caminhos antes de aprovar',
92
+ testar: (ctx) =>
93
+ ctx.segmentos.some((s) => {
94
+ const apagar = apagarRecursivo(s);
95
+ if (!apagar) return false;
96
+ const liberado = apagar.literal && apagar.alvos.length > 0 && apagar.alvos.every((a) => descartavel(a, ctx.seguranca.pastas_descartaveis));
97
+ return !liberado;
98
+ }),
99
+ },
100
+ ];