@acropole/skills 0.0.0-stage → 1.1.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/README.md +181 -2
- package/agents/revisor-deploy.md +73 -0
- package/agents/revisor-documentacao.md +78 -0
- package/agents/revisor-orfeu.md +80 -0
- package/agents/revisor-trismegisto.md +81 -0
- package/bin/install.js +252 -0
- package/package.json +15 -4
- package/skills/acropole/SKILL.md +80 -0
- package/skills/acropole/references/arquitetura.md +174 -0
- package/skills/acropole/references/fluxos/app-novo.md +34 -0
- package/skills/acropole/references/fluxos/doctor.md +55 -0
- package/skills/acropole/references/fluxos/endpoint-novo.md +22 -0
- package/skills/acropole/references/fluxos/revisar.md +56 -0
- package/skills/acropole/references/fluxos/tela-nova.md +27 -0
- package/skills/acropole/scripts/doctor.mjs +439 -0
- package/skills/angular/SKILL.md +155 -0
- package/skills/angular/references/armadilhas.md +99 -0
- package/skills/angular/references/dados.md +251 -0
- package/skills/angular/references/estrutura.md +279 -0
- package/skills/angular/references/features.md +219 -0
- package/skills/angular/references/testes-build.md +257 -0
- package/skills/angular/scripts/checar.mjs +182 -0
- package/skills/angular/scripts/nucleo.mjs +227 -0
- package/skills/apollo/SKILL.md +226 -0
- package/skills/apollo/references/armadilhas.md +99 -0
- package/skills/apollo/references/envelope-erros.md +120 -0
- package/skills/apollo/references/estrutura-bootstrap.md +310 -0
- package/skills/apollo/references/schema-resolvers.md +183 -0
- package/skills/apollo/references/subscriptions.md +224 -0
- package/skills/apollo/references/testes-build.md +181 -0
- package/skills/apollo/scripts/checar.mjs +160 -0
- package/skills/apollo/scripts/nucleo.mjs +227 -0
- package/skills/docker/SKILL.md +102 -0
- package/skills/docker/references/modelos.md +251 -0
- package/skills/docker/references/porques.md +286 -0
- package/skills/documentacao/SKILL.md +146 -0
- package/skills/documentacao/references/checklist-coerencia.md +59 -0
- package/skills/documentacao/references/ligar-app-novo.md +107 -0
- package/skills/documentacao/references/modelo-especificacao.md +51 -0
- package/skills/documentacao/references/modelo-readme.md +75 -0
- package/skills/documentacao/scripts/checar.mjs +454 -0
- package/skills/documentacao/scripts/nucleo.mjs +227 -0
- package/skills/express/SKILL.md +156 -0
- package/skills/express/references/dados.md +180 -0
- package/skills/express/references/estrutura.md +157 -0
- package/skills/express/references/middlewares.md +227 -0
- package/skills/express/references/rotas-erros.md +286 -0
- package/skills/express/references/testes-deploy.md +154 -0
- package/skills/express/scripts/checar.mjs +115 -0
- package/skills/express/scripts/nucleo.mjs +227 -0
- package/skills/fastapi/SKILL.md +132 -0
- package/skills/fastapi/references/banco.md +197 -0
- package/skills/fastapi/references/estrutura.md +325 -0
- package/skills/fastapi/references/integracoes.md +145 -0
- package/skills/fastapi/references/rotas-erros.md +140 -0
- package/skills/fastapi/references/testes-deploy.md +190 -0
- package/skills/fastapi/scripts/checar.mjs +108 -0
- package/skills/fastapi/scripts/nucleo.mjs +227 -0
- package/skills/hefesto/SKILL.md +119 -0
- package/skills/hefesto/references/conceitos.md +131 -0
- package/skills/hefesto/references/diagnostico.md +70 -0
- package/skills/hefesto/references/fluxo.md +122 -0
- package/skills/hefesto/references/preparar-app.md +105 -0
- package/skills/orfeu/SKILL.md +162 -0
- package/skills/orfeu/references/angular-api.md +201 -0
- package/skills/orfeu/references/angular-armadilhas.md +116 -0
- package/skills/orfeu/references/angular-recipes.md +474 -0
- package/skills/orfeu/references/angular.md +212 -0
- package/skills/orfeu/references/diferencas.md +56 -0
- package/skills/orfeu/references/node-api.md +354 -0
- package/skills/orfeu/references/node-armadilhas.md +158 -0
- package/skills/orfeu/references/node-recipes.md +541 -0
- package/skills/orfeu/references/node.md +204 -0
- package/skills/orfeu/references/python-api.md +346 -0
- package/skills/orfeu/references/python-recipes.md +479 -0
- package/skills/orfeu/references/python.md +240 -0
- package/skills/orfeu/scripts/checar.mjs +126 -0
- package/skills/orfeu/scripts/nucleo.mjs +227 -0
- package/skills/trismegisto/SKILL.md +194 -0
- package/skills/trismegisto/references/angular-api.md +2788 -0
- package/skills/trismegisto/references/angular-exports.md +4020 -0
- package/skills/trismegisto/references/angular-recipes.md +1883 -0
- package/skills/trismegisto/references/angular-types.md +492 -0
- package/skills/trismegisto/references/angular.md +390 -0
- package/skills/trismegisto/references/catalogo/icones.json +912 -0
- package/skills/trismegisto/references/catalogo/seletores.json +7013 -0
- package/skills/trismegisto/references/catalogo/tokens.json +240 -0
- package/skills/trismegisto/references/spine-api.md +1530 -0
- package/skills/trismegisto/references/spine-recipes.md +581 -0
- package/skills/trismegisto/references/spine.md +343 -0
- package/skills/trismegisto/scripts/checar.mjs +216 -0
- package/skills/trismegisto/scripts/nucleo.mjs +227 -0
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Fluxo: revisar
|
|
2
|
+
|
|
3
|
+
Revisão do que mudou (ou do caminho indicado) com os verificadores das skills e os subagentes
|
|
4
|
+
revisores. **Só relata.** Não corrija nada sem o usuário pedir — nem "de passagem".
|
|
5
|
+
|
|
6
|
+
## 1. Alvo
|
|
7
|
+
|
|
8
|
+
- Com argumento: o caminho indicado.
|
|
9
|
+
- Sem argumento: os arquivos alterados (`git diff --name-only` e `git status --porcelain`, só leitura).
|
|
10
|
+
Sem git ou sem mudança: pergunte o alvo.
|
|
11
|
+
|
|
12
|
+
## 2. Verificadores (por tipo de arquivo)
|
|
13
|
+
|
|
14
|
+
Rode só os que se aplicam, cada um uma vez, com `--json`. Procure em `./.claude/skills/<skill>/scripts/`
|
|
15
|
+
e depois em `~/.claude/skills/<skill>/scripts/`.
|
|
16
|
+
|
|
17
|
+
| Arquivos | Verificadores |
|
|
18
|
+
| --- | --- |
|
|
19
|
+
| `.html`, `.scss`, componente `.ts` de app Angular | `trismegisto`, `angular` |
|
|
20
|
+
| tela, rota (`features.routes.ts`) ou `.md` de feature Angular | `documentacao` (sobre a pasta do app) |
|
|
21
|
+
| `.ts` de servidor com `@apollo/server` | `apollo`, `orfeu` |
|
|
22
|
+
| `.ts` de servidor Express | `express`, `orfeu` |
|
|
23
|
+
| `.py` de serviço FastAPI | `fastapi`, `orfeu` |
|
|
24
|
+
| `Dockerfile`, `.dockerignore` | `docker` |
|
|
25
|
+
| configuração de deploy da plataforma | `hefesto` |
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
node ~/.claude/skills/<skill>/scripts/checar.mjs --json <arquivos>
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Código de saída 1 = achou algo (não é falha do comando). Verificador ausente: registre em uma linha e
|
|
32
|
+
siga. Linhas com `acropole-ignore-next-line <regra> -- <motivo>` já saem filtradas.
|
|
33
|
+
|
|
34
|
+
## 3. Revisores
|
|
35
|
+
|
|
36
|
+
Chame em paralelo, só os que se aplicam, passando a lista de arquivos e o JSON dos verificadores:
|
|
37
|
+
|
|
38
|
+
- `revisor-trismegisto` — houve arquivo de interface;
|
|
39
|
+
- `revisor-documentacao` — houve tela ou rota alterada, ou o verificador `documentacao` acusou algo
|
|
40
|
+
(ele confere a doc contra a tela; o registro da revisão fica para depois, com o usuário);
|
|
41
|
+
- `revisor-orfeu` — houve rota, resolver, chamada entre serviços, auditoria ou sessão no front;
|
|
42
|
+
- `revisor-deploy` — houve Dockerfile/deploy.
|
|
43
|
+
|
|
44
|
+
Eles confirmam cada achado lendo o arquivo. Achado de verificador que o revisor não confirmou sai do
|
|
45
|
+
relatório (falso positivo).
|
|
46
|
+
|
|
47
|
+
## 4. Relatório
|
|
48
|
+
|
|
49
|
+
Um bloco por área (Interface, Documentação, Orfeu, Deploy), em ordem de gravidade, um achado por linha:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
caminho:linha problema → correção
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Sem achados numa área: uma linha. No fim, pergunte se o usuário quer que você corrija — tudo, só os
|
|
56
|
+
graves, ou nada.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Fluxo: tela nova
|
|
2
|
+
|
|
3
|
+
Tela Angular de ponta a ponta. Cada passo diz **qual skill manda**; os detalhes (nomes de API, exemplos,
|
|
4
|
+
armadilhas) estão nela — abra a seção indicada em vez de escrever de memória.
|
|
5
|
+
|
|
6
|
+
Antes de começar, confirme com o usuário: nome da tela, o que ela lista/edita, quais dados vêm de qual
|
|
7
|
+
serviço, e se o `router_id` já existe no Argos. Não invente `router_id`, nome de operação nem campo de
|
|
8
|
+
schema.
|
|
9
|
+
|
|
10
|
+
| # | Passo | Skill | Onde |
|
|
11
|
+
| --- | --- | --- | --- |
|
|
12
|
+
| 1 | **Roteador no Argos**: cadastrar o roteador do client (com descrição), **liberá-lo para os grupos** que devem ver a tela (roteador privado sem liberação não aparece no menu) e anotar o `router_id`. É feito no painel do Argos pelo usuário — peça o id, não crie por código | angular | `SKILL.md` "Receita: tela nova", `references/features.md` |
|
|
13
|
+
| 2 | **Operação no backend** que a tela vai chamar (Query/Mutation ou rota REST), com operação do Orfeu, `Method` explícito, `Level` e auditoria. Se ainda não existe, rode antes o fluxo [endpoint-novo](endpoint-novo.md) | apollo / fastapi / express + orfeu | ver endpoint-novo |
|
|
14
|
+
| 3 | **Documento GraphQL** em `src/app/services/<dominio>/<dominio>.graphql` + `npm run codegen` com o GraphQL local de pé (gera `<dominio>.generated.ts`, commitado) | angular | `references/dados.md` |
|
|
15
|
+
| 4 | **Service** `providedIn: 'root'` com `injectGraphqlClient` + `unwrap`; erro vira estado da tela | angular | `SKILL.md` "Dados", `references/dados.md` |
|
|
16
|
+
| 5 | **Componente** standalone, OnPush, signals; interface **só** com `hm-*` e tokens `--hm-*`; ícones do catálogo; a11y (label, `intent="danger"`, `(clicked)`) | angular → trismegisto | trismegisto `SKILL.md` §3 e `references/angular.md` §4 ("Preciso de… / Use"), `references/angular-api.md` |
|
|
17
|
+
| 6 | **Registro** em `features.routes.ts` com `id` = `router_id` e `load` lazy | angular | `references/features.md` |
|
|
18
|
+
| 7 | **Sessão e headers**: nada a fazer se o app já tem `provideAuth` e `provideHttpClient(withInterceptorsFromDi())`; confira | orfeu | orfeu `references/angular.md` |
|
|
19
|
+
| 8 | **Testes**: componente por harness (`@trismegisto/angular/testing`), service com cliente simulado; `lint:a11y` | angular + trismegisto | angular `references/testes-build.md`, trismegisto §3.7 |
|
|
20
|
+
| 9 | **Documentação**: `README.md` (e `ESPECIFICACAO.md`, se houver regra a registrar) na pasta da tela, ligado em `document` na rota; verificador da skill sem achados e revisão registrada | documentacao | `SKILL.md` §2–§4, `references/modelo-readme.md` |
|
|
21
|
+
| 10 | **Revisão**: rode o fluxo [revisar](revisar.md) sobre os arquivos novos | acropole | — |
|
|
22
|
+
|
|
23
|
+
Ordem importa: o passo 2 antes do 3 (o codegen precisa do schema), o 5 antes do 6 (registro aponta para
|
|
24
|
+
o componente), o 9 depois do 5 (o README cita os rótulos que estão no template). Se o backend for de outra pessoa/equipe, pare no passo 2 e diga o que falta.
|
|
25
|
+
|
|
26
|
+
Ao terminar, liste os arquivos criados/alterados e o que o usuário precisa fazer fora do código
|
|
27
|
+
(cadastro no Argos, permissão da operação para os grupos no Argos).
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Diagnóstico de configuração de um projeto da plataforma (skill `acropole`, fluxo doctor).
|
|
3
|
+
// Node >= 18, sem dependências, sem rede. Só lê arquivos de manifesto/config/código.
|
|
4
|
+
// Severidades: `corrige` (o ajuste é um só e não muda comportamento além do pretendido; --fix aplica),
|
|
5
|
+
// `avisa` (o usuário decide versão/instalação) e `pergunta` (precisa de revisão com contexto antes de mexer).
|
|
6
|
+
// Nunca lê .env/.npmrc (só verifica se existem).
|
|
7
|
+
//
|
|
8
|
+
// Uso: node doctor.mjs [pasta] [--json] [--fix]
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
const argv = process.argv.slice(2);
|
|
13
|
+
const asJson = argv.includes('--json');
|
|
14
|
+
const doFix = argv.includes('--fix');
|
|
15
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
16
|
+
console.log('Uso: node doctor.mjs [pasta] [--json] [--fix]\n\n' +
|
|
17
|
+
' [pasta] raiz a diagnosticar (padrão: diretório atual; varre até 4 níveis)\n' +
|
|
18
|
+
' --json saída em JSON ({ root, findings, fixed })\n' +
|
|
19
|
+
' --fix aplica só os achados de severidade "corrige"');
|
|
20
|
+
process.exit(0);
|
|
21
|
+
}
|
|
22
|
+
const root = path.resolve(argv.find((a) => !a.startsWith('--')) ?? '.');
|
|
23
|
+
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
|
|
24
|
+
console.error(`doctor: pasta não encontrada: ${root}`);
|
|
25
|
+
process.exit(2);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const IGNORE = new Set(['node_modules', 'dist', '.git', '.angular', '.venv', 'venv', '__pycache__', 'coverage', '.nx', '.cache', 'tmp']);
|
|
29
|
+
const MAX_DEPTH = 4;
|
|
30
|
+
const rel = (p) => path.relative(root, p).split(path.sep).join('/') || '.';
|
|
31
|
+
const read = (p) => { try { return fs.readFileSync(p, 'utf8'); } catch { return null; } };
|
|
32
|
+
const readJson = (p) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; } };
|
|
33
|
+
const lineOf = (text, index) => (index < 0 ? 1 : text.slice(0, index).split('\n').length);
|
|
34
|
+
const lineOfStr = (text, needle) => lineOf(text, text.indexOf(needle));
|
|
35
|
+
|
|
36
|
+
/** `# acropole-ignore-next-line <id> -- motivo` (ou //) na linha anterior silencia o achado. */
|
|
37
|
+
function ignored(text, line, id) {
|
|
38
|
+
if (!text || line < 2) return false;
|
|
39
|
+
const prev = text.split(/\r?\n/)[line - 2] ?? '';
|
|
40
|
+
const m = prev.match(/acropole-ignore-next-line\s+([\w,-]+)\s+--\s*\S/);
|
|
41
|
+
return !!m && m[1].split(',').includes(id);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------- varredura ----------------------------------------------------------------------------
|
|
45
|
+
const files = { pkg: [], angular: [], docker: [], req: [], pyproject: [] };
|
|
46
|
+
(function walk(dir, depth) {
|
|
47
|
+
let entries;
|
|
48
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
49
|
+
for (const e of entries) {
|
|
50
|
+
const p = path.join(dir, e.name);
|
|
51
|
+
if (e.isDirectory()) {
|
|
52
|
+
if (!IGNORE.has(e.name) && depth < MAX_DEPTH) walk(p, depth + 1);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!e.isFile()) continue;
|
|
56
|
+
if (e.name === 'package.json') files.pkg.push(p);
|
|
57
|
+
else if (e.name === 'angular.json') files.angular.push(p);
|
|
58
|
+
else if (/^Dockerfile(\..+)?$/i.test(e.name) || /\.Dockerfile$/i.test(e.name)) files.docker.push(p);
|
|
59
|
+
else if (/^requirements.*\.txt$/i.test(e.name)) files.req.push(p);
|
|
60
|
+
else if (e.name === 'pyproject.toml') files.pyproject.push(p);
|
|
61
|
+
}
|
|
62
|
+
})(root, 0);
|
|
63
|
+
|
|
64
|
+
const findings = [];
|
|
65
|
+
const add = (f) => findings.push(f);
|
|
66
|
+
const deps = (pkg) => ({ ...(pkg?.dependencies ?? {}), ...(pkg?.devDependencies ?? {}) });
|
|
67
|
+
|
|
68
|
+
/** Versão comparável: instalada em node_modules, senão a declarada (sem ^~>=, ou a do nome do .tgz). */
|
|
69
|
+
function effectiveVersion(pkgDir, name, declared) {
|
|
70
|
+
const installed = readJson(path.join(pkgDir, 'node_modules', ...name.split('/'), 'package.json'));
|
|
71
|
+
if (installed?.version) return installed.version;
|
|
72
|
+
const local = String(declared).match(/^(?:file|link):(.+)$/);
|
|
73
|
+
if (local && !/.tgz$/.test(local[1])) return readJson(path.join(path.resolve(pkgDir, local[1]), 'package.json'))?.version ?? null;
|
|
74
|
+
if (/^workspace:/.test(String(declared))) return null;
|
|
75
|
+
const tgz = String(declared).match(/(\d+\.\d+\.\d+[\w.-]*?)\.tgz$/);
|
|
76
|
+
if (tgz) return tgz[1];
|
|
77
|
+
const m = String(declared).match(/\d+(\.\d+){0,2}([\w.-]*)?/);
|
|
78
|
+
return m ? m[0] : String(declared);
|
|
79
|
+
}
|
|
80
|
+
const majorOf = (v) => { const m = String(v).match(/\d+/); return m ? Number(m[0]) : null; };
|
|
81
|
+
|
|
82
|
+
// ---------- 1. @trismegisto/* alinhados ----------------------------------------------------------
|
|
83
|
+
const npmOrfeu = []; // { version, where }
|
|
84
|
+
for (const file of files.pkg) {
|
|
85
|
+
const pkg = readJson(file);
|
|
86
|
+
if (!pkg) continue;
|
|
87
|
+
const dir = path.dirname(file);
|
|
88
|
+
const text = read(file);
|
|
89
|
+
const all = deps(pkg);
|
|
90
|
+
const tris = Object.entries(all).filter(([n]) => n.startsWith('@trismegisto/'))
|
|
91
|
+
.map(([n, d]) => ({ name: n, version: effectiveVersion(dir, n, d) }))
|
|
92
|
+
.filter((t) => t.version);
|
|
93
|
+
const distinct = [...new Set(tris.map((t) => t.version))];
|
|
94
|
+
if (distinct.length > 1) {
|
|
95
|
+
const line = lineOfStr(text, `"${tris[0].name}"`);
|
|
96
|
+
if (!ignored(text, line, 'trismegisto-versoes')) {
|
|
97
|
+
add({
|
|
98
|
+
id: 'trismegisto-versoes', severity: 'avisa', path: rel(file), line,
|
|
99
|
+
summary: `@trismegisto/* em versões diferentes: ${tris.map((t) => `${t.name}@${t.version}`).join(', ')}`,
|
|
100
|
+
fix: 'declare todos os @trismegisto/* na mesma versão e reinstale (npm install)',
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
for (const [n, d] of Object.entries(all)) {
|
|
105
|
+
if (n.startsWith('@orfeu/') && effectiveVersion(dir, n, d)) npmOrfeu.push({ name: n, version: effectiveVersion(dir, n, d), where: rel(file) });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ---------- 2. uma cópia só de @orfeu/angular --------------------------------------------------
|
|
109
|
+
if (all['@orfeu/angular'] || all['@trismegisto/spine']) {
|
|
110
|
+
const nm = path.join(dir, 'node_modules');
|
|
111
|
+
const candidates = [path.join(nm, '@orfeu', 'angular')];
|
|
112
|
+
let top = [];
|
|
113
|
+
try { top = fs.readdirSync(nm, { withFileTypes: true }); } catch { /* sem node_modules */ }
|
|
114
|
+
for (const e of top) {
|
|
115
|
+
if (!e.isDirectory() || e.name.startsWith('.')) continue;
|
|
116
|
+
const names = e.name.startsWith('@')
|
|
117
|
+
? (() => { try { return fs.readdirSync(path.join(nm, e.name)).map((s) => path.join(e.name, s)); } catch { return []; } })()
|
|
118
|
+
: [e.name];
|
|
119
|
+
for (const n of names) candidates.push(path.join(nm, n, 'node_modules', '@orfeu', 'angular'));
|
|
120
|
+
}
|
|
121
|
+
const copies = new Map();
|
|
122
|
+
for (const c of candidates) {
|
|
123
|
+
const pj = readJson(path.join(c, 'package.json'));
|
|
124
|
+
if (!pj) continue;
|
|
125
|
+
let real = c;
|
|
126
|
+
try { real = fs.realpathSync(c); } catch { /* mantém */ }
|
|
127
|
+
if (!copies.has(real)) copies.set(real, `${rel(c)}@${pj.version}`);
|
|
128
|
+
}
|
|
129
|
+
if (copies.size > 1) {
|
|
130
|
+
const line = lineOfStr(text, '"@orfeu/angular"');
|
|
131
|
+
if (!ignored(text, line, 'orfeu-angular-duplicado')) {
|
|
132
|
+
add({
|
|
133
|
+
id: 'orfeu-angular-duplicado', severity: 'avisa', path: rel(file), line,
|
|
134
|
+
summary: `${copies.size} cópias de @orfeu/angular: ${[...copies.values()].join(', ')}`,
|
|
135
|
+
fix: 'alinhe a versão de @orfeu/angular com a pedida pelo @trismegisto/spine (ou use "overrides") e rode npm dedupe',
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---------- 3. ordem de styles no angular.json ---------------------------------------------------
|
|
143
|
+
const isTokens = (s) => /@trismegisto\/tokens\b.*tokens\.css$/.test(s);
|
|
144
|
+
const isCore = (s) => /@trismegisto\/core\b.*core\.css$/.test(s);
|
|
145
|
+
const styleName = (s) => (typeof s === 'string' ? s : s?.input ?? '');
|
|
146
|
+
const angularDirs = new Set();
|
|
147
|
+
for (const file of files.angular) {
|
|
148
|
+
const text = read(file);
|
|
149
|
+
const data = readJson(file);
|
|
150
|
+
const dir = path.dirname(file);
|
|
151
|
+
angularDirs.add(dir);
|
|
152
|
+
if (!data?.projects) continue;
|
|
153
|
+
const pkg = readJson(path.join(dir, 'package.json'));
|
|
154
|
+
const usesTris = !!deps(pkg)['@trismegisto/angular'];
|
|
155
|
+
for (const [proj, cfg] of Object.entries(data.projects)) {
|
|
156
|
+
const targets = cfg?.architect ?? cfg?.targets ?? {};
|
|
157
|
+
for (const [target, t] of Object.entries(targets)) {
|
|
158
|
+
const styles = t?.options?.styles;
|
|
159
|
+
if (!Array.isArray(styles)) continue;
|
|
160
|
+
const names = styles.map(styleName);
|
|
161
|
+
const ti = names.findIndex(isTokens);
|
|
162
|
+
const ci = names.findIndex(isCore);
|
|
163
|
+
if (ti >= 0 && ci >= 0 && ci < ti) {
|
|
164
|
+
const line = lineOfStr(text, names[ci]);
|
|
165
|
+
if (!ignored(text, line, 'styles-ordem')) {
|
|
166
|
+
add({
|
|
167
|
+
id: 'styles-ordem', severity: 'corrige', path: rel(file), line,
|
|
168
|
+
summary: `${proj} › ${target}: core.css vem antes de tokens.css no "styles"`,
|
|
169
|
+
fix: 'mover tokens.css para antes de core.css',
|
|
170
|
+
_fix: { kind: 'styles', file, proj, target },
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
} else if (usesTris && target === 'build' && (ti < 0 || ci < 0)) {
|
|
174
|
+
const line = lineOfStr(text, '"styles"');
|
|
175
|
+
if (!ignored(text, line, 'styles-ausente')) {
|
|
176
|
+
add({
|
|
177
|
+
id: 'styles-ausente', severity: 'avisa', path: rel(file), line,
|
|
178
|
+
summary: `${proj} › build: "styles" sem ${ti < 0 ? 'tokens.css' : ''}${ti < 0 && ci < 0 ? ' e ' : ''}${ci < 0 ? 'core.css' : ''} do Trismegisto`,
|
|
179
|
+
fix: 'incluir node_modules/@trismegisto/tokens/dist/tokens.css e depois node_modules/@trismegisto/core/dist/core.css (skill trismegisto §2)',
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ---------- 4. provideHttpClient(withInterceptorsFromDi()) ---------------------------------------
|
|
188
|
+
for (const file of files.pkg) {
|
|
189
|
+
if (deps(readJson(file))['@angular/core']) angularDirs.add(path.dirname(file));
|
|
190
|
+
}
|
|
191
|
+
// O interceptor que manda x-route-id é do spine/@orfeu/angular: sem eles a regra não se aplica.
|
|
192
|
+
const usesAuthInterceptor = (dir) => { const d = deps(readJson(path.join(dir, 'package.json'))); return !!(d['@trismegisto/spine'] || d['@orfeu/angular']); };
|
|
193
|
+
function tsFiles(dir, out = []) {
|
|
194
|
+
let entries;
|
|
195
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
|
|
196
|
+
for (const e of entries) {
|
|
197
|
+
const p = path.join(dir, e.name);
|
|
198
|
+
if (e.isDirectory()) { if (!IGNORE.has(e.name)) tsFiles(p, out); }
|
|
199
|
+
else if (e.isFile() && e.name.endsWith('.ts') && !e.name.endsWith('.spec.ts') && !e.name.endsWith('.d.ts')) out.push(p);
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
function closingParen(text, open) {
|
|
204
|
+
let depth = 0;
|
|
205
|
+
for (let i = open; i < text.length; i++) {
|
|
206
|
+
if (text[i] === '(') depth++;
|
|
207
|
+
else if (text[i] === ')' && --depth === 0) return i;
|
|
208
|
+
}
|
|
209
|
+
return -1;
|
|
210
|
+
}
|
|
211
|
+
const HTTP_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*['"]@angular\/common\/http['"]/;
|
|
212
|
+
const seenTs = new Set();
|
|
213
|
+
for (const dir of angularDirs) {
|
|
214
|
+
if (!usesAuthInterceptor(dir)) continue;
|
|
215
|
+
for (const file of tsFiles(path.join(dir, 'src'))) {
|
|
216
|
+
if (seenTs.has(file)) continue;
|
|
217
|
+
seenTs.add(file);
|
|
218
|
+
const text = read(file);
|
|
219
|
+
if (!text || !text.includes('provideHttpClient')) continue;
|
|
220
|
+
const re = /provideHttpClient\s*\(/g;
|
|
221
|
+
let m;
|
|
222
|
+
while ((m = re.exec(text))) {
|
|
223
|
+
const open = m.index + m[0].length - 1;
|
|
224
|
+
const close = closingParen(text, open);
|
|
225
|
+
if (close < 0) continue;
|
|
226
|
+
if (/withInterceptorsFromDi/.test(text.slice(open + 1, close))) continue;
|
|
227
|
+
const line = lineOf(text, m.index);
|
|
228
|
+
if (ignored(text, line, 'http-interceptors')) continue;
|
|
229
|
+
const importOk = (text.match(HTTP_IMPORT_RE)?.[1] ?? '').includes('provideHttpClient');
|
|
230
|
+
add({
|
|
231
|
+
id: 'http-interceptors', severity: importOk ? 'corrige' : 'avisa', path: rel(file), line,
|
|
232
|
+
summary: 'provideHttpClient sem withInterceptorsFromDi(): o interceptor do spine não roda e o x-route-id some da auditoria',
|
|
233
|
+
fix: 'provideHttpClient(withInterceptorsFromDi()) importando withInterceptorsFromDi de @angular/common/http',
|
|
234
|
+
...(importOk ? { _fix: { kind: 'http', file } } : {}),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ---------- 5. Dockerfile -------------------------------------------------------------------------
|
|
241
|
+
function dockerInstructions(text) {
|
|
242
|
+
const lines = text.split(/\r?\n/);
|
|
243
|
+
const out = [];
|
|
244
|
+
let buf = '';
|
|
245
|
+
let start = 0;
|
|
246
|
+
for (let i = 0; i < lines.length; i++) {
|
|
247
|
+
const raw = lines[i];
|
|
248
|
+
if (!buf && (/^\s*#/.test(raw) || !raw.trim())) continue;
|
|
249
|
+
if (!buf) start = i + 1;
|
|
250
|
+
if (/\\\s*$/.test(raw)) { buf += raw.replace(/\\\s*$/, ' '); continue; }
|
|
251
|
+
buf += raw;
|
|
252
|
+
const m = buf.trim().match(/^(\w+)\s+([\s\S]*)$/);
|
|
253
|
+
if (m) out.push({ op: m[1].toUpperCase(), rest: m[2].trim(), line: start });
|
|
254
|
+
buf = '';
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
for (const file of files.docker) {
|
|
259
|
+
const text = read(file);
|
|
260
|
+
if (!text) continue;
|
|
261
|
+
const ins = dockerInstructions(text);
|
|
262
|
+
const lastFrom = ins.map((x) => x.op).lastIndexOf('FROM');
|
|
263
|
+
ins.forEach((x, idx) => {
|
|
264
|
+
if ((x.op === 'CMD' || x.op === 'ENTRYPOINT') && idx > lastFrom) {
|
|
265
|
+
let problem = null;
|
|
266
|
+
if (x.rest.startsWith('[')) {
|
|
267
|
+
let arr = null;
|
|
268
|
+
try { arr = JSON.parse(x.rest); } catch { /* inválido */ }
|
|
269
|
+
if (!Array.isArray(arr)) problem = `${x.op} com JSON inválido (o Docker cai para a forma shell)`;
|
|
270
|
+
else if (/^(\/bin\/)?(ba)?sh$/.test(arr[0] ?? '') && arr[1] === '-c' && !/(^|[;&|\s])exec\s/.test(arr[2] ?? '')) {
|
|
271
|
+
problem = `${x.op} com "sh -c" sem exec: o sh fica como PID 1 e não repassa SIGTERM`;
|
|
272
|
+
}
|
|
273
|
+
} else if (!/^exec\s/.test(x.rest)) {
|
|
274
|
+
problem = `${x.op} em forma shell: o sh fica como PID 1 e não repassa SIGTERM (auditoria do Orfeu se perde no stop)`;
|
|
275
|
+
}
|
|
276
|
+
if (problem && !ignored(text, x.line, 'docker-cmd-shell')) {
|
|
277
|
+
add({
|
|
278
|
+
id: 'docker-cmd-shell', severity: 'pergunta', path: rel(file), line: x.line, summary: problem,
|
|
279
|
+
fix: 'forma exec (ex.: CMD ["node", "dist/index.js"] ou CMD ["uvicorn", "src.main:app", ...]) — revise com /acropole revisar <Dockerfile> (revisor-deploy, skill docker)',
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const copyLike = x.op === 'COPY' || x.op === 'ADD';
|
|
284
|
+
const npmrcInImage =
|
|
285
|
+
(copyLike && /(^|[\s/"'])\.npmrc\b/.test(x.rest)) ||
|
|
286
|
+
(x.op === 'RUN' && !/--mount=type=secret/.test(x.rest) && (/>>?\s*\S*\.npmrc\b/.test(x.rest) || /_authToken/.test(x.rest)));
|
|
287
|
+
if (npmrcInImage && !ignored(text, x.line, 'docker-npmrc')) {
|
|
288
|
+
add({
|
|
289
|
+
id: 'docker-npmrc', severity: 'avisa', path: rel(file), line: x.line,
|
|
290
|
+
summary: `.npmrc/credencial de registry gravada numa camada da imagem (${x.op})`,
|
|
291
|
+
fix: 'os pacotes vêm do registry público: remova o .npmrc da imagem (se precisar mesmo, use RUN --mount=type=secret)',
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
if (copyLike) {
|
|
295
|
+
const parts = x.rest.split(/\s+/).filter((p) => !p.startsWith('--'));
|
|
296
|
+
const ctx = path.dirname(file);
|
|
297
|
+
if (idx > lastFrom && parts.length >= 2 && parts.slice(0, -1).some((s) => s === '.' || s === './') && fs.existsSync(path.join(ctx, '.npmrc'))) {
|
|
298
|
+
const di = read(path.join(ctx, '.dockerignore')) ?? '';
|
|
299
|
+
const excluded = di.split(/\r?\n/).map((l) => l.trim()).some((l) => /^(\*\*\/)?\.npmrc$|^\*$|^\.\*$/.test(l));
|
|
300
|
+
if (!excluded && !ignored(text, x.line, 'docker-npmrc')) {
|
|
301
|
+
add({
|
|
302
|
+
id: 'docker-npmrc', severity: 'avisa', path: rel(file), line: x.line,
|
|
303
|
+
summary: 'COPY do contexto inteiro no estágio final com um .npmrc na pasta e sem .npmrc no .dockerignore',
|
|
304
|
+
fix: 'adicione .npmrc (e .env*) ao .dockerignore',
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ---------- 6. orfeu Python na mesma major das libs ----------------------------------------------
|
|
313
|
+
const npmMajors = [...new Set(npmOrfeu.map((o) => majorOf(o.version)).filter((v) => v !== null))];
|
|
314
|
+
function checkPyOrfeu(file, line, spec, text) {
|
|
315
|
+
if (!spec.trim()) {
|
|
316
|
+
if (!ignored(text, line, 'orfeu-python-sem-versao')) {
|
|
317
|
+
add({
|
|
318
|
+
id: 'orfeu-python-sem-versao', severity: 'avisa', path: rel(file), line,
|
|
319
|
+
summary: 'orfeu sem versão: cada build pode trazer uma major diferente',
|
|
320
|
+
fix: 'fixe a major, ex.: orfeu[fastapi]>=1.0,<2',
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const major = majorOf(spec);
|
|
326
|
+
if (major === null || !npmMajors.length || npmMajors.includes(major)) return;
|
|
327
|
+
if (ignored(text, line, 'orfeu-python-major')) return;
|
|
328
|
+
add({
|
|
329
|
+
id: 'orfeu-python-major', severity: 'avisa', path: rel(file), line,
|
|
330
|
+
summary: `orfeu (Python) na major ${major}, libs npm @orfeu/* na major ${npmMajors.join('/')} (${npmOrfeu.map((o) => `${o.name}@${o.version}`).join(', ')})`,
|
|
331
|
+
fix: `use orfeu na major ${npmMajors[0]} (ex.: orfeu[fastapi]>=${npmMajors[0]}.0,<${npmMajors[0] + 1})`,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
for (const file of files.req) {
|
|
335
|
+
const text = read(file);
|
|
336
|
+
if (!text) continue;
|
|
337
|
+
text.split(/\r?\n/).forEach((raw, i) => {
|
|
338
|
+
const l = raw.replace(/\s+#.*$/, '').trim();
|
|
339
|
+
const m = l.match(/^orfeu(\[[^\]]*\])?\s*(.*)$/i);
|
|
340
|
+
if (m && !/^[\w-]/.test(m[2])) checkPyOrfeu(file, i + 1, m[2].replace(/;.*$/, ''), text);
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
for (const file of files.pyproject) {
|
|
344
|
+
const text = read(file);
|
|
345
|
+
if (!text) continue;
|
|
346
|
+
// O próprio pacote orfeu não depende de si mesmo.
|
|
347
|
+
if (/^\s*name\s*=\s*["']orfeu["']/m.test(text)) continue;
|
|
348
|
+
// Só olha onde se declaram dependências: `dependencies = [...]` (PEP 621), seções
|
|
349
|
+
// [project.optional-dependencies]/[dependency-groups] e as tabelas de dependências do Poetry.
|
|
350
|
+
let section = '';
|
|
351
|
+
let inDepsArray = false;
|
|
352
|
+
text.split(/\r?\n/).forEach((raw, i) => {
|
|
353
|
+
const header = raw.match(/^\s*\[+([^\]]+)\]+\s*$/);
|
|
354
|
+
if (header) { section = header[1].trim(); inDepsArray = false; return; }
|
|
355
|
+
if (section === 'project' && /^\s*dependencies\s*=\s*\[/.test(raw)) inDepsArray = true;
|
|
356
|
+
const depsSection = inDepsArray || /^(project\.optional-dependencies|dependency-groups)$/.test(section);
|
|
357
|
+
if (depsSection) {
|
|
358
|
+
const m = raw.match(/["']orfeu(\[[^\]]*\])?\s*([^"';]*)/i); // "orfeu[fastapi]>=1.0,<2"
|
|
359
|
+
if (m && !/^[\w-]/.test(m[2])) checkPyOrfeu(file, i + 1, m[2], text);
|
|
360
|
+
} else if (/dependencies$/.test(section)) {
|
|
361
|
+
const m = raw.match(/^\s*orfeu\s*=\s*(?:["']([^"']*)["']|\{[^}]*version\s*=\s*["']([^"']*)["'])/i); // Poetry
|
|
362
|
+
if (m) checkPyOrfeu(file, i + 1, m[1] ?? m[2] ?? '', text);
|
|
363
|
+
}
|
|
364
|
+
if (inDepsArray && /\]\s*(#.*)?$/.test(raw)) inDepsArray = false;
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ---------- --fix ---------------------------------------------------------------------------------
|
|
369
|
+
const fixed = [];
|
|
370
|
+
if (doFix) {
|
|
371
|
+
const byFile = new Map();
|
|
372
|
+
for (const f of findings.filter((x) => x.severity === 'corrige' && x._fix)) {
|
|
373
|
+
if (!byFile.has(f._fix.file)) byFile.set(f._fix.file, []);
|
|
374
|
+
byFile.get(f._fix.file).push(f);
|
|
375
|
+
}
|
|
376
|
+
for (const [file, list] of byFile) {
|
|
377
|
+
if (list[0]._fix.kind === 'styles') {
|
|
378
|
+
const text = read(file);
|
|
379
|
+
const data = JSON.parse(text);
|
|
380
|
+
for (const f of list) {
|
|
381
|
+
const t = (data.projects[f._fix.proj].architect ?? data.projects[f._fix.proj].targets)[f._fix.target];
|
|
382
|
+
const styles = t.options.styles;
|
|
383
|
+
const ti = styles.map(styleName).findIndex(isTokens);
|
|
384
|
+
const [tok] = styles.splice(ti, 1);
|
|
385
|
+
styles.splice(styles.map(styleName).findIndex(isCore), 0, tok);
|
|
386
|
+
}
|
|
387
|
+
const indent = text.match(/\n([ \t]+)"/)?.[1] ?? ' ';
|
|
388
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
389
|
+
fs.writeFileSync(file, JSON.stringify(data, null, indent).replace(/\n/g, eol) + (/\r?\n$/.test(text) ? eol : ''));
|
|
390
|
+
} else {
|
|
391
|
+
let text = read(file);
|
|
392
|
+
// de trás para frente, para os índices continuarem válidos
|
|
393
|
+
const calls = [];
|
|
394
|
+
const re = /provideHttpClient\s*\(/g;
|
|
395
|
+
let m;
|
|
396
|
+
while ((m = re.exec(text))) {
|
|
397
|
+
const open = m.index + m[0].length - 1;
|
|
398
|
+
const close = closingParen(text, open);
|
|
399
|
+
if (close >= 0 && !/withInterceptorsFromDi/.test(text.slice(open + 1, close))) calls.push({ open, empty: !text.slice(open + 1, close).trim() });
|
|
400
|
+
}
|
|
401
|
+
for (const c of calls.reverse()) {
|
|
402
|
+
text = text.slice(0, c.open + 1) + 'withInterceptorsFromDi()' + (c.empty ? '' : ', ') + text.slice(c.open + 1).replace(/^\s*/, c.empty ? '' : '');
|
|
403
|
+
}
|
|
404
|
+
text = text.replace(HTTP_IMPORT_RE, (all, names) => {
|
|
405
|
+
if (/\bwithInterceptorsFromDi\b/.test(names)) return all;
|
|
406
|
+
const trimmed = names.replace(/\s*,?\s*$/, '');
|
|
407
|
+
const tail = names.slice(trimmed.length).replace(/^\s*,/, '');
|
|
408
|
+
return all.replace(`{${names}}`, `{${trimmed}, withInterceptorsFromDi${tail}}`);
|
|
409
|
+
});
|
|
410
|
+
fs.writeFileSync(file, text);
|
|
411
|
+
}
|
|
412
|
+
for (const f of list) fixed.push(f);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// ---------- saída ---------------------------------------------------------------------------------
|
|
417
|
+
const remaining = findings.filter((f) => !fixed.includes(f));
|
|
418
|
+
const clean = (f) => { const { _fix, ...rest } = f; return rest; };
|
|
419
|
+
if (asJson) {
|
|
420
|
+
console.log(JSON.stringify({ root, findings: remaining.map(clean), fixed: fixed.map(clean) }, null, 2));
|
|
421
|
+
} else {
|
|
422
|
+
console.log(`acropole doctor — ${root}\n`);
|
|
423
|
+
for (const f of fixed) console.log(`Corrigido: ${f.path}:${f.line} ${f.id} ${f.fix}`);
|
|
424
|
+
if (fixed.length) console.log('');
|
|
425
|
+
if (!remaining.length) console.log(fixed.length ? 'Nenhum achado restante.' : 'Nenhum achado.');
|
|
426
|
+
const groups = [
|
|
427
|
+
['corrige', 'Corrige (--fix aplica; rode só a pedido do usuário)'],
|
|
428
|
+
['avisa', 'Avisa (a correção é decisão do usuário)'],
|
|
429
|
+
['pergunta', 'Pergunta (revisar com contexto antes de mexer)'],
|
|
430
|
+
];
|
|
431
|
+
for (const [sev, title] of groups) {
|
|
432
|
+
const list = remaining.filter((f) => f.severity === sev);
|
|
433
|
+
if (!list.length) continue;
|
|
434
|
+
console.log(`${title}:`);
|
|
435
|
+
for (const f of list) console.log(` ${f.path}:${f.line} ${f.id} ${f.summary} → ${f.fix}`);
|
|
436
|
+
console.log('');
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
process.exit(0);
|