@spec-wave/cli 1.0.7 → 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 +91 -59
- package/src/commands/decompose.mjs +258 -221
- package/src/commands/doctor.mjs +16 -11
- package/src/commands/generate-bug.mjs +51 -44
- package/src/commands/generate-plan.mjs +83 -63
- package/src/commands/generate-qa-plan.mjs +145 -117
- package/src/commands/generate-spec.mjs +33 -28
- package/src/commands/implement.mjs +155 -79
- package/src/commands/info.mjs +4 -3
- package/src/commands/init.mjs +11 -5
- package/src/commands/install-skill.mjs +19 -0
- package/src/commands/issue.mjs +26 -39
- package/src/commands/merge.mjs +71 -20
- package/src/commands/mode.mjs +11 -6
- 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 +30 -17
- package/src/commands/qa-run.mjs +125 -103
- 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 +12 -4
- 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 +31 -22
- 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/cli-ref.mjs +75 -0
- package/src/lib/config-file.mjs +2 -1
- package/src/lib/doc-availability.mjs +10 -3
- package/src/lib/doc-source.mjs +9 -9
- package/src/lib/execution-mode.mjs +5 -3
- package/src/lib/implement-board.mjs +23 -26
- package/src/lib/issue-type.mjs +5 -1
- package/src/lib/plugin-skills.mjs +10 -0
- 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/qa-report.mjs +2 -1
- package/src/lib/skill-compose.mjs +3 -0
- 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/templates/workflows/code/code-review.yml +1 -1
- package/src/templates/workflows/code/qa.yml +1 -1
package/src/commands/init.mjs
CHANGED
|
@@ -7,7 +7,8 @@ import { runWizard } from '../ui/wizard.mjs';
|
|
|
7
7
|
import { setupProject } from '../setup/project.mjs';
|
|
8
8
|
import { setupLabels } from '../setup/labels.mjs';
|
|
9
9
|
import { setupFiles } from '../setup/files.mjs';
|
|
10
|
-
import {
|
|
10
|
+
import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
|
|
11
|
+
import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
|
|
11
12
|
import {
|
|
12
13
|
CONFIG_FILE, AI_PROVIDERS, getProvider, DEFAULT_PROVIDER, PORTAL_URL, WORKFLOW_FILES, CODE_WORKFLOW_FILES,
|
|
13
14
|
ISSUE_TEMPLATE_FILES, STATUS_OPTIONS, ALL_LABELS, HUB_DISPATCH_SECRET,
|
|
@@ -18,6 +19,7 @@ import { REPO_ROLES, DEFAULT_REPO_ROLE, parseRepoRef } from '../lib/repo-role.mj
|
|
|
18
19
|
// (SPEC_WAVE_CLI_VERSION) — este comando roda dentro de um bundle no init
|
|
19
20
|
// server-side da UI, onde não existe package.json dois níveis acima.
|
|
20
21
|
import { CLI_VERSION } from '../lib/templates.mjs';
|
|
22
|
+
import { cliRef } from '../lib/cli-ref.mjs';
|
|
21
23
|
|
|
22
24
|
export async function init(options) {
|
|
23
25
|
// --- Papel (RFC-005) ---
|
|
@@ -135,7 +137,10 @@ export async function init(options) {
|
|
|
135
137
|
ownerSpinner.start(`Verificando se ${owner} é uma organização...`);
|
|
136
138
|
let ownerType;
|
|
137
139
|
try {
|
|
138
|
-
|
|
140
|
+
// `verify()` é a sonda org-vs-user: o GitHub App só alcança Projects v2 de
|
|
141
|
+
// ORGANIZAÇÃO, e é aqui que o init recusa antes de criar qualquer coisa.
|
|
142
|
+
const diag = await createGithubTracker({ token, owner, repo }).verify();
|
|
143
|
+
ownerType = diag.facts.ownerType;
|
|
139
144
|
} catch (err) {
|
|
140
145
|
ownerSpinner.stop('');
|
|
141
146
|
p.log.error(`Erro ao verificar owner "${owner}": ${err.message}`);
|
|
@@ -183,7 +188,8 @@ export async function init(options) {
|
|
|
183
188
|
const localConfigPath = path.join(process.cwd(), CONFIG_FILE);
|
|
184
189
|
const raw = existsSync(localConfigPath)
|
|
185
190
|
? readFileSync(localConfigPath, 'utf-8')
|
|
186
|
-
: await
|
|
191
|
+
: await createGithubScm({ link: githubLink({ owner, repo }), token })
|
|
192
|
+
.readFile({ path: CONFIG_FILE });
|
|
187
193
|
if (raw) {
|
|
188
194
|
const existing = JSON.parse(raw);
|
|
189
195
|
if (existing.project) {
|
|
@@ -314,7 +320,7 @@ export async function init(options) {
|
|
|
314
320
|
` Próximos passos:\n` +
|
|
315
321
|
(configWritten ? ` 1. Commite o ${CONFIG_FILE} (git add ${CONFIG_FILE} && git commit) — os despachantes o leem em runtime\n` : '') +
|
|
316
322
|
` ${configWritten ? '2' : '1'}. Autenticação do despacho para o hub: a GitHub App da org (secrets SPEC_WAVE_APP_ID + SPEC_WAVE_APP_PRIVATE_KEY, App instalada nos dois repos) ou o secret ${HUB_DISPATCH_SECRET} com um token de escrita em Contents no hub\n` +
|
|
317
|
-
` ${configWritten ? '3' : '2'}. No hub, rode \`npx
|
|
323
|
+
` ${configWritten ? '3' : '2'}. No hub, rode \`npx ${cliRef()} update\` para instalar o pr-events.yml (recebe os despachos)\n` +
|
|
318
324
|
` ${configWritten ? '4' : '3'}. Registre este repo no hub: \`repositories: [{ "slug": "<slug>", "owner": "${owner}", "repo": "${repo}" }]\` no ${CONFIG_FILE} do hub\n` +
|
|
319
325
|
` ${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` +
|
|
320
326
|
` Nos PRs deste repo, vincule a Story com \`Closes ${hub.owner}/${hub.repo}#<n>\` — a forma qualificada é a que o hub reconhece.`
|
|
@@ -350,7 +356,7 @@ export async function init(options) {
|
|
|
350
356
|
` ${configWritten ? '3' : '2'}. Configure o board view para agrupar por "Etapa"\n` +
|
|
351
357
|
` ${configWritten ? '4' : '3'}. Crie uma Feature com o prefixo [FEATURE] no título\n` +
|
|
352
358
|
` ${configWritten ? '5' : '4'}. Use a skill spec-wave para guiar o fluxo\n\n` +
|
|
353
|
-
` ${chalk.dim('Para instalar a skill no seu agente: npx
|
|
359
|
+
` ${chalk.dim('Para instalar a skill no seu agente: npx ${cliRef()} install-skill')}\n\n` +
|
|
354
360
|
` 🌐 Acesse o Portal Web da ferramenta em ${chalk.cyan(PORTAL_URL)}`
|
|
355
361
|
);
|
|
356
362
|
}
|
|
@@ -5,6 +5,7 @@ import { homedir } from 'node:os';
|
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { parseSkill } from '../lib/skill-file.mjs';
|
|
7
7
|
import { listPluginSkills, planPluginSkillFiles } from '../lib/plugin-skills.mjs';
|
|
8
|
+
import { pinCliRefs } from '../lib/cli-ref.mjs';
|
|
8
9
|
// TEMPLATES_DIR e CLI_VERSION já tratam os escapes de empacotamento
|
|
9
10
|
// (SPEC_WAVE_TEMPLATES_DIR / SPEC_WAVE_CLI_VERSION) — ver lib/templates.mjs.
|
|
10
11
|
import { TEMPLATES_DIR, CLI_VERSION } from '../lib/templates.mjs';
|
|
@@ -104,6 +105,10 @@ export { parseSkill };
|
|
|
104
105
|
|
|
105
106
|
// Banner de versão inserido no topo do corpo da skill instalada. O agente lê
|
|
106
107
|
// esta linha e, se `npx @spec-wave/cli@latest --version` for maior, orienta reinstalar.
|
|
108
|
+
// `@latest` PERMANECE aqui: o banner entra na skill e a saída inteira do
|
|
109
|
+
// render passa por `pinCliRefs`, que o troca pela major de quem instalou.
|
|
110
|
+
// Chamar `cliRef()` daqui leria o config do cwd de quem gera, não de quem
|
|
111
|
+
// recebe a cópia — duas fontes para a mesma decisão.
|
|
107
112
|
export function versionBanner(version) {
|
|
108
113
|
return (
|
|
109
114
|
`> ⚙️ **spec-wave skill v${version}** — esta skill é uma cópia estática. ` +
|
|
@@ -114,7 +119,21 @@ export function versionBanner(version) {
|
|
|
114
119
|
}
|
|
115
120
|
|
|
116
121
|
// Converte o SKILL.md para o formato exigido por cada agente, carimbando a versão.
|
|
122
|
+
//
|
|
123
|
+
// A saída passa inteira por `pinCliRefs`: o arquivo-fonte guarda
|
|
124
|
+
// `@spec-wave/cli@latest` (legível, sem versão a manter à mão) e a CÓPIA
|
|
125
|
+
// instalada sai presa à MAJOR de quem a instalou — um agente que leia a skill e
|
|
126
|
+
// execute literalmente não atravessa a fronteira 0.x ↔ 1.x (lib/cli-ref.mjs).
|
|
127
|
+
//
|
|
128
|
+
// Inteira, e não só o corpo, por causa do frontmatter: `allowed-tools` traz
|
|
129
|
+
// `Bash(npx @spec-wave/cli@latest *)`, que é uma PERMISSÃO. Pinar os comandos e
|
|
130
|
+
// deixar a permissão em `@latest` faria o agente pedir aprovação a cada chamada
|
|
131
|
+
// — o padrão precisa casar com o que a skill manda rodar.
|
|
117
132
|
export function renderContent(format, parsed, version) {
|
|
133
|
+
return pinCliRefs(renderContentRaw(format, parsed, version), version);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function renderContentRaw(format, parsed, version) {
|
|
118
137
|
const { meta, frontmatter, body } = parsed;
|
|
119
138
|
const description = meta.description ?? 'Skill spec-wave.';
|
|
120
139
|
const banner = versionBanner(version);
|
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 {
|
|
@@ -24,6 +28,7 @@ import {
|
|
|
24
28
|
configuredMode, variableValueFor, describeModeState, shouldWriteVariable,
|
|
25
29
|
} from '../lib/execution-mode.mjs';
|
|
26
30
|
import { loadConfig } from '../lib/project-root.mjs';
|
|
31
|
+
import { cliRef } from '../lib/cli-ref.mjs';
|
|
27
32
|
|
|
28
33
|
/**
|
|
29
34
|
* Workflows instalados que NÃO carregam a guarda (função quase pura — só lê o fs).
|
|
@@ -44,7 +49,7 @@ export function unguardedWorkflows(root) {
|
|
|
44
49
|
// verificável", e quem chama distingue isso de "não existe" (null).
|
|
45
50
|
async function readVariable(token, owner, repo) {
|
|
46
51
|
try {
|
|
47
|
-
return await
|
|
52
|
+
return await scmDe(token, owner, repo).getVariable({ name: EXECUTION_VARIABLE });
|
|
48
53
|
} catch (err) {
|
|
49
54
|
if (err.status === 403 || err.status === 404) return undefined;
|
|
50
55
|
throw err;
|
|
@@ -56,7 +61,7 @@ export async function mode({ target, dryRun = false } = {}) {
|
|
|
56
61
|
|
|
57
62
|
const { config, root, configPath } = loadConfig();
|
|
58
63
|
if (!config) {
|
|
59
|
-
p.log.error(`${CONFIG_FILE} não encontrado — rode \`npx
|
|
64
|
+
p.log.error(`${CONFIG_FILE} não encontrado — rode \`npx ${cliRef()} init\` antes.`);
|
|
60
65
|
process.exit(1);
|
|
61
66
|
}
|
|
62
67
|
|
|
@@ -141,12 +146,12 @@ export async function mode({ target, dryRun = false } = {}) {
|
|
|
141
146
|
if (token && owner && repo) {
|
|
142
147
|
try {
|
|
143
148
|
if (esperado === null) {
|
|
144
|
-
const removida = await
|
|
149
|
+
const removida = await scmDe(token, owner, repo).deleteVariable({ name: EXECUTION_VARIABLE });
|
|
145
150
|
p.log.success(removida
|
|
146
151
|
? `Variável ${EXECUTION_VARIABLE} removida — os workflows voltam a disparar.`
|
|
147
152
|
: `Variável ${EXECUTION_VARIABLE} já não existia.`);
|
|
148
153
|
} else {
|
|
149
|
-
await
|
|
154
|
+
await scmDe(token, owner, repo).setVariable({ name: EXECUTION_VARIABLE, value: esperado });
|
|
150
155
|
p.log.success(`Variável ${EXECUTION_VARIABLE}=${esperado} — os jobs passam a ser pulados (0 minutos).`);
|
|
151
156
|
}
|
|
152
157
|
} catch (err) {
|
|
@@ -166,7 +171,7 @@ export async function mode({ target, dryRun = false } = {}) {
|
|
|
166
171
|
if (alvo === 'local' && semGuarda.length > 0) {
|
|
167
172
|
p.log.warn(
|
|
168
173
|
`Estes workflows instalados ainda não têm a guarda \`${EXECUTION_GUARD}\` e vão rodar mesmo assim: ` +
|
|
169
|
-
`${semGuarda.join(', ')}. Rode \`npx
|
|
174
|
+
`${semGuarda.join(', ')}. Rode \`npx ${cliRef()} update\`.`
|
|
170
175
|
);
|
|
171
176
|
}
|
|
172
177
|
|
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;
|