the-crew 0.0.0-stage → 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 (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -2
  3. package/core/agents/README.md +268 -0
  4. package/core/agents/deploy/devops.md +435 -0
  5. package/core/agents/deploy/infra-release.md +396 -0
  6. package/core/agents/desenvolve/backend-dev.md +462 -0
  7. package/core/agents/desenvolve/code-reviewer.md +443 -0
  8. package/core/agents/desenvolve/database-organizer.md +469 -0
  9. package/core/agents/desenvolve/frontend-dev.md +423 -0
  10. package/core/agents/desenvolve/orchestrator.md +456 -0
  11. package/core/agents/desenvolve/tech-lead.md +416 -0
  12. package/core/agents/planeja/architect.md +379 -0
  13. package/core/agents/planeja/product-manager.md +381 -0
  14. package/core/agents/planeja/product-owner.md +426 -0
  15. package/core/agents/planeja/technical-writer.md +344 -0
  16. package/core/agents/planeja/ux-ui-design.md +406 -0
  17. package/core/agents/testa/backend-tester.md +454 -0
  18. package/core/agents/testa/frontend-tester.md +371 -0
  19. package/core/agents/testa/qa.md +426 -0
  20. package/core/agents/testa/secops.md +450 -0
  21. package/core/contracts/topology.json +1956 -0
  22. package/core/skills/crew-gates/SKILL.md +35 -0
  23. package/core/skills/crew-handoff/SKILL.md +37 -0
  24. package/core/skills/crew-obsidian/SKILL.md +25 -0
  25. package/core/skills/db-organizer/SKILL.md +15 -0
  26. package/core/skills/manifest.json +791 -0
  27. package/core/skills/new-project/SKILL.md +27 -0
  28. package/core/skills/po-backlog/SKILL.md +17 -0
  29. package/core/skills/projects/SKILL.md +10 -0
  30. package/dist/scripts/validate-contracts.js +14 -0
  31. package/dist/src/cli/commands/exec.js +29 -0
  32. package/dist/src/cli/commands/install.js +300 -0
  33. package/dist/src/cli/commands/login.js +19 -0
  34. package/dist/src/cli/commands/new-project.js +86 -0
  35. package/dist/src/cli/commands/projects.js +24 -0
  36. package/dist/src/cli/commands/uninstall.js +308 -0
  37. package/dist/src/cli/commands/validate.js +21 -0
  38. package/dist/src/cli/index.js +53 -0
  39. package/dist/src/cli/lib/args.js +172 -0
  40. package/dist/src/cli/lib/common.js +120 -0
  41. package/dist/src/cli/lib/credentials.js +101 -0
  42. package/dist/src/cli/lib/github.js +36 -0
  43. package/dist/src/cli/lib/install-record.js +39 -0
  44. package/dist/src/cli/lib/legacy.js +230 -0
  45. package/dist/src/cli/lib/paths.js +26 -0
  46. package/dist/src/cli/lib/plans.js +251 -0
  47. package/dist/src/cli/lib/prompt.js +104 -0
  48. package/dist/src/cli/lib/registry.js +21 -0
  49. package/dist/src/cli/lib/skills.js +186 -0
  50. package/dist/src/cli/lib/writer.js +169 -0
  51. package/dist/src/validate/report.js +13 -0
  52. package/dist/src/validate/topology.js +240 -0
  53. package/package.json +43 -4
  54. package/templates/obsidian/project/00 Painel.md +26 -0
  55. package/templates/obsidian/team/00 Time.md +20 -0
  56. package/templates/obsidian/team/_templates/ADR.md +14 -0
  57. package/templates/obsidian/team/_templates/Achado de seguranca.md +15 -0
  58. package/templates/obsidian/team/_templates/Bug.md +14 -0
  59. package/templates/obsidian/team/_templates/Handoff.md +24 -0
  60. package/templates/obsidian/team/_templates/Historia.md +19 -0
  61. package/templates/obsidian/team/_templates/Release.md +18 -0
  62. package/templates/obsidian/team/_templates/Run.md +12 -0
  63. package/templates/office/AGENTS.md +12 -0
  64. package/templates/office/README.md +15 -0
  65. package/templates/project/AGENTS.md +5 -0
  66. package/templates/project/PROJECT.md +31 -0
  67. package/templates/rules/team.md +14 -0
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: new-project
3
+ description: Cria um projeto novo administrado pelo time the-crew (repositório local, PROJECT.md, pasta no vault do Obsidian, registro e, se pedido, repositório no GitHub) e inicia o planejamento com o Product Owner. Use quando o humano pedir /new-project ou quiser começar um projeto.
4
+ ---
5
+
6
+ # /new-project
7
+
8
+ Você está abrindo um projeto novo para o time the-crew. O escritório do time fica em `{{officeDir}}`.
9
+
10
+ 1. **Pergunte de uma vez só**, e espere a resposta:
11
+ - nome do projeto;
12
+ - em 1 a 3 frases, o problema que ele resolve e para quem;
13
+ - se quer um repositório no GitHub também, e se privado (padrão) ou público.
14
+ Se o humano já deu essas informações na mensagem, não pergunte de novo.
15
+
16
+ 2. **Crie o projeto** com o CLI (não crie os arquivos à mão):
17
+
18
+ ```bash
19
+ {{crewCli}} new-project "<nome>" --description "<descrição>" [--github] [--public]
20
+ ```
21
+
22
+ O comando cria o repositório em `{{projectsDir}}/<slug>`, roda `git init`, grava `PROJECT.md`, `AGENTS.md`, `CLAUDE.md`, `.agents/`, `.gitignore` e os MCPs; cria a pasta do projeto no vault do Obsidian; registra o projeto em `{{officeDir}}/projects.json`. Com `--github`, cria o repositório remoto com o token salvo e configura o `origin`.
23
+ O token nunca aparece na saída. Se o comando falhar, mostre a mensagem de erro ao humano e pare.
24
+
25
+ 3. **Passe ao Product Owner**: leia a spec `{{officeDir}}/agents/planeja/product-owner.md` (no Claude Code, delegue ao subagente `crew-product-owner`) e comece pelo `PROJECT.md` do projeto novo: complete o que der com o que o humano disse e liste as lacunas como perguntas no `docs/product/backlog/gap-report.md`.
26
+
27
+ 4. **Responda ao humano** com: caminho do projeto, link do repositório no GitHub (se criado), pasta no vault (se houver) e as primeiras perguntas do Product Owner.
@@ -0,0 +1,17 @@
1
+ ---
2
+ name: po-backlog
3
+ description: Transformar PROJECT.md ou um PRD em gap report, escopo de MVP, épicos, histórias e critérios de aceite em Gherkin no formato do the-crew. Use quando o Product Owner planeja ou refina o backlog.
4
+ ---
5
+
6
+ # Backlog do Product Owner
7
+
8
+ Spec completa: `{{officeDir}}/agents/planeja/product-owner.md`.
9
+
10
+ 1. **Gap report** (`docs/product/backlog/gap-report.md`): lacunas, ambiguidades e perguntas ao humano sobre `PROJECT.md` ou `prd.md`. Proponha IDs `REQ-###` se faltarem.
11
+ 2. **MVP** (`docs/product/mvp-scope.md`): dentro, fora e por quê.
12
+ 3. **Épicos** (`docs/product/backlog/EP-xx.md`): fatias verticais de valor, com `after` / `blocked-by`.
13
+ 4. **Histórias** (`docs/product/backlog/US-xx.y.md`): "Como / quero / para", INVEST, rastreadas a `REQ-###`.
14
+ 5. **AC** (`features/*.feature`): Gherkin com tags `@EP-xx @US-xx.y @AC-xx.y.n @REQ-###`.
15
+ 6. **Definition of Ready**: AC testáveis, spec de UI quando há tela, dependências conhecidas. Só então marque `status:ready`, o que dispara o Orchestrator.
16
+
17
+ Mudança de escopo depois do MVP aprovado vai ao humano e é registrada na seção "Backlog/Escopo" de `docs/product/decisions-log.md`.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: projects
3
+ description: Lista os projetos administrados pelo time the-crew, com caminho, repositório no GitHub e pasta no vault. Use quando o humano pedir /projects ou perguntar em que projetos o time trabalha.
4
+ ---
5
+
6
+ # /projects
7
+
8
+ 1. Rode `{{crewCli}} projects --json` (ou leia `{{officeDir}}/projects.json`).
9
+ 2. Para cada projeto, mostre nome, caminho local, repositório no GitHub e data de criação. Se o caminho não existir mais, avise.
10
+ 3. Se o humano escolher um projeto, trabalhe a partir do caminho dele: leia `PROJECT.md` e o backlog em `docs/product/backlog/` para dizer em que fase o projeto está (planejamento, execução, release).
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Valida a simetria dos contratos entre os 17 agentes.
3
+ * Uso: npm run validate [-- <raiz>] (padrão: raiz do pacote)
4
+ * Sai com código 1 se houver erro.
5
+ */
6
+ import { join, resolve } from 'node:path';
7
+ import { packageRoot } from '../src/cli/lib/paths.js';
8
+ import { formatReport } from '../src/validate/report.js';
9
+ import { loadTopology, validateTopology } from '../src/validate/topology.js';
10
+ const root = process.argv[2] ? resolve(process.argv[2]) : packageRoot();
11
+ const file = join(root, 'core', 'contracts', 'topology.json');
12
+ const result = validateTopology(loadTopology(file), root);
13
+ console.log(formatReport(result, file));
14
+ process.exitCode = result.errors.length > 0 ? 1 : 0;
@@ -0,0 +1,29 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readCredentials, tokenEnv } from '../lib/credentials.js';
3
+ /**
4
+ * Executa um comando com o token do GitHub só no ambiente do processo filho.
5
+ * Ex.: npx the-crew exec -- claude
6
+ * O token não vai para o histórico do shell, para o perfil nem para arquivos do projeto.
7
+ */
8
+ export function runExec(argv, log, env = process.env) {
9
+ if (argv.length === 0) {
10
+ log('Uso: the-crew exec -- <comando> [args...]');
11
+ return Promise.resolve(2);
12
+ }
13
+ const gh = readCredentials(env).github;
14
+ if (!gh)
15
+ log('! Nenhum token salvo. Rode `npx the-crew@latest` ou `npx the-crew login`. Executando sem token.');
16
+ const [cmd, ...args] = argv;
17
+ return new Promise((resolveExit) => {
18
+ const child = spawn(cmd, args, {
19
+ stdio: 'inherit',
20
+ env: { ...env, ...(gh ? tokenEnv(gh.token) : {}) },
21
+ shell: process.platform === 'win32',
22
+ });
23
+ child.on('error', (e) => {
24
+ log(`Não consegui executar "${cmd}": ${e.message}`);
25
+ resolveExit(127);
26
+ });
27
+ child.on('exit', (code) => resolveExit(code ?? 1));
28
+ });
29
+ }
@@ -0,0 +1,300 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { loadTopology } from '../../validate/topology.js';
6
+ import { IDE_OPTIONS, MCP_OPTIONS } from '../lib/common.js';
7
+ import { maskToken, readCredentials, readGlobalConfig, saveGithubToken, tokenKind, userHome, verifyGithubToken, writeGlobalConfig, } from '../lib/credentials.js';
8
+ import { updateInstallRecord } from '../lib/install-record.js';
9
+ import { packageRoot, packageVersion } from '../lib/paths.js';
10
+ import { planAssistants, planOffice, planVaultProject, planVaultTeam, vaultProjectDir } from '../lib/plans.js';
11
+ import { projectList, readRegistry, writeRegistry } from '../lib/registry.js';
12
+ import { installSkills, loadManifest, skillRulesByAgent, skillsByAgent } from '../lib/skills.js';
13
+ import { SafeWriter, summarize } from '../lib/writer.js';
14
+ export function expandHome(p, home) {
15
+ return p === '~' || p.startsWith('~/') || p.startsWith('~\\') ? join(home, p.slice(1)) : p;
16
+ }
17
+ /**
18
+ * Caminho colado pelo usuário, como ele chega do terminal ou do Finder:
19
+ * tira espaços das pontas e aspas, desfaz escapes do shell (`Mobile\ Documents`,
20
+ * `iCloud\~md\~obsidian`), aceita `file://` e expande `~`. No Windows a barra
21
+ * invertida é separador, então não é tratada como escape.
22
+ */
23
+ export function normalizeUserPath(input, home, platform = process.platform) {
24
+ let p = input.trim();
25
+ if (/^(["']).*\1$/.test(p))
26
+ p = p.slice(1, -1).trim();
27
+ if (p.startsWith('file://')) {
28
+ try {
29
+ p = fileURLToPath(p);
30
+ }
31
+ catch {
32
+ /* segue com o texto */
33
+ }
34
+ }
35
+ else if (platform !== 'win32') {
36
+ p = p.replace(/\\(.)/g, '$1');
37
+ }
38
+ if (p.length > 1 && !/^[A-Za-z]:[\\/]$/.test(p))
39
+ p = p.replace(/[\\/]+$/, '');
40
+ return resolve(expandHome(p, home));
41
+ }
42
+ function isDir(p) {
43
+ try {
44
+ return statSync(p).isDirectory();
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ async function askVault(flags, deps, home, current) {
51
+ const { prompter, log } = deps;
52
+ if (flags.vault === false)
53
+ return null;
54
+ let candidate = typeof flags.vault === 'string' ? flags.vault : undefined;
55
+ if (candidate === undefined) {
56
+ if (!prompter.interactive)
57
+ return current;
58
+ if (!(await prompter.confirm('Integrar com um vault do Obsidian?', true)))
59
+ return null;
60
+ }
61
+ for (let attempt = 0; attempt < 3; attempt++) {
62
+ if (!candidate) {
63
+ candidate = await prompter.text('Cole o caminho do vault do Obsidian', current ?? '');
64
+ if (!candidate.trim())
65
+ return null;
66
+ }
67
+ const abs = normalizeUserPath(candidate, home);
68
+ if (!isDir(abs)) {
69
+ const why = existsSync(abs) ? 'existe, mas não é uma pasta' : 'não foi encontrada';
70
+ log(` ✗ A pasta ${abs} ${why}.`);
71
+ if (abs.includes('Mobile Documents')) {
72
+ log(' Vault no iCloud: confira o nome em Finder > iCloud Drive > Obsidian, ou no Obsidian em "Gerenciar vaults".');
73
+ }
74
+ if (!prompter.interactive)
75
+ throw new Error(`Vault do Obsidian não encontrado. Caminho testado: ${abs}`);
76
+ candidate = undefined;
77
+ continue;
78
+ }
79
+ if (!existsSync(join(abs, '.obsidian')) && existsSync(join(abs, '.obsidian.icloud'))) {
80
+ log(` ! ${abs} está no iCloud e ainda não foi baixado neste computador. Vou usá-lo mesmo assim;`);
81
+ log(' para baixar, abra o vault no Obsidian ou, no Finder, clique com o botão direito e escolha "Baixar agora".');
82
+ return abs;
83
+ }
84
+ if (!existsSync(join(abs, '.obsidian'))) {
85
+ log(` ! ${abs} não tem a pasta .obsidian, então não parece um vault (o Obsidian cria essa pasta ao abrir o vault).`);
86
+ if (prompter.interactive && !(await prompter.confirm('Usar essa pasta mesmo assim?', false))) {
87
+ candidate = undefined;
88
+ continue;
89
+ }
90
+ }
91
+ return abs;
92
+ }
93
+ return null;
94
+ }
95
+ async function askGithub(flags, deps) {
96
+ const { prompter, log, env } = deps;
97
+ if (!flags.github)
98
+ return undefined;
99
+ let token = env.THE_CREW_GITHUB_TOKEN?.trim() ?? '';
100
+ const stored = readCredentials(env).github;
101
+ if (!token && stored && prompter.interactive) {
102
+ if (await prompter.confirm(`Já existe um token salvo para @${stored.login}. Manter?`, true))
103
+ return stored.login;
104
+ }
105
+ if (!token) {
106
+ if (!prompter.interactive)
107
+ return stored?.login;
108
+ if (!(await prompter.confirm('Configurar o GitHub (fine-grained token para repositórios, commits e deploys)?', true)))
109
+ return undefined;
110
+ log([
111
+ ' Crie um fine-grained token em https://github.com/settings/personal-access-tokens/new',
112
+ ' Para o /new-project criar repositórios: "All repositories" + Administration (read/write).',
113
+ ' Para os agentes trabalharem: Contents, Pull requests e Issues (read/write); Actions e Metadata (read);',
114
+ ' Workflows (read/write) só se os agentes forem editar o CI.',
115
+ ' O token fica salvo fora de qualquer repositório e nunca é exibido.',
116
+ ].join('\n'));
117
+ }
118
+ for (let attempt = 0; attempt < 3; attempt++) {
119
+ if (!token)
120
+ token = await prompter.secret('Cole o token (não aparece na tela)');
121
+ if (!token)
122
+ return undefined;
123
+ const kind = tokenKind(token);
124
+ if (kind === 'classic')
125
+ log(' ! Este é um token clássico. Prefira um fine-grained.');
126
+ if (kind === 'unknown')
127
+ log(' ! O formato não parece um token do GitHub (esperado: github_pat_…).');
128
+ const check = await verifyGithubToken(token, deps.fetchImpl);
129
+ if (check.ok) {
130
+ const where = saveGithubToken(token, check.login, env);
131
+ log(` ✓ Token ${maskToken(token)} válido para @${check.login}. Salvo em ${where}.`);
132
+ return check.login;
133
+ }
134
+ log(` ✗ Não consegui validar o token: ${check.reason}.`);
135
+ if (!prompter.interactive)
136
+ throw new Error(`Token do GitHub inválido: ${check.reason}`);
137
+ token = '';
138
+ }
139
+ return undefined;
140
+ }
141
+ export function gitInit(dir, log) {
142
+ if (existsSync(join(dir, '.git')))
143
+ return;
144
+ let r = spawnSync('git', ['init', '-b', 'main'], { cwd: dir, stdio: 'ignore' });
145
+ if (r.status !== 0)
146
+ r = spawnSync('git', ['init'], { cwd: dir, stdio: 'ignore' });
147
+ if (r.status !== 0)
148
+ log(` ! git não encontrado; rode \`git init\` em ${dir} depois.`);
149
+ }
150
+ /** Defesa em profundidade: o token não pode aparecer em nenhum arquivo gravado. */
151
+ export function assertNoTokenLeak(results, token) {
152
+ if (!token)
153
+ return;
154
+ for (const r of results) {
155
+ if (existsSync(r.path) && statSync(r.path).isFile() && readFileSync(r.path, 'utf8').includes(token)) {
156
+ throw new Error(`Falha de segurança: o token apareceu em ${r.path}. Apague o arquivo e revogue o token.`);
157
+ }
158
+ }
159
+ }
160
+ export function buildCtx(env, cfg) {
161
+ const pkgRoot = packageRoot();
162
+ return {
163
+ pkgRoot,
164
+ version: packageVersion(),
165
+ topology: loadTopology(join(pkgRoot, 'core', 'contracts', 'topology.json')),
166
+ home: userHome(env),
167
+ date: new Date().toISOString().slice(0, 10),
168
+ ...cfg,
169
+ };
170
+ }
171
+ /** Instala o time uma vez na máquina: escritório, registro global nos assistentes, vault e GitHub. */
172
+ export async function runInstall(flags, deps) {
173
+ const { prompter, log, env } = deps;
174
+ const home = userHome(env);
175
+ const prev = readGlobalConfig(env);
176
+ log(`\nthe-crew v${packageVersion()}: instalando o time de 17 agentes nesta máquina\n`);
177
+ if (prev)
178
+ log(` Já instalado em ${prev.officeDir}. Vou atualizar sem sobrescrever o que você mudou.\n`);
179
+ const officeDir = normalizeUserPath(flags.office ?? (await prompter.text('Pasta do escritório do time (repositório local)', prev?.officeDir ?? join(home, 'the-crew'))), home);
180
+ const projectsDir = normalizeUserPath(flags.projectsDir ?? (await prompter.text('Pasta onde os projetos novos serão criados', prev?.projectsDir ?? join(home, 'projetos'))), home);
181
+ const ides = flags.ides ?? (await prompter.multiselect('Quais assistentes você usa?', IDE_OPTIONS, prev?.ides ?? ['claude-code']));
182
+ const mcp = flags.mcp ?? (await prompter.multiselect('Quais MCPs recomendados configurar?', MCP_OPTIONS, prev?.mcp ?? ['github', 'context7']));
183
+ const vaultPath = await askVault(flags, deps, home, prev?.vaultPath ?? null);
184
+ const githubLogin = await askGithub(flags, deps);
185
+ const ctx = buildCtx(env, { officeDir, projectsDir, vaultPath, ides, mcp });
186
+ const all = [];
187
+ const section = async (title, root, plan) => {
188
+ if (plan.length === 0)
189
+ return;
190
+ const w = new SafeWriter({ prompter, force: flags.force, dryRun: flags.dryRun, displayRoot: root });
191
+ await w.apply(plan);
192
+ log(`\n${flags.dryRun ? '(dry-run) ' : ''}${title} (${root}):`);
193
+ log(summarize(w.results, root));
194
+ all.push(...w.results);
195
+ return w.results;
196
+ };
197
+ if (!flags.dryRun) {
198
+ mkdirSync(officeDir, { recursive: true });
199
+ mkdirSync(projectsDir, { recursive: true });
200
+ if (flags.gitInit)
201
+ gitInit(officeDir, log);
202
+ }
203
+ await section('Escritório do time', officeDir, planOffice(ctx));
204
+ if (flags.skills) {
205
+ const manifest = deps.skillManifest ?? loadManifest(ctx.pkgRoot);
206
+ const skillDirs = [
207
+ ...(ides.includes('claude-code') ? [join(home, '.claude', 'skills')] : []),
208
+ ...(ides.includes('codex') ? [join(home, '.agents', 'skills')] : []),
209
+ ];
210
+ log(`\n${flags.dryRun ? '(dry-run) ' : ''}Skills de terceiros (commits fixados em skills/manifest.json):`);
211
+ const report = installSkills({
212
+ manifest,
213
+ vendorDir: join(officeDir, 'vendor'),
214
+ skillDirs,
215
+ claudePlugins: ides.includes('claude-code'),
216
+ dryRun: flags.dryRun,
217
+ log,
218
+ runClaude: deps.runClaude,
219
+ });
220
+ const installedNames = report.installed.map((i) => i.name);
221
+ ctx.agentSkills = skillsByAgent(manifest, installedNames);
222
+ ctx.agentSkillRules = skillRulesByAgent(manifest, installedNames);
223
+ log(skillSummary(report, skillDirs));
224
+ if (!flags.dryRun) {
225
+ writeFileSync(join(officeDir, 'skills', 'installed.json'), JSON.stringify({ installedAt: new Date().toISOString(), ...report }, null, 2) + '\n');
226
+ }
227
+ }
228
+ const assistantsPlan = planAssistants(ctx);
229
+ const assistantsResults = await section('Assistentes (registro global)', home, assistantsPlan);
230
+ if (vaultPath) {
231
+ const projects = existsSync(officeDir) ? projectList(readRegistry(officeDir)) : [];
232
+ // Projetos criados antes do vault (ou com outro vault) ganham a pasta deles agora.
233
+ const toLink = projects.filter((p) => p.vaultDir !== vaultProjectDir(vaultPath, p.slug) || !existsSync(p.vaultDir));
234
+ const vaultPlan = [
235
+ ...planVaultTeam(ctx, projects),
236
+ ...toLink.flatMap((p) => planVaultProject(ctx, { ...p, vaultDir: vaultProjectDir(vaultPath, p.slug) }, projects)),
237
+ ];
238
+ await section('Vault do Obsidian', vaultPath, vaultPlan);
239
+ if (toLink.length && !flags.dryRun)
240
+ linkProjectsToVault(officeDir, vaultPath, toLink.map((p) => p.slug), log);
241
+ }
242
+ assertNoTokenLeak(all, githubLogin ? readCredentials(env).github?.token : undefined);
243
+ if (!flags.dryRun) {
244
+ if (assistantsResults)
245
+ updateInstallRecord(env, assistantsPlan, assistantsResults);
246
+ writeGlobalConfig({ version: ctx.version, officeDir, projectsDir, vaultPath, ides, mcp, installedAt: prev?.installedAt ?? new Date().toISOString() }, env);
247
+ }
248
+ const cmdHint = ides.includes('codex') && !ides.includes('claude-code') ? '$new-project' : '/new-project';
249
+ log([
250
+ '',
251
+ 'Time instalado. Próximos passos:',
252
+ ` 1. Abra seu assistente${githubLogin ? ' com o token só nessa sessão: npx the-crew exec -- claude' : ''}.`,
253
+ ` 2. Peça ${cmdHint} e descreva a ideia. O time cria o repositório, o PROJECT.md e a pasta no vault, e o Product Owner começa o planejamento.`,
254
+ ...(ides.some((i) => i === 'cursor' || i === 'windsurf')
255
+ ? [` No Cursor/Windsurf, os /comandos aparecem com o escritório (${officeDir}) ou um projeto aberto.`]
256
+ : []),
257
+ '',
258
+ `Skills instaladas e as que ficaram de fora: ${join(officeDir, 'skills', 'installed.json')} e skills/manifest.json.`,
259
+ ].join('\n'));
260
+ return 0;
261
+ }
262
+ /** Atualiza o registro e o .the-crew/local.json dos projetos com a pasta deles no vault. */
263
+ function linkProjectsToVault(officeDir, vaultPath, slugs, log) {
264
+ const reg = readRegistry(officeDir);
265
+ for (const slug of slugs) {
266
+ const rec = reg.projects[slug];
267
+ if (!rec)
268
+ continue;
269
+ rec.vaultDir = vaultProjectDir(vaultPath, slug);
270
+ const local = join(rec.dir, '.the-crew', 'local.json');
271
+ if (existsSync(local)) {
272
+ try {
273
+ const data = JSON.parse(readFileSync(local, 'utf8'));
274
+ data.vaultProjectDir = rec.vaultDir;
275
+ writeFileSync(local, JSON.stringify(data, null, 2) + '\n', 'utf8');
276
+ }
277
+ catch {
278
+ log(` ! ${local} não é um JSON válido; ajuste vaultProjectDir à mão.`);
279
+ }
280
+ }
281
+ log(` ✓ Projeto ${rec.name} ligado ao vault: ${rec.vaultDir}`);
282
+ }
283
+ writeRegistry(officeDir, reg);
284
+ }
285
+ function skillSummary(r, dirs) {
286
+ const lines = [];
287
+ if (dirs.length === 0)
288
+ lines.push(' Nenhum assistente com pasta global de skills escolhido (Claude Code ou Codex).');
289
+ else
290
+ lines.push(` ${r.installed.length} skills registradas em ${dirs.join(' e ')}`);
291
+ const sources = [...new Set(r.installed.map((i) => i.source))];
292
+ if (sources.length)
293
+ lines.push(` de ${sources.join(', ')}`);
294
+ for (const p of r.plugins) {
295
+ lines.push(p.status === 'installed' ? ` ✓ plugin ${p.name}` : ` ! plugin ${p.name}: instale com \`${p.command}\``);
296
+ }
297
+ for (const s of r.skipped)
298
+ lines.push(` ! ${s.name}: ${s.reason}`);
299
+ return lines.join('\n');
300
+ }
@@ -0,0 +1,19 @@
1
+ import { maskToken, saveGithubToken, tokenKind, verifyGithubToken } from '../lib/credentials.js';
2
+ /** Salva ou troca o token do GitHub sem reinstalar nada. */
3
+ export async function runLogin(prompter, log, env) {
4
+ const token = env.THE_CREW_GITHUB_TOKEN?.trim() || (prompter.interactive ? await prompter.secret('Cole o fine-grained token (não aparece na tela)') : '');
5
+ if (!token) {
6
+ log('Nenhum token informado. Sem terminal interativo, use a variável THE_CREW_GITHUB_TOKEN.');
7
+ return 2;
8
+ }
9
+ if (tokenKind(token) === 'classic')
10
+ log('! Token clássico. Prefira um fine-grained com escopo só nos repositórios do projeto.');
11
+ const check = await verifyGithubToken(token);
12
+ if (!check.ok) {
13
+ log(`✗ Token não validado: ${check.reason}.`);
14
+ return 1;
15
+ }
16
+ const where = saveGithubToken(token, check.login, env);
17
+ log(`✓ Token ${maskToken(token)} de @${check.login} salvo em ${where}.`);
18
+ return 0;
19
+ }
@@ -0,0 +1,86 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readdirSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { slugify } from '../lib/common.js';
5
+ import { readCredentials, readGlobalConfig } from '../lib/credentials.js';
6
+ import { createGithubRepo } from '../lib/github.js';
7
+ import { planProject, planVaultProject, vaultProjectDir } from '../lib/plans.js';
8
+ import { projectList, readRegistry, writeRegistry } from '../lib/registry.js';
9
+ import { SafeWriter, summarize } from '../lib/writer.js';
10
+ import { assertNoTokenLeak, buildCtx, gitInit, normalizeUserPath } from './install.js';
11
+ /** Cria um projeto administrado pelo time. Chamado pelo /new-project dos assistentes. */
12
+ export async function runNewProject(flags, deps) {
13
+ const { log, env } = deps;
14
+ const cfg = readGlobalConfig(env);
15
+ if (!cfg)
16
+ throw new Error('O time não está instalado nesta máquina. Rode `npx the-crew@latest` primeiro.');
17
+ const name = (flags.name ?? (await deps.prompter.text('Nome do projeto'))).trim();
18
+ if (!name)
19
+ throw new Error('Informe o nome do projeto: the-crew new-project "<nome>".');
20
+ const slug = slugify(name);
21
+ const reg = readRegistry(cfg.officeDir);
22
+ if (reg.projects[slug])
23
+ throw new Error(`Já existe um projeto "${slug}" em ${reg.projects[slug].dir}.`);
24
+ const ctx = buildCtx(env, { ...cfg, ides: cfg.ides, mcp: cfg.mcp });
25
+ const dir = flags.dir ? normalizeUserPath(flags.dir, ctx.home) : resolve(join(cfg.projectsDir, slug));
26
+ if (existsSync(dir) && readdirSync(dir).length > 0) {
27
+ throw new Error(`${dir} já existe e não está vazia. Escolha outro nome ou passe --dir.`);
28
+ }
29
+ // Repositório remoto primeiro: se falhar, nada local fica pela metade.
30
+ let github = null;
31
+ let cloneUrl = null;
32
+ const token = readCredentials(env).github?.token;
33
+ if (flags.github) {
34
+ if (!token)
35
+ throw new Error('Nenhum token do GitHub salvo. Rode `the-crew login` ou crie o projeto sem --github.');
36
+ if (!flags.dryRun) {
37
+ const repo = await createGithubRepo(token, { name: slug, description: flags.description, private: !flags.public }, deps.fetchImpl);
38
+ github = repo.htmlUrl;
39
+ cloneUrl = repo.cloneUrl;
40
+ }
41
+ }
42
+ const info = {
43
+ name,
44
+ slug,
45
+ dir,
46
+ description: flags.description,
47
+ vaultDir: cfg.vaultPath ? vaultProjectDir(cfg.vaultPath, slug) : null,
48
+ github,
49
+ };
50
+ const record = { ...info, createdAt: new Date().toISOString() };
51
+ const all = [...projectList(reg), record];
52
+ if (!flags.dryRun) {
53
+ mkdirSync(dir, { recursive: true });
54
+ gitInit(dir, log);
55
+ if (cloneUrl)
56
+ spawnSync('git', ['remote', 'add', 'origin', cloneUrl], { cwd: dir, stdio: 'ignore' });
57
+ }
58
+ const pw = new SafeWriter({ prompter: deps.prompter, force: false, dryRun: flags.dryRun, displayRoot: dir });
59
+ await pw.apply(planProject(ctx, info));
60
+ const results = [...pw.results];
61
+ if (cfg.vaultPath) {
62
+ const vw = new SafeWriter({ prompter: deps.prompter, force: false, dryRun: flags.dryRun, displayRoot: cfg.vaultPath });
63
+ await vw.apply(planVaultProject(ctx, info, all));
64
+ results.push(...vw.results);
65
+ }
66
+ assertNoTokenLeak(results, token);
67
+ if (!flags.dryRun) {
68
+ reg.projects[slug] = record;
69
+ writeRegistry(cfg.officeDir, reg);
70
+ }
71
+ if (flags.json) {
72
+ log(JSON.stringify(record, null, 2));
73
+ }
74
+ else {
75
+ log(`${flags.dryRun ? '(dry-run) ' : ''}✓ Projeto "${name}" criado.`);
76
+ log(` Repositório local: ${dir}`);
77
+ if (github)
78
+ log(` GitHub: ${github} (origin configurado)`);
79
+ if (info.vaultDir)
80
+ log(` Vault: ${info.vaultDir}`);
81
+ log(` Registro: ${join(cfg.officeDir, 'projects.json')}`);
82
+ log(summarize(pw.results, dir));
83
+ log(' Próximo passo: o Product Owner lê o PROJECT.md e começa o planejamento.');
84
+ }
85
+ return 0;
86
+ }
@@ -0,0 +1,24 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readGlobalConfig } from '../lib/credentials.js';
3
+ import { projectList, readRegistry } from '../lib/registry.js';
4
+ export function runProjects(json, log, env) {
5
+ const cfg = readGlobalConfig(env);
6
+ if (!cfg) {
7
+ log('O time não está instalado nesta máquina. Rode `npx the-crew@latest`.');
8
+ return 2;
9
+ }
10
+ const list = projectList(readRegistry(cfg.officeDir)).map((p) => ({ ...p, exists: existsSync(p.dir) }));
11
+ if (json) {
12
+ log(JSON.stringify(list, null, 2));
13
+ return 0;
14
+ }
15
+ if (list.length === 0) {
16
+ log('Nenhum projeto ainda. Peça /new-project ao seu assistente.');
17
+ return 0;
18
+ }
19
+ for (const p of list) {
20
+ log(`• ${p.name} (${p.slug})${p.exists ? '' : ' [pasta não encontrada]'}`);
21
+ log(` ${p.dir}${p.github ? ` · ${p.github}` : ''}`);
22
+ }
23
+ return 0;
24
+ }