@fontdata/ai-harness 4.5.2 → 4.7.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.
@@ -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
+ ];
@@ -0,0 +1,131 @@
1
+ // @ts-check
2
+ import { invocacao, palavras } from '../comando-texto.mjs';
3
+
4
+ const GLOBAIS_COM_VALOR = ['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--super-prefix', '--config-env'];
5
+
6
+ /** @param {string} segmento @returns {{ sub: string, args: string[] } | null} */
7
+ function git(segmento) {
8
+ const { nome, args } = invocacao(palavras(segmento));
9
+ if (nome !== 'git') return null;
10
+ let k = 0;
11
+ while ((args[k] ?? '').startsWith('-')) k += GLOBAIS_COM_VALOR.includes(args[k] ?? '') ? 2 : 1;
12
+ const sub = args[k];
13
+ return sub === undefined ? null : { sub, args: args.slice(k + 1) };
14
+ }
15
+
16
+ /**
17
+ * Abre flags agrupadas (`-fdx`); as letras de `comValor` e as `longasComValor` consomem o valor seguinte.
18
+ * @param {string[]} args @param {string} comValor @param {string[]} [longasComValor] */
19
+ function opcoes(args, comValor, longasComValor = []) {
20
+ const letras = new Set();
21
+ const longas = new Set();
22
+ /** @type {string[]} */
23
+ const posicionais = [];
24
+ let fim = -1;
25
+ for (let k = 0; k < args.length; k++) {
26
+ const atual = args[k] ?? '';
27
+ if (atual === '--') {
28
+ fim = posicionais.length;
29
+ posicionais.push(...args.slice(k + 1));
30
+ break;
31
+ }
32
+ if (atual.startsWith('--')) {
33
+ const nome = atual.split('=')[0] ?? atual;
34
+ longas.add(nome);
35
+ if (!atual.includes('=') && longasComValor.includes(nome)) k++;
36
+ } else if (/^-[^-]/.test(atual)) {
37
+ for (let j = 1; j < atual.length; j++) {
38
+ const letra = atual[j] ?? '';
39
+ letras.add(letra);
40
+ if (comValor.includes(letra)) {
41
+ if (j === atual.length - 1) k++;
42
+ break;
43
+ }
44
+ }
45
+ } else posicionais.push(atual);
46
+ }
47
+ return { letras, longas, posicionais, aposSeparador: fim === -1 ? [] : posicionais.slice(fim) };
48
+ }
49
+
50
+ /** Pathspec que nunca é nome de branch nem de commit: `.`, `./x`, `:/`, curinga ou barra no fim. */
51
+ function soCaminho(/** @type {string} */ arg) {
52
+ return /^[.:]|[*?[]|\/$/.test(arg);
53
+ }
54
+
55
+ function arvoreInteira(/** @type {string} */ arg) {
56
+ return /^(\.\/?|:\/?|\*|:\/\*)$/.test(arg);
57
+ }
58
+
59
+ /** @type {Record<string, (args: string[]) => boolean>} */
60
+ const DESTRUTIVOS = {
61
+ reset: (args) => args.includes('--hard'),
62
+ clean: (args) => {
63
+ const o = opcoes(args, 'e', ['--exclude']);
64
+ const forca = o.letras.has('f') || o.longas.has('--force');
65
+ return forca && !o.letras.has('n') && !o.longas.has('--dry-run');
66
+ },
67
+ checkout: (args) => {
68
+ const o = opcoes(args, 'bB', ['--orphan', '--conflict', '--pathspec-from-file']);
69
+ if (o.aposSeparador.length || o.longas.has('--pathspec-from-file')) return true;
70
+ return o.posicionais.some(soCaminho);
71
+ },
72
+ restore: (args) => {
73
+ const o = opcoes(args, 's', ['--source', '--pathspec-from-file']);
74
+ const soIndice = o.letras.has('S') || o.longas.has('--staged');
75
+ return !soIndice || o.letras.has('W') || o.longas.has('--worktree');
76
+ },
77
+ stash: (args) => {
78
+ const acao = args.find((a) => !a.startsWith('-'));
79
+ return acao === 'drop' || acao === 'clear';
80
+ },
81
+ branch: (args) => {
82
+ const o = opcoes(args, 'u', ['--set-upstream-to', '--contains', '--no-contains', '--merged', '--no-merged', '--points-at', '--sort', '--format']);
83
+ const apagar = o.letras.has('d') || o.longas.has('--delete');
84
+ const forca = o.letras.has('f') || o.longas.has('--force');
85
+ return o.letras.has('D') || (apagar && forca);
86
+ },
87
+ push: (args) => {
88
+ const o = opcoes(args, 'o', ['--push-option', '--repo', '--receive-pack', '--exec']);
89
+ return o.letras.has('d') || o.longas.has('--delete') || o.posicionais.some((a) => /^\+?:./.test(a));
90
+ },
91
+ };
92
+
93
+ /** @param {string} segmento */
94
+ function gitDestrutivo(segmento) {
95
+ const chamada = git(segmento);
96
+ return Boolean(chamada && Object.hasOwn(DESTRUTIVOS, chamada.sub) && DESTRUTIVOS[chamada.sub]?.(chamada.args));
97
+ }
98
+
99
+ /** @param {string} segmento */
100
+ function addEmMassa(segmento) {
101
+ const chamada = git(segmento);
102
+ if (chamada?.sub === 'add') {
103
+ const o = opcoes(chamada.args, '', ['--chmod', '--pathspec-from-file']);
104
+ const todos = o.letras.has('A') || o.letras.has('u') || o.longas.has('--all') || o.longas.has('--update') || o.longas.has('--no-ignore-removal');
105
+ return (todos && o.posicionais.length === 0) || o.posicionais.some(arvoreInteira);
106
+ }
107
+ if (chamada?.sub === 'commit') {
108
+ // semTextoLivre já tirou a mensagem de -m/--message: consumir a palavra seguinte engoliria um `--all`.
109
+ const o = opcoes(chamada.args, 'FCct', ['--file', '--reuse-message', '--reedit-message', '--fixup', '--squash', '--author', '--date', '--template', '--trailer', '--cleanup']);
110
+ return o.letras.has('a') || o.longas.has('--all');
111
+ }
112
+ return false;
113
+ }
114
+
115
+ /** @type {import('../comando-texto.mjs').Regra[]} */
116
+ export const REGRAS = [
117
+ {
118
+ id: 'git-descarta-mudancas',
119
+ decisao: 'perguntar',
120
+ motivo:
121
+ 'git destrutivo (reset --hard, clean -f, checkout -- <caminho>, checkout ., restore sem --staged, stash drop, stash clear, branch -D, push --delete ou push <remoto> :<ref>); com sessões paralelas no mesmo repositório, ele apaga o trabalho não commitado ou as refs das outras',
122
+ testar: (ctx) => ctx.segmentos.some(gitDestrutivo),
123
+ },
124
+ {
125
+ id: 'git-add-em-massa',
126
+ decisao: 'perguntar',
127
+ motivo:
128
+ 'git add -A, git add ., git add --all ou git commit -a com dois ou mais trabalhos ativos mistura arquivos de outro trabalho; prefira passar os caminhos da task',
129
+ testar: (ctx) => ctx.segmentos.some(addEmMassa) && ctx.trabalhosAtivos.length >= 2,
130
+ },
131
+ ];
@@ -0,0 +1,228 @@
1
+ // @ts-check
2
+ import { invocacao, palavras, semTextoLivre } from '../comando-texto.mjs';
3
+ import { isEnvFile } from '../segredos.mjs';
4
+
5
+ const FAMILIA_SH = ['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish', 'csh', 'tcsh'];
6
+ const POWERSHELL = ['pwsh', 'powershell'];
7
+ const PS_COM_VALOR = ['executionpolicy', 'ep', 'windowstyle', 'workingdirectory', 'wd', 'configurationname', 'outputformat', 'of', 'inputformat', 'if', 'version', 'psconsolefile', 'custompipename', 'settingsfile'];
8
+ const BASE64_LONGO = /^[A-Za-z0-9+/]{16,}={0,2}$/;
9
+ const LEITORES = ['cat', 'head', 'tail', 'less', 'more', 'type', 'get-content', 'source', '.'];
10
+ const ENTRADA_PADRAO = ['-', '/dev/stdin', '/dev/fd/0'];
11
+ const FRONTEIRA = /[\s;|&()"'`]/;
12
+ const DEPOIS_DE_PIPE = /(^|[^|])\|&?[\s(]*$/;
13
+
14
+ const CURL_CURTAS_COM_VALOR = 'AbcCdDeEFHKmoPQrtTuUwxXyYz';
15
+ const CURL_LONGAS = { '--data': 'd', '--data-binary': 'd', '--data-ascii': 'd', '--json': 'd', '--data-urlencode': 'u', '--form': 'F', '--upload-file': 'T' };
16
+ const SCP_COM_VALOR = 'cFiJlLoPSDX';
17
+ const RSYNC_CURTAS_COM_VALOR = 'eBfTM';
18
+ const RSYNC_LONGAS_COM_VALOR = [
19
+ '--exclude', '--include', '--exclude-from', '--include-from', '--files-from', '--filter', '--rsh', '--rsync-path', '--temp-dir',
20
+ '--partial-dir', '--backup-dir', '--compare-dest', '--copy-dest', '--link-dest', '--chmod', '--chown', '--log-file',
21
+ '--password-file', '--port', '--bwlimit', '--timeout', '--suffix', '--max-size', '--min-size',
22
+ ];
23
+
24
+ /** @param {string} caminho */
25
+ function arquivoDeSegredo(caminho) {
26
+ const partes = caminho.replace(/\\/g, '/').replace(/\/+$/, '').split('/');
27
+ const nome = partes.at(-1) ?? '';
28
+ if (partes.some((p) => p === '.ssh' || p === '.aws')) return true;
29
+ return isEnvFile(nome) || /\.(pem|key)$/i.test(nome) || /^id_(rsa|ed25519)/.test(nome);
30
+ }
31
+
32
+ /** @param {string[]} args */
33
+ function shLeEntrada(args) {
34
+ for (let k = 0; k < args.length; k++) {
35
+ const a = args[k] ?? '';
36
+ if (a === '--') return !args[k + 1] || ENTRADA_PADRAO.includes(args[k + 1] ?? '');
37
+ if (a.startsWith('--')) {
38
+ if (['--rcfile', '--init-file'].includes(a)) k++;
39
+ } else if (/^[-+][A-Za-z]+$/.test(a)) {
40
+ if (a.includes('c')) return false;
41
+ if (a.includes('s')) return true;
42
+ if (/[oO]/.test(a)) k++;
43
+ } else return ENTRADA_PADRAO.includes(a);
44
+ }
45
+ return true;
46
+ }
47
+
48
+ function opcaoPs(/** @type {string} */ a) {
49
+ return /^[-/][A-Za-z]+$/.test(a) ? a.slice(1).toLowerCase() : null;
50
+ }
51
+
52
+ /** @param {string} nome */
53
+ const prefixoDe = (nome) => (/** @type {string | null} */ opcao) => opcao !== null && nome.startsWith(opcao);
54
+ const ehEncoded = (/** @type {string | null} */ opcao) => opcao === 'ec' || prefixoDe('encodedcommand')(opcao);
55
+ const ehScriptPs = (/** @type {string | null} */ opcao) => ehEncoded(opcao) || prefixoDe('command')(opcao) || prefixoDe('file')(opcao);
56
+
57
+ /** @param {string[]} args */
58
+ function pwshLeEntrada(args) {
59
+ for (let k = 0; k < args.length; k++) {
60
+ const a = args[k] ?? '';
61
+ const opcao = opcaoPs(a);
62
+ if (ehScriptPs(opcao)) return ENTRADA_PADRAO.includes(args[k + 1] ?? '');
63
+ if (opcao === null) return ENTRADA_PADRAO.includes(a);
64
+ if (PS_COM_VALOR.some((nome) => opcao.length >= 2 && nome.startsWith(opcao))) k++;
65
+ }
66
+ return true;
67
+ }
68
+
69
+ /** @param {string} texto @param {string} linha @param {number} desde */
70
+ function ocorrencia(texto, linha, desde) {
71
+ for (let pos = texto.indexOf(linha, desde); pos !== -1; pos = texto.indexOf(linha, pos + 1)) {
72
+ const antes = texto[pos - 1] ?? '';
73
+ const depois = texto[pos + linha.length] ?? '';
74
+ if ((antes === '' || FRONTEIRA.test(antes)) && (depois === '' || FRONTEIRA.test(depois))) return pos;
75
+ }
76
+ return -1;
77
+ }
78
+
79
+ /** @param {string} texto @param {string[]} lista */
80
+ function posicoes(texto, lista) {
81
+ let cursor = 0;
82
+ return lista.map((segmento) => {
83
+ const linha = segmento.split('\n')[0] ?? '';
84
+ const pos = linha ? ocorrencia(texto, linha, cursor) : -1;
85
+ if (pos === -1) return -1;
86
+ const { nome } = invocacao(palavras(segmento));
87
+ // Os segmentos do script de `-c` vêm logo depois do interpretador e estão dentro do texto dele.
88
+ cursor = [...FAMILIA_SH, ...POWERSHELL, 'cmd'].includes(nome) ? pos + 1 : pos + linha.length;
89
+ return pos;
90
+ });
91
+ }
92
+
93
+ /** @param {string} texto @param {string} segmento */
94
+ function emAlgumPipe(texto, segmento) {
95
+ const linha = segmento.split('\n')[0] ?? '';
96
+ for (let pos = ocorrencia(texto, linha, 0); linha && pos !== -1; pos = ocorrencia(texto, linha, pos + 1)) {
97
+ if (DEPOIS_DE_PIPE.test(texto.slice(0, pos))) return true;
98
+ }
99
+ return false;
100
+ }
101
+
102
+ /** @param {string} segmento @param {() => boolean} recebePipe */
103
+ function interpretaEntrada(segmento, recebePipe) {
104
+ const lista = palavras(segmento);
105
+ const { nome, args } = invocacao(lista);
106
+ let le = false;
107
+ if (FAMILIA_SH.includes(nome)) le = shLeEntrada(args);
108
+ else if (POWERSHELL.includes(nome)) le = pwshLeEntrada(args);
109
+ else if (nome === 'cmd') le = !args.some((a) => /^\/[ck]$/i.test(a));
110
+ else if (nome === 'source' || nome === '.') le = args.length === 0 || ENTRADA_PADRAO.includes(args[0] ?? '');
111
+ if (!le) return false;
112
+ return segmento.includes('<<') || lista.some((p) => /^0?<(?![<>&])/.test(p)) || recebePipe();
113
+ }
114
+
115
+ function executaTexto(/** @type {string} */ segmento) {
116
+ const { nome, args } = invocacao(palavras(segmento));
117
+ if (nome === 'iex' || nome === 'invoke-expression') return true;
118
+ if (nome === 'eval') return args.length > 0;
119
+ if (FAMILIA_SH.includes(nome)) {
120
+ const k = args.findIndex((a) => /^-[a-z]*c[a-z]*$/i.test(a));
121
+ const script = k === -1 ? undefined : args[k + 1];
122
+ return script !== undefined && (/\$\((?!\()|`/.test(script) || /^\s*\$\{?\w+\}?\s*$/.test(script));
123
+ }
124
+ if (POWERSHELL.includes(nome)) return args.some((a, k) => ehEncoded(opcaoPs(a)) && BASE64_LONGO.test(args[k + 1] ?? ''));
125
+ return false;
126
+ }
127
+
128
+ /** @param {string[]} args */
129
+ function arquivosDoCurl(args) {
130
+ /** @type {Array<[string, string]>} */
131
+ const valores = [];
132
+ for (let k = 0; k < args.length; k++) {
133
+ const a = args[k] ?? '';
134
+ const igual = a.indexOf('=');
135
+ const longa = a.startsWith('--') ? (igual === -1 ? a : a.slice(0, igual)) : '';
136
+ const tipo = /** @type {Record<string, string>} */ (CURL_LONGAS)[longa];
137
+ if (tipo) valores.push([tipo, igual === -1 ? (args[++k] ?? '') : a.slice(igual + 1)]);
138
+ else if (/^-[^-]/.test(a)) {
139
+ for (let c = 1; c < a.length; c++) {
140
+ const letra = a[c] ?? '';
141
+ if (!CURL_CURTAS_COM_VALOR.includes(letra)) continue;
142
+ const valor = c + 1 < a.length ? a.slice(c + 1) : (args[++k] ?? '');
143
+ if ('dFT'.includes(letra)) valores.push([letra, valor]);
144
+ break;
145
+ }
146
+ }
147
+ }
148
+ return valores.flatMap(([tipo, valor]) => {
149
+ if (tipo === 'd') return valor.startsWith('@') ? [valor.slice(1)] : [];
150
+ if (tipo === 'u') return /^[^=@]*@(.+)$/.exec(valor)?.slice(1, 2) ?? [];
151
+ if (tipo === 'F') return /^[^=]*=[@<]([^;]*)/.exec(valor)?.slice(1, 2) ?? [];
152
+ return [valor];
153
+ });
154
+ }
155
+
156
+ /** @param {string[]} args @param {(a: string) => boolean} pulaValor */
157
+ function origensLocais(args, pulaValor) {
158
+ /** @type {string[]} */
159
+ const posicionais = [];
160
+ for (let k = 0; k < args.length; k++) {
161
+ const a = args[k] ?? '';
162
+ if (a === '--') {
163
+ posicionais.push(...args.slice(k + 1));
164
+ break;
165
+ }
166
+ if (a.startsWith('-') && a !== '-') {
167
+ if (pulaValor(a)) k++;
168
+ } else posicionais.push(a);
169
+ }
170
+ return posicionais.slice(0, -1).filter((a) => /^[a-z]:[\\/]/i.test(a) || !/^[^/\\:]+:|^[a-z]+:\/\//i.test(a));
171
+ }
172
+
173
+ /** @param {string} segmento */
174
+ function enviaSegredo(segmento) {
175
+ const { nome, args } = invocacao(palavras(segmento));
176
+ if (nome === 'curl') return arquivosDoCurl(args).some(arquivoDeSegredo);
177
+ if (nome === 'scp') return origensLocais(args, (a) => /^-[A-Za-z0-9]*$/.test(a) && SCP_COM_VALOR.includes(a.at(-1) ?? '')).some(arquivoDeSegredo);
178
+ if (nome === 'rsync') {
179
+ const pulaValor = (/** @type {string} */ a) =>
180
+ a.startsWith('--') ? RSYNC_LONGAS_COM_VALOR.includes(a) : RSYNC_CURTAS_COM_VALOR.includes(a.at(-1) ?? '');
181
+ return origensLocais(args, pulaValor).some(arquivoDeSegredo);
182
+ }
183
+ return false;
184
+ }
185
+
186
+ /** @param {string} segmento */
187
+ function leSegredo(segmento) {
188
+ const lista = palavras(segmento);
189
+ const { nome, args } = invocacao(lista);
190
+ if (LEITORES.includes(nome) && args.some((a) => !a.startsWith('-') && arquivoDeSegredo(a))) return true;
191
+ return lista.some((p, k) => {
192
+ if (/^0?<$/.test(p)) return arquivoDeSegredo(lista[k + 1] ?? '');
193
+ const alvo = /^0?<(?![<>&])(.+)$/.exec(p)?.[1];
194
+ return alvo !== undefined && arquivoDeSegredo(alvo);
195
+ });
196
+ }
197
+
198
+ /** @type {import('../comando-texto.mjs').Regra[]} */
199
+ export const REGRAS = [
200
+ {
201
+ id: 'texto-para-interpretador',
202
+ decisao: 'negar',
203
+ motivo:
204
+ 'texto jogado num interpretador de shell (… | sh, … | iex, eval, bash -c "$(…)", bash <(…), -EncodedCommand), qualquer que seja a origem',
205
+ testar: (ctx) => {
206
+ const texto = semTextoLivre(ctx.comando);
207
+ const pos = posicoes(texto, ctx.segmentos);
208
+ return ctx.segmentos.some((s, k) => {
209
+ const p = pos[k] ?? -1;
210
+ const recebePipe = () => (p === -1 ? emAlgumPipe(ctx.comando, s) : DEPOIS_DE_PIPE.test(texto.slice(0, p)));
211
+ return executaTexto(s) || interpretaEntrada(s, recebePipe);
212
+ });
213
+ },
214
+ },
215
+ {
216
+ id: 'enviar-segredo',
217
+ decisao: 'negar',
218
+ motivo: 'envio de arquivo de segredo (.env, *.pem, *.key, id_rsa, id_ed25519, ~/.ssh, ~/.aws) por curl, scp ou rsync',
219
+ testar: (ctx) => ctx.segmentos.some(enviaSegredo),
220
+ },
221
+ {
222
+ id: 'ler-segredo',
223
+ decisao: 'perguntar',
224
+ motivo:
225
+ 'leitura de arquivo de segredo pelo terminal; o deny de Read não cobre o Bash (opt-out em seguranca.negar_leitura_segredos do .ai-harness/config.json)',
226
+ testar: (ctx) => ctx.seguranca.negar_leitura_segredos && ctx.segmentos.some(leSegredo),
227
+ },
228
+ ];
@@ -0,0 +1,63 @@
1
+ // @ts-check
2
+ import { invocacao, nomeBase, palavras, segmentos, semTextoLivre } from '../comando-texto.mjs';
3
+
4
+ const CLIENTES = new Set(['psql', 'mysql', 'mariadb', 'sqlite3', 'sqlcmd', 'isql']);
5
+ const PALAVRA_CHAVE = /(?<![\w$.\\/-])(insert|update|delete|drop|alter|truncate|create|grant|revoke)(?![\w.\\/-])/i;
6
+ const OPCAO_DE_ARQUIVO = /^-[fi]|^--?(file|input|init)(=|$)/;
7
+ const METACOMANDO_DE_ARQUIVO = /\\(i|ir|include|include_relative)(?![\w])|(?:^|[\s;'"])\\\.\s|(?:^|[;'"\n])\s*source\s+\S|(?:^|[\s;'"])\.(read|restore|import)(?![\w])/i;
8
+ const ORIGEM_LITERAL = new Set(['echo', 'printf']);
9
+
10
+ /** Quebra também o texto entre aspas, para achar o cliente em `ssh h "psql …"`. @param {string} segmento */
11
+ function chamadaDeCliente(segmento) {
12
+ const lista = palavras(segmento).flatMap((p) => p.split(/\s+/)).filter(Boolean);
13
+ const k = lista.findIndex((p) => CLIENTES.has(nomeBase(p)));
14
+ return k === -1 ? null : { cliente: nomeBase(lista[k] ?? ''), args: lista.slice(k + 1) };
15
+ }
16
+
17
+ /** @param {import('../comando-texto.mjs').ContextoComando} ctx */
18
+ function clientes(ctx) {
19
+ return ctx.segmentos.flatMap((segmento) => {
20
+ const chamada = chamadaDeCliente(segmento);
21
+ return chamada ? [{ segmento, ...chamada }] : [];
22
+ });
23
+ }
24
+
25
+ /** Cliente lendo o stdin de um pipe de origem não literal (`cat dump.sql | psql`). @param {string} comando */
26
+ function pipeDeOrigemOpaca(comando) {
27
+ const lista = segmentos(comando);
28
+ let cursor = 0;
29
+ return lista.some((segmento, k) => {
30
+ const inicio = comando.indexOf(segmento.split('\n')[0] ?? '', cursor);
31
+ if (inicio === -1) return false;
32
+ cursor = inicio + 1;
33
+ if (k === 0 || !chamadaDeCliente(semTextoLivre(segmento))) return false;
34
+ const antes = comando.slice(0, inicio).trimEnd();
35
+ if (!/(^|[^|])\|&?$/.test(antes)) return false;
36
+ return !ORIGEM_LITERAL.has(invocacao(palavras(lista[k - 1] ?? '')).nome);
37
+ });
38
+ }
39
+
40
+ /** @type {import('../comando-texto.mjs').Regra[]} */
41
+ export const REGRAS = [
42
+ {
43
+ id: 'sql-ddl-dml',
44
+ decisao: 'perguntar',
45
+ motivo:
46
+ 'DDL/DML (INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, CREATE, GRANT, REVOKE) no comando de um cliente SQL ' +
47
+ '(psql, mysql, mariadb, sqlite3, sqlcmd, isql); o MCP de banco é somente leitura e o terminal não deve contorná-lo',
48
+ testar: (ctx) => PALAVRA_CHAVE.test(ctx.comando) && clientes(ctx).length > 0,
49
+ },
50
+ {
51
+ id: 'sql-arquivo',
52
+ decisao: 'perguntar',
53
+ motivo:
54
+ 'cliente SQL executando arquivo ou stdin de origem desconhecida (-f, -i, --file, < arquivo.sql, | psql, ' +
55
+ '\\i, source, .read); confira o conteúdo antes de aprovar',
56
+ testar: (ctx) =>
57
+ pipeDeOrigemOpaca(ctx.comando) ||
58
+ clientes(ctx).some(
59
+ ({ segmento, args }) =>
60
+ args.some((a) => OPCAO_DE_ARQUIVO.test(a) || /^\d*<(?!<)/.test(a)) || METACOMANDO_DE_ARQUIVO.test(segmento)
61
+ ),
62
+ },
63
+ ];
@@ -28,7 +28,7 @@ function isPlaceholder(value) {
28
28
  * `.env`, `.env.local`, `.env.production`... mas não `.env.example`, `.env.sample` ou `.env.template`.
29
29
  * @param {string} path
30
30
  */
31
- function isEnvFile(path) {
31
+ export function isEnvFile(path) {
32
32
  const name = basename(path);
33
33
  return /^\.env(\..+)?$/.test(name) && !/\.(example|sample|template|dist)$/.test(name);
34
34
  }
@@ -0,0 +1,83 @@
1
+ # Segurança: comandos destrutivos e arquivos sensíveis
2
+
3
+ Os hooks do harness leem o texto de cada comando e o caminho de cada gravação antes de rodar. Eles não são uma
4
+ fronteira de segurança completa: são uma rede contra o erro comum, inclusive com 2 ou 3 sessões em paralelo no mesmo
5
+ repositório.
6
+
7
+ ## Camadas
8
+
9
+ | Camada | O que faz |
10
+ |---|---|
11
+ | Hook `comando-destrutivo` (`Bash`/`PowerShell`) | nega o catastrófico e pede aprovação para o destrutivo legítimo |
12
+ | Hook `arquivo-sensivel` (`Edit`/`Write`/`MultiEdit`/`NotebookEdit`) | nega e pergunta conforme o caminho gravado |
13
+ | `permissions.deny` do `.claude/settings.json` | `git push --force` e a leitura de segredos pela ferramenta `Read` |
14
+ | Aprovação humana | o dev decide quando o hook pergunta; a documentação do Claude Code garante a aprovação no modo `auto`, mas não diz nada sobre `bypassPermissions` e `acceptEdits` |
15
+ | Sandbox do Claude Code | recomendado; o harness não o ativa |
16
+
17
+ ## O que nega
18
+
19
+ - Apagar recursivo com alvo na raiz do disco, `/`, `~`, `$HOME`, `%USERPROFILE%`, caminho com variável, nome curto
20
+ 8.3 (`USUARI~1`) ou `/c/` do Git Bash.
21
+ - Formatar ou limpar disco (`Format-Volume`, `diskpart`, `format X:`, `mkfs`, `dd of=/dev/…`, `cipher /w`).
22
+ - Texto jogado num interpretador de shell: `… | sh`, `… | iex`, `bash -c "$(…)"`, `eval "$(…)"`, `-EncodedCommand`.
23
+ - Enviar arquivo de segredo para fora (`curl -d @`, `-F …=@`, `-T`, `scp`, `rsync`).
24
+ - Gravar em `.git/`, `~/.ssh/`, `~/.aws/`, `~/.config/gh/`, `~/.gnupg/` e no `.ai-harness/lock.json`.
25
+
26
+ ## O que pergunta
27
+
28
+ - Apagar recursivo (`rm -r`, `find -delete`, `xargs rm`, `rimraf`, `Remove-Item -Recurse`, `rd /s`…). Passa direto
29
+ só `rm`, `rimraf`, `Remove-Item`, `rd` e `del` cujos alvos são caminhos relativos simples terminados numa pasta de
30
+ `seguranca.pastas_descartaveis` (`dist`, `./dist/`, `packages/a/dist`; não `dist/*` nem `../dist`).
31
+ - Git que descarta mudança: `reset --hard`, `clean -f`, `checkout -- <caminho>`, `checkout .`, `restore` sem
32
+ `--staged`, `stash drop`/`clear`, `branch -D`, `push --delete`.
33
+ - `git add -A`, `git add .` e `git commit -a` com dois ou mais trabalhos ativos: passe os caminhos da task.
34
+ - DDL/DML ou arquivo `.sql` por `psql`, `mysql`, `mariadb`, `sqlite3`, `sqlcmd` ou `isql`; `SELECT` passa.
35
+ - Ler arquivo de segredo pelo terminal (`cat`, `Get-Content`, `source`…).
36
+ - Gravar nos arquivos que configuram a proteção (`.ai-harness/config.json`, `.claude/settings*.json`,
37
+ `~/.claude/settings*.json`) e fora da raiz. Fora da raiz passam sem pergunta as pastas temporárias (`os.tmpdir()`,
38
+ `/tmp`, `/private/tmp`) e o resto de `~/.claude/` (memória, planos).
39
+
40
+ ## Leitura de segredos: `Read` × terminal
41
+
42
+ - Pela ferramenta `Read`, só os nomes listados em `permissions.deny` são negados (`**/.env`, `**/.env.local`,
43
+ `**/.env.production`, `*.pem`, `*.key`, `~/.ssh/**`…). Um `.env.qa` fica legível: quem usa outros nomes os
44
+ acrescenta ao `permissions.deny`.
45
+ - Pelo terminal, todo `.env*` secreto pede aprovação; `.env.example`, `.env.sample`, `.env.template` e `.env.dist`
46
+ passam.
47
+
48
+ ## Conduta quando bloqueado
49
+
50
+ - Negado: não rode. Mostre ao usuário o comando exato ou os caminhos exatos e peça que ele rode, se quiser, com
51
+ `! <comando>` no prompt.
52
+ - Pergunta: espere a decisão do usuário; recusa é resposta final.
53
+ - Nunca tente um comando equivalente que contorne a regra (outro binário, script, `node -e`, variável, caminho
54
+ reescrito). Se a regra parece errada, diga isso ao usuário.
55
+
56
+ ## Consultar antes
57
+
58
+ ```bash
59
+ npx @fontdata/ai-harness checar-comando "<comando>"
60
+ ```
61
+
62
+ Responde `NEGADO` (saída 2), `PERGUNTA` (3) ou `LIBERADO` (0), com a regra e o motivo, sem gravar nada no projeto.
63
+
64
+ ## Configuração
65
+
66
+ Seção `seguranca` do `.ai-harness/config.json`:
67
+
68
+ | Chave | Padrão | Efeito |
69
+ |---|---|---|
70
+ | `pastas_descartaveis` | `node_modules`, `dist`, `build`, `out`, `coverage`, `.next`, `.turbo`, `.cache`, `.vite`, `tmp`, `temp`, `__history`, `__recovery` | lista que substitui a padrão |
71
+ | `negar_leitura_segredos` | `true` | com `false`, o `update` remove os denys de leitura e o terminal deixa de perguntar |
72
+ | `desligar_bypass` | `false` | com `true`, o `update` grava `permissions.disableBypassPermissionsMode: "disable"` |
73
+
74
+ Voltar `desligar_bypass` a `false` não remove a chave: apague `disableBypassPermissionsMode` do
75
+ `.claude/settings.json` à mão. Mudanças nos denys entram com `npx @fontdata/ai-harness update --yes`.
76
+
77
+ Saída de emergência: o modo `"aviso"`. Se o hook travar comandos válidos (inclusive por erro interno), ponha
78
+ `hooks.comando-destrutivo` ou `hooks.arquivo-sensivel` em `"aviso"` no `.ai-harness/config.json`: ele só avisa até a
79
+ correção. Com `"desligado"`, o hook continua registrado, mas libera tudo sem avisar.
80
+
81
+ ## Crédito
82
+
83
+ Inspirado no `no-wipe` (github.com/matheusbattisti/no-wipe, licença MIT), reimplementado nos padrões do harness.