agent-engineering-skills 1.0.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.
Files changed (48) hide show
  1. package/AGENTS.md +249 -0
  2. package/LICENSE +21 -0
  3. package/README.md +113 -0
  4. package/bin/cli.js +223 -0
  5. package/docs/agent-integration.md +200 -0
  6. package/docs/philosophy.md +131 -0
  7. package/docs/reference-authoring.md +117 -0
  8. package/docs/skill-authoring.md +126 -0
  9. package/examples/authorization-bypass.md +191 -0
  10. package/examples/frontend-review.md +244 -0
  11. package/examples/race-condition.md +128 -0
  12. package/examples/xp-reward-loop.md +123 -0
  13. package/package.json +45 -0
  14. package/references/engineering.yaml +88 -0
  15. package/references/frontend.yaml +139 -0
  16. package/references/product.yaml +54 -0
  17. package/references/research.yaml +88 -0
  18. package/references/security.yaml +85 -0
  19. package/references/ux.yaml +37 -0
  20. package/scripts/validate.py +454 -0
  21. package/skills/audit/adversarial-review/SKILL.md +190 -0
  22. package/skills/audit/business-logic-audit/SKILL.md +182 -0
  23. package/skills/audit/edge-case-hunter/SKILL.md +159 -0
  24. package/skills/audit/error-flow-audit/SKILL.md +184 -0
  25. package/skills/audit/state-consistency-audit/SKILL.md +174 -0
  26. package/skills/audit/user-flow-audit/SKILL.md +161 -0
  27. package/skills/frontend/accessibility-review/SKILL.md +186 -0
  28. package/skills/frontend/animation-review/SKILL.md +171 -0
  29. package/skills/frontend/interaction-design/SKILL.md +162 -0
  30. package/skills/frontend/ux-review/SKILL.md +172 -0
  31. package/skills/frontend/visual-quality-review/SKILL.md +160 -0
  32. package/skills/meta/research-router/SKILL.md +184 -0
  33. package/skills/meta/skill-router/SKILL.md +206 -0
  34. package/skills/product/gamification-audit/SKILL.md +213 -0
  35. package/skills/reliability/data-integrity-audit/SKILL.md +187 -0
  36. package/skills/reliability/idempotency-audit/SKILL.md +191 -0
  37. package/skills/reliability/race-condition-hunter/SKILL.md +181 -0
  38. package/skills/research/github-reference-research/SKILL.md +197 -0
  39. package/skills/research/implementation-research/SKILL.md +181 -0
  40. package/skills/research/market-research/SKILL.md +202 -0
  41. package/skills/research/reference-research/SKILL.md +186 -0
  42. package/skills/security/api-abuse-audit/SKILL.md +178 -0
  43. package/skills/security/authorization-audit/SKILL.md +176 -0
  44. package/skills/security/input-trust-audit/SKILL.md +178 -0
  45. package/templates/audit-report.md +89 -0
  46. package/templates/bug-report.md +107 -0
  47. package/templates/design-review.md +122 -0
  48. package/templates/research-report.md +96 -0
package/AGENTS.md ADDED
@@ -0,0 +1,249 @@
1
+ # AGENTS.md — Regras globais do agente
2
+
3
+ > **Don't just review the code. Attack the assumptions behind the system.**
4
+
5
+ Este arquivo define as regras globais que todo agente que opera sobre este repositório
6
+ deve seguir. As skills em `skills/` ensinam **como pensar**; as referências em `references/`
7
+ ensinam **onde olhar**; este arquivo define o **comportamento base** que governa ambos.
8
+
9
+ O objetivo final não é criar um agente que sabe mais.
10
+ É criar um agente que **sabe como descobrir mais, onde procurar, quais perguntas fazer
11
+ e como verificar se está certo**.
12
+
13
+ ---
14
+
15
+ ## 1. Regras de investigação
16
+
17
+ Antes de concluir qualquer coisa, o agente deve:
18
+
19
+ * **Investigar antes de concluir.** Nunca reportar um bug a partir de uma hipótese
20
+ não verificada. Toda conclusão precisa de evidência.
21
+ * **Pensar em invariantes.** Para cada componente, identificar o que **deve** ser
22
+ sempre verdade. Um invariant violado é quase sempre um bug real.
23
+ * **Considerar estados.** Toda operação ocorre sobre um estado. Perguntar: qual o
24
+ estado antes? qual o estado depois? quais estados são possíveis? quais são
25
+ impossíveis? quais são não-desejados mas alcançáveis?
26
+ * **Testar repetição.** O que acontece se a mesma operação for executada N vezes?
27
+ (Recompensa duplicada? contador inflado? recurso criado várias vezes?)
28
+ * **Testar reversão.** O que acontece se a operação for desfeita e refeita?
29
+ (Farming infinito? estado inconsistente? perda de dados?)
30
+ * **Testar concorrência.** O que acontece se dois requests modificam o mesmo estado
31
+ simultaneamente? (Race condition? double-spend? estado corrompido?)
32
+ * **Não confiar no frontend.** O frontend é uma sugestão, não uma fonte de verdade.
33
+ Validação de cliente pode ser ignorada. Campos como `userId`, `role`, `price`, `XP`
34
+ nunca devem ser confiados sem validação no servidor.
35
+ * **Verificar APIs diretamente.** Tratar a API como diretamente acessível, ignorando
36
+ a UI. O usuário malicioso não usa o frontend; ele chama os endpoints.
37
+ * **Pesquisar referências quando necessário.** Para tarefas não triviais, perguntar
38
+ "alguém já resolveu esse problema?" e consultar `references/` antes de reinventar.
39
+ Ver `references/` e o `research-router`.
40
+ * **Distinguir inspiração de evidência.** Referências externas são inspiração
41
+ (princípios, padrões, trade-offs), não especificação. Extrair ideias, nunca copiar
42
+ cegamente código, layout, branding ou componentes proprietários.
43
+ * **Minimizar falsos positivos.** Antes de reportar um comportamento estranho como
44
+ bug, confirmar que ele é realmente um defeito e não um comportamento aceitável ou
45
+ intencional. Consultar a seção "False Positives" da skill usada.
46
+ * **Reportar evidências.** Todo finding deve ser classificado por nível de confiança
47
+ (ver abaixo) e incluir reprodução, causa raiz e impacto.
48
+
49
+ ---
50
+
51
+ ## 2. Classificação de evidência
52
+
53
+ Todo finding deve ser classificado em um destes quatro níveis. Nunca transformar uma
54
+ hipótese em bug confirmado.
55
+
56
+ ```text
57
+ CONFIRMED — reproduzido com evidência direta (logs, teste, reprodução passo a passo)
58
+ HIGH CONFIDENCE — forte indício técnico, mas sem reprodução completa
59
+ POSSIBLE — plausível, exige mais investigação para confirmar ou descartar
60
+ SPECULATIVE — hipótese sem evidência direta; reportar apenas como risco, não como bug
61
+ ```
62
+
63
+ Regra prática: se você não consegue reproduzir, no máximo é `HIGH CONFIDENCE`.
64
+ Se você não consegue apontar o mecanismo exato, no máximo é `POSSIBLE`.
65
+ Se é "acho que pode acontecer", é `SPECULATIVE` — e findings `SPECULATIVE` não devem
66
+ bloquear implementação, apenas ser listados como riscos a verificar.
67
+
68
+ ---
69
+
70
+ ## 3. Pesquisar antes de reinventar
71
+
72
+ Para tarefas não triviais, o agente deve seguir o fluxo:
73
+
74
+ ```text
75
+ UNDERSTAND → CLASSIFY → RESEARCH → COMPARE → DECIDE → IMPLEMENT
76
+ ```
77
+
78
+ Não:
79
+
80
+ ```text
81
+ UNDERSTAND → IMPLEMENT
82
+ ```
83
+
84
+ Mas **pesquisa deve ser proporcional à complexidade**.
85
+
86
+ * Um botão simples não precisa de pesquisa.
87
+ * Uma arquitetura nova provavelmente precisa.
88
+ * Um padrão de concorrência em pagamentos certamente precisa.
89
+
90
+ Quando apropriado, pesquisar nesta ordem:
91
+
92
+ 1. código existente no projeto;
93
+ 2. documentação oficial;
94
+ 3. GitHub;
95
+ 4. produtos reais;
96
+ 5. design systems;
97
+ 6. sites especializados;
98
+ 7. artigos técnicos;
99
+ 8. galerias de inspiração.
100
+
101
+ A ordem reflete confiabilidade: o que já existe no projeto e a documentação oficial
102
+ vêm antes de inspiração externa.
103
+
104
+ ---
105
+
106
+ ## 4. Workflow completo de auditoria
107
+
108
+ Para uma auditoria (não apenas uma implementação), o fluxo é:
109
+
110
+ ```text
111
+ ┌──────────────────────┐
112
+ │ REQUEST │
113
+ └──────────┬───────────┘
114
+
115
+ ┌──────────────────────┐
116
+ │ UNDERSTAND │
117
+ └──────────┬───────────┘
118
+
119
+ ┌──────────────────────┐
120
+ │ CLASSIFY TASK │
121
+ └──────────┬───────────┘
122
+
123
+ ┌──────────────────────┐
124
+ │ SKILL ROUTER │
125
+ └──────────┬───────────┘
126
+
127
+ ┌──────────────────────┐
128
+ │ RESEARCH ROUTER │
129
+ └──────────┬───────────┘
130
+
131
+ ┌──────────────────────┐
132
+ │ RESEARCH │
133
+ └──────────┬───────────┘
134
+
135
+ ┌──────────────────────┐
136
+ │ ANALYZE │
137
+ └──────────┬───────────┘
138
+
139
+ ┌──────────────────────┐
140
+ │ IMPLEMENT │
141
+ └──────────┬───────────┘
142
+
143
+ ┌──────────────────────┐
144
+ │ ADVERSARIAL TEST │
145
+ └──────────┬───────────┘
146
+
147
+ ┌──────────────────────┐
148
+ │ VERIFY │
149
+ └──────────┬───────────┘
150
+
151
+ ┌──────────────────────┐
152
+ │ REPORT │
153
+ └──────────────────────┘
154
+ ```
155
+
156
+ * **SKILL ROUTER** (`skills/meta/skill-router/`) — analisa a tarefa e seleciona
157
+ quais skills ativar. Nem toda tarefa precisa de todas as skills.
158
+ * **RESEARCH ROUTER** (`skills/meta/research-router/`) — decide **onde** pesquisar
159
+ com base no tipo de problema.
160
+ * **ADVERSARIAL TEST** — testa a implementação como um usuário adversarial
161
+ (repeat, reverse, replay, concurrent). Ver `adversarial-review`.
162
+
163
+ ---
164
+
165
+ ## 5. Síntese de pesquisa
166
+
167
+ O agente **nunca** deve retornar apenas uma lista de links. Toda pesquisa deve
168
+ ser sintetizada no formato:
169
+
170
+ ```markdown
171
+ ## Research
172
+
173
+ ### Reference
174
+ [Name]
175
+
176
+ ### Relevant Pattern
177
+ O que foi encontrado.
178
+
179
+ ### Why It Matters
180
+ Por que este padrão é útil.
181
+
182
+ ### Adaptation
183
+ Como ele poderia se aplicar ao projeto atual.
184
+
185
+ ### Trade-offs
186
+ Que problemas ele introduz.
187
+
188
+ ### Recommendation
189
+ O que deve de fato ser adotado.
190
+ ```
191
+
192
+ ---
193
+
194
+ ## 6. Evitar overengineering
195
+
196
+ O sistema deve evitar:
197
+
198
+ * pesquisar tudo sempre;
199
+ * executar todas as skills;
200
+ * produzir relatórios gigantes;
201
+ * consultar referências irrelevantes;
202
+ * transformar qualquer comportamento estranho em bug;
203
+ * adicionar dependências desnecessárias.
204
+
205
+ Princípio:
206
+
207
+ > **Research proportional to uncertainty and impact.**
208
+
209
+ Quanto maior:
210
+
211
+ ```text
212
+ uncertainty + impact + irreversibility
213
+ ```
214
+
215
+ maior deve ser o nível de pesquisa. Uma mudança trivial e reversível não justifica
216
+ uma auditoria completa; uma mudança em fluxo de pagamento, irreversível e de alto
217
+ impacto, justifica o workflow completo.
218
+
219
+ ---
220
+
221
+ ## 7. Composição entre skills
222
+
223
+ Skills devem trabalhar em conjunto. O `skill-router` define a composição, mas a
224
+ regra geral é: uma tarefa raramente ativa uma skill isolada.
225
+
226
+ Exemplos:
227
+
228
+ * `payment` → `business-logic-audit`, `idempotency-audit`, `race-condition-hunter`,
229
+ `data-integrity-audit`, `error-flow-audit`, `authorization-audit`.
230
+ * `social reactions` → `gamification-audit`, `business-logic-audit`,
231
+ `idempotency-audit`, `race-condition-hunter`, `api-abuse-audit`.
232
+
233
+ Ao combinar skills, **deduplicar findings**: quando duas skills apontam o mesmo
234
+ defeito, consolidar em um único finding com a análise combinada.
235
+
236
+ ---
237
+
238
+ ## 8. Referências rápidas
239
+
240
+ | Precisa de… | Onde |
241
+ |---|---|
242
+ | Formato de uma skill | `docs/skill-authoring.md` |
243
+ | Formato de uma referência | `docs/reference-authoring.md` |
244
+ | Filosofia e princípios | `docs/philosophy.md` |
245
+ | Integração do agente (workflows) | `docs/agent-integration.md` |
246
+ | Catálogo de referências | `references/*.yaml` |
247
+ | Template de relatório de auditoria | `templates/audit-report.md` |
248
+ | Template de bug report | `templates/bug-report.md` |
249
+ | Validação (lint de skills/refs) | `scripts/validate.py` |
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 1arley-agent-skills contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # Agent Engineering Skills
2
+
3
+ > **Don't just review the code. Attack the assumptions behind the system.**
4
+
5
+ Um repositório de skills modulares que ensinam agentes de IA a **entender → pesquisar
6
+ → questionar → testar → verificar → implementar → revisar**.
7
+
8
+ O objetivo não é criar um agente que sabe mais.
9
+ É criar um agente que **sabe como descobrir mais, onde procurar, quais perguntas fazer
10
+ e como verificar se está certo**.
11
+
12
+ ---
13
+
14
+ ## O que isto é
15
+
16
+ Três camadas, separadas de propósito:
17
+
18
+ ```text
19
+ skills/ → como pensar (modelo mental, perguntas, padrões de ataque, evidência)
20
+ knowledge/ → o que considerar
21
+ references/ → onde pesquisar (catálogo centralizado de fontes externas)
22
+ ```
23
+
24
+ As skills ensinam raciocínio. As referências ensinam onde olhar. Nenhuma skill depende
25
+ de conhecimento implícito que não esteja documentado ou disponível através das
26
+ referências.
27
+
28
+ ## Estrutura
29
+
30
+ ```text
31
+ ├── AGENTS.md # regras globais do agente
32
+ ├── plan.md # especificação completa (fases, formato, definição de pronto)
33
+ ├── LICENSE # MIT
34
+
35
+ ├── skills/
36
+ │ ├── audit/ # auditoria de sistemas e descoberta de bugs
37
+ │ ├── security/ # autorização, abuso de API, confiança de input
38
+ │ ├── reliability/ # race conditions, idempotência, integridade de dados
39
+ │ ├── product/ # regras de negócio e gamificação
40
+ │ ├── frontend/ # UX, visual, interação, animação, acessibilidade
41
+ │ ├── research/ # descoberta de referências e implementações
42
+ │ └── meta/ # routers que despacham para skills e fontes
43
+
44
+ ├── references/ # catálogo YAML de fontes externas
45
+ ├── knowledge/ # material "o que considerar"
46
+ ├── templates/ # templates de relatório (audit, bug, design, research)
47
+ ├── examples/ # exemplos concretos de auditorias
48
+ ├── docs/ # filosofia, authoring, integração
49
+ └── scripts/ # validação (lint de skills e referências)
50
+ ```
51
+
52
+ Cada skill é `skills/<categoria>/<nome>/SKILL.md` com frontmatter YAML e nove seções
53
+ fixas. Ver `docs/skill-authoring.md`.
54
+
55
+ ## Skills (primeira versão — 24)
56
+
57
+ | Categoria | Skills |
58
+ |---|---|
59
+ | **Core audit** | `adversarial-review`, `user-flow-audit`, `business-logic-audit`, `edge-case-hunter`, `state-consistency-audit`, `error-flow-audit` |
60
+ | **Security** | `authorization-audit`, `api-abuse-audit`, `input-trust-audit` |
61
+ | **Reliability** | `race-condition-hunter`, `idempotency-audit`, `data-integrity-audit` |
62
+ | **Product** | `gamification-audit` |
63
+ | **Frontend** | `ux-review`, `visual-quality-review`, `interaction-design`, `animation-review`, `accessibility-review` |
64
+ | **Research** | `reference-research`, `github-reference-research`, `market-research`, `implementation-research` |
65
+ | **Meta** | `skill-router`, `research-router` |
66
+
67
+ A prioridade é **qualidade, composição e capacidade de raciocínio — não quantidade**.
68
+
69
+ ## Como usar
70
+
71
+ 1. Leia `AGENTS.md` para as regras globais.
72
+ 2. Para uma tarefa, comece pelo `skills/meta/skill-router/` — ele seleciona quais
73
+ skills ativar com base no tipo de tarefa.
74
+ 3. Para pesquisa, use `skills/meta/research-router/` — ele aponta quais fontes em
75
+ `references/` consultar.
76
+ 4. Ao reportar findings, siga `templates/audit-report.md` e classifique cada um por
77
+ nível de evidência (`CONFIRMED` / `HIGH CONFIDENCE` / `POSSIBLE` / `SPECULATIVE`).
78
+
79
+ ## Workflow completo
80
+
81
+ ```text
82
+ REQUEST → UNDERSTAND → CLASSIFY → SKILL ROUTER → RESEARCH ROUTER →
83
+ RESEARCH → ANALYZE → IMPLEMENT → ADVERSARIAL TEST → VERIFY → REPORT
84
+ ```
85
+
86
+ Pesquisa é proporcional à complexidade: um botão simples não precisa de pesquisa;
87
+ uma arquitetura nova provavelmente precisa; concorrência em pagamentos certamente.
88
+
89
+ ## Status
90
+
91
+ **Primeira versão completa.** 24 skills implementadas, 6 catálogos de referências,
92
+ 4 templates de relatório, 4 exemplos concretos, 2 meta routers, validador.
93
+
94
+ ```bash
95
+ python3 scripts/validate.py
96
+ ```
97
+
98
+ Verifica que toda `skills/**/SKILL.md` tem o frontmatter e as nove seções exigidas,
99
+ que toda `references/*.yaml` segue o schema de catálogo, e que as referências do
100
+ `skill-router` são consistentes. Ver `docs/skill-authoring.md` e
101
+ `docs/reference-authoring.md`.
102
+
103
+ ## Documentação
104
+
105
+ * `docs/philosophy.md` — princípios e filosofia central.
106
+ * `docs/skill-authoring.md` — como escrever uma skill (formato `SKILL.md`).
107
+ * `docs/reference-authoring.md` — como adicionar referências (schema YAML).
108
+ * `docs/agent-integration.md` — como o agente integra skills, routers e workflows.
109
+ * `plan.md` — especificação completa e Definition of Done.
110
+
111
+ ## Licença
112
+
113
+ MIT — ver `LICENSE`.
package/bin/cli.js ADDED
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * agent-engineering-skills — CLI
4
+ *
5
+ * Usage:
6
+ * npx agent-engineering-skills install [--target <dir>] [--link] [--force]
7
+ * npx agent-engineering-skills validate
8
+ * npx agent-engineering-skills --help
9
+ *
10
+ * `install` copies (or symlinks) the 24 skills into a Claude Code skills directory
11
+ * (default: ~/.claude/skills), adapting the frontmatter to Claude Code's native
12
+ * format (name + description) and making each skill user-invocable.
13
+ *
14
+ * Zero runtime dependencies — Node >= 18 only.
15
+ */
16
+
17
+ import { execFileSync } from "node:child_process";
18
+ import { createRequire } from "node:module";
19
+ import { fileURLToPath } from "node:url";
20
+ import fs from "node:fs";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+
24
+ const require = createRequire(import.meta.url);
25
+ const PKG = require("../package.json");
26
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
+ const ROOT = path.resolve(__dirname, "..");
28
+
29
+ const SKILLS_GLOB = path.join(ROOT, "skills");
30
+ const DEFAULT_TARGET = path.join(os.homedir(), ".claude", "skills");
31
+
32
+ const HELP = `agent-engineering-skills v${PKG.version}
33
+
34
+ Modular skills that teach AI agents to audit systems, find bugs, review
35
+ UX/frontend, and research before reinventing.
36
+
37
+ Usage:
38
+ agent-engineering-skills install [options] Install the 24 skills into a
39
+ Claude Code skills directory
40
+ agent-engineering-skills validate Run the repo validator
41
+ agent-engineering-skills --help Show this help
42
+ agent-engineering-skills --version Show version
43
+
44
+ Options (install):
45
+ --target <dir> Destination skills directory (default: ~/.claude/skills)
46
+ --link Create symlinks instead of copying
47
+ --force Overwrite existing skills with the same name
48
+ `;
49
+
50
+ function log(msg = "") {
51
+ process.stdout.write(msg + "\n");
52
+ }
53
+
54
+ function err(msg) {
55
+ process.stderr.write(msg + "\n");
56
+ }
57
+
58
+ /** List every <category>/<skill>/ directory under skills/. */
59
+ function findSkillDirs() {
60
+ const dirs = [];
61
+ if (!fs.existsSync(SKILLS_GLOB)) return dirs;
62
+ for (const category of fs.readdirSync(SKILLS_GLOB)) {
63
+ const catPath = path.join(SKILLS_GLOB, category);
64
+ if (!fs.statSync(catPath).isDirectory()) continue;
65
+ for (const skill of fs.readdirSync(catPath)) {
66
+ const skillPath = path.join(catPath, skill);
67
+ if (!fs.statSync(skillPath).isDirectory()) continue;
68
+ if (!fs.existsSync(path.join(skillPath, "SKILL.md"))) continue;
69
+ dirs.push({ category, name: skill, src: skillPath });
70
+ }
71
+ }
72
+ return dirs.sort((a, b) => a.name.localeCompare(b.name));
73
+ }
74
+
75
+ /**
76
+ * Rewrite a SKILL.md frontmatter into Claude Code's native shape:
77
+ * - keep name + description (the fields the harness matches on)
78
+ * - add user_invocable so the skill can be invoked via slash command
79
+ * - drop plan.md-only fields (category/triggers/priority) that the harness
80
+ * does not use; their routing duty lives in the skill-router instead
81
+ * Returns the rewritten file content (or original if unchanged).
82
+ */
83
+ function adaptFrontmatter(original) {
84
+ const m = original.match(/^---\r?\n([\s\S]*?)\r?\n---/);
85
+ if (!m) return original;
86
+ const fm = m[1];
87
+ const body = original.slice(m[0].length);
88
+
89
+ const get = (key) => {
90
+ const re = new RegExp(`^${key}:\\s*(.+)$`, "m");
91
+ const hit = fm.match(re);
92
+ return hit ? hit[1].trim().replace(/^['"]|['"]$/g, "") : null;
93
+ };
94
+
95
+ const name = get("name");
96
+ const description = get("description");
97
+ if (!name || !description) return original; // don't mangle malformed files
98
+
99
+ const adapted = `---\nname: ${name}\ndescription: ${description}\nuser_invocable: true\n---\n${body}`;
100
+ return adapted;
101
+ }
102
+
103
+ function copyDir(src, dest) {
104
+ fs.mkdirSync(dest, { recursive: true });
105
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
106
+ const from = path.join(src, entry.name);
107
+ const to = path.join(dest, entry.name);
108
+ if (entry.isDirectory()) {
109
+ copyDir(from, to);
110
+ } else if (entry.isFile()) {
111
+ let content = fs.readFileSync(from, "utf8");
112
+ if (entry.name === "SKILL.md") {
113
+ content = adaptFrontmatter(content);
114
+ }
115
+ fs.writeFileSync(to, content);
116
+ }
117
+ }
118
+ }
119
+
120
+ function installSkill(skill, target, { link, force }) {
121
+ const dest = path.join(target, skill.name);
122
+ if (fs.existsSync(dest)) {
123
+ if (!force) {
124
+ return { name: skill.name, status: "skipped (exists — use --force)" };
125
+ }
126
+ fs.rmSync(dest, { recursive: true, force: true });
127
+ }
128
+ if (link) {
129
+ fs.symlinkSync(skill.src, dest, "dir");
130
+ return { name: skill.name, status: "linked" };
131
+ }
132
+ copyDir(skill.src, dest);
133
+ return { name: skill.name, status: "installed" };
134
+ }
135
+
136
+ function runInstall(target, { link, force }) {
137
+ const skills = findSkillDirs();
138
+ if (!skills.length) {
139
+ err(`No skills found under ${SKILLS_GLOB}`);
140
+ process.exitCode = 1;
141
+ return;
142
+ }
143
+ fs.mkdirSync(target, { recursive: true });
144
+ log(`agent-engineering-skills v${PKG.version} — installing ${skills.length} skills`);
145
+ log(`target: ${target}${link ? " (symlink mode)" : ""}${force ? " (force)" : ""}`);
146
+ log("");
147
+
148
+ const results = skills.map((s) => installSkill(s, target, { link, force }));
149
+ const counts = { installed: 0, linked: 0, skipped: 0 };
150
+ for (const r of results) {
151
+ if (r.status.startsWith("installed")) counts.installed++;
152
+ else if (r.status === "linked") counts.linked++;
153
+ else counts.skipped++;
154
+ log(` ${r.status.startsWith("skipped") ? "•" : "✓"} ${r.name} — ${r.status}`);
155
+ }
156
+ log("");
157
+ log(
158
+ `Done: ${counts.installed} installed, ${counts.linked} linked, ` +
159
+ `${counts.skipped} skipped.`
160
+ );
161
+ log("");
162
+ log("Skills are now available in your Claude Code skills directory.");
163
+ log("Dispatch between them with skills/meta/skill-router (installed too).");
164
+ log("Next: run 'python3 scripts/validate.py' or 'npx agent-engineering-skills validate'.");
165
+ }
166
+
167
+ function runValidate() {
168
+ const script = path.join(ROOT, "scripts", "validate.py");
169
+ if (!fs.existsSync(script)) {
170
+ err(`Validator not found at ${script}`);
171
+ process.exitCode = 1;
172
+ return;
173
+ }
174
+ try {
175
+ execFileSync("python3", [script], { stdio: "inherit" });
176
+ } catch {
177
+ process.exitCode = 1;
178
+ }
179
+ }
180
+
181
+ function parseArgs(argv) {
182
+ const opts = { target: DEFAULT_TARGET, link: false, force: false, command: null };
183
+ for (let i = 0; i < argv.length; i++) {
184
+ const a = argv[i];
185
+ if (a === "--help" || a === "-h") {
186
+ log(HELP);
187
+ process.exit(0);
188
+ } else if (a === "--version" || a === "-v") {
189
+ log(PKG.version);
190
+ process.exit(0);
191
+ } else if (a === "--target") {
192
+ opts.target = path.resolve(argv[++i] || "");
193
+ } else if (a === "--link") {
194
+ opts.link = true;
195
+ } else if (a === "--force") {
196
+ opts.force = true;
197
+ } else if (a.startsWith("-")) {
198
+ err(`Unknown option: ${a}\n`);
199
+ log(HELP);
200
+ process.exitCode = 1;
201
+ return null;
202
+ } else if (!opts.command) {
203
+ opts.command = a;
204
+ }
205
+ }
206
+ return opts;
207
+ }
208
+
209
+ function main() {
210
+ const opts = parseArgs(process.argv.slice(2));
211
+ if (!opts) return;
212
+ if (!opts.command || opts.command === "install") {
213
+ runInstall(opts.target, { link: opts.link, force: opts.force });
214
+ } else if (opts.command === "validate") {
215
+ runValidate();
216
+ } else {
217
+ err(`Unknown command: ${opts.command}\n`);
218
+ log(HELP);
219
+ process.exitCode = 1;
220
+ }
221
+ }
222
+
223
+ main();