@spec-wave/cli 1.8.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spec-wave/cli",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "Setup spec-driven GitHub workflow with Projects v2, labels, issue templates, and AI-powered Actions",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.mjs CHANGED
@@ -574,6 +574,16 @@ cacheado por ${'`cache.ttlSec`'} (default 600s; SPEC_WAVE_CACHE_TTL na env; 0 de
574
574
  staleness sempre visível. blocked_by criado SÓ pela UI não está nas fontes locais: use --remote
575
575
  para incluí-lo na consulta, ou --sync para gravá-lo em definitivo nos artefatos.`);
576
576
 
577
+ program
578
+ .command('progress')
579
+ .description('Andamento de uma Feature: Stories e Tasks concluídas — a base da barra de progresso do dev-agent')
580
+ .argument('<feature>', 'Número da issue da Feature, ex.: 12 ou #12')
581
+ .option('--json', 'Saída em JSON estável (para o spec-wave-agent/scripts), sem ANSI')
582
+ .action(async (feature, options) => {
583
+ const { progress } = await import('./commands/progress.mjs');
584
+ await progress({ feature, ...options }).catch(err => exitWithFailure(err));
585
+ });
586
+
577
587
  program
578
588
  .command('merge')
579
589
  .description('Mergeia os PRs empilhados das Stories de uma Feature na ordem topológica e move o board até QA')
@@ -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
@@ -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
+ }
@@ -16,6 +16,7 @@ import { detectIssueType } from '../lib/issue-type.mjs';
16
16
  import { openTracker, advanceToStage, setProgress } from '../lib/board.mjs';
17
17
  import { resolveHubContext } from '../lib/project-root.mjs';
18
18
  import { requireTracker } from '../ports/index.mjs';
19
+ import { emitProgress } from '../lib/progress-events.mjs';
19
20
  import {
20
21
  CONFIG_FILE, STAGE_DEVELOPMENT, STAGE_DONE,
21
22
  PROGRESS_IN_PROGRESS, PROGRESS_DONE,
@@ -164,6 +165,10 @@ export async function task({ action, issue: issueArg, deps = {} }) {
164
165
  }
165
166
  }
166
167
 
168
+ // Sob o spec-wave-agent: avisa que a Task terminou (barra de progresso da
169
+ // tela Development). Sem SPEC_WAVE_STREAM_DIR, não faz nada.
170
+ if (action === 'done') emitProgress({ event: 'task_done', task: issueNumber });
171
+
167
172
  p.outro(
168
173
  action === 'start'
169
174
  ? `${chalk.green('✓')} Task #${issueNumber} em andamento. Ao concluir: spec-wave task done ${issueNumber}`
@@ -0,0 +1,46 @@
1
+ // Eventos de progresso por Task para o spec-wave-agent (RFC-008).
2
+ //
3
+ // A tela Development mostra o andamento de uma Feature como barra de
4
+ // progresso, e a unidade dela é a TASK. O dev-agent não tem como saber que uma
5
+ // Task terminou olhando para o executor: quem sabe é a CLI, no `task done` e
6
+ // no fim de um `implement <story>`. Então, sob o agente (que define
7
+ // SPEC_WAVE_STREAM_DIR), a CLI acrescenta uma linha JSON por acontecimento em
8
+ // `<dir>/progress.jsonl`, e o agente acompanha o arquivo e reporta.
9
+ //
10
+ // O arquivo é só um SINAL: o retrato completo (quantas Tasks a Feature tem e
11
+ // quais já estão concluídas) vem do `spec-wave progress <feature> --json`.
12
+ // Repetir um evento é inofensivo — o agente guarda o conjunto de Tasks
13
+ // concluídas, não um contador.
14
+ //
15
+ // Sem SPEC_WAVE_STREAM_DIR, nada acontece.
16
+
17
+ import { appendFileSync, mkdirSync } from 'node:fs';
18
+ import path from 'node:path';
19
+ import { STREAM_DIR_ENV } from './implement-stream.mjs';
20
+
21
+ export const PROGRESS_FILE = 'progress.jsonl';
22
+
23
+ export function progressFileFor(dir) {
24
+ return path.join(dir, PROGRESS_FILE);
25
+ }
26
+
27
+ /**
28
+ * Acrescenta um evento ao arquivo de progresso. Melhor esforço: falha de disco
29
+ * não pode derrubar a implementação nem o `task done` — só atrasa a barra.
30
+ *
31
+ * @param {{event: 'task_done'|'story_done', task?: number, story?: number, tasks?: number[]}} event
32
+ * @param {Record<string, string|undefined>} [env]
33
+ * @returns {boolean} true quando a linha foi gravada
34
+ */
35
+ export function emitProgress(event, env = process.env) {
36
+ const dir = env[STREAM_DIR_ENV];
37
+ if (!dir) return false;
38
+ try {
39
+ mkdirSync(dir, { recursive: true });
40
+ // Uma escrita por linha (O_APPEND): stories em paralelo não se intercalam.
41
+ appendFileSync(progressFileFor(dir), `${JSON.stringify(event)}\n`);
42
+ return true;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "spec-wave",
3
3
  "displayName": "Spec Wave",
4
- "version": "1.8.0",
4
+ "version": "1.9.0",
5
5
  "description": "Fluxo spec-driven no GitHub (RFC-001): Projects v2, labels de gatilho, spec/plan gerados por Action, decomposição em duas etapas e implementação orientada a Stories/Tasks.",
6
6
  "author": {
7
7
  "name": "Astratech",