@spec-wave/cli 1.7.6 → 1.9.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/README.md +1 -1
- package/package.json +1 -1
- package/src/agent/errors.mjs +31 -1
- package/src/agent/openrouter-agent.mjs +25 -2
- package/src/api/github-graphql.mjs +31 -0
- package/src/api/github-rest.mjs +20 -0
- package/src/cli.mjs +103 -36
- package/src/commands/auth-check.mjs +72 -0
- package/src/commands/decompose.mjs +14 -2
- package/src/commands/doctor.mjs +139 -2
- package/src/commands/generate-bug.mjs +6 -6
- package/src/commands/generate-plan.mjs +9 -8
- package/src/commands/generate-qa-plan.mjs +9 -6
- package/src/commands/generate-spec.mjs +12 -7
- package/src/commands/implement.mjs +21 -0
- package/src/commands/init.mjs +2 -2
- package/src/commands/preflight.mjs +38 -2
- package/src/commands/progress.mjs +144 -0
- package/src/commands/relink.mjs +105 -0
- package/src/commands/report-failure.mjs +99 -0
- package/src/commands/retry.mjs +91 -0
- package/src/commands/task.mjs +5 -0
- package/src/commands/update.mjs +70 -0
- package/src/config.mjs +8 -8
- package/src/lib/cited-paths.mjs +89 -0
- package/src/lib/claude.mjs +4 -2
- package/src/lib/cli-line.mjs +153 -0
- package/src/lib/cli-ref.mjs +53 -2
- package/src/lib/failure-report.mjs +319 -0
- package/src/lib/progress-events.mjs +46 -0
- package/src/lib/repo-identity.mjs +55 -0
- package/src/lib/spec-index.mjs +114 -0
- package/src/lib/tech-context.mjs +144 -5
- package/src/plugin/.claude-plugin/plugin.json +1 -1
- package/src/plugin/skills/plan/SKILL.md +1 -1
- package/src/plugin/skills/plan/reference/tech-context.md +12 -4
- package/src/plugin/skills/setup/SKILL.md +1 -1
- package/src/plugin/skills/spec/model-prompt.md +8 -1
- package/src/plugins/scm-github/index.mjs +8 -1
- package/src/plugins/tracker-github-projects/index.mjs +11 -4
- package/src/ports/tracker.mjs +2 -1
- package/src/setup/labels.mjs +5 -3
- package/src/setup/project.mjs +5 -3
- package/src/templates/config/tech_context.yml +29 -25
- package/src/templates/skill/SKILL.md +27 -9
- package/src/templates/skill/core.md +25 -7
- package/src/templates/workflows/code-review.yml +1 -0
- package/src/templates/workflows/critique.yml +11 -0
- package/src/templates/workflows/decompose.yml +27 -0
- package/src/templates/workflows/generate-bug.yml +26 -0
- package/src/templates/workflows/generate-plan.yml +26 -0
- package/src/templates/workflows/generate-qa-plan.yml +27 -0
- package/src/templates/workflows/generate-spec.yml +26 -0
- package/src/templates/workflows/pr-events.yml +5 -0
- package/src/templates/workflows/qa.yml +1 -0
- package/src/templates/workflows/validate.yml +11 -0
|
@@ -52,6 +52,7 @@ import {
|
|
|
52
52
|
LABEL_DECOMPOSED, LABEL_CRITIQUE_FAILED, LABEL_NEEDS_HUMAN, LABEL_RISK_ACCEPTED, TARGET_LANGUAGE,
|
|
53
53
|
STAGE_READY, PROGRESS_TODO, DEFAULT_MAX_CRITIQUE_ATTEMPTS, labelNames,
|
|
54
54
|
} from '../config.mjs';
|
|
55
|
+
import { classifyFailure } from '../lib/failure-report.mjs';
|
|
55
56
|
|
|
56
57
|
// Adiciona a issue ao board na Etapa ✅ Ready / Status Todo. Best-effort; a
|
|
57
58
|
// Etapa nunca retrocede (advanceToStage não toca itens já adiante).
|
|
@@ -1271,9 +1272,17 @@ async function resolveBoard({ token, projectToken, owner, repo, root, deps = {}
|
|
|
1271
1272
|
* @param {number[]} [params.createdItems] issues já criadas por este run
|
|
1272
1273
|
* @param {'apply'|'draft'} [params.mode]
|
|
1273
1274
|
*/
|
|
1274
|
-
export function renderApplyFailureComment({ trigger, message, createdItems = [], mode = 'apply' }) {
|
|
1275
|
+
export function renderApplyFailureComment({ trigger, message, createdItems = [], mode = 'apply', causa = null }) {
|
|
1276
|
+
// A causa classificada vem ANTES do erro bruto: é ela que o PM lê. Com issues
|
|
1277
|
+
// já criadas, o próximo passo genérico ("reaplique") é omitido — o conselho
|
|
1278
|
+
// específico abaixo é o que vale.
|
|
1279
|
+
const linhaCausa = causa
|
|
1280
|
+
? `**Causa provável (${causa.kind}):** ${causa.resumo}\n` +
|
|
1281
|
+
(createdItems.length === 0 ? `**Próximo passo:** ${causa.proximoPasso}\n` : '') + '\n'
|
|
1282
|
+
: '';
|
|
1275
1283
|
const cabecalho =
|
|
1276
1284
|
`❌ **Falha no decompose (${mode === 'apply' ? 'aplicação' : 'rascunho'}).**\n\n` +
|
|
1285
|
+
linhaCausa +
|
|
1277
1286
|
`\`\`\`\n${message}\n\`\`\`\n\n`;
|
|
1278
1287
|
if (createdItems.length === 0) {
|
|
1279
1288
|
return cabecalho +
|
|
@@ -1431,8 +1440,11 @@ export async function decompose({ issueNumber, apply, deps = {} }) {
|
|
|
1431
1440
|
body:
|
|
1432
1441
|
renderApplyFailureComment({
|
|
1433
1442
|
trigger, message: err.message, createdItems: ctx.createdItems, mode,
|
|
1443
|
+
causa: classifyFailure(err),
|
|
1434
1444
|
}),
|
|
1435
|
-
}).catch(() => {});
|
|
1445
|
+
}).then(() => { err.issueNotified = true; }).catch(() => {});
|
|
1446
|
+
} else {
|
|
1447
|
+
err.issueNotified = true;
|
|
1436
1448
|
}
|
|
1437
1449
|
throw err;
|
|
1438
1450
|
} finally {
|
package/src/commands/doctor.mjs
CHANGED
|
@@ -40,6 +40,10 @@ import {
|
|
|
40
40
|
tokenMismatchWarning, parseActiveAccount,
|
|
41
41
|
} from '../api/auth.mjs';
|
|
42
42
|
import { configuredRole } from '../lib/repo-role.mjs';
|
|
43
|
+
import { detectRepoMove, gitRemoteRepo } from '../lib/repo-identity.mjs';
|
|
44
|
+
import { fetchLatestVersion, inspectCliLine, installedPluginVersion } from '../lib/cli-line.mjs';
|
|
45
|
+
import { workflowPinnedVersion } from '../lib/cli-ref.mjs';
|
|
46
|
+
import { inspectTechContext, techContextTemplateHint, TECH_CONTEXT_PATH } from '../lib/tech-context.mjs';
|
|
43
47
|
import {
|
|
44
48
|
CONFIG_FILE, WORKFLOW_FILES, CODE_WORKFLOW_FILES, ARTIFACT_WORKFLOW_FILES, getProvider, DEFAULT_PROVIDER,
|
|
45
49
|
AI_PROVIDERS, STATUS_OPTIONS,
|
|
@@ -705,6 +709,56 @@ async function checkBoardHygiene(ctx) {
|
|
|
705
709
|
return { name, status, detail: notes.join('\n') };
|
|
706
710
|
}
|
|
707
711
|
|
|
712
|
+
/**
|
|
713
|
+
* Linha da CLI: config × workflows × CLI em execução × plugin × npm.
|
|
714
|
+
* Ver lib/cli-line.mjs. O `latest` do npm só é consultado fora do CI (ou via
|
|
715
|
+
* costura): o resto é disco.
|
|
716
|
+
*/
|
|
717
|
+
export async function checkCliLine(ctx) {
|
|
718
|
+
const name = 'Linha da CLI (config, workflows, plugin)';
|
|
719
|
+
const root = ctx.root;
|
|
720
|
+
const latestVersion = ctx.latestCliVersion !== undefined
|
|
721
|
+
? ctx.latestCliVersion
|
|
722
|
+
: (process.env.CI ? null : await fetchLatestVersion());
|
|
723
|
+
const { status, notes } = inspectCliLine({
|
|
724
|
+
configVersion: ctx.cfg?.version ?? null,
|
|
725
|
+
workflowVersion: root ? workflowPinnedVersion(root) : null,
|
|
726
|
+
cliVersion: CLI_VERSION,
|
|
727
|
+
pluginVersion: ctx.pluginVersion !== undefined ? ctx.pluginVersion : (root ? installedPluginVersion(root) : null),
|
|
728
|
+
latestVersion,
|
|
729
|
+
});
|
|
730
|
+
return { name, status, detail: notes.join('\n') };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* O tech_context descreve o sistema de verdade? (só lê disco)
|
|
735
|
+
*
|
|
736
|
+
* ✗ quando ainda é o template: o arquivo é sintaticamente válido, então nada
|
|
737
|
+
* mais no fluxo percebe — e um stack de exemplo lido como verdade fez specs e
|
|
738
|
+
* planos de um app Kotlin Multiplatform falarem de Postgres e Redis. Ausência é
|
|
739
|
+
* só aviso: o `generate-plan` segue sem contexto estático, e diz isso.
|
|
740
|
+
* Repositório de código não tem tech_context (ele é do hub).
|
|
741
|
+
*/
|
|
742
|
+
export function checkTechContext(ctx) {
|
|
743
|
+
const name = `Tech context (${TECH_CONTEXT_PATH})`;
|
|
744
|
+
if (!ctx.root || configuredRole(ctx.cfg) === 'code') {
|
|
745
|
+
return { name, status: 'skip', detail: 'Só se aplica ao hub (o tech_context mora lá).' };
|
|
746
|
+
}
|
|
747
|
+
const { state, reason, error } = inspectTechContext(ctx.root);
|
|
748
|
+
if (state === 'template') return { name, status: 'fail', detail: techContextTemplateHint(reason) };
|
|
749
|
+
if (state === 'invalid') {
|
|
750
|
+
return { name, status: 'fail', detail: `${TECH_CONTEXT_PATH} não parseia como YAML: ${error}` };
|
|
751
|
+
}
|
|
752
|
+
if (state === 'missing') {
|
|
753
|
+
return {
|
|
754
|
+
name, status: 'warn',
|
|
755
|
+
detail: `${TECH_CONTEXT_PATH} ausente — o plano técnico sai sem contexto estático. ` +
|
|
756
|
+
'Crie-o com o stack real (o modelo está em src/templates/config/tech_context.yml do pacote).',
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
return { name, status: 'ok', detail: 'Preenchido (tem conteúdo e não é o template do scaffold).' };
|
|
760
|
+
}
|
|
761
|
+
|
|
708
762
|
async function checkRepoAccess(ctx) {
|
|
709
763
|
const name = 'Acesso ao repositório';
|
|
710
764
|
const { cfg } = ctx;
|
|
@@ -722,6 +776,41 @@ async function checkRepoAccess(ctx) {
|
|
|
722
776
|
const nome = fatoDaPorta(ctx.scmVerify, 'repoFullName');
|
|
723
777
|
const privado = fatoDaPorta(ctx.scmVerify, 'repoPrivate');
|
|
724
778
|
const visibilidade = privado.estado === 'ok' ? ` (${privado.valor ? 'privado' : 'público'})` : '';
|
|
779
|
+
// Repo transferido/renomeado: a API segue o redirecionamento e devolve o
|
|
780
|
+
// nome ATUAL; o config guarda o antigo — e com ele o Project do dono antigo.
|
|
781
|
+
// Quem decide é a API: o repo CONFIGURADO resolveu para outro nome. O
|
|
782
|
+
// `origin` sozinho não prova nada — num fork ele difere com o config certo.
|
|
783
|
+
// `gitRemote: null` na costura DESLIGA a leitura do git (`??` cairia nela).
|
|
784
|
+
const remote = ctx.gitRemote !== undefined ? ctx.gitRemote : (ctx.root ? gitRemoteRepo(ctx.root) : null);
|
|
785
|
+
const mudanca = detectRepoMove({
|
|
786
|
+
configured: `${cfg.owner}/${cfg.repo}`,
|
|
787
|
+
apiName: nome.estado === 'ok' ? nome.valor : null,
|
|
788
|
+
remote,
|
|
789
|
+
});
|
|
790
|
+
if (mudanca.moved) {
|
|
791
|
+
return {
|
|
792
|
+
name,
|
|
793
|
+
status: 'fail',
|
|
794
|
+
detail:
|
|
795
|
+
`O ${CONFIG_FILE} aponta para ${cfg.owner}/${cfg.repo}, mas o repositório é ${mudanca.actual} ` +
|
|
796
|
+
'(a API do GitHub segue o redirecionamento). ' +
|
|
797
|
+
'Transferência ou renomeação: owner, repo e o Project do config ficaram com o dono antigo.\n' +
|
|
798
|
+
// `--repo` explícito: o padrão do relink é o `origin`, que num clone
|
|
799
|
+
// de fork reapontaria o config para o fork.
|
|
800
|
+
`Rode \`npx ${cliRef()} relink --repo ${mudanca.actual} --project <url do Project do dono atual>\` — ` +
|
|
801
|
+
'reescreve owner/repo e os ids do board (campos e opções).',
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
if (mudanca.remoteDiffers) {
|
|
805
|
+
return {
|
|
806
|
+
name,
|
|
807
|
+
status: 'ok',
|
|
808
|
+
detail:
|
|
809
|
+
`Token enxerga ${nome.estado === 'ok' ? nome.valor : `${cfg.owner}/${cfg.repo}`}${visibilidade}. ` +
|
|
810
|
+
`O git remote origin deste clone é ${remote} (fork ou outro remote) — o ${CONFIG_FILE} segue ` +
|
|
811
|
+
'apontando para o repositório certo; nada a corrigir.',
|
|
812
|
+
};
|
|
813
|
+
}
|
|
725
814
|
return {
|
|
726
815
|
name,
|
|
727
816
|
status: 'ok',
|
|
@@ -919,19 +1008,60 @@ async function checkAi(ctx) {
|
|
|
919
1008
|
notes.push(appPresent
|
|
920
1009
|
? 'Autenticação dos workflows: GitHub App da organização (SPEC_WAVE_APP_*); os PATs, se existirem, são fallback.'
|
|
921
1010
|
: 'Autenticação dos workflows: PATs (GH_PROJECT_TOKEN, GH_PR_TOKEN). Uma GitHub App da org (SPEC_WAVE_APP_ID + SPEC_WAVE_APP_PRIVATE_KEY) os substitui sem depender de uma pessoa.');
|
|
922
|
-
|
|
1011
|
+
// Secrets de ORGANIZAÇÃO não chegam a repositório PRIVADO no plano Free
|
|
1012
|
+
// — `organization-secrets` do repo volta vazio, sem erro. A App da org
|
|
1013
|
+
// fica inutilizável e os workflows caem nos PATs (caso real: semseguro).
|
|
1014
|
+
//
|
|
1015
|
+
// Só é aviso quando FALTA secret exigido: nesse plano a lista que a porta
|
|
1016
|
+
// devolve é a do próprio repositório, então quem já os configurou nele
|
|
1017
|
+
// está certo, e avisar para sempre ensinaria a ignorar o doctor.
|
|
1018
|
+
const plano = fatoDaPorta(ctx.scmVerify, 'ownerPlan');
|
|
1019
|
+
const privado = fatoDaPorta(ctx.scmVerify, 'repoPrivate');
|
|
1020
|
+
const freePrivado = plano.estado === 'ok' && String(plano.valor).toLowerCase() === 'free' &&
|
|
1021
|
+
privado.estado === 'ok' && privado.valor === true;
|
|
1022
|
+
// Sem a App, quem abre PR que dispara workflow é o GH_PR_TOKEN — o
|
|
1023
|
+
// GITHUB_TOKEN abre, mas o PR dele não aciona os checks. Ele é a
|
|
1024
|
+
// credencial ALTERNATIVA de abrir PR (ver `inspectPrPublishing`), então
|
|
1025
|
+
// só deixa de ser exigido quando os fatos mostram que o GITHUB_TOKEN
|
|
1026
|
+
// basta: o Actions pode abrir PR e não há check obrigatório na default.
|
|
1027
|
+
// Fato ilegível não dispensa — "não consegui olhar" não é "não precisa".
|
|
1028
|
+
const podeAbrir = fatoDaPorta(ctx.scmVerify, 'automationCanOpenPullRequest');
|
|
1029
|
+
const checks = fatoDaPorta(ctx.scmVerify, 'protectedChecks');
|
|
1030
|
+
const prTokenDispensavel = podeAbrir.estado === 'ok' && podeAbrir.valor === true &&
|
|
1031
|
+
checks.estado === 'ok' && Array.isArray(checks.valor) && checks.valor.length === 0;
|
|
1032
|
+
const required = appPresent
|
|
1033
|
+
? [provider.secret]
|
|
1034
|
+
: [provider.secret, 'GH_PROJECT_TOKEN', ...(prTokenDispensavel ? [] : ['GH_PR_TOKEN'])];
|
|
923
1035
|
const missing = required.filter((s) => !secretNames.includes(s));
|
|
1036
|
+
if (!appPresent && prTokenDispensavel && !secretNames.includes('GH_PR_TOKEN')) {
|
|
1037
|
+
notes.push(
|
|
1038
|
+
'GH_PR_TOKEN não definido — dispensável aqui: o Actions pode abrir Pull Requests com o ' +
|
|
1039
|
+
'GITHUB_TOKEN e a branch default não exige status check. Passa a ser necessário se um ' +
|
|
1040
|
+
'check obrigatório for criado (PR aberto pelo GITHUB_TOKEN não dispara workflow).'
|
|
1041
|
+
);
|
|
1042
|
+
}
|
|
924
1043
|
if (missing.length > 0) {
|
|
925
1044
|
status = 'warn';
|
|
926
1045
|
notes.push(`Secrets do Actions faltando em ${cfg.owner}/${cfg.repo}: ${missing.join(', ')} — configure em Settings → Secrets.`);
|
|
1046
|
+
if (freePrivado) {
|
|
1047
|
+
notes.push(
|
|
1048
|
+
`${cfg.owner} está no plano Free e ${cfg.repo} é privado: secrets de ORGANIZAÇÃO não chegam ` +
|
|
1049
|
+
'a este repositório. Configure os secrets (SPEC_WAVE_APP_ID/SPEC_WAVE_APP_PRIVATE_KEY, ' +
|
|
1050
|
+
`${provider.secret}, PATs) no próprio repositório — Settings → Secrets and variables → Actions.`
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
927
1053
|
} else {
|
|
928
1054
|
// PRESENÇA, não validade — a API expõe só os nomes dos secrets, nunca os
|
|
929
1055
|
// valores, então não há como testar daqui se o token funciona. Dizer só
|
|
930
1056
|
// "presentes" dava uma confiança que o check não sustenta: o
|
|
931
1057
|
// GH_PROJECT_TOKEN do caso real ESTAVA presente e não alcançava o
|
|
932
1058
|
// Project da organização, e as 27 issues criadas nasceram sem Etapa.
|
|
1059
|
+
// O GH_PR_TOKEN dispensável, quando existe, é listado: é ele que abre o PR.
|
|
1060
|
+
const presentes = !appPresent && prTokenDispensavel && secretNames.includes('GH_PR_TOKEN')
|
|
1061
|
+
? [...required, 'GH_PR_TOKEN']
|
|
1062
|
+
: required;
|
|
933
1063
|
notes.push(
|
|
934
|
-
`Secrets do Actions presentes: ${
|
|
1064
|
+
`Secrets do Actions presentes: ${presentes.join(', ')} ` +
|
|
935
1065
|
'(só o NOME é verificável — a API não expõe o valor, então isto não atesta ' +
|
|
936
1066
|
'que os tokens funcionam nem que têm o escopo necessário).'
|
|
937
1067
|
);
|
|
@@ -1813,6 +1943,11 @@ async function abrirPortas(ctx, deps = {}) {
|
|
|
1813
1943
|
*/
|
|
1814
1944
|
export async function doctorResults(options = {}, deps = {}) {
|
|
1815
1945
|
const ctx = { cwd: process.cwd(), deep: !!options.deep, deps };
|
|
1946
|
+
// Costuras do que vem de FORA do repositório: o npm, o registro de plugins
|
|
1947
|
+
// do Claude Code e o git remote. Ausentes, cada check lê o real.
|
|
1948
|
+
for (const k of ['latestCliVersion', 'pluginVersion', 'gitRemote']) {
|
|
1949
|
+
if (k in deps) ctx[k] = deps[k];
|
|
1950
|
+
}
|
|
1816
1951
|
// Procurado subindo na árvore: rodar o doctor de um subdiretório deve
|
|
1817
1952
|
// diagnosticar o repositório, não reportar "não inicializado".
|
|
1818
1953
|
ctx.configPath = findConfigPath(ctx.cwd);
|
|
@@ -1848,6 +1983,8 @@ export async function doctorResults(options = {}, deps = {}) {
|
|
|
1848
1983
|
// nossa conta.
|
|
1849
1984
|
Object.assign(checkOwnerType, { requires: ["tracker.boardProvisioning === 'create'"] }),
|
|
1850
1985
|
checkConfig,
|
|
1986
|
+
checkCliLine,
|
|
1987
|
+
checkTechContext,
|
|
1851
1988
|
checkRepoAccess,
|
|
1852
1989
|
// Higiene de board precisa de board.
|
|
1853
1990
|
Object.assign(checkBoardHygiene, { requires: ["tracker.boardProvisioning === 'create'"] }),
|
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
LABEL_BUG, LABEL_CRITIQUE_FAILED, LABEL_NEEDS_HUMAN, REQUIRED_BUG_SECTIONS,
|
|
27
27
|
TARGET_LANGUAGE, DEFAULT_MAX_CRITIQUE_ATTEMPTS, labelNames,
|
|
28
28
|
} from '../config.mjs';
|
|
29
|
+
import { classifyFailure, renderFailureComment, actionsRunUrl } from '../lib/failure-report.mjs';
|
|
29
30
|
|
|
30
31
|
// Relato = corpo + comentários humanos, na ordem cronológica. Comentários do
|
|
31
32
|
// próprio spec-wave são ruído aqui (críticas anteriores, relatórios de uso):
|
|
@@ -171,12 +172,11 @@ export async function generateBug({ issueNumber, deps = {} }) {
|
|
|
171
172
|
await tracker.removeTag({ ref: ref, tag: LABEL_BUG }).catch(() => {});
|
|
172
173
|
await tracker.addComment({
|
|
173
174
|
ref: ref,
|
|
174
|
-
body:
|
|
175
|
-
'
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}).catch(() => {});
|
|
175
|
+
body: renderFailureComment({
|
|
176
|
+
titulo: 'Falha ao gerar o bug.md', message: err.message, causa: classifyFailure(err),
|
|
177
|
+
trigger: LABEL_BUG, runUrl: actionsRunUrl(), issueNumber: String(n),
|
|
178
|
+
}),
|
|
179
|
+
}).then(() => { err.issueNotified = true; }).catch(() => {});
|
|
180
180
|
throw err;
|
|
181
181
|
} finally {
|
|
182
182
|
await recordUsage({ token, owner, repo, tracker: deps.tracker ?? null, issueNumber: n, entries: usageEntries });
|
|
@@ -21,8 +21,9 @@ import { publishArtifact } from '../lib/artifact-publish.mjs';
|
|
|
21
21
|
import { loadArtifact } from '../lib/doc-source.mjs';
|
|
22
22
|
import { awaitingMergeBlock, renderPrLine } from '../lib/artifact-pr.mjs';
|
|
23
23
|
import { isAwaitingMerge } from '../lib/doc-source.mjs';
|
|
24
|
-
import { buildTechContext } from '../lib/tech-context.mjs';
|
|
24
|
+
import { buildTechContext, techContextTemplateHint } from '../lib/tech-context.mjs';
|
|
25
25
|
import { loadPrompt, systemPromptWithTools } from '../lib/prompt-loader.mjs';
|
|
26
|
+
import { classifyFailure, renderFailureComment, actionsRunUrl } from '../lib/failure-report.mjs';
|
|
26
27
|
|
|
27
28
|
// Aviso anexado ao comentário quando o lint de idioma ainda reprova após o
|
|
28
29
|
// retry automático do generateDocument (excertos ao redor de cada vazamento).
|
|
@@ -272,6 +273,7 @@ export async function generatePlan({ issueNumber, deps = {} }) {
|
|
|
272
273
|
`${renderPrLine(published)}\n\n` +
|
|
273
274
|
`Revise o plano **no Pull Request** e faça o merge. Depois, valide a Feature: mova o card para **✅ Ready** ou use:\n` +
|
|
274
275
|
`\`\`\`\ngh issue edit ${issueNumber} --add-label "spec-wave:ready"\n\`\`\`` +
|
|
276
|
+
(tech.unfilled ? `\n\n⚠️ ${techContextTemplateHint(tech.unfilledReason)}` : '') +
|
|
275
277
|
formatLintWarning(lintFindings),
|
|
276
278
|
});
|
|
277
279
|
|
|
@@ -294,13 +296,12 @@ export async function generatePlan({ issueNumber, deps = {} }) {
|
|
|
294
296
|
// (O catch acima, na crítica adversarial, cobre só aquele trecho.)
|
|
295
297
|
await tracker.removeTag({ ref, tag: 'spec-wave:plan' }).catch(() => {});
|
|
296
298
|
await tracker.addComment({
|
|
297
|
-
ref,
|
|
298
|
-
body:
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
}).catch(() => {});
|
|
299
|
+
ref: ref,
|
|
300
|
+
body: renderFailureComment({
|
|
301
|
+
titulo: 'Falha ao gerar o plan.md', message: err.message, causa: classifyFailure(err),
|
|
302
|
+
trigger: 'spec-wave:plan', runUrl: actionsRunUrl(), issueNumber: String(issueNumber),
|
|
303
|
+
}),
|
|
304
|
+
}).then(() => { err.issueNotified = true; }).catch(() => {});
|
|
304
305
|
throw err;
|
|
305
306
|
} finally {
|
|
306
307
|
// Best-effort: nunca propaga erro (ver recordUsage).
|
|
@@ -38,6 +38,7 @@ import {
|
|
|
38
38
|
LABEL_QA, LABEL_QA_READY, LABEL_CRITIQUE_FAILED, LABEL_NEEDS_HUMAN,
|
|
39
39
|
LABEL_RISK_ACCEPTED, DEFAULT_MAX_CRITIQUE_ATTEMPTS, TARGET_LANGUAGE, labelNames,
|
|
40
40
|
} from '../config.mjs';
|
|
41
|
+
import { classifyFailure, renderFailureComment, actionsRunUrl } from '../lib/failure-report.mjs';
|
|
41
42
|
|
|
42
43
|
/**
|
|
43
44
|
* Parada por decisão do fluxo: o comentário já foi postado; o erro precisa
|
|
@@ -221,12 +222,14 @@ export async function generateQaPlan({ issueNumber, deps = {} }) {
|
|
|
221
222
|
await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
|
|
222
223
|
await tracker.addComment({
|
|
223
224
|
ref: { key: String(number) },
|
|
224
|
-
body:
|
|
225
|
-
'
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
225
|
+
body: renderFailureComment({
|
|
226
|
+
titulo: 'Falha ao gerar o plano de QA', message: err.message, causa: classifyFailure(err),
|
|
227
|
+
trigger: LABEL_QA, runUrl: actionsRunUrl(), issueNumber: String(number),
|
|
228
|
+
}),
|
|
229
|
+
}).then(() => { err.issueNotified = true; }).catch(() => {});
|
|
230
|
+
} else {
|
|
231
|
+
// Parada por decisão do fluxo: o comentário já foi postado.
|
|
232
|
+
err.issueNotified = true;
|
|
230
233
|
}
|
|
231
234
|
throw err;
|
|
232
235
|
} finally {
|
|
@@ -9,6 +9,8 @@ import { renderPrLine } from '../lib/artifact-pr.mjs';
|
|
|
9
9
|
import { loadPrompt, systemPromptWithTools } from '../lib/prompt-loader.mjs';
|
|
10
10
|
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
11
11
|
import { requireTracker } from '../ports/index.mjs';
|
|
12
|
+
import { collectSpecIndex, renderSpecIndex } from '../lib/spec-index.mjs';
|
|
13
|
+
import { classifyFailure, renderFailureComment, actionsRunUrl } from '../lib/failure-report.mjs';
|
|
12
14
|
import {
|
|
13
15
|
allowsSpecPlan, SPEC_PLAN_EXCLUDED_TYPES, TARGET_LANGUAGE, labelNames,
|
|
14
16
|
} from '../config.mjs';
|
|
@@ -84,7 +86,11 @@ export async function generateSpec({ issueNumber, deps = {} }) {
|
|
|
84
86
|
raw: issue.body || '(sem descrição)',
|
|
85
87
|
},
|
|
86
88
|
};
|
|
87
|
-
|
|
89
|
+
// O índice das specs vizinhas vai PRONTO: é o que o modelo procurava abrindo
|
|
90
|
+
// todas, e abrir todas foi o que esgotou o teto de turnos (ver spec-index.mjs).
|
|
91
|
+
const indice = renderSpecIndex(collectSpecIndex(root, { excludeSlug: slug }));
|
|
92
|
+
const userContent = `Gere o spec.md a partir deste payload JSON:\n\n${JSON.stringify(payload, null, 2)}` +
|
|
93
|
+
(indice ? `\n\n${indice}` : '');
|
|
88
94
|
|
|
89
95
|
// Coletor de uso de IA — o finally registra o custo já incorrido mesmo se o
|
|
90
96
|
// fluxo falhar depois da geração.
|
|
@@ -146,12 +152,11 @@ export async function generateSpec({ issueNumber, deps = {} }) {
|
|
|
146
152
|
await tracker.removeTag({ ref, tag: 'spec-wave:spec' }).catch(() => {});
|
|
147
153
|
await tracker.addComment({
|
|
148
154
|
ref,
|
|
149
|
-
body:
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
}).catch(() => {});
|
|
155
|
+
body: renderFailureComment({
|
|
156
|
+
titulo: 'Falha ao gerar a spec.md', message: err.message, causa: classifyFailure(err),
|
|
157
|
+
trigger: 'spec-wave:spec', runUrl: actionsRunUrl(), issueNumber: String(issueNumber),
|
|
158
|
+
}),
|
|
159
|
+
}).then(() => { err.issueNotified = true; }).catch(() => {});
|
|
155
160
|
throw err;
|
|
156
161
|
} finally {
|
|
157
162
|
// Best-effort: nunca propaga erro (ver recordUsage).
|
|
@@ -35,6 +35,7 @@ import { loadArtifact } from '../lib/doc-source.mjs';
|
|
|
35
35
|
import { buildBugContext } from '../lib/bug-context.mjs';
|
|
36
36
|
import { slugify } from '../lib/slugify.mjs';
|
|
37
37
|
import { parseDependencies, orderStories, formatDependencyLine } from '../lib/dependencies.mjs';
|
|
38
|
+
import { emitProgress } from '../lib/progress-events.mjs';
|
|
38
39
|
import { STREAM_DIR_ENV, runStreamed, specKitEnv, streamFileFor, withStreamJson } from '../lib/implement-stream.mjs';
|
|
39
40
|
import { loadProjectConfig } from '../lib/board.mjs';
|
|
40
41
|
import { planBoardMoves, applyBoardMoves } from '../lib/implement-board.mjs';
|
|
@@ -294,6 +295,18 @@ export function buildContext({
|
|
|
294
295
|
lines.push(' 2. **Implemente** a Task por completo.');
|
|
295
296
|
lines.push(` 3. **Ao concluir:** **avance a Task para a Etapa ${STAGE_DONE}** com Status **${PROGRESS_DONE}**.`);
|
|
296
297
|
lines.push(' 4. Só então avance para a próxima Task.');
|
|
298
|
+
if (mode === 'agent') {
|
|
299
|
+
// Sob o dev-agent o board continua automático, com UMA exceção: o
|
|
300
|
+
// `task done` é o sinal que alimenta a barra de progresso da tela
|
|
301
|
+
// Development — sem ele a barra só anda no fim da Story.
|
|
302
|
+
lines.push('');
|
|
303
|
+
lines.push(
|
|
304
|
+
' > **Obrigatório sob o dev-agent:** ao concluir **cada** Task, rode ' +
|
|
305
|
+
'`npx spec-wave task done <número da Task>` **antes** de começar a próxima. ' +
|
|
306
|
+
'É esse comando que reporta o progresso da Feature (uma Task por vez) para quem ' +
|
|
307
|
+
'acompanha a execução. Se ele falhar, siga em frente — não tente de novo nem pare por isso.'
|
|
308
|
+
);
|
|
309
|
+
}
|
|
297
310
|
lines.push('');
|
|
298
311
|
lines.push(`3. **Ao concluir TODA a Story** (todas as Tasks na Etapa ${STAGE_DONE}):`);
|
|
299
312
|
lines.push(
|
|
@@ -1267,6 +1280,14 @@ export async function implement({
|
|
|
1267
1280
|
story: type === 'Story' ? { nodeId: issue.node_id, number: itemNumber(issue) } : null,
|
|
1268
1281
|
tasks: tasks.map(t => ({ nodeId: t.nodeId, number: t.number })),
|
|
1269
1282
|
}) });
|
|
1283
|
+
// Barra de progresso do dev-agent: a Story terminou, logo todas as
|
|
1284
|
+
// Tasks dela terminaram — inclusive as que o executor não sinalizou uma
|
|
1285
|
+
// a uma com `task done`.
|
|
1286
|
+
emitProgress({
|
|
1287
|
+
event: 'story_done',
|
|
1288
|
+
story: type === 'Story' ? itemNumber(issue) : null,
|
|
1289
|
+
tasks: tasks.map(t => t.number),
|
|
1290
|
+
});
|
|
1270
1291
|
// Última Story da Feature? Então a Feature avança junto.
|
|
1271
1292
|
//
|
|
1272
1293
|
// Este é o caminho que o dev-agent realmente percorre: o feature_prompt
|
package/src/commands/init.mjs
CHANGED
|
@@ -223,7 +223,7 @@ export async function init(options) {
|
|
|
223
223
|
const projectSpinner = p.spinner();
|
|
224
224
|
projectSpinner.start('Criando GitHub Project...');
|
|
225
225
|
try {
|
|
226
|
-
const result = await setupProject(token, owner, repo, projectTitle, projectSpinner);
|
|
226
|
+
const result = await setupProject(token, owner, repo, projectTitle, projectSpinner, { kind: trackerKind });
|
|
227
227
|
projectUrl = result.projectUrl;
|
|
228
228
|
projectId = result.projectId;
|
|
229
229
|
projectNumber = result.projectNumber;
|
|
@@ -252,7 +252,7 @@ export async function init(options) {
|
|
|
252
252
|
const labelSpinner = p.spinner();
|
|
253
253
|
labelSpinner.start('Criando labels...');
|
|
254
254
|
try {
|
|
255
|
-
await setupLabels(token, owner, repo, labelSpinner);
|
|
255
|
+
await setupLabels(token, owner, repo, labelSpinner, undefined, undefined, { kind: trackerKind });
|
|
256
256
|
labelSpinner.stop(`Labels criadas (${ALL_LABELS.length} labels)`);
|
|
257
257
|
} catch (err) {
|
|
258
258
|
labelSpinner.stop('');
|
|
@@ -30,6 +30,9 @@ import { featureDocPaths } from '../lib/doc-paths.mjs';
|
|
|
30
30
|
import { STEPS } from '../lib/next-step.mjs';
|
|
31
31
|
import { loadConfig } from '../lib/project-root.mjs';
|
|
32
32
|
import { unguardedWorkflows } from './mode.mjs';
|
|
33
|
+
import { groupMissingPaths, missingCitedPaths } from '../lib/cited-paths.mjs';
|
|
34
|
+
import { codeRepositories } from '../lib/repo-role.mjs';
|
|
35
|
+
import { inspectTechContext, techContextTemplateHint, TECH_CONTEXT_PATH } from '../lib/tech-context.mjs';
|
|
33
36
|
|
|
34
37
|
const TRIGGER_LABELS = Object.values(STEPS).map(s => s.trigger).filter(Boolean);
|
|
35
38
|
|
|
@@ -123,13 +126,31 @@ export function resolveMilestone(milestones = [], titulo = '') {
|
|
|
123
126
|
* @returns {{ status: 'ok'|'aviso'|'bloqueio', bloqueios: string[], avisos: string[] }}
|
|
124
127
|
*/
|
|
125
128
|
export function inspectPreflight({
|
|
126
|
-
tokenOk = true, modo = null, publicacao = null, inventario = null,
|
|
129
|
+
tokenOk = true, modo = null, publicacao = null, inventario = null, caminhosAusentes = {},
|
|
130
|
+
techContext = null, techContextReason = undefined,
|
|
127
131
|
} = {}) {
|
|
128
132
|
const bloqueios = [];
|
|
129
133
|
const avisos = [];
|
|
130
134
|
|
|
135
|
+
// Fonte citada que não está no repo: aviso, não bloqueio — a spec sai, mas
|
|
136
|
+
// sem a fonte, e ninguém fica sabendo se não for aqui.
|
|
137
|
+
for (const [caminho, issues] of Object.entries(caminhosAusentes || {})) {
|
|
138
|
+
avisos.push(
|
|
139
|
+
`${issues.map(n => `#${n}`).join(', ')} cita(m) \`${caminho}\`, que não existe no repositório — ` +
|
|
140
|
+
'commite o arquivo ou corrija a referência antes de gerar (o modelo não terá a fonte).'
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
131
144
|
if (!tokenOk) bloqueios.push('Sem token utilizável para este repositório.');
|
|
132
145
|
|
|
146
|
+
// Template não preenchido BLOQUEIA: a rodada inteira sairia ancorada num stack
|
|
147
|
+
// de exemplo. Ausente é aviso — o plano segue sem contexto e diz isso.
|
|
148
|
+
if (techContext === 'template') bloqueios.push(techContextTemplateHint(techContextReason));
|
|
149
|
+
else if (techContext === 'invalid') bloqueios.push(`${TECH_CONTEXT_PATH} não parseia como YAML.`);
|
|
150
|
+
else if (techContext === 'missing') {
|
|
151
|
+
avisos.push(`${TECH_CONTEXT_PATH} ausente — os planos sairão sem contexto técnico estático.`);
|
|
152
|
+
}
|
|
153
|
+
|
|
133
154
|
if (modo?.status === 'problem') bloqueios.push(modo.summary);
|
|
134
155
|
else if (modo?.status === 'warn') avisos.push(modo.summary);
|
|
135
156
|
|
|
@@ -282,13 +303,28 @@ export async function preflight({ milestone: milestoneArg, json = false, deps =
|
|
|
282
303
|
}
|
|
283
304
|
|
|
284
305
|
const inventario = inspectMilestone({ issues: issues.map(comoIssue), specStates });
|
|
285
|
-
|
|
306
|
+
// Só as Features que ainda vão ser geradas: é para elas que a fonte importa.
|
|
307
|
+
const aGerar = new Set(inventario.gerar.map(f => f.number));
|
|
308
|
+
const multiRepo = codeRepositories(config).length > 0;
|
|
309
|
+
const caminhosAusentes = groupMissingPaths(featureIssues
|
|
310
|
+
.filter(i => aGerar.has(Number(i.ref.key)))
|
|
311
|
+
.map(i => ({
|
|
312
|
+
number: Number(i.ref.key),
|
|
313
|
+
// Hub multi-repo: a fonte pode morar num repo de código — ver a lib.
|
|
314
|
+
missing: missingCitedPaths(i.body || '', root, undefined, { multiRepo }),
|
|
315
|
+
})));
|
|
316
|
+
const { state: techContext, reason: techContextReason } = inspectTechContext(root);
|
|
317
|
+
const veredito = inspectPreflight({
|
|
318
|
+
tokenOk: true, modo, publicacao, inventario, caminhosAusentes, techContext, techContextReason,
|
|
319
|
+
});
|
|
286
320
|
s?.stop(`Milestone "${milestone.title}": ${inventario.features.length} Feature(s).`);
|
|
287
321
|
|
|
288
322
|
Object.assign(saida, {
|
|
289
323
|
milestone: { title: milestone.title, number: Number(milestone.key), base },
|
|
290
324
|
modo: { configured: configuredMode(config), variable: variable ?? null, status: modo.status, summary: modo.summary },
|
|
291
325
|
publicacao: { status: publicacao.status, notes: publicacao.notes },
|
|
326
|
+
caminhosAusentes,
|
|
327
|
+
techContext,
|
|
292
328
|
inventario,
|
|
293
329
|
veredito,
|
|
294
330
|
});
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Retrato do andamento de uma Feature: Stories e Tasks concluídas.
|
|
2
|
+
//
|
|
3
|
+
// Existe para o spec-wave-agent montar a barra de progresso da tela
|
|
4
|
+
// Development: ele roda `spec-wave progress <feature> --json` no começo da
|
|
5
|
+
// execução (o total de Tasks e o que já estava pronto de uma execução
|
|
6
|
+
// anterior) e depois soma os eventos de lib/progress-events.mjs.
|
|
7
|
+
//
|
|
8
|
+
// Concluída = issue fechada OU na Etapa de conclusão do tipo: Task em 🎉 Done
|
|
9
|
+
// (é para onde o `task done` e o fim do `implement` a levam), Story em 👀 Code
|
|
10
|
+
// Review ou adiante (o mesmo critério do `implement <feature>` para pular).
|
|
11
|
+
//
|
|
12
|
+
// Custo: 1 leitura da Feature + 1 listagem de filhos por Story + 1 retrato do
|
|
13
|
+
// board — sempre lido da API (nunca do cache do `order`, que ele só renova).
|
|
14
|
+
import * as p from '@clack/prompts';
|
|
15
|
+
import chalk from 'chalk';
|
|
16
|
+
import { resolveToken } from '../api/auth.mjs';
|
|
17
|
+
import { detectIssueType } from '../lib/issue-type.mjs';
|
|
18
|
+
import { loadProjectConfig } from '../lib/board.mjs';
|
|
19
|
+
import { resolveHubContext, loadConfig } from '../lib/project-root.mjs';
|
|
20
|
+
import { loadBoardSnapshot } from '../lib/story-graph.mjs';
|
|
21
|
+
import { CONFIG_FILE, STAGE_ORDER, STAGE_CODE_REVIEW, STAGE_DONE } from '../config.mjs';
|
|
22
|
+
import { requireTracker } from '../ports/index.mjs';
|
|
23
|
+
|
|
24
|
+
/** Etapa `stage` está em `target` ou adiante? Desconhecida conta como "não". */
|
|
25
|
+
function stageAtOrAfter(stage, target) {
|
|
26
|
+
const i = STAGE_ORDER.indexOf(stage);
|
|
27
|
+
return i >= 0 && i >= STAGE_ORDER.indexOf(target);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Monta o retrato (função PURA).
|
|
32
|
+
*
|
|
33
|
+
* @param {object} params
|
|
34
|
+
* @param {number} params.feature
|
|
35
|
+
* @param {Array<{number:number, state:string, tasks:Array<{number:number, state:string}>}>} params.stories
|
|
36
|
+
* @param {Map<number, string|null>} [params.stageOf] Etapa por issue; ausente = só o estado conta
|
|
37
|
+
*/
|
|
38
|
+
export function buildProgress({ feature, stories = [], stageOf = new Map() }) {
|
|
39
|
+
const out = stories.map((s) => {
|
|
40
|
+
const tasks = (s.tasks || []).map(t => ({
|
|
41
|
+
number: t.number,
|
|
42
|
+
done: t.state === 'closed' || stageAtOrAfter(stageOf.get(t.number), STAGE_DONE),
|
|
43
|
+
}));
|
|
44
|
+
const done = s.state === 'closed' || stageAtOrAfter(stageOf.get(s.number), STAGE_CODE_REVIEW);
|
|
45
|
+
// Story concluída arrasta as Tasks: uma Task esquecida aberta numa Story
|
|
46
|
+
// já entregue não é trabalho pendente do agente.
|
|
47
|
+
return { number: s.number, done, tasks: done ? tasks.map(t => ({ ...t, done: true })) : tasks };
|
|
48
|
+
});
|
|
49
|
+
const tasks = out.flatMap(s => s.tasks);
|
|
50
|
+
return {
|
|
51
|
+
feature,
|
|
52
|
+
storiesDone: out.filter(s => s.done).length,
|
|
53
|
+
storiesTotal: out.length,
|
|
54
|
+
tasksDone: tasks.filter(t => t.done).length,
|
|
55
|
+
tasksTotal: tasks.length,
|
|
56
|
+
stories: out,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function progress({ feature: featureArg, json = false, deps = {} } = {}) {
|
|
61
|
+
const fail = (msg) => {
|
|
62
|
+
if (json) console.error(msg);
|
|
63
|
+
else p.log.error(msg);
|
|
64
|
+
process.exitCode = 1;
|
|
65
|
+
};
|
|
66
|
+
const featureNumber = parseInt(String(featureArg).replace('#', ''), 10);
|
|
67
|
+
if (!Number.isInteger(featureNumber) || featureNumber <= 0) {
|
|
68
|
+
return fail(`Feature inválida: "${featureArg}". Use o número da issue, ex.: 12 ou #12.`);
|
|
69
|
+
}
|
|
70
|
+
const { owner, repo } = resolveHubContext();
|
|
71
|
+
if (!owner || !repo) {
|
|
72
|
+
return fail(
|
|
73
|
+
'Não foi possível determinar owner/repo.\n' +
|
|
74
|
+
`Rode dentro de um repositório com ${CONFIG_FILE} (\`spec-wave init\`) ou defina GITHUB_REPOSITORY=owner/repo.`
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
let token;
|
|
78
|
+
try {
|
|
79
|
+
token = await resolveToken();
|
|
80
|
+
} catch (err) {
|
|
81
|
+
return fail(err.message);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let stories;
|
|
85
|
+
try {
|
|
86
|
+
const tracker = await requireTracker({ token, owner, repo, deps });
|
|
87
|
+
const featureIssue = await tracker.getWorkItem({ ref: { key: String(featureNumber) } });
|
|
88
|
+
const type = detectIssueType(featureIssue);
|
|
89
|
+
if (type !== 'Feature') {
|
|
90
|
+
return fail(
|
|
91
|
+
'`spec-wave progress` só aceita issues do tipo Feature. ' +
|
|
92
|
+
`Issue #${featureNumber} é do tipo ${type || 'desconhecido'} (${featureIssue.title}).`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
const filhos = (await tracker.listChildren({ ref: featureIssue.ref }))
|
|
96
|
+
.filter(s => detectIssueType(s) === 'Story');
|
|
97
|
+
stories = await Promise.all(filhos.map(async s => ({
|
|
98
|
+
number: Number(s.ref.key),
|
|
99
|
+
state: s.state,
|
|
100
|
+
tasks: (await tracker.listChildren({ ref: s.ref }))
|
|
101
|
+
.filter(t => detectIssueType(t) === 'Task')
|
|
102
|
+
.map(t => ({ number: Number(t.ref.key), state: t.state })),
|
|
103
|
+
})));
|
|
104
|
+
} catch (err) {
|
|
105
|
+
return fail(`Não foi possível ler a Feature #${featureNumber}: ${err.message}`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Etapas: melhor esforço. Sem board, vale só aberta/fechada.
|
|
109
|
+
const stageOf = new Map();
|
|
110
|
+
const { project, error: projectError } = loadProjectConfig();
|
|
111
|
+
if (!projectError) {
|
|
112
|
+
try {
|
|
113
|
+
const { root } = loadConfig();
|
|
114
|
+
// `fresh`: o retrato é a base da barra — cache de 10 min mostraria como
|
|
115
|
+
// pendente a Task que acabou de ir para Done.
|
|
116
|
+
const snapshot = await loadBoardSnapshot({
|
|
117
|
+
token, owner, repo, project, root, fresh: true, tracker: deps.tracker,
|
|
118
|
+
});
|
|
119
|
+
for (const s of stories) {
|
|
120
|
+
for (const n of [s.number, ...s.tasks.map(t => t.number)]) {
|
|
121
|
+
stageOf.set(n, snapshot.index.get(n)?.fields?.Etapa ?? null);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} catch (err) {
|
|
125
|
+
if (!json) p.log.warn(`Etapas do board não consultáveis agora (${err.message}) — contando só issues fechadas.`);
|
|
126
|
+
}
|
|
127
|
+
} else if (!json) {
|
|
128
|
+
p.log.warn(`${projectError} — contando só issues fechadas.`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const result = buildProgress({ feature: featureNumber, stories, stageOf });
|
|
132
|
+
if (json) {
|
|
133
|
+
console.log(JSON.stringify(result));
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
p.intro(chalk.bold(`spec-wave progress #${featureNumber}`));
|
|
137
|
+
for (const s of result.stories) {
|
|
138
|
+
const feitas = s.tasks.filter(t => t.done).length;
|
|
139
|
+
p.log.message(`${s.done ? chalk.green('✓') : '·'} Story #${s.number} — tasks ${feitas}/${s.tasks.length}`);
|
|
140
|
+
}
|
|
141
|
+
p.outro(
|
|
142
|
+
`Tasks ${result.tasksDone}/${result.tasksTotal} · Stories ${result.storiesDone}/${result.storiesTotal}`
|
|
143
|
+
);
|
|
144
|
+
}
|