@fontdata/ai-harness 4.6.0 → 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.
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +8 -0
- package/dist/cli.js +7 -0
- package/dist/config/config.js +47 -5
- package/dist/doctor/checks.js +2 -0
- package/dist/doctor/seguranca.js +101 -0
- package/dist/init.js +1 -1
- package/dist/install/plan.js +16 -3
- package/dist/install/settings.js +83 -13
- package/dist/seguranca/checar-comando.js +90 -0
- package/dist/update/update.js +17 -13
- package/package.json +1 -1
- package/templates/hooks/arquivo-sensivel.mjs +83 -0
- package/templates/hooks/comando-destrutivo.mjs +74 -0
- package/templates/hooks/hooks.json +9 -2
- package/templates/hooks/lib/comando-texto.mjs +386 -0
- package/templates/hooks/lib/config.mjs +43 -0
- package/templates/hooks/lib/hook.mjs +22 -12
- package/templates/hooks/lib/regras/apagar.mjs +100 -0
- package/templates/hooks/lib/regras/git.mjs +131 -0
- package/templates/hooks/lib/regras/remoto.mjs +228 -0
- package/templates/hooks/lib/regras/sql.mjs +63 -0
- package/templates/hooks/lib/segredos.mjs +1 -1
- package/templates/rules/seguranca.md +83 -0
package/dist/update/update.js
CHANGED
|
@@ -8,10 +8,10 @@ import { suggestFlag } from '../install/flags.js';
|
|
|
8
8
|
import { HOOKS_ITEM_ID, isHarnessPluginEnabled, projectHooksConfig } from '../install/hooks.js';
|
|
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
|
-
import { agentsForaDoLock, itemSources, packageInfo, PROJECT_RULE_PATH, projectRuleContent } from '../install/plan.js';
|
|
11
|
+
import { agentsForaDoLock, itemSources, packageInfo, PROJECT_RULE_PATH, projectRuleContent, SECURITY_RULE_ID } from '../install/plan.js';
|
|
12
12
|
import { PERFIL_DELPHI_HOOK_COMMAND, perfilDelphiHooksConfig, perfilRecusadoNoConfig, PERFIS, perfisDoProjeto } from '../install/perfis.js';
|
|
13
13
|
import { neededSkillsFor } from '../install/selection.js';
|
|
14
|
-
import { BANCO_PERMISSIONS_LEGADAS, combineHooks,
|
|
14
|
+
import { BANCO_PERMISSIONS_LEGADAS, bypassDesligado, combineHooks, harnessDeny, harnessPermissions, hasAllowRule, hookCommands, hooksRegistrados, mergeSettings, normalizarComandoHook, SEGREDOS_DENY, SETTINGS_PATH, } from '../install/settings.js';
|
|
15
15
|
import { adoptLegacyInstall } from './legado.js';
|
|
16
16
|
const PERFIL_DELPHI_ITEM = 'perfil:delphi';
|
|
17
17
|
/** Pastas que os arquivos do item ocupam no projeto (`.claude/<tipo>/<nome>/`), as que ainda existem. */
|
|
@@ -41,7 +41,7 @@ function perfilDelphiRegistrado(root) {
|
|
|
41
41
|
const comando = normalizarComandoHook(PERFIL_DELPHI_HOOK_COMMAND);
|
|
42
42
|
return Object.keys(perfilDelphiHooksConfig()).every((evento) => hookCommands({ [evento]: hooks[evento] ?? [] }).map(normalizarComandoHook).includes(comando));
|
|
43
43
|
}
|
|
44
|
-
/** O settings do projeto já registra cada
|
|
44
|
+
/** O settings do projeto já registra cada hook do núcleo no evento dele, com o mesmo `command`, `matcher` e `if`. */
|
|
45
45
|
function hooksNucleoRegistrados(root) {
|
|
46
46
|
let hooks;
|
|
47
47
|
try {
|
|
@@ -50,13 +50,7 @@ function hooksNucleoRegistrados(root) {
|
|
|
50
50
|
catch {
|
|
51
51
|
return false;
|
|
52
52
|
}
|
|
53
|
-
|
|
54
|
-
return false;
|
|
55
|
-
const registrados = hooks;
|
|
56
|
-
return Object.entries(projectHooksConfig()).every(([evento, grupos]) => {
|
|
57
|
-
const existentes = new Set(hookCommands({ [evento]: registrados[evento] ?? [] }).map(normalizarComandoHook));
|
|
58
|
-
return hookCommands({ [evento]: grupos }).every((comando) => existentes.has(normalizarComandoHook(comando)));
|
|
59
|
-
});
|
|
53
|
+
return hooksRegistrados(hooks, projectHooksConfig());
|
|
60
54
|
}
|
|
61
55
|
function isPlainObject(value) {
|
|
62
56
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
@@ -209,6 +203,8 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
|
|
|
209
203
|
}
|
|
210
204
|
for (const id of agentsForaDoLock(catalog, lock))
|
|
211
205
|
addItem('agent', id, true);
|
|
206
|
+
if (trackedItems.has(`hook:${HOOKS_ITEM_ID}`) || isHarnessPluginEnabled(root, home))
|
|
207
|
+
addItem('rule', SECURITY_RULE_ID, true);
|
|
212
208
|
const registrarHooksNucleo = !adotada && lock.itens.some((item) => item.tipo === 'hook' && item.id === HOOKS_ITEM_ID) && !isHarnessPluginEnabled(root, home) && !hooksNucleoRegistrados(root);
|
|
213
209
|
// O padrão de comentários também chega ao lock anterior a ele, salvo com a recusa no config ou na flag. O hook é a
|
|
214
210
|
// referência: o comando `comentarios` não registra a rule quando o projeto já tem uma própria.
|
|
@@ -226,9 +222,14 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
|
|
|
226
222
|
const registrarPerfilDelphi = instalarPerfis.includes('delphi') || (!!itemDoPerfil('delphi') && !recusados.has(PERFIL_DELPHI_ITEM) && !perfilDelphiRegistrado(root));
|
|
227
223
|
const registrarMcpConfig = config.banco_dados.registrar_mcp;
|
|
228
224
|
const permissoesBanco = !semBanco && registrarMcpConfig;
|
|
225
|
+
const seguranca = { negarLeituraSegredos: config.seguranca.negar_leitura_segredos, desligarBypass: config.seguranca.desligar_bypass };
|
|
229
226
|
const permissoesFaltando = [
|
|
230
227
|
...harnessPermissions({ banco: permissoesBanco }).filter((rule) => !hasAllowRule(root, rule)),
|
|
231
|
-
...
|
|
228
|
+
...harnessDeny({ negarLeituraSegredos: seguranca.negarLeituraSegredos })
|
|
229
|
+
.filter((rule) => !hasAllowRule(root, rule, 'deny'))
|
|
230
|
+
.map((rule) => `deny ${rule}`),
|
|
231
|
+
...(seguranca.negarLeituraSegredos ? [] : SEGREDOS_DENY.filter((rule) => hasAllowRule(root, rule, 'deny')).map((rule) => `remover deny ${rule}`)),
|
|
232
|
+
...(seguranca.desligarBypass && !bypassDesligado(root) ? ['disableBypassPermissionsMode "disable"'] : []),
|
|
232
233
|
];
|
|
233
234
|
const permissoesLegadas = BANCO_PERMISSIONS_LEGADAS.filter((rule) => hasAllowRule(root, rule));
|
|
234
235
|
const registrarMcp = !semBanco && registrarMcpConfig && !isHarnessPluginEnabled(root, home);
|
|
@@ -244,6 +245,7 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
|
|
|
244
245
|
recusarComentarios: semComentarios && config.comentarios.instalar,
|
|
245
246
|
permissaoAusente: permissoesFaltando.length > 0,
|
|
246
247
|
permissoesFaltando,
|
|
248
|
+
seguranca,
|
|
247
249
|
permissoesLegadas,
|
|
248
250
|
permissoesBanco,
|
|
249
251
|
registrarMcp,
|
|
@@ -295,8 +297,10 @@ export function applyUpdate(root, report, options, pkg, now = new Date()) {
|
|
|
295
297
|
const settings = mergeSettings(root, {
|
|
296
298
|
hooks,
|
|
297
299
|
allow: harnessPermissions({ banco: report.permissoesBanco }),
|
|
298
|
-
deny:
|
|
300
|
+
deny: harnessDeny({ negarLeituraSegredos: report.seguranca.negarLeituraSegredos }),
|
|
299
301
|
removeAllow: BANCO_PERMISSIONS_LEGADAS,
|
|
302
|
+
removeDeny: report.seguranca.negarLeituraSegredos ? [] : SEGREDOS_DENY,
|
|
303
|
+
disableBypass: report.seguranca.desligarBypass,
|
|
300
304
|
removeHooks: itensRecusados(report.perfisRecusados).has(PERFIL_DELPHI_ITEM) ? [PERFIL_DELPHI_HOOK_COMMAND] : [],
|
|
301
305
|
}, now);
|
|
302
306
|
if (settings.changed)
|
|
@@ -422,7 +426,7 @@ export function describeUpdate(report) {
|
|
|
422
426
|
const nucleo = report.registrarHooksNucleo ? [`Faltam hooks do harness em ${SETTINGS_PATH}; o --yes registra os que faltam.`] : [];
|
|
423
427
|
const permission = report.permissaoAusente && !report.adotada
|
|
424
428
|
? [
|
|
425
|
-
`Faltam permissões do harness em .claude/settings.json (${report.permissoesFaltando.join(', ')}); o --yes as
|
|
429
|
+
`Faltam permissões do harness em .claude/settings.json (${report.permissoesFaltando.join(', ')}); o --yes as aplica.`,
|
|
426
430
|
]
|
|
427
431
|
: [];
|
|
428
432
|
const comentarios = [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fontdata/ai-harness",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.7.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": {
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { homedir, tmpdir } from 'node:os';
|
|
4
|
+
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
5
|
+
import { runHook } from './lib/hook.mjs';
|
|
6
|
+
|
|
7
|
+
const SEM_CAIXA = process.platform === 'darwin' || process.platform === 'win32';
|
|
8
|
+
|
|
9
|
+
/** Resolve os links pelo maior ancestral que existe, porque o alvo pode não existir. @param {string} caminho */
|
|
10
|
+
function normalizar(caminho) {
|
|
11
|
+
let atual = resolve(caminho);
|
|
12
|
+
/** @type {string[]} */
|
|
13
|
+
const resto = [];
|
|
14
|
+
for (;;) {
|
|
15
|
+
try {
|
|
16
|
+
const real = realpathSync.native(atual);
|
|
17
|
+
return resto.length ? join(real, ...resto.reverse()) : real;
|
|
18
|
+
} catch {
|
|
19
|
+
const pai = dirname(atual);
|
|
20
|
+
if (pai === atual) return resolve(caminho);
|
|
21
|
+
resto.push(basename(atual));
|
|
22
|
+
atual = pai;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param {string} caminho */
|
|
28
|
+
const chave = (caminho) => (SEM_CAIXA ? caminho.toLowerCase() : caminho);
|
|
29
|
+
|
|
30
|
+
/** @param {string} caminho @param {string} base ambos já normalizados */
|
|
31
|
+
function dentro(caminho, base) {
|
|
32
|
+
const c = chave(caminho);
|
|
33
|
+
const b = chave(base);
|
|
34
|
+
return c === b || c.startsWith(b.endsWith(sep) ? b : b + sep);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param {string} raiz @param {string} alvo @returns {{ id: string, motivo: string, decisao: 'negar' | 'perguntar' } | null} */
|
|
38
|
+
function avaliar(raiz, alvo) {
|
|
39
|
+
const home = normalizar(homedir());
|
|
40
|
+
const emHome = (/** @type {string[]} */ ...partes) => normalizar(join(home, ...partes));
|
|
41
|
+
const emRaiz = (/** @type {string[]} */ ...partes) => normalizar(join(raiz, ...partes));
|
|
42
|
+
const igual = (/** @type {string} */ outro) => chave(alvo) === chave(outro);
|
|
43
|
+
|
|
44
|
+
if (alvo.split(sep).some((segmento) => chave(segmento) === '.git')) {
|
|
45
|
+
return { id: 'git-interno', motivo: `${alvo} fica dentro de .git/; gravar ali corrompe o repositório`, decisao: 'negar' };
|
|
46
|
+
}
|
|
47
|
+
const credenciais = [['.ssh'], ['.aws'], ['.config', 'gh'], ['.gnupg']].map((partes) => emHome(...partes));
|
|
48
|
+
if (credenciais.some((pasta) => dentro(alvo, pasta))) {
|
|
49
|
+
return { id: 'credenciais', motivo: `${alvo} fica numa pasta de credenciais do usuário`, decisao: 'negar' };
|
|
50
|
+
}
|
|
51
|
+
if (igual(emRaiz('.ai-harness', 'lock.json'))) {
|
|
52
|
+
return { id: 'lock-harness', motivo: 'o .ai-harness/lock.json só é gravado pelo init e pelo update do ai-harness', decisao: 'negar' };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const protecao = [
|
|
56
|
+
emRaiz('.ai-harness', 'config.json'),
|
|
57
|
+
emRaiz('.claude', 'settings.json'),
|
|
58
|
+
emRaiz('.claude', 'settings.local.json'),
|
|
59
|
+
emHome('.claude', 'settings.json'),
|
|
60
|
+
emHome('.claude', 'settings.local.json'),
|
|
61
|
+
];
|
|
62
|
+
if (protecao.some(igual)) {
|
|
63
|
+
return { id: 'protecao-propria', motivo: `${alvo} configura os hooks e permissões; alterá-lo pode desligar a proteção`, decisao: 'perguntar' };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const liberadas = [raiz, normalizar(tmpdir()), normalizar('/tmp'), normalizar('/private/tmp'), emHome('.claude')];
|
|
67
|
+
if (liberadas.some((pasta) => dentro(alvo, pasta))) return null;
|
|
68
|
+
return { id: 'fora-da-raiz', motivo: `${alvo} fica fora da raiz do projeto (${raiz})`, decisao: 'perguntar' };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
await runHook('arquivo-sensivel', (input, { root }) => {
|
|
72
|
+
const caminho = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
|
|
73
|
+
if (caminho === undefined || caminho === null || caminho === '') return null;
|
|
74
|
+
if (typeof caminho !== 'string') {
|
|
75
|
+
throw new Error(
|
|
76
|
+
`o caminho do arquivo não é texto (${typeof caminho}); se o hook travar gravações válidas, ponha ` +
|
|
77
|
+
'hooks.arquivo-sensivel em "aviso" no .ai-harness/config.json até a correção'
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const raiz = normalizar(root);
|
|
81
|
+
const regra = avaliar(raiz, normalizar(resolve(raiz, caminho)));
|
|
82
|
+
return regra && { motivo: `${regra.id}: ${regra.motivo}`, decisao: regra.decisao };
|
|
83
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { invocacao, palavras, segmentos, semTextoLivre } from './lib/comando-texto.mjs';
|
|
3
|
+
import { segurancaConfig } from './lib/config.mjs';
|
|
4
|
+
import { runHook } from './lib/hook.mjs';
|
|
5
|
+
import { findActiveWorks } from './lib/rastro.mjs';
|
|
6
|
+
import { REGRAS as APAGAR } from './lib/regras/apagar.mjs';
|
|
7
|
+
import { REGRAS as GIT } from './lib/regras/git.mjs';
|
|
8
|
+
import { REGRAS as REMOTO } from './lib/regras/remoto.mjs';
|
|
9
|
+
import { REGRAS as SQL } from './lib/regras/sql.mjs';
|
|
10
|
+
|
|
11
|
+
const TODAS = [...APAGAR, ...GIT, ...SQL, ...REMOTO];
|
|
12
|
+
const REGRAS = [...TODAS.filter((r) => r.decisao === 'negar'), ...TODAS.filter((r) => r.decisao === 'perguntar')];
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Os segmentos e, depois de cada um, os do script passado a `sh -c`, `pwsh -Command` ou `cmd /c`.
|
|
16
|
+
* @param {string[]} lista @param {number} [profundidade] @returns {string[]} */
|
|
17
|
+
function comScriptsInternos(lista, profundidade = 0) {
|
|
18
|
+
return lista.flatMap((segmento) => {
|
|
19
|
+
const { nome, args } = invocacao(palavras(segmento));
|
|
20
|
+
let script = null;
|
|
21
|
+
if (['sh', 'bash', 'zsh', 'dash', 'ksh'].includes(nome)) {
|
|
22
|
+
const k = args.findIndex((a) => /^-[a-z]*c[a-z]*$/i.test(a));
|
|
23
|
+
if (k !== -1) script = args[k + 1] ?? null;
|
|
24
|
+
} else if (['pwsh', 'powershell'].includes(nome)) {
|
|
25
|
+
const k = args.findIndex((a) => /^-c(ommand)?$/i.test(a));
|
|
26
|
+
if (k !== -1) script = args.slice(k + 1).join(' ');
|
|
27
|
+
} else if (nome === 'cmd') {
|
|
28
|
+
const k = args.findIndex((a) => /^\/[ck]$/i.test(a));
|
|
29
|
+
if (k !== -1) script = args.slice(k + 1).join(' ');
|
|
30
|
+
}
|
|
31
|
+
if (!script || profundidade >= 3) return [segmento];
|
|
32
|
+
return [segmento, ...comScriptsInternos(segmentos(semTextoLivre(script)), profundidade + 1)];
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param {string} comando */
|
|
37
|
+
function rodarComExclamacao(comando) {
|
|
38
|
+
const linha = comando.trim();
|
|
39
|
+
return !linha.includes('\n') && linha.length <= 200 ? `! ${linha}` : '! <comando>';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
await runHook('comando-destrutivo', (input, { root }) => {
|
|
43
|
+
const comando = input.tool_input?.command;
|
|
44
|
+
if (comando === undefined || comando === null) return null;
|
|
45
|
+
try {
|
|
46
|
+
if (typeof comando !== 'string') throw new Error(`tool_input.command não é texto (${typeof comando})`);
|
|
47
|
+
/** @type {string[] | undefined} */
|
|
48
|
+
let ativos;
|
|
49
|
+
/** @type {import('./lib/comando-texto.mjs').ContextoComando} */
|
|
50
|
+
const ctx = {
|
|
51
|
+
comando,
|
|
52
|
+
segmentos: comScriptsInternos(segmentos(semTextoLivre(comando))),
|
|
53
|
+
raiz: root,
|
|
54
|
+
seguranca: segurancaConfig(root),
|
|
55
|
+
get trabalhosAtivos() {
|
|
56
|
+
return (ativos ??= findActiveWorks(root));
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
const regra = REGRAS.find((r) => r.testar(ctx));
|
|
60
|
+
if (!regra) return null;
|
|
61
|
+
if (regra.decisao === 'perguntar') return { motivo: `${regra.id}: ${regra.motivo}`, decisao: 'perguntar' };
|
|
62
|
+
return {
|
|
63
|
+
motivo:
|
|
64
|
+
`${regra.id}: ${regra.motivo}. O agente não roda este comando; se for isso mesmo, o dev pode rodá-lo ele ` +
|
|
65
|
+
`mesmo na sessão com ${rodarComExclamacao(comando)}`,
|
|
66
|
+
decisao: 'negar',
|
|
67
|
+
};
|
|
68
|
+
} catch (erro) {
|
|
69
|
+
const motivo = erro instanceof Error ? erro.message : String(erro);
|
|
70
|
+
throw new Error(
|
|
71
|
+
`${motivo}; se o hook travar comandos válidos, ponha hooks.comando-destrutivo em "aviso" no .ai-harness/config.json até a correção`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
@@ -9,9 +9,16 @@
|
|
|
9
9
|
],
|
|
10
10
|
"PreToolUse": [
|
|
11
11
|
{
|
|
12
|
-
"matcher": "Bash",
|
|
12
|
+
"matcher": "Bash|PowerShell",
|
|
13
13
|
"hooks": [
|
|
14
|
-
{ "type": "command", "
|
|
14
|
+
{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/templates/hooks/segredo-no-commit.mjs\"" },
|
|
15
|
+
{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/templates/hooks/comando-destrutivo.mjs\"" }
|
|
16
|
+
]
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"matcher": "Edit|Write|MultiEdit|NotebookEdit",
|
|
20
|
+
"hooks": [
|
|
21
|
+
{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/templates/hooks/arquivo-sensivel.mjs\"" }
|
|
15
22
|
]
|
|
16
23
|
},
|
|
17
24
|
{
|
|
@@ -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
|
+
}
|