the-crew 0.1.0 → 0.3.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 (52) hide show
  1. package/README.md +141 -58
  2. package/core/agents/README.md +1 -1
  3. package/core/agents/desenvolve/frontend-dev.md +4 -3
  4. package/core/agents/planeja/ux-ui-design.md +2 -1
  5. package/core/skills/crew-gates/SKILL.md +1 -1
  6. package/core/skills/crew-obsidian/SKILL.md +2 -2
  7. package/core/skills/db-organizer/SKILL.md +1 -1
  8. package/core/skills/manifest.json +791 -0
  9. package/core/skills/new-project/SKILL.md +27 -0
  10. package/core/skills/po-backlog/SKILL.md +1 -1
  11. package/core/skills/projects/SKILL.md +10 -0
  12. package/dist/src/cli/commands/exec.js +1 -1
  13. package/dist/src/cli/commands/install.js +300 -0
  14. package/dist/src/cli/commands/new-project.js +86 -0
  15. package/dist/src/cli/commands/projects.js +24 -0
  16. package/dist/src/cli/commands/uninstall.js +308 -0
  17. package/dist/src/cli/commands/validate.js +6 -5
  18. package/dist/src/cli/index.js +26 -21
  19. package/dist/src/cli/lib/args.js +99 -41
  20. package/dist/src/cli/lib/common.js +120 -0
  21. package/dist/src/cli/lib/credentials.js +26 -0
  22. package/dist/src/cli/lib/github.js +36 -0
  23. package/dist/src/cli/lib/install-record.js +39 -0
  24. package/dist/src/cli/lib/legacy.js +230 -0
  25. package/dist/src/cli/lib/plans.js +251 -0
  26. package/dist/src/cli/lib/registry.js +21 -0
  27. package/dist/src/cli/lib/skills.js +186 -0
  28. package/dist/src/cli/lib/writer.js +13 -2
  29. package/package.json +10 -3
  30. package/templates/obsidian/{00 Painel.md → project/00 Painel.md } +4 -6
  31. package/templates/obsidian/team/00 Time.md +20 -0
  32. package/templates/office/AGENTS.md +12 -0
  33. package/templates/office/README.md +15 -0
  34. package/templates/project/AGENTS.md +5 -0
  35. package/templates/project/PROJECT.md +31 -0
  36. package/templates/rules/team.md +14 -0
  37. package/core/skills/catalog.json +0 -30
  38. package/dist/src/cli/commands/init.js +0 -185
  39. package/dist/src/cli/lib/plan.js +0 -300
  40. package/templates/docs/PROJECT.md +0 -36
  41. package/templates/entrypoints/crew-block.md +0 -28
  42. package/templates/entrypoints/cursor.mdc +0 -6
  43. package/templates/entrypoints/obsidian-rules.md +0 -18
  44. package/templates/entrypoints/windsurf.md +0 -5
  45. package/templates/workflows/crew-integrity.yml +0 -24
  46. /package/templates/obsidian/{_templates → team/_templates}/ADR.md +0 -0
  47. /package/templates/obsidian/{_templates → team/_templates}/Achado de seguranca.md +0 -0
  48. /package/templates/obsidian/{_templates → team/_templates}/Bug.md +0 -0
  49. /package/templates/obsidian/{_templates → team/_templates}/Handoff.md +0 -0
  50. /package/templates/obsidian/{_templates → team/_templates}/Historia.md +0 -0
  51. /package/templates/obsidian/{_templates → team/_templates}/Release.md +0 -0
  52. /package/templates/obsidian/{_templates → team/_templates}/Run.md +0 -0
@@ -0,0 +1,251 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { agentById, agentTable, GITIGNORE_BLOCK, listFiles, mcpServers, noteName, officeDisplay, owned, render, skillVars, specCompact, specMission, teamName, teamRules, toPosix, tpl, written, yamlString, } from './common.js';
4
+ /** Skills que viram /comandos. */
5
+ export const COMMAND_SKILLS = ['new-project', 'projects'];
6
+ function file(base, rel, content) {
7
+ return { kind: 'file', path: join(base, rel), content };
8
+ }
9
+ function skillFiles(ctx) {
10
+ const dir = join(ctx.pkgRoot, 'core', 'skills');
11
+ return listFiles(dir).map((f) => {
12
+ const raw = readFileSync(f, 'utf8');
13
+ return { rel: relative(dir, f), content: f.endsWith('.md') ? render(raw, skillVars(ctx)) : raw };
14
+ });
15
+ }
16
+ function skillBody(content) {
17
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(content);
18
+ const description = /^description:\s*(.*)$/m.exec(m?.[1] ?? '')?.[1] ?? '';
19
+ return { description, body: (m?.[2] ?? content).trim() + '\n' };
20
+ }
21
+ /** Topologia como fica no escritório: specs em agents/ em vez de core/agents/. */
22
+ export function officeTopology(t) {
23
+ return { ...t, agents: t.agents.map((a) => ({ ...a, spec: a.spec.replace(/^core\/agents\//, 'agents/') })) };
24
+ }
25
+ /** Arquivos de /comandos para IDEs que só leem comandos por pasta (Cursor, Windsurf). */
26
+ function commandFiles(ctx, base) {
27
+ const out = [];
28
+ const skills = skillFiles(ctx).filter((s) => COMMAND_SKILLS.some((c) => toPosix(s.rel) === `${c}/SKILL.md`));
29
+ for (const s of skills) {
30
+ const name = toPosix(s.rel).split('/')[0];
31
+ const { description, body } = skillBody(s.content);
32
+ if (ctx.ides.includes('cursor'))
33
+ out.push(file(base, join('.cursor', 'commands', `${name}.md`), body));
34
+ if (ctx.ides.includes('windsurf')) {
35
+ out.push(file(base, join('.windsurf', 'workflows', `${name}.md`), `---\ndescription: ${description}\n---\n\n${body}`));
36
+ }
37
+ }
38
+ return out;
39
+ }
40
+ /** Escritório do time: um repositório local com specs, contratos, skills e o registro de projetos. */
41
+ export function planOffice(ctx) {
42
+ const o = ctx.officeDir;
43
+ const plan = [];
44
+ const agentsDir = join(ctx.pkgRoot, 'core', 'agents');
45
+ for (const f of listFiles(agentsDir))
46
+ plan.push(file(o, join('agents', relative(agentsDir, f)), readFileSync(f, 'utf8')));
47
+ plan.push(file(o, join('contracts', 'topology.json'), JSON.stringify(officeTopology(ctx.topology), null, 2) + '\n'));
48
+ for (const s of skillFiles(ctx))
49
+ plan.push(file(o, join('skills', s.rel), s.content));
50
+ plan.push(file(o, 'README.md', render(tpl(ctx, 'office', 'README.md'), { date: ctx.date, projectsDir: ctx.projectsDir })));
51
+ const agentsMd = render(tpl(ctx, 'office', 'AGENTS.md'), {
52
+ version: `v${ctx.version}`,
53
+ agentTable: agentTable(ctx.topology, officeDisplay(ctx)),
54
+ teamRules: teamRules(ctx),
55
+ });
56
+ plan.push({ kind: 'block', path: join(o, 'AGENTS.md'), content: agentsMd, comment: 'html' });
57
+ plan.push({ kind: 'block', path: join(o, 'CLAUDE.md'), content: '@AGENTS.md', comment: 'html' });
58
+ plan.push({
59
+ kind: 'block',
60
+ path: join(o, '.gitignore'),
61
+ content: `${GITIGNORE_BLOCK}\n# Skills de terceiros baixadas (commit fixado em skills/manifest.json)\nvendor/`,
62
+ comment: 'hash',
63
+ });
64
+ plan.push({ kind: 'json-merge', path: join(o, 'projects.json'), key: 'projects', entries: {} });
65
+ plan.push(...commandFiles(ctx, o));
66
+ return plan;
67
+ }
68
+ function claudeSubagent(ctx, a, spec) {
69
+ const t = ctx.topology;
70
+ const byId = agentById(t);
71
+ const office = officeDisplay(ctx);
72
+ const talks = a.talksTo.map((id) => byId.get(id)?.name ?? id).join(', ');
73
+ const own = owned(t, a.id).flatMap((x) => x.paths).map((p) => `\`${p}\``).join(', ');
74
+ const wr = written(t, a.id).map((x) => `\`${x.paths[0]}\` (só a própria seção)`).join(', ');
75
+ const skillsLine = [...(ctx.agentSkills?.get(a.id) ?? []), ...(ctx.agentSkills?.get('*') ?? [])].join(', ');
76
+ return [
77
+ '---',
78
+ `name: crew-${a.id}`,
79
+ `description: ${yamlString(`${a.name} do the-crew (${teamName(t, a.team)}). ${specMission(spec)}`)}`,
80
+ '---',
81
+ '',
82
+ `Você é o **${a.name}** do the-crew (${teamName(t, a.team)}). O time é um só e administra vários projetos; trabalhe no repositório do projeto em questão (lista em \`${office}/projects.json\`).`,
83
+ '',
84
+ `Antes de agir, leia sua spec completa em \`${office}/agents/${a.team}/${a.id}.md\`. Contratos: \`${office}/contracts/topology.json\`.`,
85
+ '',
86
+ '## Resumo',
87
+ '',
88
+ specCompact(spec),
89
+ '',
90
+ '## Contratos',
91
+ '',
92
+ `- Conversa com: ${talks}.`,
93
+ `- Dono de (no repositório do projeto): ${own || 'nenhum arquivo'}.`,
94
+ ...(skillsLine ? [`- Skills instaladas para este papel: ${skillsLine}.`] : []),
95
+ ...(ctx.agentSkillRules?.get(a.id) ?? []).map((r) => `- Regra de uso de ${r}`),
96
+ ...(wr ? [`- Também escreve em: ${wr}.`] : []),
97
+ '- Escale ao humano antes de deploy em produção, migração destrutiva, mudança de escopo ou aceite de risco Critical/High.',
98
+ '',
99
+ ].join('\n');
100
+ }
101
+ const GLOBAL_NOTE = (ctx) => [
102
+ '# the-crew',
103
+ '',
104
+ `O time the-crew está instalado nesta máquina (escritório em \`${officeDisplay(ctx)}\`). Use **/new-project** para criar um projeto e **/projects** para ver os existentes.`,
105
+ 'Quando o repositório atual tiver `PROJECT.md` e um `AGENTS.md` do the-crew, siga as regras do time descritas ali.',
106
+ ].join('\n');
107
+ /** Registro global nos assistentes, para os agentes e /comandos funcionarem em qualquer pasta. */
108
+ export function planAssistants(ctx) {
109
+ const plan = [];
110
+ const h = ctx.home;
111
+ const skills = skillFiles(ctx).filter((s) => s.rel.endsWith('SKILL.md'));
112
+ if (ctx.ides.includes('claude-code')) {
113
+ for (const a of ctx.topology.agents) {
114
+ const spec = readFileSync(join(ctx.pkgRoot, a.spec), 'utf8');
115
+ plan.push(file(h, join('.claude', 'agents', `crew-${a.id}.md`), claudeSubagent(ctx, a, spec)));
116
+ }
117
+ for (const s of skills)
118
+ plan.push(file(h, join('.claude', 'skills', s.rel), s.content));
119
+ plan.push({ kind: 'block', path: join(h, '.claude', 'CLAUDE.md'), content: GLOBAL_NOTE(ctx), comment: 'html' });
120
+ }
121
+ if (ctx.ides.includes('codex')) {
122
+ for (const s of skills)
123
+ plan.push(file(h, join('.agents', 'skills', s.rel), s.content));
124
+ plan.push({ kind: 'block', path: join(h, '.codex', 'AGENTS.md'), content: GLOBAL_NOTE(ctx), comment: 'html' });
125
+ }
126
+ if (ctx.ides.includes('cursor') && ctx.mcp.length > 0) {
127
+ plan.push({ kind: 'json-merge', path: join(h, '.cursor', 'mcp.json'), key: 'mcpServers', entries: mcpServers('cursor', ctx.mcp) });
128
+ }
129
+ return plan;
130
+ }
131
+ /** Arquivos de um projeto novo. */
132
+ export function planProject(ctx, p) {
133
+ const plan = [];
134
+ const d = p.dir;
135
+ plan.push(file(d, 'PROJECT.md', render(tpl(ctx, 'project', 'PROJECT.md'), {
136
+ projectName: p.name,
137
+ description: p.description || 'Que dor existe hoje, para quem, e como ela é resolvida (mal) atualmente?',
138
+ })));
139
+ const agentsMd = render(tpl(ctx, 'project', 'AGENTS.md'), {
140
+ projectName: p.name,
141
+ officeDir: officeDisplay(ctx),
142
+ teamRules: teamRules(ctx),
143
+ });
144
+ plan.push({ kind: 'block', path: join(d, 'AGENTS.md'), content: agentsMd, comment: 'html' });
145
+ if (ctx.ides.includes('claude-code')) {
146
+ plan.push({ kind: 'block', path: join(d, 'CLAUDE.md'), content: '@AGENTS.md', comment: 'html' });
147
+ if (ctx.mcp.length > 0) {
148
+ plan.push({ kind: 'json-merge', path: join(d, '.mcp.json'), key: 'mcpServers', entries: mcpServers('claude-code', ctx.mcp) });
149
+ }
150
+ }
151
+ if (ctx.ides.includes('cursor'))
152
+ plan.push(file(d, join('.cursor', 'rules', 'the-crew.mdc'), `---\ndescription: Time the-crew\nalwaysApply: true\n---\n\n${agentsMd}`));
153
+ if (ctx.ides.includes('windsurf'))
154
+ plan.push(file(d, join('.windsurf', 'rules', 'the-crew.md'), `---\ntrigger: always_on\n---\n\n${agentsMd}`));
155
+ plan.push(...commandFiles(ctx, d));
156
+ for (const sub of ['plan', 'runs', 'handoffs'])
157
+ plan.push(file(d, join('.agents', sub, '.gitkeep'), ''));
158
+ plan.push({ kind: 'block', path: join(d, '.gitignore'), content: GITIGNORE_BLOCK, comment: 'hash' });
159
+ plan.push(file(d, join('.the-crew', 'local.json'), JSON.stringify({ project: p.slug, officeDir: ctx.officeDir, vaultProjectDir: p.vaultDir }, null, 2) + '\n'));
160
+ return plan;
161
+ }
162
+ export const VAULT_FOLDERS = ['01 Produto', '02 Backlog', '03 Decisões', '04 Handoffs', '05 Gates', '06 Releases', '07 Runs'];
163
+ export function vaultTeamDir(vault) {
164
+ return join(vault, 'the-crew');
165
+ }
166
+ export function vaultProjectDir(vault, slug) {
167
+ return join(vaultTeamDir(vault), 'Projetos', slug);
168
+ }
169
+ function agentNote(t, a, mission, office) {
170
+ const byId = agentById(t);
171
+ const link = (id) => `[[${noteName(byId.get(id)?.name ?? id)}]]`;
172
+ return [
173
+ '---',
174
+ `tags: [agente, ${a.team}]`,
175
+ `id: ${a.id}`,
176
+ `time: ${yamlString(teamName(t, a.team))}`,
177
+ `entrada: ${a.entrypoint ? 'true' : 'false'}`,
178
+ `spec: ${office}/agents/${a.team}/${a.id}.md`,
179
+ '---',
180
+ '',
181
+ `# ${a.name}`,
182
+ '',
183
+ mission,
184
+ '',
185
+ '## Conversa com',
186
+ '',
187
+ ...a.talksTo.map((id) => `- ${link(id)}`),
188
+ '',
189
+ '## Dono de (em cada projeto)',
190
+ '',
191
+ ...owned(t, a.id).map((x) => `- \`${x.paths.join('`, `')}\``),
192
+ ...(written(t, a.id).length
193
+ ? ['', '## Escreve também (só a própria seção)', '', ...written(t, a.id).map((x) => `- \`${x.paths[0]}\` (de ${link(x.owner)})`)]
194
+ : []),
195
+ '',
196
+ '## Lê',
197
+ '',
198
+ ...t.artifacts.filter((x) => a.inputs.includes(x.id)).map((x) => `- \`${x.paths[0]}\` (de ${link(x.owner)})`),
199
+ '',
200
+ ].join('\n');
201
+ }
202
+ /** Vault: estrutura do time (uma vez), conforme a lógica de comunicação dos agentes. */
203
+ export function planVaultTeam(ctx, projects) {
204
+ if (!ctx.vaultPath)
205
+ return [];
206
+ const t = ctx.topology;
207
+ const base = vaultTeamDir(ctx.vaultPath);
208
+ const plan = [];
209
+ const teamLinks = t.teams
210
+ .map((team) => `- **${team.name}:** ${t.agents.filter((a) => a.team === team.id).map((a) => `[[${noteName(a.name)}]]`).join(' · ')}`)
211
+ .join('\n');
212
+ plan.push(file(base, '00 Time.md', render(tpl(ctx, 'obsidian', 'team', '00 Time.md'), { date: ctx.date, teamLinks })));
213
+ plan.push(vaultProjectsIndex(ctx.vaultPath, projects));
214
+ // Os modelos usam {{date}} do plugin Templates do Obsidian: são copiados sem renderizar.
215
+ const tplDir = join(ctx.pkgRoot, 'templates', 'obsidian', 'team', '_templates');
216
+ for (const f of listFiles(tplDir))
217
+ plan.push(file(base, join('_templates', relative(tplDir, f)), readFileSync(f, 'utf8')));
218
+ for (const a of t.agents) {
219
+ const spec = readFileSync(join(ctx.pkgRoot, a.spec), 'utf8');
220
+ plan.push(file(base, join('Agentes', noteName(teamName(t, a.team)), `${noteName(a.name)}.md`), agentNote(t, a, specMission(spec), officeDisplay(ctx))));
221
+ }
222
+ return plan;
223
+ }
224
+ /** Vault: pasta de um projeto, mais o link no painel do time. */
225
+ export function planVaultProject(ctx, p, allProjects) {
226
+ if (!ctx.vaultPath || !p.vaultDir)
227
+ return [];
228
+ const plan = [];
229
+ plan.push(file(p.vaultDir, `${noteName(p.name)}.md`, render(tpl(ctx, 'obsidian', 'project', '00 Painel.md'), {
230
+ projectName: p.name,
231
+ projectDir: toPosix(p.dir),
232
+ date: ctx.date,
233
+ description: p.description,
234
+ })));
235
+ for (const d of VAULT_FOLDERS)
236
+ plan.push(file(p.vaultDir, join(d, '.gitkeep'), ''));
237
+ plan.push(vaultProjectsIndex(ctx.vaultPath, allProjects));
238
+ return plan;
239
+ }
240
+ /** Índice de projetos no vault (bloco gerenciado: o resto da nota é do humano). */
241
+ export function vaultProjectsIndex(vault, projects) {
242
+ const list = projects.length
243
+ ? projects.map((x) => `- [[Projetos/${x.slug}/${noteName(x.name)}|${x.name}]]`).join('\n')
244
+ : '_Nenhum projeto ainda. Use /new-project._';
245
+ return {
246
+ kind: 'block',
247
+ path: join(vaultTeamDir(vault), 'Projetos', 'Projetos.md'),
248
+ content: `# Projetos do time\n\nLista mantida pelo /new-project.\n\n${list}`,
249
+ comment: 'html',
250
+ };
251
+ }
@@ -0,0 +1,21 @@
1
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export function registryPath(officeDir) {
4
+ return join(officeDir, 'projects.json');
5
+ }
6
+ export function readRegistry(officeDir) {
7
+ const p = registryPath(officeDir);
8
+ if (!existsSync(p))
9
+ return { projects: {} };
10
+ const data = JSON.parse(readFileSync(p, 'utf8'));
11
+ return { projects: data.projects ?? {} };
12
+ }
13
+ export function writeRegistry(officeDir, reg) {
14
+ const p = registryPath(officeDir);
15
+ const tmp = `${p}.tmp`;
16
+ writeFileSync(tmp, JSON.stringify(reg, null, 2) + '\n', 'utf8');
17
+ renameSync(tmp, p);
18
+ }
19
+ export function projectList(reg) {
20
+ return Object.values(reg.projects).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
21
+ }
@@ -0,0 +1,186 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, relative, resolve, sep } from 'node:path';
4
+ export function loadManifest(pkgRoot) {
5
+ return JSON.parse(readFileSync(join(pkgRoot, 'core', 'skills', 'manifest.json'), 'utf8'));
6
+ }
7
+ export function vendorPath(vendorDir, s) {
8
+ return join(vendorDir, `${s.repo.replace('/', '__')}@${s.commit.slice(0, 12)}`);
9
+ }
10
+ function git(args, cwd) {
11
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
12
+ return { ok: r.status === 0, out: `${r.stdout ?? ''}${r.stderr ?? ''}`.trim() };
13
+ }
14
+ export function hasGit() {
15
+ return spawnSync('git', ['--version'], { stdio: 'ignore' }).status === 0;
16
+ }
17
+ const DONE = '.the-crew-source.json';
18
+ /** Baixa uma fonte no commit fixado. Idempotente. */
19
+ export function fetchSource(s, vendorDir) {
20
+ const dest = vendorPath(vendorDir, s);
21
+ if (existsSync(join(dest, DONE)))
22
+ return dest;
23
+ if (!/^[0-9a-f]{40}$/.test(s.commit))
24
+ throw new Error(`${s.id}: commit inválido no manifest`);
25
+ const tmp = `${dest}.tmp`;
26
+ rmSync(tmp, { recursive: true, force: true });
27
+ mkdirSync(tmp, { recursive: true });
28
+ const url = s.url ?? `https://github.com/${s.repo}.git`;
29
+ const steps = [
30
+ ['init', '-q'],
31
+ ['remote', 'add', 'origin', url],
32
+ ['sparse-checkout', 'set', '--no-cone', ...s.paths.map((p) => `/${p}/`)],
33
+ ['fetch', '-q', '--depth', '1', '--filter=blob:none', 'origin', s.commit],
34
+ ['-c', 'advice.detachedHead=false', 'checkout', '-q', 'FETCH_HEAD'],
35
+ ];
36
+ for (const st of steps) {
37
+ let r = git(st, tmp);
38
+ // Servidores sem suporte a filtro: tenta de novo sem --filter.
39
+ if (!r.ok && st[0] === 'fetch')
40
+ r = git(st.filter((a) => !a.startsWith('--filter')), tmp);
41
+ if (!r.ok) {
42
+ rmSync(tmp, { recursive: true, force: true });
43
+ throw new Error(`${s.repo}: git ${st[0]} falhou (${r.out.split('\n').pop()})`);
44
+ }
45
+ }
46
+ const head = git(['rev-parse', 'HEAD'], tmp).out;
47
+ if (head !== s.commit) {
48
+ rmSync(tmp, { recursive: true, force: true });
49
+ throw new Error(`${s.repo}: commit baixado (${head}) difere do fixado (${s.commit})`);
50
+ }
51
+ rmSync(join(tmp, '.git'), { recursive: true, force: true });
52
+ writeFileSync(join(tmp, DONE), JSON.stringify({ repo: s.repo, commit: s.commit, license: s.license }, null, 2) + '\n');
53
+ rmSync(dest, { recursive: true, force: true });
54
+ renameSync(tmp, dest);
55
+ return dest;
56
+ }
57
+ function isInside(child, parent) {
58
+ const rel = relative(parent, child);
59
+ return rel !== '' && !rel.startsWith('..') && !rel.startsWith(sep) && !/^[A-Za-z]:/.test(rel);
60
+ }
61
+ /** Cria o link da skill. Só substitui links que apontam para o nosso vendor. */
62
+ export function linkSkill(target, link, vendorDir) {
63
+ if (!existsSync(join(target, 'SKILL.md')))
64
+ return 'missing';
65
+ mkdirSync(dirname(link), { recursive: true });
66
+ let st;
67
+ try {
68
+ st = lstatSync(link);
69
+ }
70
+ catch {
71
+ st = undefined;
72
+ }
73
+ if (st) {
74
+ if (!st.isSymbolicLink())
75
+ return 'conflict';
76
+ const current = resolve(dirname(link), readlinkSync(link));
77
+ if (current === resolve(target))
78
+ return 'unchanged';
79
+ if (!isInside(current, resolve(vendorDir)))
80
+ return 'conflict';
81
+ unlinkSync(link);
82
+ symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir');
83
+ return 'updated';
84
+ }
85
+ symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir');
86
+ return 'linked';
87
+ }
88
+ function defaultRunClaude(args) {
89
+ return spawnSync('claude', args, { stdio: 'ignore', shell: process.platform === 'win32' }).status === 0;
90
+ }
91
+ export function installSkills(o) {
92
+ const report = { installed: [], skipped: [], plugins: [] };
93
+ const sources = new Map(o.manifest.sources.map((s) => [s.id, s]));
94
+ if (o.skillDirs.length > 0 && o.manifest.skills.length > 0) {
95
+ if (!o.dryRun && !hasGit()) {
96
+ for (const sk of o.manifest.skills)
97
+ report.skipped.push({ name: sk.name, reason: 'git não encontrado' });
98
+ }
99
+ else {
100
+ const fetched = new Map();
101
+ for (const sk of o.manifest.skills) {
102
+ const src = sources.get(sk.source);
103
+ if (!src) {
104
+ report.skipped.push({ name: sk.name, reason: `fonte "${sk.source}" ausente no manifest` });
105
+ continue;
106
+ }
107
+ if (o.dryRun) {
108
+ report.installed.push({ name: sk.name, source: src.repo, commit: src.commit, license: src.license, dirs: o.skillDirs });
109
+ continue;
110
+ }
111
+ let root = fetched.get(src.id);
112
+ if (!root) {
113
+ try {
114
+ o.log(` ↓ ${src.repo}@${src.commit.slice(0, 7)}`);
115
+ root = fetchSource(src, o.vendorDir);
116
+ fetched.set(src.id, root);
117
+ }
118
+ catch (e) {
119
+ fetched.set(src.id, '');
120
+ report.skipped.push({ name: sk.name, reason: e.message });
121
+ continue;
122
+ }
123
+ }
124
+ if (root === '') {
125
+ report.skipped.push({ name: sk.name, reason: `download de ${src.repo} falhou` });
126
+ continue;
127
+ }
128
+ const dirs = [];
129
+ for (const d of o.skillDirs) {
130
+ const r = linkSkill(join(root, sk.path), join(d, sk.name), o.vendorDir);
131
+ if (r === 'conflict')
132
+ report.skipped.push({ name: sk.name, reason: `${join(d, sk.name)} já existe e não é do the-crew` });
133
+ else if (r === 'missing')
134
+ report.skipped.push({ name: sk.name, reason: `SKILL.md não encontrado em ${sk.path}` });
135
+ else
136
+ dirs.push(d);
137
+ }
138
+ if (dirs.length)
139
+ report.installed.push({ name: sk.name, source: src.repo, commit: src.commit, license: src.license, dirs });
140
+ }
141
+ }
142
+ }
143
+ if (o.claudePlugins) {
144
+ const run = o.runClaude ?? defaultRunClaude;
145
+ const added = new Set();
146
+ for (const p of o.manifest.plugins) {
147
+ const command = `claude plugin marketplace add ${p.repo} && claude plugin install ${p.name}@${p.marketplace}`;
148
+ if (o.dryRun) {
149
+ report.plugins.push({ name: p.name, status: 'installed', command });
150
+ continue;
151
+ }
152
+ // O marketplace pode já existir (o oficial vem pré-instalado): a falha do add não impede o install.
153
+ if (!added.has(p.marketplace)) {
154
+ run(['plugin', 'marketplace', 'add', p.repo]);
155
+ added.add(p.marketplace);
156
+ }
157
+ const ok = run(['plugin', 'install', `${p.name}@${p.marketplace}`]);
158
+ report.plugins.push({ name: p.name, status: ok ? 'installed' : 'manual', command });
159
+ }
160
+ }
161
+ return report;
162
+ }
163
+ /** Regras de uso (campo note) das skills instaladas, por agente. */
164
+ export function skillRulesByAgent(m, installed) {
165
+ const out = new Map();
166
+ for (const s of m.skills) {
167
+ if (!s.note || !installed.includes(s.name))
168
+ continue;
169
+ for (const a of s.agents)
170
+ out.set(a, [...(out.get(a) ?? []), `\`${s.name}\`: ${s.note}`]);
171
+ }
172
+ return out;
173
+ }
174
+ /** Skills (de terceiros e do pacote) por agente, para listar nos subagentes. */
175
+ export function skillsByAgent(m, installed) {
176
+ const out = new Map();
177
+ const add = (agent, name) => out.set(agent, [...(out.get(agent) ?? []), name]);
178
+ for (const s of m.skills)
179
+ if (installed.includes(s.name))
180
+ for (const a of s.agents)
181
+ add(a, s.name);
182
+ for (const p of m.plugins)
183
+ for (const a of p.agents)
184
+ add(a, `${p.name} (plugin)`);
185
+ return out;
186
+ }
@@ -17,6 +17,17 @@ export function upsertBlock(existing, content, comment) {
17
17
  const sep = existing === '' ? '' : existing.endsWith('\n') ? '\n' : '\n\n';
18
18
  return { text: `${existing}${sep}${block}\n`, replaced: false };
19
19
  }
20
+ /** Tira o bloco gerenciado de um texto. `found` diz se havia bloco. */
21
+ export function removeBlock(existing, comment) {
22
+ const [b, e] = markers(comment);
23
+ const start = existing.indexOf(b);
24
+ const end = existing.indexOf(e);
25
+ if (start === -1 || end < start)
26
+ return { text: existing, found: false };
27
+ const before = existing.slice(0, start).replace(/\n{2,}$/, '\n');
28
+ const after = existing.slice(end + e.length).replace(/^\r?\n/, '');
29
+ return { text: before + after, found: true };
30
+ }
20
31
  export class SafeWriter {
21
32
  opts;
22
33
  results = [];
@@ -88,7 +99,7 @@ export class SafeWriter {
88
99
  }
89
100
  if (!exists) {
90
101
  this.put(w.path, merged.text);
91
- return { path: w.path, outcome: 'created' };
102
+ return { path: w.path, outcome: 'created', added: merged.added };
92
103
  }
93
104
  if (merged.added.length === 0)
94
105
  return { path: w.path, outcome: 'unchanged' };
@@ -98,7 +109,7 @@ export class SafeWriter {
98
109
  return { path: w.path, outcome: 'skipped' };
99
110
  }
100
111
  this.put(w.path, merged.text);
101
- return { path: w.path, outcome: 'merged' };
112
+ return { path: w.path, outcome: 'merged', added: merged.added };
102
113
  }
103
114
  async writeBlock(w) {
104
115
  const exists = existsSync(w.path);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "the-crew",
3
- "version": "0.1.0",
4
- "description": "Instala o escritório de 17 agentes de IA (planejamento, desenvolvimento, testes e deploy) em qualquer repositório.",
3
+ "version": "0.3.0",
4
+ "description": "Um time de 17 agentes de IA (planejamento, desenvolvimento, testes e deploy), instalado uma vez na máquina, que cria e administra todos os seus projetos.",
5
5
  "license": "MIT",
6
6
  "author": "Rafael Viana",
7
7
  "type": "module",
@@ -30,7 +30,14 @@
30
30
  "type": "git",
31
31
  "url": "git+https://github.com/maregaRafa/the-crew.git"
32
32
  },
33
- "keywords": ["ai-agents", "claude-code", "cursor", "multi-agent", "cli", "obsidian"],
33
+ "keywords": [
34
+ "ai-agents",
35
+ "claude-code",
36
+ "cursor",
37
+ "multi-agent",
38
+ "cli",
39
+ "obsidian"
40
+ ],
34
41
  "devDependencies": {
35
42
  "@types/node": "^22.10.0",
36
43
  "typescript": "^5.7.0"
@@ -4,13 +4,11 @@ projeto: "{{projectName}}"
4
4
  repo: "{{projectDir}}"
5
5
  ---
6
6
 
7
- # {{projectName}}: painel do time
7
+ # {{projectName}}
8
8
 
9
- Caderno do time the-crew para este projeto. O repositório é a fonte de verdade; aqui ficam resumos ligados entre si. Criado em {{date}}.
9
+ Projeto administrado pelo [[00 Time|time the-crew]]. O repositório é a fonte de verdade; aqui ficam resumos ligados entre si. Criado em {{date}}.
10
10
 
11
- ## Times
12
-
13
- {{teamLinks}}
11
+ {{description}}
14
12
 
15
13
  ## Fluxo
16
14
 
@@ -25,4 +23,4 @@ Caderno do time the-crew para este projeto. O repositório é a fonte de verdade
25
23
 
26
24
  - `01 Produto` · `02 Backlog` · `03 Decisões` · `04 Handoffs` · `05 Gates` · `06 Releases` · `07 Runs`
27
25
  - Notas dos agentes em `Agentes/`. Abra a visão de grafo para ver quem fala com quem.
28
- - Modelos em `_templates/` (Templates do Obsidian: aponte "Template folder location" para esta pasta).
26
+ - Modelos em `the-crew/_templates/`.
@@ -0,0 +1,20 @@
1
+ ---
2
+ tags: [the-crew, painel]
3
+ ---
4
+
5
+ # the-crew: o time
6
+
7
+ Caderno do time the-crew. Um time só, vários projetos. Cada repositório é a fonte de verdade do seu projeto; aqui ficam resumos ligados entre si. Criado em {{date}}.
8
+
9
+ ## Times
10
+
11
+ {{teamLinks}}
12
+
13
+ ## Projetos
14
+
15
+ Criados com **/new-project**. Lista em [[Projetos]]; cada projeto tem a própria pasta em `Projetos/`.
16
+
17
+ ## Como ler
18
+
19
+ - `Agentes/`: uma nota por agente, com quem ele conversa (wikilinks), o que é dono e o que lê. Abra a visão de grafo para ver a rede do time.
20
+ - `_templates/`: modelos de Handoff, ADR, História, Bug, Achado de segurança, Release e Run (Templates do Obsidian: aponte "Template folder location" para esta pasta).
@@ -0,0 +1,12 @@
1
+ # the-crew: escritório do time
2
+
3
+ Esta pasta é o escritório do **the-crew** {{version}}: 17 agentes em quatro times (Planeja, Desenvolve, Testa, Deploy) que administram todos os projetos do humano. O humano é a autoridade final.
4
+
5
+ ## Comandos
6
+
7
+ - **/new-project**: cria um projeto novo (repositório local, `PROJECT.md`, pasta no vault, registro em `projects.json` e, se pedido, repositório no GitHub) e passa a palavra ao Product Owner.
8
+ - **/projects**: lista os projetos administrados pelo time e o estado de cada um.
9
+
10
+ {{agentTable}}
11
+
12
+ {{teamRules}}
@@ -0,0 +1,15 @@
1
+ # Escritório the-crew
2
+
3
+ Pasta criada por `npx the-crew` em {{date}}. Aqui mora o time de 17 agentes, que é um só para todos os seus projetos.
4
+
5
+ | Caminho | Conteúdo |
6
+ |---|---|
7
+ | `agents/` | Specs completas dos agentes, uma pasta por time |
8
+ | `contracts/topology.json` | Canais, donos de artefatos e ordem dos gates (`npx the-crew validate`) |
9
+ | `skills/` | Skills do time e catálogo de skills recomendadas |
10
+ | `projects.json` | Projetos administrados pelo time (`/new-project` acrescenta) |
11
+ | `AGENTS.md`, `CLAUDE.md` | Instruções para o assistente quando aberto nesta pasta |
12
+
13
+ Os projetos ficam em `{{projectsDir}}`, cada um no seu repositório. Para criar um, abra seu assistente (em qualquer pasta) e use **/new-project**.
14
+
15
+ Esta pasta é um repositório git: versione as mudanças que fizer nas specs. Rodar `npx the-crew` de novo atualiza o time sem apagar o que você mudou (arquivos alterados só são sobrescritos com sua confirmação).
@@ -0,0 +1,5 @@
1
+ # {{projectName}}
2
+
3
+ Este repositório é administrado pelo time **the-crew** (escritório em `{{officeDir}}`). Comece por `PROJECT.md`. Contexto local da máquina (vault, escritório): `.the-crew/local.json`, fora do git.
4
+
5
+ {{teamRules}}
@@ -0,0 +1,31 @@
1
+ # {{projectName}}
2
+
3
+ > Projeto administrado pelo time the-crew. O **Product Owner** lê este arquivo primeiro, aponta lacunas num `gap-report.md` e transforma o resultado em escopo de MVP, épicos e histórias. O que faltar vira pergunta.
4
+
5
+ ## Problema
6
+
7
+ {{description}}
8
+
9
+ ## Usuários
10
+
11
+ Quem usa? Quais papéis existem?
12
+
13
+ ## O que o produto precisa fazer
14
+
15
+ -
16
+
17
+ ## Fora do escopo (por enquanto)
18
+
19
+ -
20
+
21
+ ## Restrições
22
+
23
+ Prazo, orçamento, compliance (LGPD etc.), integrações obrigatórias.
24
+
25
+ ## Preferências técnicas
26
+
27
+ Stack desejada, banco, hospedagem (padrão do time: GitHub + Docker + Railway).
28
+
29
+ ## Como saber que deu certo
30
+
31
+ Uma métrica principal e o que não pode piorar.
@@ -0,0 +1,14 @@
1
+ ## Regras do time the-crew
2
+
3
+ - O time é um só e administra vários projetos. A lista de projetos fica em `{{officeDir}}/projects.json`. Cada projeto é um repositório próprio.
4
+ - Specs completas dos 17 agentes: `{{officeDir}}/agents/<time>/<agente>.md`. Leia a spec do papel antes de agir. Contratos (quem fala com quem, dono de cada artefato, ordem dos gates): `{{officeDir}}/contracts/topology.json`.
5
+ - Portas de entrada: **Product Owner** para escopo (ideias, backlog, épicos, histórias, AC) e **Orchestrator** para execução (histórias `status:ready`, despacho, gates, aceite).
6
+ - Cada agente escreve só nos artefatos de que é dono ou writer. Handoffs por tarefa em `.agents/handoffs/TASK-xx.y.n.md` do projeto, cada agente na própria seção; plano em `.agents/plan/dag.json`; log em `.agents/runs/<run-id>.jsonl`.
7
+ - Ordem canônica dos gates:
8
+ - **TASK:** CI verde → Code Reviewer (+ SecOps se label `security-review`; + Database Organizer se toca `db/`; + design review do UX/UI se é UI) e testes da camada → merge.
9
+ - **História:** QA E2E em staging → matriz de AC pelo Orchestrator → aceite do PO.
10
+ - **Release:** veredito do QA + parecer do SecOps → go/no-go do Infra & Release → aprovação humana → deploy do DevOps.
11
+ - Escale ao humano, e espere, antes de: deploy em produção, migração destrutiva, mudança de escopo e aceite de risco Critical/High.
12
+ - Commits em Conventional Commits; branch por tarefa `task/TASK-xx.y.n-slug`.
13
+ - Obsidian: se o projeto tem `vaultProjectDir` em `.the-crew/local.json`, espelhe cada artefato numa nota-resumo nessa pasta (skill `crew-obsidian`). O repositório é a fonte de verdade.
14
+ - Segredos: o token do GitHub fica fora dos repositórios e chega só pela variável `GITHUB_PERSONAL_ACCESS_TOKEN` quando a sessão é aberta com `the-crew exec -- <comando>`. Nunca imprima, registre, commite nem cole tokens em arquivos, issues, PRs ou notas.