@spec-wave/cli 0.35.0 → 1.0.2
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/package.json +2 -2
- package/src/agent/anthropic-agent.mjs +35 -2
- package/src/api/github-rest.mjs +23 -0
- package/src/cli.mjs +42 -0
- package/src/commands/code-review.mjs +31 -17
- package/src/commands/decompose.mjs +75 -4
- package/src/commands/doctor.mjs +43 -3
- package/src/commands/implement.mjs +39 -6
- package/src/commands/init.mjs +147 -29
- package/src/commands/merge.mjs +11 -8
- package/src/commands/move.mjs +4 -7
- package/src/commands/order.mjs +2 -2
- package/src/commands/qa.mjs +22 -21
- package/src/commands/repair-stage.mjs +2 -5
- package/src/commands/repo.mjs +103 -0
- package/src/commands/story.mjs +2 -2
- package/src/commands/task.mjs +2 -2
- package/src/commands/triage.mjs +2 -5
- package/src/commands/update.mjs +31 -8
- package/src/commands/validate.mjs +2 -5
- package/src/commands/workspace.mjs +112 -0
- package/src/config.mjs +19 -0
- package/src/lib/artifact-pr.mjs +1 -1
- package/src/lib/claude.mjs +4 -0
- package/src/lib/decomposition-doc.mjs +56 -3
- package/src/lib/dependency-map.mjs +3 -0
- package/src/lib/flow-run.mjs +14 -3
- package/src/lib/pr-link.mjs +65 -10
- package/src/lib/pr-ready.mjs +6 -2
- package/src/lib/project-root.mjs +51 -0
- package/src/lib/repo-role.mjs +169 -0
- package/src/lib/workspace.mjs +151 -0
- package/src/plugin/.claude-plugin/plugin.json +1 -1
- package/src/plugin/skills/decompose/SKILL.md +1 -0
- package/src/plugin/skills/decompose/model-prompt.feature.md +4 -2
- package/src/plugin/skills/implement/SKILL.md +1 -1
- package/src/plugin/skills/setup/SKILL.md +19 -0
- package/src/setup/files.mjs +35 -13
- package/src/templates/skill/SKILL.md +21 -1
- package/src/templates/workflows/code/code-review.yml +60 -0
- package/src/templates/workflows/code/qa.yml +59 -0
- package/src/templates/workflows/pr-events.yml +116 -0
package/src/commands/init.mjs
CHANGED
|
@@ -8,13 +8,49 @@ import { runWizard } from '../ui/wizard.mjs';
|
|
|
8
8
|
import { setupProject } from '../setup/project.mjs';
|
|
9
9
|
import { setupLabels } from '../setup/labels.mjs';
|
|
10
10
|
import { setupFiles } from '../setup/files.mjs';
|
|
11
|
-
import { getFileContent } from '../api/github-rest.mjs';
|
|
12
|
-
import {
|
|
11
|
+
import { getFileContent, getOwnerType } from '../api/github-rest.mjs';
|
|
12
|
+
import {
|
|
13
|
+
CONFIG_FILE, AI_PROVIDERS, getProvider, DEFAULT_PROVIDER, PORTAL_URL, WORKFLOW_FILES, CODE_WORKFLOW_FILES,
|
|
14
|
+
ISSUE_TEMPLATE_FILES, STATUS_OPTIONS, ALL_LABELS, HUB_DISPATCH_SECRET,
|
|
15
|
+
} from '../config.mjs';
|
|
16
|
+
import { REPO_ROLES, DEFAULT_REPO_ROLE, parseRepoRef } from '../lib/repo-role.mjs';
|
|
13
17
|
|
|
14
18
|
const __dir = path.dirname(fileURLToPath(import.meta.url));
|
|
15
19
|
const pkg = JSON.parse(readFileSync(path.join(__dir, '..', '..', 'package.json'), 'utf-8'));
|
|
16
20
|
|
|
17
21
|
export async function init(options) {
|
|
22
|
+
// --- Papel (RFC-005) ---
|
|
23
|
+
// hub: issues, documentos, labels, Project e os workflows do fluxo.
|
|
24
|
+
// code: só branch e PR — recebe os despachantes e um .spec-wave.json que
|
|
25
|
+
// aponta para o hub. Não há wizard para o repo de código: são duas flags.
|
|
26
|
+
const role = String(options.role ?? DEFAULT_REPO_ROLE).toLowerCase();
|
|
27
|
+
if (!REPO_ROLES.includes(role)) {
|
|
28
|
+
p.log.error(`--role inválido: "${options.role}". Use um de: ${REPO_ROLES.join(', ')}`);
|
|
29
|
+
process.exit(1);
|
|
30
|
+
}
|
|
31
|
+
let hub = null;
|
|
32
|
+
if (role === 'code') {
|
|
33
|
+
if (!options.repo || !options.hub) {
|
|
34
|
+
p.log.error(
|
|
35
|
+
'Um repositório de código precisa de --repo <owner/repo> e --hub <owner/repo>:\n' +
|
|
36
|
+
' spec-wave init --role code --repo acme/api --hub acme/hub'
|
|
37
|
+
);
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
hub = parseRepoRef(options.hub);
|
|
41
|
+
if (!hub) {
|
|
42
|
+
p.log.error(`Formato inválido para --hub: "${options.hub}". Use: owner/repo`);
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
45
|
+
if (parseRepoRef(options.repo) && options.repo.toLowerCase() === options.hub.toLowerCase()) {
|
|
46
|
+
p.log.error('--hub não pode ser o próprio repositório: o hub é outro repo, com role "hub".');
|
|
47
|
+
process.exit(1);
|
|
48
|
+
}
|
|
49
|
+
} else if (options.hub) {
|
|
50
|
+
p.log.error('--hub só faz sentido com --role code.');
|
|
51
|
+
process.exit(1);
|
|
52
|
+
}
|
|
53
|
+
|
|
18
54
|
// --- Token ---
|
|
19
55
|
let token;
|
|
20
56
|
try {
|
|
@@ -37,7 +73,8 @@ export async function init(options) {
|
|
|
37
73
|
}
|
|
38
74
|
|
|
39
75
|
const missingScopes = [];
|
|
40
|
-
|
|
76
|
+
// O repo de código não cria Project — o escopo `project` é do hub.
|
|
77
|
+
if (role !== 'code' && !tokenInfo.hasProject) missingScopes.push('project');
|
|
41
78
|
if (!tokenInfo.hasRepo) missingScopes.push('repo');
|
|
42
79
|
if (!tokenInfo.hasWorkflow) missingScopes.push('workflow');
|
|
43
80
|
|
|
@@ -52,7 +89,18 @@ export async function init(options) {
|
|
|
52
89
|
|
|
53
90
|
// --- Wizard ou flags ---
|
|
54
91
|
let owner, repo, projectTitle, provider, model;
|
|
55
|
-
if (
|
|
92
|
+
if (role === 'code') {
|
|
93
|
+
const self = parseRepoRef(options.repo);
|
|
94
|
+
if (!self) {
|
|
95
|
+
p.log.error('Formato inválido para --repo. Use: owner/repo');
|
|
96
|
+
process.exit(1);
|
|
97
|
+
}
|
|
98
|
+
({ owner, repo } = self);
|
|
99
|
+
provider = DEFAULT_PROVIDER;
|
|
100
|
+
model = getProvider(provider).defaultModel;
|
|
101
|
+
p.log.info(`Repositório de código: ${owner}/${repo}`);
|
|
102
|
+
p.log.info(`Hub: ${hub.owner}/${hub.repo}`);
|
|
103
|
+
} else if (options.repo) {
|
|
56
104
|
if (!options.repo.includes('/')) {
|
|
57
105
|
p.log.error('Formato inválido para --repo. Use: owner/repo');
|
|
58
106
|
process.exit(1);
|
|
@@ -76,19 +124,56 @@ export async function init(options) {
|
|
|
76
124
|
|
|
77
125
|
const providerMeta = getProvider(provider);
|
|
78
126
|
|
|
127
|
+
// --- Owner precisa ser organização ---
|
|
128
|
+
// O GitHub App do spec-wave só acessa Projects v2 de organizações — Projects
|
|
129
|
+
// v2 de conta pessoal não são suportados pela instalação do App. Repositório
|
|
130
|
+
// e Project pertencem sempre ao mesmo owner neste fluxo, então uma checagem
|
|
131
|
+
// cobre os dois. Roda mesmo em --dry-run e mesmo com --skip-project, porque
|
|
132
|
+
// o repositório em si também precisa estar na org.
|
|
133
|
+
const ownerSpinner = p.spinner();
|
|
134
|
+
ownerSpinner.start(`Verificando se ${owner} é uma organização...`);
|
|
135
|
+
let ownerType;
|
|
136
|
+
try {
|
|
137
|
+
ownerType = await getOwnerType(token, owner);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
ownerSpinner.stop('');
|
|
140
|
+
p.log.error(`Erro ao verificar owner "${owner}": ${err.message}`);
|
|
141
|
+
process.exit(1);
|
|
142
|
+
}
|
|
143
|
+
if (ownerType !== 'Organization') {
|
|
144
|
+
ownerSpinner.stop('');
|
|
145
|
+
p.log.error(
|
|
146
|
+
`"${owner}" é uma conta pessoal do GitHub, não uma organização.\n` +
|
|
147
|
+
'O spec-wave exige que o repositório e o GitHub Project pertençam a uma organização: ' +
|
|
148
|
+
'o GitHub App usado pelo spec-wave só tem acesso a Projects v2 de organizações ' +
|
|
149
|
+
'(Projects v2 de conta pessoal não são suportados pela instalação do App).\n' +
|
|
150
|
+
`Crie (ou use) uma organização no GitHub, transfira o repositório para ela e rode ` +
|
|
151
|
+
`"spec-wave init --repo <org>/${repo}" novamente.`
|
|
152
|
+
);
|
|
153
|
+
process.exit(1);
|
|
154
|
+
}
|
|
155
|
+
ownerSpinner.stop(`${owner} é uma organização.`);
|
|
156
|
+
|
|
79
157
|
if (options.dryRun) {
|
|
80
158
|
p.log.info(chalk.yellow('Modo dry-run: nenhuma alteração será feita.'));
|
|
81
|
-
p.log.info(` Repositório: ${owner}/${repo}`);
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
159
|
+
p.log.info(` Repositório: ${owner}/${repo} (role: ${role})`);
|
|
160
|
+
if (role === 'code') {
|
|
161
|
+
p.log.info(` Hub: ${hub.owner}/${hub.repo}`);
|
|
162
|
+
p.log.info(` Fases: despachantes (${CODE_WORKFLOW_FILES.join(', ')}) → ${CONFIG_FILE}`);
|
|
163
|
+
} else {
|
|
164
|
+
p.log.info(` Projeto: ${projectTitle}`);
|
|
165
|
+
p.log.info(` IA: ${providerMeta.label} · modelo ${model}`);
|
|
166
|
+
p.log.info(' Fases: project board → labels → workflow files');
|
|
167
|
+
}
|
|
85
168
|
p.outro('Dry-run concluído.');
|
|
86
169
|
return;
|
|
87
170
|
}
|
|
88
171
|
|
|
89
172
|
// --- Phase 1: Project Board ---
|
|
90
173
|
let projectUrl, projectId, projectNumber, projectFields;
|
|
91
|
-
if (
|
|
174
|
+
if (role === 'code') {
|
|
175
|
+
p.log.info('Repositório de código: sem GitHub Project nem labels — ficam no hub.');
|
|
176
|
+
} else if (options.skipProject) {
|
|
92
177
|
p.log.info('Pulando criação do GitHub Project (--skip-project).');
|
|
93
178
|
// Preserva o bloco project do .spec-wave.json existente (se houver).
|
|
94
179
|
// Prefere o arquivo local; recorre ao remoto para repos configurados por
|
|
@@ -136,7 +221,9 @@ export async function init(options) {
|
|
|
136
221
|
}
|
|
137
222
|
|
|
138
223
|
// --- Phase 2: Labels ---
|
|
139
|
-
if (
|
|
224
|
+
if (role === 'code') {
|
|
225
|
+
// Labels são do hub — é lá que as issues vivem.
|
|
226
|
+
} else if (options.skipLabels) {
|
|
140
227
|
p.log.info('Pulando criação das labels (--skip-labels).');
|
|
141
228
|
} else {
|
|
142
229
|
const labelSpinner = p.spinner();
|
|
@@ -159,8 +246,12 @@ export async function init(options) {
|
|
|
159
246
|
const filesSpinner = p.spinner();
|
|
160
247
|
filesSpinner.start('Criando arquivos no repositório...');
|
|
161
248
|
try {
|
|
162
|
-
await setupFiles(token, owner, repo, filesSpinner);
|
|
163
|
-
filesSpinner.stop(
|
|
249
|
+
await setupFiles(token, owner, repo, filesSpinner, { role });
|
|
250
|
+
filesSpinner.stop(
|
|
251
|
+
role === 'code'
|
|
252
|
+
? `Despachantes criados (${CODE_WORKFLOW_FILES.join(', ')})`
|
|
253
|
+
: `Arquivos criados (${WORKFLOW_FILES.length} workflows + ${ISSUE_TEMPLATE_FILES.length} issue templates)`
|
|
254
|
+
);
|
|
164
255
|
} catch (err) {
|
|
165
256
|
filesSpinner.stop('');
|
|
166
257
|
p.log.error(`Erro ao criar arquivos: ${err.message}`);
|
|
@@ -178,23 +269,36 @@ export async function init(options) {
|
|
|
178
269
|
const configSpinner = p.spinner();
|
|
179
270
|
configSpinner.start(`Gravando ${CONFIG_FILE} local...`);
|
|
180
271
|
try {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
272
|
+
// `role` é gravado nos dois casos. No hub ele é redundante (ausência já
|
|
273
|
+
// significa hub), mas explícito é legível — e um config antigo, sem o
|
|
274
|
+
// campo, continua valendo sem regravação.
|
|
275
|
+
const config = role === 'code'
|
|
276
|
+
? {
|
|
277
|
+
version: pkg.version,
|
|
278
|
+
role,
|
|
279
|
+
owner,
|
|
280
|
+
repo,
|
|
281
|
+
hub: { owner: hub.owner, repo: hub.repo },
|
|
282
|
+
initializedAt: new Date().toISOString(),
|
|
283
|
+
}
|
|
284
|
+
: {
|
|
285
|
+
version: pkg.version,
|
|
286
|
+
role,
|
|
287
|
+
owner,
|
|
288
|
+
repo,
|
|
289
|
+
project: {
|
|
290
|
+
title: projectTitle,
|
|
291
|
+
url: projectUrl ?? null,
|
|
292
|
+
id: projectId ?? null,
|
|
293
|
+
number: projectNumber ?? null,
|
|
294
|
+
fields: projectFields ?? null,
|
|
295
|
+
},
|
|
296
|
+
ai: {
|
|
297
|
+
provider: providerMeta.value,
|
|
298
|
+
model,
|
|
299
|
+
},
|
|
300
|
+
initializedAt: new Date().toISOString(),
|
|
301
|
+
};
|
|
198
302
|
writeFileSync(localConfigPath, JSON.stringify(config, null, 2) + '\n', 'utf-8');
|
|
199
303
|
configWritten = true;
|
|
200
304
|
configSpinner.stop(`${CONFIG_FILE} gravado local (spec-wave v${pkg.version})`);
|
|
@@ -203,6 +307,20 @@ export async function init(options) {
|
|
|
203
307
|
p.log.warn(`Não foi possível gravar ${CONFIG_FILE}: ${err.message}`);
|
|
204
308
|
}
|
|
205
309
|
|
|
310
|
+
if (role === 'code') {
|
|
311
|
+
p.outro(
|
|
312
|
+
`\n${chalk.green('✓')} ${owner}/${repo} configurado como repositório de código do hub ${hub.owner}/${hub.repo}.\n\n` +
|
|
313
|
+
` Próximos passos:\n` +
|
|
314
|
+
(configWritten ? ` 1. Commite o ${CONFIG_FILE} (git add ${CONFIG_FILE} && git commit) — os despachantes o leem em runtime\n` : '') +
|
|
315
|
+
` ${configWritten ? '2' : '1'}. Adicione o secret ${HUB_DISPATCH_SECRET} neste repositório: um token com escrita em Contents no hub\n` +
|
|
316
|
+
` ${configWritten ? '3' : '2'}. No hub, rode \`npx @spec-wave/cli@latest update\` para instalar o pr-events.yml (recebe os despachos)\n` +
|
|
317
|
+
` ${configWritten ? '4' : '3'}. Registre este repo no hub: \`repositories: [{ "slug": "<slug>", "owner": "${owner}", "repo": "${repo}" }]\` no ${CONFIG_FILE} do hub\n` +
|
|
318
|
+
` ${chalk.dim('(o slug vai na label repo:<slug> das Stories — minúsculas, [a-z0-9-], até 39 caracteres, e não muda depois)')}\n\n` +
|
|
319
|
+
` Nos PRs deste repo, vincule a Story com \`Closes ${hub.owner}/${hub.repo}#<n>\` — a forma qualificada é a que o hub reconhece.`
|
|
320
|
+
);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
|
|
206
324
|
p.note(
|
|
207
325
|
`As ${STATUS_OPTIONS.length} colunas do RFC-001 foram criadas no campo "Etapa".\n` +
|
|
208
326
|
'Para usá-las como colunas do board:\n' +
|
package/src/commands/merge.mjs
CHANGED
|
@@ -28,12 +28,13 @@ import { listIssuePullRequests, listOpenPullRequests } from '../api/github-graph
|
|
|
28
28
|
import { missingTrailers } from '../lib/commit-trailers.mjs';
|
|
29
29
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
30
30
|
import { orderStories } from '../lib/dependencies.mjs';
|
|
31
|
-
import {
|
|
31
|
+
import { resolveHubContext, loadConfig } from '../lib/project-root.mjs';
|
|
32
|
+
import { extractIssueRefs, hubIssueNumbers, resolveLinkMode } from '../lib/pr-link.mjs';
|
|
32
33
|
import { loadFeatureStories } from '../lib/story-graph.mjs';
|
|
33
34
|
import { resolveCacheTtl, invalidateCache } from '../lib/net-cache.mjs';
|
|
34
35
|
import { CONFIG_FILE } from '../config.mjs';
|
|
35
36
|
import { acquireLock, releaseLock } from './run.mjs';
|
|
36
|
-
import { codeReview
|
|
37
|
+
import { codeReview } from './code-review.mjs';
|
|
37
38
|
import { qa } from './qa.mjs';
|
|
38
39
|
|
|
39
40
|
/**
|
|
@@ -125,18 +126,20 @@ export function planMerge({ sorted = [], byNumber = new Map(), prsByStory = new
|
|
|
125
126
|
* @param {object} params
|
|
126
127
|
* @param {number[]} params.sorted ordem topológica (números de Story)
|
|
127
128
|
* @param {Map<number, Array>} params.prsByStory vínculos nativos já coletados
|
|
128
|
-
* @param {Array<{number, body}>} params.openPrs PRs abertos do
|
|
129
|
+
* @param {Array<{number, body}>} params.openPrs PRs abertos do hub
|
|
130
|
+
* @param {{owner:string, repo:string}} params.hub o repositório das Stories —
|
|
131
|
+
* um `#N` solto nesses PRs é issue do hub, e um `outro/repo#N` não é Story
|
|
129
132
|
* @param {'explicit'|'any-mention'} [params.linkMode]
|
|
130
133
|
* @returns {{ prsByStory: Map<number, Array>, adicionados: Array<{story:number, pr:number}> }}
|
|
131
134
|
*/
|
|
132
|
-
export function complementWithBodyLinks({ sorted = [], prsByStory = new Map(), openPrs = [], linkMode = 'explicit' } = {}) {
|
|
135
|
+
export function complementWithBodyLinks({ sorted = [], prsByStory = new Map(), openPrs = [], hub, linkMode = 'explicit' } = {}) {
|
|
133
136
|
const out = new Map(prsByStory);
|
|
134
137
|
const adicionados = [];
|
|
135
138
|
const faltantes = new Set(sorted.filter(s => (out.get(s) || []).length === 0));
|
|
136
139
|
if (faltantes.size === 0) return { prsByStory: out, adicionados };
|
|
137
140
|
|
|
138
141
|
for (const pr of openPrs) {
|
|
139
|
-
for (const n of
|
|
142
|
+
for (const n of hubIssueNumbers(extractIssueRefs(pr.body || '', { prRepo: hub, linkMode }), hub)) {
|
|
140
143
|
if (!faltantes.has(n)) continue;
|
|
141
144
|
out.set(n, [...(out.get(n) || []), pr]);
|
|
142
145
|
adicionados.push({ story: n, pr: pr.number });
|
|
@@ -164,7 +167,7 @@ export async function merge({
|
|
|
164
167
|
return;
|
|
165
168
|
}
|
|
166
169
|
|
|
167
|
-
const { owner, repo, root } =
|
|
170
|
+
const { owner, repo, root } = resolveHubContext();
|
|
168
171
|
if (!owner || !repo) {
|
|
169
172
|
p.log.error(
|
|
170
173
|
'Não foi possível determinar owner/repo.\n' +
|
|
@@ -269,8 +272,8 @@ export async function merge({
|
|
|
269
272
|
// (`Closes #N`) é a fonte que o autor de fato escreveu.
|
|
270
273
|
if (sorted.some(story => (prsByStory.get(story) || []).length === 0)) {
|
|
271
274
|
const abertos = await listOpenPullRequests(token, owner, repo).catch(() => []);
|
|
272
|
-
const linkMode = fileConfig
|
|
273
|
-
const comp = complementWithBodyLinks({ sorted, prsByStory, openPrs: abertos, linkMode });
|
|
275
|
+
const linkMode = resolveLinkMode(fileConfig);
|
|
276
|
+
const comp = complementWithBodyLinks({ sorted, prsByStory, openPrs: abertos, hub: { owner, repo }, linkMode });
|
|
274
277
|
prsByStory = comp.prsByStory;
|
|
275
278
|
if (comp.adicionados.length > 0) {
|
|
276
279
|
p.log.info(chalk.dim(
|
package/src/commands/move.mjs
CHANGED
|
@@ -17,7 +17,7 @@ import { getIssue } from '../api/github-rest.mjs';
|
|
|
17
17
|
import { addProjectItem, getItemSingleSelectValue } from '../api/github-graphql.mjs';
|
|
18
18
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
19
19
|
import { loadProjectConfig, resolveField, advanceToStage, resolveStageName } from '../lib/board.mjs';
|
|
20
|
-
import {
|
|
20
|
+
import { resolveHubContext } from '../lib/project-root.mjs';
|
|
21
21
|
import {
|
|
22
22
|
CONFIG_FILE, PROGRESS_TODO, PROGRESS_IN_PROGRESS, PROGRESS_DONE,
|
|
23
23
|
isManualStageType, MANUAL_STAGE_TYPES, isStageInTrack, STAGE_TRACKS,
|
|
@@ -117,12 +117,9 @@ export async function move({ issue: issueArg, stage: stageArg, status: statusArg
|
|
|
117
117
|
return;
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
// owner/repo: env GITHUB_REPOSITORY (padrão dos comandos de Action)
|
|
121
|
-
// fallback no .spec-wave.json, procurado subindo na árvore.
|
|
122
|
-
const
|
|
123
|
-
const { config, root } = loadConfig();
|
|
124
|
-
const owner = envOwner || config?.owner;
|
|
125
|
-
const repo = envRepo || config?.repo;
|
|
120
|
+
// owner/repo do hub: env GITHUB_REPOSITORY (padrão dos comandos de Action)
|
|
121
|
+
// com fallback no .spec-wave.json, procurado subindo na árvore.
|
|
122
|
+
const { owner, repo, config, root } = resolveHubContext();
|
|
126
123
|
if (!owner || !repo) {
|
|
127
124
|
p.log.error(
|
|
128
125
|
'Não foi possível determinar owner/repo.\n' +
|
package/src/commands/order.mjs
CHANGED
|
@@ -29,7 +29,7 @@ import { listSubIssues } from '../api/github-graphql.mjs';
|
|
|
29
29
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
30
30
|
import { parseDependencies, orderStories } from '../lib/dependencies.mjs';
|
|
31
31
|
import { loadProjectConfig, selectOpenFeatures } from '../lib/board.mjs';
|
|
32
|
-
import {
|
|
32
|
+
import { resolveHubContext, loadConfig } from '../lib/project-root.mjs';
|
|
33
33
|
import { featureDocPaths } from '../lib/doc-paths.mjs';
|
|
34
34
|
import { parseDecompositionDoc, renderDecompositionDoc } from '../lib/decomposition-doc.mjs';
|
|
35
35
|
import {
|
|
@@ -273,7 +273,7 @@ export async function order({
|
|
|
273
273
|
return;
|
|
274
274
|
}
|
|
275
275
|
|
|
276
|
-
const { owner, repo } =
|
|
276
|
+
const { owner, repo } = resolveHubContext();
|
|
277
277
|
if (!owner || !repo) {
|
|
278
278
|
emitError(opts,
|
|
279
279
|
'Não foi possível determinar owner/repo.\n' +
|
package/src/commands/qa.mjs
CHANGED
|
@@ -3,23 +3,13 @@ import { getIssue, getPR, commentOnIssue } from '../api/github-rest.mjs';
|
|
|
3
3
|
import { getIssueParent } from '../api/github-graphql.mjs';
|
|
4
4
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
5
5
|
import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
|
|
6
|
-
import {
|
|
6
|
+
import { resolveHubContext, resolvePrRepo } from '../lib/project-root.mjs';
|
|
7
|
+
import { extractIssueRefs, hubIssueNumbers, resolveLinkMode } from '../lib/pr-link.mjs';
|
|
7
8
|
import { STATUS_OPTIONS, PROGRESS_TODO } from '../config.mjs';
|
|
8
9
|
|
|
9
10
|
const QA_STAGE = STATUS_OPTIONS.find(s => s.name.includes('QA'))?.name;
|
|
10
11
|
const TODO_STATUS = PROGRESS_TODO;
|
|
11
12
|
|
|
12
|
-
function extractIssueNumbers(body) {
|
|
13
|
-
if (!body) return [];
|
|
14
|
-
const nums = new Set();
|
|
15
|
-
const re = /(?:closes?|fixes?|resolves?)\s+#(\d+)|(?<![/\w#])#(\d+)/gi;
|
|
16
|
-
for (const m of body.matchAll(re)) {
|
|
17
|
-
const n = parseInt(m[1] || m[2], 10);
|
|
18
|
-
if (n) nums.add(n);
|
|
19
|
-
}
|
|
20
|
-
return [...nums];
|
|
21
|
-
}
|
|
22
|
-
|
|
23
13
|
async function resolveFeatureIssue(token, owner, repo, issueNumber) {
|
|
24
14
|
let issue;
|
|
25
15
|
try {
|
|
@@ -42,13 +32,13 @@ async function resolveFeatureIssue(token, owner, repo, issueNumber) {
|
|
|
42
32
|
return null;
|
|
43
33
|
}
|
|
44
34
|
|
|
45
|
-
export async function qa({ prNumber }) {
|
|
35
|
+
export async function qa({ prNumber, prRepo: prRepoOpt }) {
|
|
46
36
|
const token = await resolveToken();
|
|
47
37
|
const projectToken = process.env.PROJECT_TOKEN || token;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
const repo
|
|
38
|
+
// Mesma separação do code-review: o comando roda no hub (dono das issues) e
|
|
39
|
+
// o PR pode estar num repo de código — `--pr-repo` diz qual.
|
|
40
|
+
const ctx = resolveHubContext();
|
|
41
|
+
const { owner, repo, config: cfg } = ctx;
|
|
52
42
|
|
|
53
43
|
if (!owner || !repo) {
|
|
54
44
|
throw new Error(
|
|
@@ -56,12 +46,23 @@ export async function qa({ prNumber }) {
|
|
|
56
46
|
'Defina GITHUB_REPOSITORY=owner/repo ou rode dentro de um repositório com .spec-wave.json.'
|
|
57
47
|
);
|
|
58
48
|
}
|
|
49
|
+
const hub = { owner, repo };
|
|
50
|
+
const prRepo = resolvePrRepo(prRepoOpt, ctx);
|
|
51
|
+
const prNum = parseInt(prNumber, 10);
|
|
59
52
|
|
|
60
|
-
const pr = await getPR(token, owner, repo,
|
|
61
|
-
|
|
53
|
+
const pr = await getPR(token, prRepo.owner, prRepo.repo, prNum);
|
|
54
|
+
// Mesmo parser e mesma régua do code-review: o vínculo que levou a Story a
|
|
55
|
+
// 👀 Code Review é o que a leva a 🧪 QA. Antes o qa tinha um parser próprio,
|
|
56
|
+
// mais frouxo (qualquer `#N`), que o code-review já havia abandonado.
|
|
57
|
+
const linkMode = resolveLinkMode(cfg);
|
|
58
|
+
const issueNums = hubIssueNumbers(extractIssueRefs(pr.body || '', { prRepo, linkMode }), hub);
|
|
62
59
|
|
|
63
60
|
if (issueNums.length === 0) {
|
|
64
|
-
console.log(
|
|
61
|
+
console.log(
|
|
62
|
+
linkMode === 'explicit'
|
|
63
|
+
? 'PR sem vínculo explícito (Closes/Fixes/Resolves/Implements #N) com issue do hub — board não atualizado.'
|
|
64
|
+
: 'PR sem referências a issues — nenhuma Feature atualizada.'
|
|
65
|
+
);
|
|
65
66
|
return;
|
|
66
67
|
}
|
|
67
68
|
|
|
@@ -124,7 +125,7 @@ export async function qa({ prNumber }) {
|
|
|
124
125
|
|
|
125
126
|
if (updated.length > 0) {
|
|
126
127
|
await commentOnIssue(
|
|
127
|
-
token, owner, repo,
|
|
128
|
+
token, prRepo.owner, prRepo.repo, prNum,
|
|
128
129
|
`🧪 **PR aprovado — QA iniciado**\n\n` +
|
|
129
130
|
`Item(ns) movido(s) para **${QA_STAGE}**:\n\n` +
|
|
130
131
|
updated.map(f => `- ${f}`).join('\n')
|
|
@@ -23,7 +23,7 @@ import { getIssue, commentOnIssue } from '../api/github-rest.mjs';
|
|
|
23
23
|
import { verifyTokenScopes } from '../api/auth.mjs';
|
|
24
24
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
25
25
|
import { loadProjectConfig, resolveField, setItemStage, resolveStageName } from '../lib/board.mjs';
|
|
26
|
-
import {
|
|
26
|
+
import { resolveHubContext } from '../lib/project-root.mjs';
|
|
27
27
|
import { resolveProgressName } from './move.mjs';
|
|
28
28
|
import { CONFIG_FILE } from '../config.mjs';
|
|
29
29
|
|
|
@@ -130,10 +130,7 @@ export async function repairStage(issuesArg, stageArg, options = {}) {
|
|
|
130
130
|
return;
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
-
const
|
|
134
|
-
const { config, root } = loadConfig();
|
|
135
|
-
const owner = envOwner || config?.owner;
|
|
136
|
-
const repo = envRepo || config?.repo;
|
|
133
|
+
const { owner, repo, config, root } = resolveHubContext();
|
|
137
134
|
if (!owner || !repo) {
|
|
138
135
|
p.log.error(
|
|
139
136
|
'Não foi possível determinar owner/repo.\n' +
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// `spec-wave repo link|unlink|list` — o vínculo hub ↔ repositório de código
|
|
2
|
+
// pelo lado da CLI (RFC-005). A UI grava o mesmo `repositories[]` no
|
|
3
|
+
// .spec-wave.json do hub via Contents API; este comando é o caminho de quem
|
|
4
|
+
// não usa a UI. Só edita o arquivo LOCAL (o dev commita, como no init) e cria
|
|
5
|
+
// a label `repo:<slug>` no hub, best-effort — o decompose --apply a garante de
|
|
6
|
+
// novo se faltar.
|
|
7
|
+
import * as p from '@clack/prompts';
|
|
8
|
+
import chalk from 'chalk';
|
|
9
|
+
import { resolveToken } from '../api/auth.mjs';
|
|
10
|
+
import { getRepoNodeId, createLabel } from '../api/github-rest.mjs';
|
|
11
|
+
import { resolveHubContext } from '../lib/project-root.mjs';
|
|
12
|
+
import { updateConfig } from '../lib/config-file.mjs';
|
|
13
|
+
import {
|
|
14
|
+
codeRepositories, linkRepository, unlinkRepository, parseRepoRef, repoLabelSpec,
|
|
15
|
+
} from '../lib/repo-role.mjs';
|
|
16
|
+
import { CONFIG_FILE } from '../config.mjs';
|
|
17
|
+
|
|
18
|
+
export async function repoCommand({ action, slug, repo: repoArg, dryRun = false, json = false } = {}) {
|
|
19
|
+
if (!['link', 'unlink', 'list'].includes(action)) {
|
|
20
|
+
throw new Error(`Ação inválida: "${action}". Use \`repo link <slug> <owner/repo>\`, \`repo unlink <slug>\` ou \`repo list\`.`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const ctx = resolveHubContext();
|
|
24
|
+
if (ctx.role === 'code') {
|
|
25
|
+
throw new Error(
|
|
26
|
+
`${ctx.self.owner}/${ctx.self.repo} é um repositório de código; o vínculo é registrado no hub` +
|
|
27
|
+
(ctx.owner && ctx.repo ? ` ${ctx.owner}/${ctx.repo}.` : '.')
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
if (!ctx.root || !ctx.config) {
|
|
31
|
+
throw new Error(`Rode dentro do hub (diretório com ${CONFIG_FILE}) — ${ctx.error || 'config não encontrado'}.`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (action === 'list') {
|
|
35
|
+
const repos = codeRepositories(ctx.config);
|
|
36
|
+
if (json) { console.log(JSON.stringify({ hub: { owner: ctx.owner, repo: ctx.repo }, repositories: repos }, null, 2)); return repos; }
|
|
37
|
+
if (repos.length === 0) {
|
|
38
|
+
p.log.info(`Nenhum repositório de código vinculado ao hub ${ctx.owner}/${ctx.repo} (mono-repo).`);
|
|
39
|
+
return repos;
|
|
40
|
+
}
|
|
41
|
+
p.log.info(`Hub ${ctx.owner}/${ctx.repo} — ${repos.length} repositório(s) de código:`);
|
|
42
|
+
for (const r of repos) p.log.message(` ${chalk.cyan(r.slug)} → ${r.owner}/${r.repo} (label repo:${r.slug})`);
|
|
43
|
+
return repos;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!slug) throw new Error(`Informe o slug: \`spec-wave repo ${action} <slug>${action === 'link' ? ' <owner/repo>' : ''}\`.`);
|
|
47
|
+
|
|
48
|
+
if (action === 'unlink') {
|
|
49
|
+
const preview = unlinkRepository(ctx.config, slug);
|
|
50
|
+
if (preview.error) throw new Error(preview.error);
|
|
51
|
+
if (dryRun) {
|
|
52
|
+
p.log.info(`Dry-run: ${slug} sairia de repositories[] do ${CONFIG_FILE}. As labels repo:${slug} já aplicadas ficam.`);
|
|
53
|
+
return preview.config;
|
|
54
|
+
}
|
|
55
|
+
const { changed } = updateConfig(cfg => unlinkRepository(cfg, slug).config, { cwd: ctx.root });
|
|
56
|
+
p.log.success(`${slug} desvinculado (${CONFIG_FILE}${changed ? ' atualizado' : ' já estava assim'}).`);
|
|
57
|
+
p.log.warn(`As labels repo:${slug} já aplicadas em issues não foram tocadas — são histórico. Commite o ${CONFIG_FILE}.`);
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// link
|
|
62
|
+
const target = parseRepoRef(repoArg);
|
|
63
|
+
if (!target) throw new Error(`Informe o repositório como owner/repo: \`spec-wave repo link ${slug} <owner/repo>\`.`);
|
|
64
|
+
const preview = linkRepository(ctx.config, { slug, ...target });
|
|
65
|
+
if (preview.error) throw new Error(preview.error);
|
|
66
|
+
if (!preview.changed) {
|
|
67
|
+
p.log.info(`${slug} → ${target.owner}/${target.repo} já está vinculado. Nada a fazer.`);
|
|
68
|
+
return preview.config;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// O repo precisa existir e ser legível pelo token — um slug apontando para
|
|
72
|
+
// o nada só apareceria na primeira Story, dentro do apply.
|
|
73
|
+
const token = await resolveToken();
|
|
74
|
+
try {
|
|
75
|
+
await getRepoNodeId(token, target.owner, target.repo);
|
|
76
|
+
} catch (err) {
|
|
77
|
+
throw new Error(`Não consegui ler ${target.owner}/${target.repo}: ${err.status === 404 ? 'não existe ou o token não o enxerga' : err.message}.`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (dryRun) {
|
|
81
|
+
p.log.info(`Dry-run: ${slug} → ${target.owner}/${target.repo} entraria em repositories[] do ${CONFIG_FILE}; label repo:${slug} seria criada no hub.`);
|
|
82
|
+
return preview.config;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const { changed } = updateConfig(cfg => linkRepository(cfg, { slug, ...target }).config, { cwd: ctx.root });
|
|
86
|
+
p.log.success(`${chalk.cyan(slug)} → ${target.owner}/${target.repo} vinculado (${CONFIG_FILE}${changed ? ' atualizado' : ' já estava assim'}).`);
|
|
87
|
+
|
|
88
|
+
const spec = repoLabelSpec(slug);
|
|
89
|
+
try {
|
|
90
|
+
await createLabel(token, ctx.owner, ctx.repo, spec);
|
|
91
|
+
p.log.success(`Label ${spec.name} garantida em ${ctx.owner}/${ctx.repo}.`);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
p.log.warn(`Não consegui criar a label ${spec.name}: ${err.message} — o decompose --apply tenta de novo.`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
p.note(
|
|
97
|
+
`1. Commite o ${CONFIG_FILE} (os workflows do hub leem repositories[] da branch default).\n` +
|
|
98
|
+
`2. No repositório de código: npx @spec-wave/cli@latest init --role code --repo ${target.owner}/${target.repo} --hub ${ctx.owner}/${ctx.repo}\n` +
|
|
99
|
+
`3. Nas Stories, declare \`**Repos:** ${slug}\` no decomposition.md (vira a label ${spec.name}).`,
|
|
100
|
+
'Próximos passos'
|
|
101
|
+
);
|
|
102
|
+
return null;
|
|
103
|
+
}
|
package/src/commands/story.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { getIssue } from '../api/github-rest.mjs';
|
|
|
12
12
|
import { addProjectItem, getItemSingleSelectValue } from '../api/github-graphql.mjs';
|
|
13
13
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
14
14
|
import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
|
|
15
|
-
import {
|
|
15
|
+
import { resolveHubContext } from '../lib/project-root.mjs';
|
|
16
16
|
import { CONFIG_FILE, STAGE_CODE_REVIEW, PROGRESS_TODO } from '../config.mjs';
|
|
17
17
|
|
|
18
18
|
export async function story({ action, issue: issueArg }) {
|
|
@@ -32,7 +32,7 @@ export async function story({ action, issue: issueArg }) {
|
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
const { owner, repo } =
|
|
35
|
+
const { owner, repo } = resolveHubContext();
|
|
36
36
|
if (!owner || !repo) {
|
|
37
37
|
p.log.error(
|
|
38
38
|
'Não foi possível determinar owner/repo.\n' +
|
package/src/commands/task.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { getIssue } from '../api/github-rest.mjs';
|
|
|
15
15
|
import { addProjectItem, getIssueParent, listSubIssues, getItemSingleSelectValue } from '../api/github-graphql.mjs';
|
|
16
16
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
17
17
|
import { loadProjectConfig, resolveField, advanceToStage, setItemStatus } from '../lib/board.mjs';
|
|
18
|
-
import {
|
|
18
|
+
import { resolveHubContext } from '../lib/project-root.mjs';
|
|
19
19
|
import {
|
|
20
20
|
CONFIG_FILE, STAGE_DEVELOPMENT, STAGE_DONE,
|
|
21
21
|
PROGRESS_IN_PROGRESS, PROGRESS_DONE,
|
|
@@ -53,7 +53,7 @@ export async function task({ action, issue: issueArg }) {
|
|
|
53
53
|
return;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
const { owner, repo } =
|
|
56
|
+
const { owner, repo } = resolveHubContext();
|
|
57
57
|
if (!owner || !repo) {
|
|
58
58
|
p.log.error(
|
|
59
59
|
'Não foi possível determinar owner/repo.\n' +
|
package/src/commands/triage.mjs
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
} from '../api/github-rest.mjs';
|
|
17
17
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
18
18
|
import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
|
|
19
|
-
import {
|
|
19
|
+
import { resolveHubContext } from '../lib/project-root.mjs';
|
|
20
20
|
import { resolveTriageAction, canAcceptBug } from '../lib/bug-triage.mjs';
|
|
21
21
|
import {
|
|
22
22
|
CONFIG_FILE, STAGE_READY, PROGRESS_TODO, PRIORITY_LABELS,
|
|
@@ -45,10 +45,7 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
|
|
|
45
45
|
return;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
const
|
|
49
|
-
const { config, root } = loadConfig();
|
|
50
|
-
const owner = envOwner || config?.owner;
|
|
51
|
-
const repo = envRepo || config?.repo;
|
|
48
|
+
const { owner, repo, config, root } = resolveHubContext();
|
|
52
49
|
if (!owner || !repo) {
|
|
53
50
|
p.log.error(
|
|
54
51
|
'Não foi possível determinar owner/repo.\n' +
|