@spec-wave/cli 1.0.8 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/commands/audit.mjs +24 -18
- package/src/commands/code-review.mjs +89 -58
- package/src/commands/decompose.mjs +254 -218
- package/src/commands/generate-bug.mjs +51 -44
- package/src/commands/generate-plan.mjs +83 -63
- package/src/commands/generate-qa-plan.mjs +144 -117
- package/src/commands/generate-spec.mjs +33 -28
- package/src/commands/implement.mjs +154 -79
- package/src/commands/init.mjs +8 -3
- package/src/commands/issue.mjs +26 -39
- package/src/commands/merge.mjs +71 -20
- package/src/commands/mode.mjs +8 -4
- package/src/commands/move.mjs +16 -20
- package/src/commands/order.mjs +33 -22
- package/src/commands/preflight.mjs +24 -13
- package/src/commands/qa-lead.mjs +28 -16
- package/src/commands/qa-run.mjs +122 -101
- package/src/commands/qa.mjs +55 -44
- package/src/commands/refresh.mjs +24 -16
- package/src/commands/repair-stage.mjs +29 -16
- package/src/commands/repo.mjs +10 -3
- package/src/commands/run.mjs +23 -11
- package/src/commands/story.mjs +20 -25
- package/src/commands/task.mjs +21 -27
- package/src/commands/triage.mjs +33 -31
- package/src/commands/uninstall.mjs +7 -3
- package/src/commands/update.mjs +29 -21
- package/src/commands/validate.mjs +60 -52
- package/src/commands/workspace.mjs +7 -5
- package/src/config.mjs +7 -1
- package/src/lib/artifact-publish.mjs +20 -18
- package/src/lib/board-policy.mjs +144 -0
- package/src/lib/board.mjs +134 -233
- package/src/lib/doc-availability.mjs +10 -3
- package/src/lib/doc-source.mjs +9 -9
- package/src/lib/implement-board.mjs +23 -26
- package/src/lib/issue-type.mjs +5 -1
- package/src/lib/pr-ready.mjs +48 -10
- package/src/lib/pr-step.mjs +3 -1
- package/src/lib/qa-exec.mjs +3 -1
- package/src/lib/qa-lead.mjs +11 -3
- package/src/lib/qa-plan-doc.mjs +10 -4
- package/src/lib/spec-audit.mjs +1 -1
- package/src/lib/story-graph.mjs +62 -8
- package/src/lib/usage-report.mjs +8 -5
- package/src/lib/work-item-ref.mjs +176 -0
- package/src/plugin/.claude-plugin/plugin.json +1 -1
- package/src/plugins/scm-github/index.mjs +439 -0
- package/src/plugins/tracker-github-projects/fields.mjs +73 -0
- package/src/plugins/tracker-github-projects/index.mjs +625 -0
- package/src/ports/scm.mjs +197 -0
- package/src/ports/tracker.mjs +239 -0
- package/src/ports/types.mjs +254 -0
- package/src/setup/files.mjs +14 -12
- package/src/setup/labels.mjs +17 -12
- package/src/setup/project.mjs +40 -59
package/src/commands/issue.mjs
CHANGED
|
@@ -4,8 +4,7 @@ import { readFileSync } from 'node:fs';
|
|
|
4
4
|
import { resolveToken } from '../api/auth.mjs';
|
|
5
5
|
import { CONFIG_FILE, PRIORITY_LABELS, WORK_ITEM_TYPES, initialStageForType } from '../config.mjs';
|
|
6
6
|
import { findConfigPath } from '../lib/project-root.mjs';
|
|
7
|
-
import {
|
|
8
|
-
import { addProjectItem, setItemSingleSelect, getSingleSelectField, addSubIssue } from '../api/github-graphql.mjs';
|
|
7
|
+
import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
|
|
9
8
|
|
|
10
9
|
const VALID_PRIORITIES = PRIORITY_LABELS.map(l => l.name);
|
|
11
10
|
|
|
@@ -27,27 +26,6 @@ function buildBody(options, parent) {
|
|
|
27
26
|
return parts.join('\n\n') || '_(sem descrição)_';
|
|
28
27
|
}
|
|
29
28
|
|
|
30
|
-
// Resolve um campo SINGLE_SELECT pelo nome: usa o .spec-wave.json, cai para o
|
|
31
|
-
// formato legado (etapaFieldId/stageOptions) e, por fim, consulta o Project.
|
|
32
|
-
async function resolveField(token, project, name) {
|
|
33
|
-
if (project.fields && project.fields[name]) return project.fields[name];
|
|
34
|
-
if (name === 'Etapa' && project.etapaFieldId) {
|
|
35
|
-
return { id: project.etapaFieldId, options: project.stageOptions || {} };
|
|
36
|
-
}
|
|
37
|
-
return await getSingleSelectField(token, project.id, name);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Seta o valor de um campo do item no board. Retorna true se aplicou.
|
|
41
|
-
async function setField(token, project, itemId, fieldName, optionName) {
|
|
42
|
-
const field = await resolveField(token, project, fieldName);
|
|
43
|
-
const optionId = field?.options?.[optionName];
|
|
44
|
-
if (field?.id && optionId) {
|
|
45
|
-
await setItemSingleSelect(token, project.id, itemId, field.id, optionId);
|
|
46
|
-
return true;
|
|
47
|
-
}
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
29
|
// Cria um work item (issue tipada), opcionalmente como sub-issue de um parent,
|
|
52
30
|
// adiciona ao Project e define Etapa, Work Item Type, Prioridade e Área no board.
|
|
53
31
|
export async function issue(options) {
|
|
@@ -99,6 +77,8 @@ export async function issue(options) {
|
|
|
99
77
|
return;
|
|
100
78
|
}
|
|
101
79
|
|
|
80
|
+
const tracker = options.deps?.tracker ?? createGithubTracker({ token, owner, repo, project });
|
|
81
|
+
|
|
102
82
|
p.intro(chalk.bold(`spec-wave issue (${type})`));
|
|
103
83
|
|
|
104
84
|
// Resolve o parent (se informado) — precisamos do node id para a sub-issue.
|
|
@@ -111,8 +91,8 @@ export async function issue(options) {
|
|
|
111
91
|
return;
|
|
112
92
|
}
|
|
113
93
|
try {
|
|
114
|
-
const data = await
|
|
115
|
-
parent = { number: data.
|
|
94
|
+
const data = await tracker.getWorkItem({ ref: { key: String(parentNumber) } });
|
|
95
|
+
parent = { number: Number(data.ref.key), nodeId: data.ref.id, ref: data.ref, title: data.title };
|
|
116
96
|
} catch (err) {
|
|
117
97
|
p.log.error(`Não foi possível ler a issue pai #${parentNumber}: ${err.message}`);
|
|
118
98
|
process.exitCode = 1;
|
|
@@ -129,8 +109,13 @@ export async function issue(options) {
|
|
|
129
109
|
issueSpinner.start('Criando issue...');
|
|
130
110
|
let created;
|
|
131
111
|
try {
|
|
132
|
-
created = await
|
|
133
|
-
|
|
112
|
+
created = await tracker.createWorkItem({
|
|
113
|
+
title: `${tag} ${options.title}`,
|
|
114
|
+
body: buildBody(options, parent),
|
|
115
|
+
type,
|
|
116
|
+
tags: labels,
|
|
117
|
+
});
|
|
118
|
+
issueSpinner.stop(`Issue #${created.key} criada: ${chalk.cyan(created.url)}`);
|
|
134
119
|
} catch (err) {
|
|
135
120
|
issueSpinner.stop('');
|
|
136
121
|
p.log.error(`Erro ao criar issue: ${err.message}`);
|
|
@@ -141,7 +126,7 @@ export async function issue(options) {
|
|
|
141
126
|
// 2. Vincula como sub-issue do parent (relação nativa do GitHub).
|
|
142
127
|
if (parent) {
|
|
143
128
|
try {
|
|
144
|
-
await
|
|
129
|
+
await tracker.addChild({ parent: parent.ref, child: created });
|
|
145
130
|
p.log.success(`Vinculada como sub-issue de #${parent.number}.`);
|
|
146
131
|
} catch (err) {
|
|
147
132
|
p.log.warn(`Issue criada, mas falhou ao vincular ao parent #${parent.number}: ${err.message}`);
|
|
@@ -154,7 +139,7 @@ export async function issue(options) {
|
|
|
154
139
|
`Project não configurado no ${CONFIG_FILE} — a issue não foi adicionada ao board.\n` +
|
|
155
140
|
'Re-rode `spec-wave init` (sem --skip-project) ou `spec-wave refresh --config`.'
|
|
156
141
|
);
|
|
157
|
-
p.outro(`${type} #${created.
|
|
142
|
+
p.outro(`${type} #${created.key} criado (fora do board).`);
|
|
158
143
|
return;
|
|
159
144
|
}
|
|
160
145
|
|
|
@@ -162,15 +147,17 @@ export async function issue(options) {
|
|
|
162
147
|
// (✅ Ready quando o Bug já nasce P0). Ver initialStageForType.
|
|
163
148
|
const initialStage = initialStageForType(type, options.priority || null);
|
|
164
149
|
|
|
150
|
+
let stageOk = true;
|
|
165
151
|
const boardSpinner = p.spinner();
|
|
166
152
|
boardSpinner.start('Adicionando ao Project...');
|
|
167
153
|
try {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if (options.
|
|
154
|
+
// A Etapa de NASCIMENTO não passa pelo guard de avanço: o item ainda não
|
|
155
|
+
// tem etapa, e `setStage` é a escrita direta. Quem protege a ordem depois é
|
|
156
|
+
// `advanceToStage`, no fluxo.
|
|
157
|
+
await tracker.setStage({ ref: created, stage: initialStage }).catch(() => { stageOk = false; });
|
|
158
|
+
const typeOk = await tracker.setField({ ref: created, field: 'workItemType', value: type });
|
|
159
|
+
if (options.priority) await tracker.setField({ ref: created, field: 'priority', value: options.priority });
|
|
160
|
+
if (options.area) await tracker.setField({ ref: created, field: 'area', value: options.area });
|
|
174
161
|
|
|
175
162
|
boardSpinner.stop(`Adicionada ao Project${stageOk ? ` em "${initialStage}"` : ''}.`);
|
|
176
163
|
if (!stageOk) p.log.warn(`Não foi possível definir a Etapa "${initialStage}" (campo não encontrado).`);
|
|
@@ -182,12 +169,12 @@ export async function issue(options) {
|
|
|
182
169
|
|
|
183
170
|
const parentLine = parent ? ` (sub-issue de #${parent.number})` : '';
|
|
184
171
|
const hints = {
|
|
185
|
-
Feature: `Próximo: \`/spec-wave plan ${created.
|
|
186
|
-
Initiative: `Próximo: crie Epics sob esta Initiative com \`spec-wave issue --type epic --parent ${created.
|
|
187
|
-
Epic: `Próximo: crie Features sob este Epic com \`spec-wave feature --parent ${created.
|
|
172
|
+
Feature: `Próximo: \`/spec-wave plan ${created.key}\` para o planejamento técnico.`,
|
|
173
|
+
Initiative: `Próximo: crie Epics sob esta Initiative com \`spec-wave issue --type epic --parent ${created.key} --title "..."\`.`,
|
|
174
|
+
Epic: `Próximo: crie Features sob este Epic com \`spec-wave feature --parent ${created.key} --title "..."\`.`,
|
|
188
175
|
};
|
|
189
176
|
p.outro(
|
|
190
|
-
`${chalk.green('✓')} ${type} #${created.
|
|
177
|
+
`${chalk.green('✓')} ${type} #${created.key} criado em "${initialStage}"${parentLine}.\n` +
|
|
191
178
|
` ${hints[type] || ''}`
|
|
192
179
|
);
|
|
193
180
|
}
|
package/src/commands/merge.mjs
CHANGED
|
@@ -20,11 +20,8 @@ import * as p from '@clack/prompts';
|
|
|
20
20
|
import chalk from 'chalk';
|
|
21
21
|
|
|
22
22
|
import { resolveToken } from '../api/auth.mjs';
|
|
23
|
-
import {
|
|
24
|
-
|
|
25
|
-
listPullRequestCommitMessages,
|
|
26
|
-
} from '../api/github-rest.mjs';
|
|
27
|
-
import { listIssuePullRequests, listOpenPullRequests } from '../api/github-graphql.mjs';
|
|
23
|
+
import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
|
|
24
|
+
import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
|
|
28
25
|
import { missingTrailers } from '../lib/commit-trailers.mjs';
|
|
29
26
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
30
27
|
import { orderStories } from '../lib/dependencies.mjs';
|
|
@@ -211,6 +208,50 @@ export function complementWithBodyLinks({ sorted = [], prsByStory = new Map(), o
|
|
|
211
208
|
return { prsByStory: out, adicionados };
|
|
212
209
|
}
|
|
213
210
|
|
|
211
|
+
/**
|
|
212
|
+
* Porta de SCM de um repositório, memoizada por `link.id`.
|
|
213
|
+
*
|
|
214
|
+
* O `merge` é o comando MAIS multi-repo do fluxo: ele toca o hub, cada repo de
|
|
215
|
+
* código da Feature e o repo de cada PR. Uma instância por repositório é o que
|
|
216
|
+
* o contrato manda — e memoizar evita recriar a mesma porta dentro do laço da
|
|
217
|
+
* fila sem mudar contagem de chamada nenhuma.
|
|
218
|
+
*/
|
|
219
|
+
/**
|
|
220
|
+
* `PullRequestRef` → a forma que `planMerge` consome.
|
|
221
|
+
*
|
|
222
|
+
* `planMerge` é PURA e testada contra `merged`/`isDraft`/`baseRefName`, que é o
|
|
223
|
+
* shape do GraphQL. A porta normaliza (`state: 'merged'`, `draft`, `baseRef`),
|
|
224
|
+
* e passar o novo direto faria o plano ler `undefined` em todos os campos de
|
|
225
|
+
* decisão — um PR em rascunho deixaria de bloquear, e a pilha seria mergeada
|
|
226
|
+
* por cima da revisão que ainda não aconteceu. Traduzir no ponto de LEITURA
|
|
227
|
+
* mantém a função protegida onde ela já está.
|
|
228
|
+
*/
|
|
229
|
+
function comoPrLegado(pr) {
|
|
230
|
+
return pr && {
|
|
231
|
+
id: pr.id,
|
|
232
|
+
number: Number(pr.number),
|
|
233
|
+
state: pr.state === 'merged' ? 'closed' : pr.state,
|
|
234
|
+
merged: pr.state === 'merged',
|
|
235
|
+
isDraft: pr.draft,
|
|
236
|
+
baseRefName: pr.baseRef,
|
|
237
|
+
headRefName: pr.headRef,
|
|
238
|
+
body: pr.body || '',
|
|
239
|
+
repo: pr.link?.config || null,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function criarScmDe(token, hub) {
|
|
244
|
+
const cache = new Map();
|
|
245
|
+
return (r) => {
|
|
246
|
+
const link = githubLink({
|
|
247
|
+
owner: r.owner, repo: r.repo,
|
|
248
|
+
role: r.owner === hub.owner && r.repo === hub.repo ? 'hub' : 'code',
|
|
249
|
+
});
|
|
250
|
+
if (!cache.has(link.id)) cache.set(link.id, createGithubScm({ link, token }));
|
|
251
|
+
return cache.get(link.id);
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
214
255
|
export async function merge({
|
|
215
256
|
feature: featureArg, yes = false, dryRun = false, keepBranches = false,
|
|
216
257
|
remote = false, refresh = false,
|
|
@@ -253,11 +294,15 @@ export async function merge({
|
|
|
253
294
|
const s = p.spinner();
|
|
254
295
|
s.start('Montando o plano de merge...');
|
|
255
296
|
|
|
297
|
+
const scmDe = criarScmDe(token, { owner, repo });
|
|
298
|
+
const hubScm = scmDe({ owner, repo });
|
|
299
|
+
|
|
256
300
|
let featureIssue;
|
|
257
301
|
let defaultBranch;
|
|
258
302
|
try {
|
|
259
|
-
featureIssue = await
|
|
260
|
-
|
|
303
|
+
featureIssue = await createGithubTracker({ token, owner, repo })
|
|
304
|
+
.getWorkItem({ ref: { key: String(featureNumber) } });
|
|
305
|
+
defaultBranch = await scmDe({ owner, repo }).defaultBranch();
|
|
261
306
|
} catch (err) {
|
|
262
307
|
s.stop('');
|
|
263
308
|
p.log.error(`Não foi possível ler ${owner}/${repo}#${featureNumber}: ${err.message}`);
|
|
@@ -283,7 +328,9 @@ export async function merge({
|
|
|
283
328
|
try {
|
|
284
329
|
carga = await loadFeatureStories({
|
|
285
330
|
token, owner, repo, root: repoRoot,
|
|
286
|
-
|
|
331
|
+
// `ref.id`: sem ele, `loadFeatureStories` chama listChildren sem node id
|
|
332
|
+
// e o plugin paga um getIssue a mais para reidratar o que já estava aqui.
|
|
333
|
+
feature: { number: featureNumber, nodeId: featureIssue.ref?.id, title: featureIssue.title },
|
|
287
334
|
remote: executa || remote,
|
|
288
335
|
refresh: executa || refresh,
|
|
289
336
|
ttlSec,
|
|
@@ -317,7 +364,7 @@ export async function merge({
|
|
|
317
364
|
// Stories declaram por label. No mono-repo a lista é só o hub — nada muda.
|
|
318
365
|
const hub = { owner, repo };
|
|
319
366
|
const { repos: codeRepos, unknown: desconhecidos } = codeReposForItems(fileConfig, {
|
|
320
|
-
labels: featureIssue.
|
|
367
|
+
labels: featureIssue.tags, children: stories,
|
|
321
368
|
});
|
|
322
369
|
if (desconhecidos.length > 0) {
|
|
323
370
|
p.log.warn(`Story(ies) declaram repositório(s) que o hub não conhece (${desconhecidos.join(', ')}) — PRs de lá não entram no plano; registre em repositories[] do ${CONFIG_FILE}.`);
|
|
@@ -325,7 +372,7 @@ export async function merge({
|
|
|
325
372
|
const repos = [hub, ...codeRepos.map(r => ({ owner: r.owner, repo: r.repo, slug: r.slug }))];
|
|
326
373
|
const defaultBranches = new Map();
|
|
327
374
|
for (const r of codeRepos) {
|
|
328
|
-
const branch = await
|
|
375
|
+
const branch = await scmDe(r).defaultBranch().catch(() => null);
|
|
329
376
|
if (branch) defaultBranches.set(repoKey(r), branch);
|
|
330
377
|
else p.log.warn(`Não consegui ler a branch default de ${r.owner}/${r.repo} — assumindo "${defaultBranch}".`);
|
|
331
378
|
}
|
|
@@ -345,7 +392,9 @@ export async function merge({
|
|
|
345
392
|
|
|
346
393
|
let prsByStory = new Map();
|
|
347
394
|
for (const story of sorted) {
|
|
348
|
-
prsByStory.set(story, await
|
|
395
|
+
prsByStory.set(story, (await hubScm
|
|
396
|
+
.findPullRequestsReferencing({ ref: { key: String(story), id: byNumber.get(story).nodeId } })
|
|
397
|
+
.catch(() => [])).map(comoPrLegado));
|
|
349
398
|
}
|
|
350
399
|
|
|
351
400
|
// Vínculo nativo só existe com base na default — numa pilha, só o PR de
|
|
@@ -355,7 +404,7 @@ export async function merge({
|
|
|
355
404
|
if (codeRepos.length > 0 || sorted.some(story => (prsByStory.get(story) || []).length === 0)) {
|
|
356
405
|
const abertos = [];
|
|
357
406
|
for (const r of repos) {
|
|
358
|
-
const lista = await
|
|
407
|
+
const lista = (await scmDe(r).listOpenPullRequests().catch(() => [])).map(comoPrLegado);
|
|
359
408
|
abertos.push(...lista.map(pr => ({ ...pr, repo: { owner: r.owner, repo: r.repo } })));
|
|
360
409
|
}
|
|
361
410
|
const linkMode = resolveLinkMode(fileConfig);
|
|
@@ -392,7 +441,7 @@ export async function merge({
|
|
|
392
441
|
// chamada extra por PR; falha de rede não afirma nada, só é pulada.
|
|
393
442
|
for (const { story, pr } of plano.fila) {
|
|
394
443
|
const r = prRepoOf(pr, hub);
|
|
395
|
-
const messages = await
|
|
444
|
+
const messages = await scmDe(r).listPullRequestCommitMessages({ number: String(pr.number) }).catch(() => null);
|
|
396
445
|
if (messages === null) continue;
|
|
397
446
|
const { missingStories } = missingTrailers(messages, { stories: [story] });
|
|
398
447
|
if (missingStories.length > 0) {
|
|
@@ -428,17 +477,19 @@ export async function merge({
|
|
|
428
477
|
const ref = prRef(pr, hub);
|
|
429
478
|
const prRepoOpt = sameRepo(r, hub) ? undefined : `${r.owner}/${r.repo}`;
|
|
430
479
|
// Estado fresco: a fila pode ter envelhecido entre o plano e este ponto.
|
|
431
|
-
const atual = await
|
|
432
|
-
if (atual.
|
|
480
|
+
const atual = await scmDe(r).getPullRequest({ number: String(pr.number) });
|
|
481
|
+
if (atual.state === 'merged') {
|
|
433
482
|
p.log.info(`PR ${ref} já estava mergeado — seguindo.`);
|
|
434
483
|
continue;
|
|
435
484
|
}
|
|
436
|
-
if (atual.
|
|
437
|
-
p.log.step(`PR ${ref}: base ${atual.
|
|
438
|
-
await
|
|
485
|
+
if (atual.baseRef !== def) {
|
|
486
|
+
p.log.step(`PR ${ref}: base ${atual.baseRef} → ${def}`);
|
|
487
|
+
await scmDe(r).setPullRequestBase({ number: String(pr.number), base: def });
|
|
439
488
|
}
|
|
440
489
|
try {
|
|
441
|
-
|
|
490
|
+
// `merge` e não squash: squash reescreveria o merge-base dos
|
|
491
|
+
// dependentes e o retarget deixaria de ser limpo.
|
|
492
|
+
await scmDe(r).mergePullRequest({ number: String(pr.number), strategy: 'merge' });
|
|
442
493
|
} catch (err) {
|
|
443
494
|
// 405 = draft/check pendente/conflito. Parar AQUI preserva a ordem: os
|
|
444
495
|
// dependentes continuam com branch e PR intactos, e rodar de novo retoma.
|
|
@@ -469,7 +520,7 @@ export async function merge({
|
|
|
469
520
|
if (!keepBranches) {
|
|
470
521
|
for (const { repo: r, head } of mergedHeads) {
|
|
471
522
|
if (!head) continue;
|
|
472
|
-
await
|
|
523
|
+
await scmDe(r).deleteBranch({ branch: head }).catch(err =>
|
|
473
524
|
p.log.warn(`Branch ${head} (${r.owner}/${r.repo}) não apagada: ${err.message}`));
|
|
474
525
|
}
|
|
475
526
|
}
|
package/src/commands/mode.mjs
CHANGED
|
@@ -16,7 +16,11 @@ import * as p from '@clack/prompts';
|
|
|
16
16
|
import chalk from 'chalk';
|
|
17
17
|
|
|
18
18
|
import { resolveToken } from '../api/auth.mjs';
|
|
19
|
-
import {
|
|
19
|
+
import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
|
|
20
|
+
|
|
21
|
+
/** Porta de SCM do repositório corrente — só a variável de execução sai daqui. */
|
|
22
|
+
const scmDe = (token, owner, repo) =>
|
|
23
|
+
createGithubScm({ link: githubLink({ owner, repo }), token });
|
|
20
24
|
import { CONFIG_FILE, WORKFLOW_FILES } from '../config.mjs';
|
|
21
25
|
import { updateConfig } from '../lib/config-file.mjs';
|
|
22
26
|
import {
|
|
@@ -45,7 +49,7 @@ export function unguardedWorkflows(root) {
|
|
|
45
49
|
// verificável", e quem chama distingue isso de "não existe" (null).
|
|
46
50
|
async function readVariable(token, owner, repo) {
|
|
47
51
|
try {
|
|
48
|
-
return await
|
|
52
|
+
return await scmDe(token, owner, repo).getVariable({ name: EXECUTION_VARIABLE });
|
|
49
53
|
} catch (err) {
|
|
50
54
|
if (err.status === 403 || err.status === 404) return undefined;
|
|
51
55
|
throw err;
|
|
@@ -142,12 +146,12 @@ export async function mode({ target, dryRun = false } = {}) {
|
|
|
142
146
|
if (token && owner && repo) {
|
|
143
147
|
try {
|
|
144
148
|
if (esperado === null) {
|
|
145
|
-
const removida = await
|
|
149
|
+
const removida = await scmDe(token, owner, repo).deleteVariable({ name: EXECUTION_VARIABLE });
|
|
146
150
|
p.log.success(removida
|
|
147
151
|
? `Variável ${EXECUTION_VARIABLE} removida — os workflows voltam a disparar.`
|
|
148
152
|
: `Variável ${EXECUTION_VARIABLE} já não existia.`);
|
|
149
153
|
} else {
|
|
150
|
-
await
|
|
154
|
+
await scmDe(token, owner, repo).setVariable({ name: EXECUTION_VARIABLE, value: esperado });
|
|
151
155
|
p.log.success(`Variável ${EXECUTION_VARIABLE}=${esperado} — os jobs passam a ser pulados (0 minutos).`);
|
|
152
156
|
}
|
|
153
157
|
} catch (err) {
|
package/src/commands/move.mjs
CHANGED
|
@@ -13,10 +13,9 @@
|
|
|
13
13
|
import * as p from '@clack/prompts';
|
|
14
14
|
import chalk from 'chalk';
|
|
15
15
|
import { resolveToken } from '../api/auth.mjs';
|
|
16
|
-
import {
|
|
17
|
-
import { addProjectItem, getItemSingleSelectValue } from '../api/github-graphql.mjs';
|
|
16
|
+
import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
|
|
18
17
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
19
|
-
import {
|
|
18
|
+
import { openTracker, advanceToStage, resolveStageName } from '../lib/board.mjs';
|
|
20
19
|
import { resolveHubContext } from '../lib/project-root.mjs';
|
|
21
20
|
import {
|
|
22
21
|
CONFIG_FILE, PROGRESS_TODO, PROGRESS_IN_PROGRESS, PROGRESS_DONE,
|
|
@@ -96,7 +95,7 @@ export function readinessWarnings({ type, stage, labels = [] } = {}) {
|
|
|
96
95
|
return avisos;
|
|
97
96
|
}
|
|
98
97
|
|
|
99
|
-
export async function move({ issue: issueArg, stage: stageArg, status: statusArg }) {
|
|
98
|
+
export async function move({ issue: issueArg, stage: stageArg, status: statusArg, deps = {} }) {
|
|
100
99
|
const issueNumber = parseInt(String(issueArg).replace('#', ''), 10);
|
|
101
100
|
if (!Number.isInteger(issueNumber) || issueNumber <= 0) {
|
|
102
101
|
p.log.error(`Issue inválida: "${issueArg}". Use o número da issue, ex.: 12 ou #12.`);
|
|
@@ -142,7 +141,8 @@ export async function move({ issue: issueArg, stage: stageArg, status: statusArg
|
|
|
142
141
|
|
|
143
142
|
let issue;
|
|
144
143
|
try {
|
|
145
|
-
issue = await
|
|
144
|
+
issue = await (deps.tracker ?? createGithubTracker({ token, owner, repo }))
|
|
145
|
+
.getWorkItem({ ref: { key: String(issueNumber) } });
|
|
146
146
|
} catch (err) {
|
|
147
147
|
p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
|
|
148
148
|
process.exitCode = 1;
|
|
@@ -171,36 +171,32 @@ export async function move({ issue: issueArg, stage: stageArg, status: statusArg
|
|
|
171
171
|
}
|
|
172
172
|
|
|
173
173
|
// Portões do fluxo: aviso antes de escrever, com a issue já em mãos.
|
|
174
|
-
|
|
174
|
+
// `issue` e não `issue.labels`: o WorkItem da porta guarda as labels em
|
|
175
|
+
// `tags`, e `labelNames` aceita a issue inteira. Lendo `.labels`, o default
|
|
176
|
+
// `= []` engolia tudo e o aviso de Ready NUNCA saía.
|
|
177
|
+
for (const aviso of readinessWarnings({ type, stage, labels: issue })) {
|
|
175
178
|
p.log.warn(`#${issueNumber} ${aviso}`);
|
|
176
179
|
}
|
|
177
180
|
|
|
178
|
-
const {
|
|
181
|
+
const { tracker, error: projectError } = openTracker({ token, owner, repo, cwd: root || process.cwd(), tracker: deps.tracker });
|
|
179
182
|
if (projectError) {
|
|
180
183
|
p.log.error(`${projectError} — board não atualizado. Rode \`spec-wave init\` (ou \`spec-wave refresh --config\`).`);
|
|
181
184
|
process.exitCode = 1;
|
|
182
185
|
return;
|
|
183
186
|
}
|
|
184
|
-
const
|
|
185
|
-
const statusField = await resolveField(token, project, 'Status').catch(() => null);
|
|
186
|
-
// O `move` também REPARA o Work Item Type quando ele está vazio (o `apply` não
|
|
187
|
-
// o escrevia, então há board com dezenas de itens sem tipo). Só no vazio, e
|
|
188
|
-
// mesmo quando a Etapa não avança — ver ensureWorkItemType.
|
|
189
|
-
const typeField = await resolveField(token, project, 'Work Item Type').catch(() => null);
|
|
187
|
+
const ref = issue.ref;
|
|
190
188
|
|
|
191
189
|
// A Etapa de PARTIDA, lida antes de escrever: a mensagem de sucesso imprime a
|
|
192
190
|
// transição real ("✅ Ready → 🧪 QA"), não a intenção do comando.
|
|
193
|
-
const lerEtapa =
|
|
194
|
-
const itemId = await addProjectItem(token, project.id, issue.node_id);
|
|
195
|
-
return etapaField?.id ? await getItemSingleSelectValue(token, itemId, etapaField.id) : null;
|
|
196
|
-
};
|
|
191
|
+
const lerEtapa = () => tracker.getStage({ ref });
|
|
197
192
|
const antes = await lerEtapa().catch(() => null);
|
|
198
193
|
|
|
199
194
|
let moved;
|
|
200
195
|
try {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
196
|
+
// `itemType` REPARA o Work Item Type quando ele está vazio (o `apply` não o
|
|
197
|
+
// escrevia, então há board com dezenas de itens sem tipo). Só no vazio, e
|
|
198
|
+
// mesmo quando a Etapa não avança — ver ensureWorkItemType.
|
|
199
|
+
moved = await advanceToStage({ tracker, ref, stage, progress: status, itemType: type });
|
|
204
200
|
} catch (err) {
|
|
205
201
|
p.log.error(`Falha ao atualizar o board: ${err.message}`);
|
|
206
202
|
process.exitCode = 1;
|
package/src/commands/order.mjs
CHANGED
|
@@ -24,8 +24,7 @@ import path from 'node:path';
|
|
|
24
24
|
import * as p from '@clack/prompts';
|
|
25
25
|
import chalk from 'chalk';
|
|
26
26
|
import { resolveToken } from '../api/auth.mjs';
|
|
27
|
-
import {
|
|
28
|
-
import { listSubIssues } from '../api/github-graphql.mjs';
|
|
27
|
+
import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
|
|
29
28
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
30
29
|
import { parseDependencies, orderStories } from '../lib/dependencies.mjs';
|
|
31
30
|
import { loadProjectConfig, selectOpenFeatures } from '../lib/board.mjs';
|
|
@@ -68,14 +67,21 @@ export function featureLabel(feature) {
|
|
|
68
67
|
* @returns {string[]} uma linha de aviso por Story divergente
|
|
69
68
|
*/
|
|
70
69
|
export function milestoneMismatches(featureMilestone, stories = []) {
|
|
71
|
-
|
|
72
|
-
|
|
70
|
+
// Aceita as DUAS formas: `key` (MilestoneRef, o que a porta devolve) e
|
|
71
|
+
// `number` (a milestone crua, que ainda chega pelo story-graph). Sem isso a
|
|
72
|
+
// função devolveria [] em silêncio na forma nova — e um aviso que some é
|
|
73
|
+
// pior que um aviso errado, porque ninguém vai procurá-lo.
|
|
74
|
+
const chave = m => (m?.key != null ? String(m.key) : (Number.isInteger(m?.number) ? String(m.number) : null));
|
|
75
|
+
const alvo = chave(featureMilestone);
|
|
76
|
+
if (!alvo) return [];
|
|
77
|
+
const ref = featureMilestone.title || `#${alvo}`;
|
|
73
78
|
const out = [];
|
|
74
79
|
for (const s of stories) {
|
|
75
|
-
|
|
80
|
+
const dela = chave(s?.milestone);
|
|
81
|
+
if (!dela) {
|
|
76
82
|
out.push(`#${s.number} está SEM milestone — a Feature está em "${ref}".`);
|
|
77
|
-
} else if (
|
|
78
|
-
out.push(`#${s.number} está em "${s.milestone.title || `#${
|
|
83
|
+
} else if (dela !== alvo) {
|
|
84
|
+
out.push(`#${s.number} está em "${s.milestone.title || `#${dela}`}", mas a Feature está em "${ref}".`);
|
|
79
85
|
}
|
|
80
86
|
}
|
|
81
87
|
return out;
|
|
@@ -136,7 +142,7 @@ async function orderBoard({ token, owner, repo, root, ttlSec, opts }) {
|
|
|
136
142
|
|
|
137
143
|
let snapshot;
|
|
138
144
|
try {
|
|
139
|
-
snapshot = await loadBoardSnapshot({ token, project, root, refresh: opts.refresh, ttlSec });
|
|
145
|
+
snapshot = await loadBoardSnapshot({ token, owner, repo, project, root, refresh: opts.refresh, ttlSec });
|
|
140
146
|
} catch (err) {
|
|
141
147
|
emitError(opts, `Não foi possível ler os itens do Project: ${err.message}`);
|
|
142
148
|
process.exitCode = 1;
|
|
@@ -317,7 +323,8 @@ export async function order({
|
|
|
317
323
|
// 1. Lê a Feature e valida o tipo (1 chamada — a issue-alvo nunca vem de cache).
|
|
318
324
|
let featureIssue;
|
|
319
325
|
try {
|
|
320
|
-
featureIssue = await
|
|
326
|
+
featureIssue = await createGithubTracker({ token, owner, repo })
|
|
327
|
+
.getWorkItem({ ref: { key: String(featureNumber) } });
|
|
321
328
|
} catch (err) {
|
|
322
329
|
emitError(opts, `Não foi possível ler a issue #${featureNumber}: ${err.message}`);
|
|
323
330
|
process.exitCode = 1;
|
|
@@ -338,7 +345,7 @@ export async function order({
|
|
|
338
345
|
try {
|
|
339
346
|
carga = await loadFeatureStories({
|
|
340
347
|
token, owner, repo, root,
|
|
341
|
-
feature: { number: featureNumber, nodeId: featureIssue.
|
|
348
|
+
feature: { number: featureNumber, nodeId: featureIssue.ref.id, title: featureIssue.title },
|
|
342
349
|
remote, refresh, ttlSec,
|
|
343
350
|
});
|
|
344
351
|
} catch (err) {
|
|
@@ -365,7 +372,7 @@ export async function order({
|
|
|
365
372
|
if (!json) p.log.warn(`${projectError} — Etapas do board não consultadas.`);
|
|
366
373
|
} else {
|
|
367
374
|
try {
|
|
368
|
-
const snapshot = await loadBoardSnapshot({ token, project, root, refresh, ttlSec });
|
|
375
|
+
const snapshot = await loadBoardSnapshot({ token, owner, repo, project, root, refresh, ttlSec });
|
|
369
376
|
for (const s of enriched) stageOf.set(s.number, snapshot.index.get(s.number)?.fields?.Etapa ?? null);
|
|
370
377
|
boardMeta = {
|
|
371
378
|
stages: snapshot.fromCache ? 'cache' : 'board',
|
|
@@ -513,10 +520,11 @@ function commitSyncedFiles(root, filesRel, featureNumber) {
|
|
|
513
520
|
}
|
|
514
521
|
|
|
515
522
|
async function syncDependencies({ token, owner, repo, root, opts, featureNumber }) {
|
|
523
|
+
const tracker = createGithubTracker({ token, owner, repo });
|
|
516
524
|
// Alvos: a Feature pedida, ou as Features abertas do board (--milestone filtra).
|
|
517
525
|
let targets = [];
|
|
518
526
|
if (featureNumber) {
|
|
519
|
-
const issue = await
|
|
527
|
+
const issue = await tracker.getWorkItem({ ref: { key: String(featureNumber) } }).catch((err) => {
|
|
520
528
|
emitError(opts, `Não foi possível ler a issue #${featureNumber}: ${err.message}`);
|
|
521
529
|
return null;
|
|
522
530
|
});
|
|
@@ -526,7 +534,9 @@ async function syncDependencies({ token, owner, repo, root, opts, featureNumber
|
|
|
526
534
|
process.exitCode = 1;
|
|
527
535
|
return;
|
|
528
536
|
}
|
|
529
|
-
|
|
537
|
+
// `ref.id`: o WorkItem da porta não tem `node_id`, e um nodeId ausente faz
|
|
538
|
+
// o plugin pagar um getIssue a mais para reidratar o que já estava aqui.
|
|
539
|
+
targets = [{ number: featureNumber, nodeId: issue.ref?.id, title: issue.title }];
|
|
530
540
|
} else {
|
|
531
541
|
const { project, error } = loadProjectConfig();
|
|
532
542
|
if (error) {
|
|
@@ -535,7 +545,7 @@ async function syncDependencies({ token, owner, repo, root, opts, featureNumber
|
|
|
535
545
|
return;
|
|
536
546
|
}
|
|
537
547
|
// Sync é reconciliação: sempre parte de um snapshot FRESCO.
|
|
538
|
-
const snapshot = await loadBoardSnapshot({ token, project, root, refresh: true });
|
|
548
|
+
const snapshot = await loadBoardSnapshot({ token, owner, repo, project, root, refresh: true });
|
|
539
549
|
let features = selectOpenFeatures(snapshot.items);
|
|
540
550
|
if (opts.milestone) features = filterItemsByMilestone(features, opts.milestone);
|
|
541
551
|
targets = features;
|
|
@@ -544,14 +554,14 @@ async function syncDependencies({ token, owner, repo, root, opts, featureNumber
|
|
|
544
554
|
let synced = 0;
|
|
545
555
|
let untouched = 0;
|
|
546
556
|
for (const feature of targets) {
|
|
547
|
-
const resultado = await syncOneFeature({ token, owner, repo, root, feature });
|
|
557
|
+
const resultado = await syncOneFeature({ token, owner, repo, tracker, root, feature });
|
|
548
558
|
if (resultado === 'synced') synced += 1;
|
|
549
559
|
else if (resultado === 'unchanged') untouched += 1;
|
|
550
560
|
}
|
|
551
561
|
p.outro(`${chalk.green('✓')} sync: ${synced} Feature(s) atualizada(s), ${untouched} já em dia.`);
|
|
552
562
|
}
|
|
553
563
|
|
|
554
|
-
async function syncOneFeature({ token, owner, repo, root, feature }) {
|
|
564
|
+
async function syncOneFeature({ token, owner, repo, tracker, root, feature }) {
|
|
555
565
|
let paths;
|
|
556
566
|
try {
|
|
557
567
|
paths = featureDocPaths(root, { title: feature.title }, 'Feature');
|
|
@@ -578,16 +588,17 @@ async function syncOneFeature({ token, owner, repo, root, feature }) {
|
|
|
578
588
|
|
|
579
589
|
// Leitura VIVA: body ∪ blocked_by, sempre frescos — sync que lê cache
|
|
580
590
|
// reconciliaria o doc com ele mesmo.
|
|
581
|
-
const subs = (await
|
|
582
|
-
|
|
591
|
+
const subs = (await tracker.listChildren({
|
|
592
|
+
ref: { key: String(feature.number), id: feature.nodeId || feature.node_id },
|
|
593
|
+
})).filter(s => detectIssueType(s) === 'Story');
|
|
583
594
|
const remoteEdges = [];
|
|
584
595
|
for (const s of subs) {
|
|
585
|
-
const blockedBy = (await listBlockedBy(
|
|
586
|
-
.map(b => b.
|
|
587
|
-
remoteEdges.push({ number: s.
|
|
596
|
+
const blockedBy = (await tracker.listBlockedBy({ ref: s.ref }).catch(() => []))
|
|
597
|
+
.map(b => Number(b.ref.key));
|
|
598
|
+
remoteEdges.push({ number: Number(s.ref.key), dependsOn: blockedBy });
|
|
588
599
|
}
|
|
589
600
|
const liveDeps = mergeDependencyEdges(
|
|
590
|
-
subs.map(s => ({ number: s.
|
|
601
|
+
subs.map(s => ({ number: Number(s.ref.key), dependsOn: parseDependencies(s.body) })),
|
|
591
602
|
remoteEdges,
|
|
592
603
|
);
|
|
593
604
|
|