@polymorphism-tech/morph-spec 10.11.0 → 10.12.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.
Files changed (79) hide show
  1. package/README.md +2 -2
  2. package/bin/morph-spec.js +3 -1
  3. package/claude-plugin.json +1 -1
  4. package/docs/CHEATSHEET.md +1 -1
  5. package/docs/QUICKSTART.md +1 -1
  6. package/framework/CLAUDE.md +4 -3
  7. package/framework/MORPH.md +14 -12
  8. package/framework/commands/morph-review.md +1 -1
  9. package/framework/commands/morph-status.md +2 -6
  10. package/framework/docs/CLI.md +22 -7
  11. package/framework/hooks/claude-code/core/enforce-phase-writes.js +12 -11
  12. package/framework/hooks/claude-code/core/gate-guard.js +19 -14
  13. package/framework/hooks/claude-code/core/heavy-gate.js +4 -1
  14. package/framework/hooks/claude-code/core/loop-detect.js +8 -7
  15. package/framework/hooks/claude-code/core/masked-exit.js +5 -2
  16. package/framework/hooks/claude-code/core/protect-spec-files.js +13 -11
  17. package/framework/hooks/claude-code/core/state-sync.js +20 -12
  18. package/framework/hooks/claude-code/core/validate-completion.js +6 -5
  19. package/framework/hooks/claude-code/core/worktree-context.js +47 -43
  20. package/framework/hooks/shared/e2e-check.js +49 -9
  21. package/framework/hooks/shared/gate-question.js +8 -0
  22. package/framework/hooks/shared/host-services.js +7 -3
  23. package/framework/hooks/shared/next-step.js +54 -23
  24. package/framework/hooks/shared/owner-words.js +146 -0
  25. package/framework/hooks/shared/report-progress.js +84 -10
  26. package/framework/phases.json +7 -7
  27. package/framework/rules/implement-report.md +8 -7
  28. package/framework/rules/plan-grammar.md +4 -1
  29. package/framework/schemas/feature.schema.json +3 -2
  30. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  31. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  32. package/framework/skills/core/morph-apply/SKILL.md +6 -5
  33. package/framework/skills/core/morph-apply/references/hotfix.md +6 -2
  34. package/framework/skills/core/morph-apply/references/review.md +9 -5
  35. package/framework/skills/core/morph-plan/SKILL.md +5 -5
  36. package/framework/skills/core/morph-plan/references/interview.md +1 -1
  37. package/framework/skills/core/morph-uiux/SKILL.md +10 -6
  38. package/framework/templates/docs/plan.md +1 -1
  39. package/package.json +1 -1
  40. package/src/commands/e2e/e2e.js +37 -29
  41. package/src/commands/project/status.js +28 -184
  42. package/src/commands/state/advance.js +44 -20
  43. package/src/commands/state/approve.js +70 -59
  44. package/src/commands/state/archive.js +20 -15
  45. package/src/commands/state/auto-approval.js +25 -23
  46. package/src/commands/state/create.js +35 -32
  47. package/src/commands/state/finish.js +179 -58
  48. package/src/commands/state/gate-check.js +43 -31
  49. package/src/commands/state/gate-decision.js +18 -14
  50. package/src/commands/state/list.js +23 -14
  51. package/src/commands/state/next.js +4 -5
  52. package/src/commands/state/report-check.js +47 -23
  53. package/src/commands/validation/plan-check.js +30 -14
  54. package/src/commands/validation/verify.js +39 -18
  55. package/src/dashboard/app/components/ActivityFeed.jsx +8 -8
  56. package/src/dashboard/app/components/CommandPalette.jsx +1 -1
  57. package/src/dashboard/app/components/GatePauses.jsx +8 -8
  58. package/src/dashboard/app/components/PhaseRail.jsx +6 -6
  59. package/src/dashboard/app/components/SessionMap.jsx +7 -7
  60. package/src/dashboard/app/lib/format.js +6 -2
  61. package/src/dashboard/app/lib/phases.js +48 -16
  62. package/src/dashboard/app/pages/FeatureDetail.jsx +87 -59
  63. package/src/dashboard/app/pages/Features.jsx +18 -18
  64. package/src/dashboard/app/pages/Guide.jsx +4 -4
  65. package/src/dashboard/app/pages/PhasePipeline.jsx +7 -7
  66. package/src/dashboard/app/pages/Portfolio.jsx +3 -3
  67. package/src/dashboard/scanner/activity-scanner.js +20 -6
  68. package/src/dashboard/scanner/features-scanner.js +43 -8
  69. package/src/dashboard/scanner/project-api.js +2 -0
  70. package/src/dashboard/vite.config.js +2 -0
  71. package/src/lib/next-step.js +3 -2
  72. package/src/lib/plan/checks.js +30 -15
  73. package/src/lib/plan/critique.js +6 -4
  74. package/src/lib/recap/recap.js +46 -20
  75. package/src/lib/risk-detector.js +260 -98
  76. package/src/lib/view/feature-html.js +19 -25
  77. package/src/lib/view/feature-view.js +6 -6
  78. package/src/utils/audience.js +27 -0
  79. package/src/utils/refusal-line.js +2 -2
@@ -7,6 +7,9 @@ import { persistFeature, setGateApproved, createDefaultFeature, readFeatureFile
7
7
  import { resolveMorphRoot } from '../../shared/payload-utils.js';
8
8
  import { contextResult, runStandalone } from '../../shared/hook-response.js';
9
9
  import { gateFromQuestion } from '../../shared/gate-question.js';
10
+ import { GATE_NAME } from '../../shared/owner-words.js';
11
+ import { SESSION_MARK } from '../../shared/next-step.js';
12
+ import { ownerRef } from '../../shared/report-progress.js';
10
13
  import {
11
14
  locateFeatureForQuestion,
12
15
  allWorkTrees,
@@ -70,6 +73,8 @@ function trackOutput(state, featureName, filePath) {
70
73
  return wasMissing;
71
74
  }
72
75
 
76
+ const gateName = (g) => GATE_NAME[g] ?? g;
77
+
73
78
  function isApprovalAnswer(answer) {
74
79
  if (typeof answer !== 'string') return false;
75
80
  const lower = answer.toLowerCase();
@@ -131,14 +136,14 @@ function handleAskUserQuestion(input, sessionRoot) {
131
136
  const allNames = allWorkTrees(sessionRoot).flatMap((r) => featureNamesIn(r));
132
137
  const candidate = unrecognizedSlugLike(question, allNames);
133
138
  const remediation = candidate
134
- ? `"${candidate}" não está registrada em nenhuma árvore conhecida. Se é uma feature nova, crie-a primeiro: ` +
135
- `morph-spec create ${candidate} --description "<o quê/porquê>" --type <feature|bug|chore|hotfix> — ` +
136
- `depois aprove com: morph-spec approve ${candidate} ${gate}`
137
- : `Aprove explicitamente: morph-spec approve <feature> ${gate}`;
139
+ ? `"${candidate}" não está registrada em nenhuma árvore conhecida; se é nova, ` +
140
+ `morph-spec create ${candidate} --description "<o quê/porquê>" --type <feature|bug|chore|hotfix>, ` +
141
+ `depois morph-spec approve ${candidate} ${gate}`
142
+ : `morph-spec approve <feature> ${gate}`;
138
143
  warnings.push(
139
- `⚠️ [morph-spec] APROVAÇÃO NÃO ATRIBUÍDA — a resposta "aprovado" ao Gate "${gate}" NÃO foi gravada: ` +
140
- `a pergunta não nomeia nenhuma feature conhecida ("${question}"). ` +
141
- `Gravar por palpite carimbaria o gate na feature errada. ${remediation}`
144
+ `⚠️ A sua aprovação (${gateName(gate)}) não foi gravada: a pergunta não diz de qual funcionalidade é ` +
145
+ `("${question}"), e gravar no palpite poderia aprovar a funcionalidade errada.\n` +
146
+ `${SESSION_MARK} ${remediation}`
142
147
  );
143
148
  continue;
144
149
  }
@@ -152,14 +157,16 @@ function handleAskUserQuestion(input, sessionRoot) {
152
157
  const existing = gates?.[gate];
153
158
  const alreadyApproved = existing === true || existing?.approved === true;
154
159
  if (alreadyApproved) continue;
160
+ const ref = ownerRef(root, featureName, feature);
155
161
 
156
162
  // Out of order still approves (never block a human in the loop); `morph-spec approve` refuses the same shape.
157
163
  const unmet = unmetGatePrereqs(gate, gates);
158
164
  if (unmet.length) {
159
165
  warnings.push(
160
- `⚠️ [morph-spec] GATE FORA DE ORDEM — o Gate "${gate}" de "${featureName}" foi aprovado, ` +
161
- `mas o(s) gate(s) anterior(es) ${unmet.join(', ')} não estão aprovados (ordem: ${unmet.join(' → ')} → ${gate}). ` +
162
- `Aprove os gates anteriores ou reveja com 'morph-spec doctor'.`
166
+ `⚠️ Aprovação fora de ordem: ${gateName(gate)} de ${ref} foi gravada, ` +
167
+ `mas antes dela falta ${unmet.map(gateName).join(' e ')}.\n` +
168
+ `${SESSION_MARK} ordem ${[...unmet, gate].join(' → ')}; aprove os anteriores ` +
169
+ `(${unmet.map((g) => `morph-spec approve ${featureName} ${g}`).join(', ')}) ou confira com morph-spec doctor`
163
170
  );
164
171
  }
165
172
 
@@ -171,8 +178,9 @@ function handleAskUserQuestion(input, sessionRoot) {
171
178
  && (feature?.workType === 'chore' ? ['reviewer.md'] : ['verifier.md', 'reviewer.md']).some((f) => !reportIn(f));
172
179
  if (selfAssessed) {
173
180
  warnings.push(
174
- `⚠️ [morph-spec] Gate 3 de "${featureName}" aprovado SEM os relatórios de review independentes (verifier.md, reviewer.md) — ` +
175
- `registrado como selfAssessed (aparece no list/fleet).`
181
+ `⚠️ A entrega de ${ref} foi aprovada sem os relatórios da revisão independente: ` +
182
+ `fica registrada como aprovada sem essa revisão.\n` +
183
+ `${SESSION_MARK} faltam 4-review/verifier.md e/ou reviewer.md; gravado selfAssessed (aparece no list/fleet)`
176
184
  );
177
185
  }
178
186
  setGateApproved(featureName, gate, { approvedBy: 'manual', ...(selfAssessed ? { selfAssessed: true } : {}) }, root);
@@ -10,14 +10,14 @@ import { contextResult, runStandalone } from '../../shared/hook-response.js';
10
10
  import { appendTelemetryEvent } from '../../shared/telemetry-logger.js';
11
11
  import { readTranscriptUsage, usageDelta } from '../../shared/transcript-usage.js';
12
12
  import { implementProgress } from '../../shared/report-progress.js';
13
+ import { scenarioLabel } from '../../shared/owner-words.js';
14
+ import { SESSION_MARK } from '../../shared/next-step.js';
13
15
 
14
16
  function auditReport(featurePath) {
15
17
  const progress = implementProgress(featurePath);
16
18
  if (!progress || progress.legacy) return [];
17
- const bare = progress.checks.filter((c) => c.status === 'feito' && !c.evidence.trim()).map((c) => c.id);
18
- return bare.length
19
- ? [`report.md: ${bare.join(', ')} feito sem evidência — o teste, a linha de código ou o passo que prova (morph-spec report-check)`]
20
- : [];
19
+ return progress.checks.filter((c) => c.status === 'feito' && !c.evidence.trim())
20
+ .map((c) => `${scenarioLabel(c)} está marcado feito sem prova (o teste, a linha de código ou o passo que mostra que funciona).`);
21
21
  }
22
22
 
23
23
  export async function run(payload) {
@@ -52,8 +52,9 @@ export async function run(payload) {
52
52
  if (reportWarnings.length > 0) {
53
53
  const hash = createHash('sha1').update(reportWarnings.join('\n')).digest('hex');
54
54
  if (warnedHashes[name]?.reports !== hash) {
55
- warnings.push('📋 3-implement/report.md:');
55
+ warnings.push('📋 Relatório da construção:');
56
56
  for (const w of reportWarnings) warnings.push(` • ${w}`);
57
+ warnings.push(`${SESSION_MARK} preencha a coluna evidência em 3-implement/report.md (morph-spec report-check ${name})`);
57
58
  warnedHashes[name] = { ...warnedHashes[name], reports: hash };
58
59
  try { writeFileSync(warnedHashesPath, JSON.stringify(warnedHashes, null, 2), 'utf-8'); } catch {}
59
60
  }
@@ -3,14 +3,10 @@
3
3
  import { readFileSync, existsSync, readdirSync } from 'fs';
4
4
  import { dirname, join, resolve } from 'path';
5
5
  import { execSync } from 'child_process';
6
- import {
7
- stateExists,
8
- getActiveFeature,
9
- getFeaturePhase,
10
- getPendingGates,
11
- } from '../../shared/state-reader.js';
6
+ import { stateExists, getActiveFeature, getFeaturePhase } from '../../shared/state-reader.js';
12
7
  import { implementProgress } from '../../shared/report-progress.js';
13
- import { collectNextSignals, decideNext, formatNext } from '../../shared/next-step.js';
8
+ import { collectNextSignals, decideNext, retratoOf, sessionLine, SESSION_MARK } from '../../shared/next-step.js';
9
+ import { featureRef, TESTS } from '../../shared/owner-words.js';
14
10
  import { contextResult, runStandalone } from '../../shared/hook-response.js';
15
11
  import { acquireClaim, foreignClaim, claimAge } from '../../shared/claim-registry.js';
16
12
  import { rotateEventsLogIfLarge } from '../../shared/telemetry-logger.js';
@@ -120,30 +116,48 @@ function buildEnvLine(dir) {
120
116
  }
121
117
  }
122
118
 
119
+ function signalsFor(dir, slug, fallbackFeature) {
120
+ let signals = null;
121
+ try { signals = collectNextSignals(slug, dir); } catch {}
122
+ if (signals) return { signals, ownSignals: true };
123
+ const featureDir = join(dir, '.morph', 'features', slug);
124
+ return {
125
+ ownSignals: false,
126
+ signals: {
127
+ feature: slug, featureJson: fallbackFeature ?? null, progress: implementProgress(featureDir),
128
+ phase: getFeaturePhase(slug, dir), hasDesign: existsSync(join(featureDir, '1-design')),
129
+ },
130
+ };
131
+ }
132
+
123
133
  // No git here, so verify staleness is unknown: an escalation the tree already moved past, or the
124
134
  // root skeleton of a feature living in a worktree, would be an order read from stale facts.
125
- function buildNextLine(dir, feature) {
126
- try {
127
- const signals = collectNextSignals(feature, dir);
128
- if (!signals) return null;
129
- if (signals.worktreePath && !samePath(resolve(signals.worktreePath), resolve(dir))) {
130
- return `▶ ${feature} vive no worktree ${signals.worktreePath}: abra a sessão lá (aqui é o esqueleto de nascimento).`;
131
- }
132
- const next = decideNext(signals);
133
- if (next.action === 'escalate') return `▶ verify vermelho de novo: rode \`morph-spec next ${feature}\` antes de agir.`;
134
- return `▶ ${formatNext(next)} (confirme com \`morph-spec next ${feature}\` depois de mudar a árvore)`;
135
- } catch {
136
- return null;
135
+ function featureBlock(dir, slug, fallbackFeature) {
136
+ const { signals, ownSignals } = signalsFor(dir, slug, fallbackFeature);
137
+ const ref = featureRef(slug, signals.featureJson, signals.progress?.summary);
138
+ if (signals.worktreePath && !samePath(resolve(signals.worktreePath), resolve(dir))) {
139
+ return {
140
+ ref,
141
+ lines: [
142
+ `Esta funcionalidade está sendo construída em outro worktree (${signals.worktreePath}): abra a sessão lá; `
143
+ + 'aqui é só o esqueleto de quando ela nasceu.',
144
+ ],
145
+ };
137
146
  }
147
+ let next = null;
148
+ try { next = ownSignals ? decideNext(signals) : null; } catch {}
149
+ const escalate = next?.action === 'escalate';
150
+ const lines = retratoOf(signals, escalate ? null : next).slice(1);
151
+ if (escalate) lines.push(`${SESSION_MARK} ${TESTS} falharam de novo: rode \`morph-spec next ${slug} --json\` antes de agir.`);
152
+ else if (next) lines.push(`${sessionLine(next)} (confirme com \`morph-spec next ${slug} --json\` depois de mudar a árvore)`);
153
+ return { ref, lines };
138
154
  }
139
155
 
140
156
  function buildWorktreeContext(dir, feature) {
141
- const phase = getFeaturePhase(feature, dir);
142
- let text = `🌳 Worktree desta feature: ${feature} (branch morph/${feature}, fase ${phase}). ` +
143
- `Trabalhe apenas nesta feature nesta sessão; o estado vive no .morph/ deste worktree.`;
144
-
145
- const nextLine = buildNextLine(dir, feature);
146
- if (nextLine) text += `\n${nextLine}`;
157
+ const { ref, lines } = featureBlock(dir, feature);
158
+ let text = `🌳 Worktree desta funcionalidade: ${ref} (branch morph/${feature}). ` +
159
+ `Trabalhe só nela nesta sessão; o estado vive no .morph/ deste worktree.`;
160
+ if (lines.length) text += `\n${lines.join('\n')}`;
147
161
 
148
162
  const envLine = buildEnvLine(dir);
149
163
  if (envLine) text += `\n${envLine}`;
@@ -172,18 +186,8 @@ function buildActiveFeatureSummary(dir) {
172
186
  const active = getActiveFeature(dir);
173
187
  if (!active) return null;
174
188
 
175
- const phase = getFeaturePhase(active.name, dir);
176
- const progress = implementProgress(join(dir, '.morph', 'features', active.name));
177
- const pending = getPendingGates(active.name, dir);
178
-
179
- let text = `MORPH-SPEC: feature ativa ${active.name} (fase ${phase})`;
180
- if (progress) text += ` · cenários ${progress.done}/${progress.total}`;
181
- if (pending.length) {
182
- text += ` · gates pendentes: ${pending.join(', ')}`;
183
- }
184
- const nextLine = buildNextLine(dir, active.name);
185
- if (nextLine) text += `\n${nextLine}`;
186
- return text;
189
+ const { ref, lines } = featureBlock(dir, active.name, active.feature);
190
+ return [`MORPH-SPEC: em andamento — ${ref}`, ...lines].join('\n');
187
191
  }
188
192
 
189
193
  // Advisory: the claim is taken even on collision; it warns, never locks.
@@ -193,12 +197,12 @@ function claimBlock(dir, feature, sessionId) {
193
197
  const other = foreignClaim(feature, { gitCommonDir, sessionId });
194
198
  acquireClaim(feature, { gitCommonDir, sessionId, pid: process.pid, path: dir });
195
199
  if (!other) return '';
196
- return `\n⚠️ ATENÇÃO — a feature ${feature} tem claim VIVO de OUTRA sessão`
197
- + `\n pid ${other.pid}${other.path ? ` · ${other.path}` : ''} · visto há ${claimAge(other)}`
198
- + '\n Duas sessões na mesma feature sobrescrevem o trabalho uma da outra.'
199
- + '\n Confirme com a outra sessão ANTES de agir —'
200
- + '\n principalmente antes de `finish`, `archive` ou `delete`.'
201
- + `\n Se aquela sessão morreu: morph-spec claim ${feature} --release`;
200
+ return `\n⚠️ ATENÇÃO: outra sessão está trabalhando agora nesta mesma funcionalidade (${feature})`
201
+ + `\n processo ${other.pid}${other.path ? ` · ${other.path}` : ''} · visto há ${claimAge(other)}`
202
+ + '\n Duas sessões na mesma funcionalidade apagam o trabalho uma da outra.'
203
+ + '\n Confirme com quem está na outra sessão antes de continuar, principalmente antes de entregar, arquivar ou apagar.'
204
+ + `\n${SESSION_MARK} claim vivo de outra sessão; confirme antes de \`finish\`, \`archive\` ou \`delete\`. `
205
+ + `Se aquela sessão morreu: morph-spec claim ${feature} --release`;
202
206
  } catch {
203
207
  return '';
204
208
  }
@@ -235,16 +235,34 @@ export function readStamp(gitCommonDir, projectName) {
235
235
  }
236
236
  }
237
237
 
238
- export function writeStamp(gitCommonDir, projectName, stamp) {
238
+ export function writeStamp(gitCommonDir, projectName, stamp, extra = {}) {
239
239
  const dir = join(gitCommonDir, 'morph-spec');
240
240
  mkdirSync(dir, { recursive: true });
241
241
  const target = stampPath(gitCommonDir, projectName);
242
242
  const tmp = `${target}.tmp.${process.pid}`;
243
- const body = { version: 1, project: projectName, stamp, builtAt: new Date().toISOString() };
243
+ const body = { version: 1, project: projectName, stamp, builtAt: new Date().toISOString(), ...extra };
244
244
  writeFileSync(tmp, `${JSON.stringify(body, null, 2)}\n`, 'utf8');
245
245
  renameSync(tmp, target);
246
246
  }
247
247
 
248
+ // Lives in the stamp so that whatever drops the stamp (down, a fresh up) drops the mark with it.
249
+ function setDataBroken(gitCommonDir, projectName, broken) {
250
+ if (!gitCommonDir) return;
251
+ const previous = readStamp(gitCommonDir, projectName);
252
+ if (Boolean(previous?.dataBroken) === broken) return;
253
+ try {
254
+ writeStamp(gitCommonDir, projectName, previous?.stamp ?? '', {
255
+ builtAt: previous?.builtAt ?? new Date().toISOString(),
256
+ ...(broken ? { dataBroken: true } : {}),
257
+ });
258
+ } catch {
259
+ }
260
+ }
261
+
262
+ export function isDataBroken(gitCommonDir, projectName) {
263
+ return Boolean(gitCommonDir && readStamp(gitCommonDir, projectName)?.dataBroken);
264
+ }
265
+
248
266
  // A stamp that outlives its containers would let the next `up` reuse a stack that no longer exists.
249
267
  export function deleteStamp(gitCommonDir, projectName) {
250
268
  if (!gitCommonDir) return false;
@@ -638,11 +656,15 @@ export function dataServices(composeConfig, projectName = null) {
638
656
  return { services, volumes: [...volumes], shared };
639
657
  }
640
658
 
659
+ const DATA_NOT_READY =
660
+ 'the e2e data was reset but is not migrated or seeded: run `morph-spec e2e up <feature> --fresh`, do not repeat the reset';
661
+
641
662
  /**
642
663
  * Puts the running stack's data back in a known state: `e2e.resetCommand`, else the services that
643
- * declare a named volume are recreated empty; then the auth seed. App services and host services
644
- * keep running. A re-seed alone would leave the previous flow's rows. A host-only stack has no
645
- * volumes: it gets the command or the seed.
664
+ * declare a named volume are recreated empty and everything that may migrate at startup (the other
665
+ * compose services, the host services) is restarted without a rebuild; then the auth seed. A
666
+ * re-seed alone would leave the previous flow's rows. A host-only stack has no volumes: it gets
667
+ * the command or the seed. A failure after the data was touched marks the stack as broken.
646
668
  */
647
669
  export function resetE2eData(
648
670
  cwd,
@@ -652,6 +674,10 @@ export function resetE2eData(
652
674
  const stackEnv = stackEnvFor(cwd, { config, projectName, env });
653
675
  const base = composeArgs(composeFile, projectName);
654
676
  const out = (fields) => ({ reset: { mode: 'none', services: [], volumes: [] }, auth: { status: 'skip', reason: null }, output: '', ...fields });
677
+ const broken = (fields) => {
678
+ setDataBroken(gitCommonDir, projectName, true);
679
+ return out({ ...fields, status: 'fail', reason: `${fields.reason} — ${DATA_NOT_READY}` });
680
+ };
655
681
 
656
682
  const up = composeFile
657
683
  ? getStackStatus(cwd, { composeFile, projectName, env: stackEnv }, exec).up
@@ -685,24 +711,34 @@ export function resetE2eData(
685
711
  const steps = [
686
712
  [...base, 'rm', '-sfv', ...data.services],
687
713
  ['volume', 'rm', '-f', ...data.volumes],
688
- [...base, 'up', '-d', '--wait', ...data.services],
714
+ // An app that only migrates at startup would keep serving an empty database.
715
+ [...base, 'up', '-d', '--wait', '--force-recreate'],
689
716
  ];
690
717
  for (const args of steps) {
691
718
  const step = exec('docker', args, { cwd, env: stackEnv, timeout: healthTimeout });
692
719
  if (step.code !== 0) {
693
- return out({ status: 'fail', reason: `reset step failed: docker ${args.join(' ')}`, output: tailLines(step.output, OUTPUT_TAIL_LINES) });
720
+ return broken({ reason: `reset step failed: docker ${args.join(' ')}`, output: tailLines(step.output, OUTPUT_TAIL_LINES) });
694
721
  }
695
722
  }
696
723
  const health = waitForHealthy(cwd, { composeFile, projectName, env: stackEnv, timeout: healthTimeout }, exec);
697
724
  if (!health.healthy) {
698
- return out({ status: 'fail', reason: 'data services were recreated but the stack never reported healthy', output: health.output });
725
+ return broken({ reason: 'the stack was recreated on empty data but never reported healthy', output: health.output });
699
726
  }
700
727
  reset = { mode: 'volumes', services: data.services, volumes: data.volumes };
728
+ if (gitCommonDir) {
729
+ const host = startHostServices(cwd, { services: config?.e2e?.hostServices, env: stackEnv, gitCommonDir, projectName, restart: true }, exec);
730
+ if (host.status === 'fail') return broken({ reason: host.reason, output: host.output ?? '', reset });
731
+ }
701
732
  }
702
733
  }
703
734
 
704
735
  const auth = prepareAuth(cwd, { config, env: stackEnv, forceSeed: true }, exec);
705
- if (auth.status === 'fail') return out({ status: 'fail', reason: auth.reason, reset, auth });
736
+ if (auth.status === 'fail') {
737
+ return reset.mode === 'none'
738
+ ? out({ status: 'fail', reason: auth.reason, reset, auth })
739
+ : broken({ reason: auth.reason, reset, auth });
740
+ }
741
+ setDataBroken(gitCommonDir, projectName, false);
706
742
  if (reset.mode === 'none' && auth.status === 'skip' && !composeFile) {
707
743
  return out({ status: 'skip', reason: 'nothing to reset: host-only stack with no e2e.resetCommand and no auth seed', reset, auth });
708
744
  }
@@ -739,6 +775,10 @@ export function bringUpE2e(
739
775
  const warnings = [];
740
776
  const stamp = computeSourceStamp(cwd, exec);
741
777
 
778
+ if (isDataBroken(gitCommonDir, projectName)) {
779
+ forceFresh = true;
780
+ warnings.push('the last `e2e reset` left the data unusable: the stack was brought up fresh');
781
+ }
742
782
  if (forceFresh && !composeFile) deleteStamp(gitCommonDir, projectName);
743
783
  const stack = composeFile
744
784
  ? bringUpStack(cwd, { composeFile, projectName, gitCommonDir, env: stackEnv, forceFresh, healthTimeout, stamp }, exec)
@@ -1,6 +1,14 @@
1
+ const OWNER_FORM = [
2
+ [/\baprovar\s+o\s+plano\s+d[eoa]\b/i, 'plan'],
3
+ [/\baprovar\s+as\s+telas\s+d[eoa]\b/i, 'uiux'],
4
+ [/\baprovar\s+a\s+entrega\s+d[eoa]\b/i, 'review'],
5
+ ];
6
+
1
7
  /** Explicit gate names win over words a feature slug may also carry ("plan", "design", "review"). */
2
8
  export function gateFromQuestion(question) {
3
9
  if (typeof question !== 'string') return null;
10
+ const head = question.split(/\r?\n/).find((l) => l.trim()) ?? '';
11
+ for (const [re, gate] of OWNER_FORM) if (re.test(head)) return gate;
4
12
  if (/gate\s+uiux/i.test(question)) return 'uiux';
5
13
  if (/gate\s+3\b/i.test(question)) return 'review';
6
14
  if (/gate\s+(?:[12]\b|d[oe]\s+plano|plan\b)/i.test(question)) return 'plan';
@@ -287,7 +287,7 @@ function launch(svc, ctx, deadline, exec) {
287
287
  const fail = (reason, output = '') => ({ ok: false, reason: `hostService "${svc.name}": ${reason}`, output });
288
288
  const remaining = () => deadline - Date.now();
289
289
 
290
- if (svc.build) {
290
+ if (svc.build && !ctx.skipBuild) {
291
291
  const [file, ...args] = tokenize(svc.build);
292
292
  const built = exec(file, args, { cwd: svc.dir, env: svc.childEnv, timeout: remaining() });
293
293
  // A build killed at its timeout comes back as a plain non-zero exit: the deadline decides first.
@@ -357,6 +357,7 @@ export function startHostServices(cwd, options = {}, exec) {
357
357
  projectName,
358
358
  stamp = null,
359
359
  forceFresh = false,
360
+ restart = false,
360
361
  readCreatedAt = readProcessCreatedAt,
361
362
  } = options;
362
363
 
@@ -394,10 +395,13 @@ export function startHostServices(cwd, options = {}, exec) {
394
395
  });
395
396
  }
396
397
 
397
- const ctx = { gitCommonDir, projectName, stamp, readCreatedAt };
398
398
  const previous = readState(gitCommonDir, projectName) ?? [];
399
+ // A restart relaunches the binaries already built: they keep the stamp of the build they came from.
400
+ const ctx = restart
401
+ ? { gitCommonDir, projectName, stamp: previous[0]?.stamp ?? stamp, readCreatedAt, skipBuild: true }
402
+ : { gitCommonDir, projectName, stamp, readCreatedAt };
399
403
  const sameSet = previous.length === resolved.length && resolved.every((s) => previous.some((r) => r.name === s.name));
400
- const divergent = forceFresh || !sameSet || previous.some((r) => r.stamp !== stamp);
404
+ const divergent = forceFresh || restart || !sameSet || previous.some((r) => r.stamp !== stamp);
401
405
  const warnings = divergent && previous.length > 0
402
406
  ? stopHostServices(gitCommonDir, projectName, { readCreatedAt }).warnings
403
407
  : [];
@@ -5,21 +5,27 @@ import { existsSync, readFileSync } from 'fs';
5
5
  import { join } from 'path';
6
6
  import { derivePhaseForFeature } from './state-reader.js';
7
7
  import { implementProgress } from './report-progress.js';
8
+ import { gateQuestion, retrato, scenarioLabel, TESTS } from './owner-words.js';
8
9
 
9
10
  export const FIX_ATTEMPTS = 3;
10
11
 
11
- const step = (action, command, reason, extra = {}) => ({ action, command, reason, ...extra });
12
+ const step = (action, command, reason, say, extra = {}) => ({ action, command, reason, say, ...extra });
13
+
14
+ function firstAndMore(checks) {
15
+ const [first, ...rest] = checks;
16
+ return rest.length ? `${scenarioLabel(first)} e mais ${rest.length}` : scenarioLabel(first);
17
+ }
12
18
 
13
19
  const HOW = {
14
20
  plan: (f) => [
15
21
  `Rode \`/morph-plan ${f}\`: escreva 2-plan/plan.md e rode \`morph-spec plan-check ${f}\` até zero erro.`,
16
22
  ],
17
- gate: (f) => [
18
- `Rode \`morph-spec gate-check ${f} plan\`; se pausar, AskUserQuestion "Gate do plano — Plano de ${f} aprovado?".`,
23
+ gate: (f, q) => [
24
+ `Rode \`morph-spec gate-check ${f} plan\`; se pausar, AskUserQuestion "${q('plan')}".`,
19
25
  ],
20
- design: (f) => [
26
+ design: (f, q) => [
21
27
  `Rode \`/morph-uiux ${f}\` (opções em 1-design/opcoes/, protótipo e prints); depois \`morph-spec gate-check ${f} uiux\`.`,
22
- `Se pausar, AskUserQuestion "Gate uiux — Design de ${f} aprovado?".`,
28
+ `Se pausar, AskUserQuestion "${q('uiux')}".`,
23
29
  ],
24
30
  implement: (f) => [
25
31
  'Implemente os Cn pendentes em sequência; ao fechar cada um, marque `feito` + evidência (teste ou arquivo:linha) '
@@ -56,7 +62,8 @@ const HOW = {
56
62
  */
57
63
  export function decideNext(s) {
58
64
  const n = decide(s);
59
- const how = (HOW[n.action] ?? HOW.status)(s.feature);
65
+ const q = (gate) => gateQuestion(gate, s.feature, s.featureJson, s.progress?.summary);
66
+ const how = (HOW[n.action] ?? HOW.status)(s.feature, q);
60
67
  const hotfix = s.workType === 'hotfix' && n.command.startsWith('/morph-hotfix');
61
68
  return { ...n, how: hotfix ? ['Fluxo de hotfix: siga .claude/skills/morph-apply/references/hotfix.md.', ...how] : how };
62
69
  }
@@ -69,30 +76,35 @@ function decide(s) {
69
76
  switch (s.phase) {
70
77
  case 'plan':
71
78
  return s.progress
72
- ? step('gate', `morph-spec gate-check ${f} plan`, 'plano extraído: o gate do plano decide a pausa')
73
- : step('plan', `/morph-plan ${f}`, 'sem checks.json: escreva o plan.md e rode plan-check até zero erro');
79
+ ? step('gate', `morph-spec gate-check ${f} plan`, 'plano extraído: o gate do plano decide a pausa',
80
+ 'a sessão confere o plano e, se houver risco, pede a sua aprovação.')
81
+ : step('plan', `/morph-plan ${f}`, 'sem checks.json: escreva o plan.md e rode plan-check até zero erro', 'a sessão escreve o plano.');
74
82
 
75
83
  case 'uiux':
76
- return step('design', `morph-spec gate-check ${f} uiux`, 'complete 1-design/ (morph-uiux) e passe o gate de uiux');
84
+ return step('design', `morph-spec gate-check ${f} uiux`, 'complete 1-design/ (morph-uiux) e passe o gate de uiux',
85
+ 'a sessão desenha as telas para você aprovar.');
77
86
 
78
87
  case 'implement': {
79
88
  const p = s.progress;
80
- if (!p) return step('plan', skill('morph-plan'), 'sem checks.json: plan.md curto e plan-check até zero erro');
81
- const blocked = p.checks.filter((c) => c.status === 'bloqueado').map((c) => c.id);
89
+ if (!p) return step('plan', skill('morph-plan'), 'sem checks.json: plan.md curto e plan-check até zero erro', 'a sessão escreve o plano.');
90
+ const blocked = p.checks.filter((c) => c.status === 'bloqueado');
82
91
  if (blocked.length) {
83
92
  return step('decide', 'AskUserQuestion (decisão do cenário)',
84
- 'Cn bloqueado no report.md: decida pelo plano/ADR ou pergunte, e siga implementando', { checks: blocked });
93
+ 'Cn bloqueado no report.md: decida pelo plano/ADR ou pergunte, e siga implementando',
94
+ `decidir o ${firstAndMore(blocked)}, que está travado.`, { checks: blocked.map((c) => c.id) });
85
95
  }
86
- const pending = p.checks.filter((c) => c.status === 'pendente').map((c) => c.id);
96
+ const pending = p.checks.filter((c) => c.status === 'pendente');
87
97
  if (pending.length) {
88
- return step('implement', skill('morph-apply'), 'implemente nesta sessão e marque cada Cn feito no report.md', { checks: pending });
98
+ return step('implement', skill('morph-apply'), 'implemente nesta sessão e marque cada Cn feito no report.md',
99
+ `a sessão constrói o ${firstAndMore(pending)}.`, { checks: pending.map((c) => c.id) });
89
100
  }
90
101
  const fullFresh = s.verification?.status && s.verificationStale !== true;
91
102
  const affectedFresh = s.affected?.status && s.affectedStale !== true;
92
103
  const v = fullFresh ? s.verification : affectedFresh ? s.affected : null;
93
104
  if (!v) {
94
105
  const ran = s.verification?.status || s.affected?.status;
95
- return step('verify', `morph-spec verify ${f} --affected`, ran ? 'a árvore andou desde o último verify' : 'todo Cn feito, sem verify');
106
+ return step('verify', `morph-spec verify ${f} --affected`, ran ? 'a árvore andou desde o último verify' : 'todo Cn feito, sem verify',
107
+ `rodar ${TESTS}.`);
96
108
  }
97
109
  if (v.status === 'fail') {
98
110
  const streak = (fullFresh ? s.failStreak : s.affected.failStreak) ?? 0;
@@ -100,27 +112,44 @@ function decide(s) {
100
112
  return step('escalate', 'AskUserQuestion (aceitar/continuar/parar)',
101
113
  `${streak} verifies vermelhos seguidos, nunca uma tentativa a mais por conta própria. `
102
114
  + `aceitar → ${skill('morph-review')} (o verify vermelho pausa o gate: o humano assina lá); `
103
- + 'continuar → corrija e rode o verify de novo; parar → encerre aqui. Segue `escalate` até a árvore andar');
115
+ + 'continuar → corrija e rode o verify de novo; parar → encerre aqui. Segue `escalate` até a árvore andar',
116
+ 'esperar a sua decisão sobre os testes automáticos.',
117
+ { ask: `${TESTS} falharam ${streak} vezes seguidas. Você decide: aceitar assim, tentar de novo ou parar.` });
104
118
  }
105
119
  return step('fix', `morph-spec verify ${f}${fullFresh ? '' : ' --affected'}`,
106
- `corrija pelo feedback do verify e rode de novo (${FIX_ATTEMPTS - (streak % FIX_ATTEMPTS)} tentativa(s) antes de perguntar)`);
120
+ `corrija pelo feedback do verify e rode de novo (${FIX_ATTEMPTS - (streak % FIX_ATTEMPTS)} tentativa(s) antes de perguntar)`,
121
+ `a sessão corrige o que ${TESTS} apontaram (${FIX_ATTEMPTS - (streak % FIX_ATTEMPTS)} tentativa(s) antes de perguntar a você).`);
107
122
  }
108
- return step('review', skill('morph-review'), 'verify verde: Gate 3');
123
+ return step('review', skill('morph-review'), 'verify verde: Gate 3', 'a revisão independente roda sozinha.');
109
124
  }
110
125
 
111
126
  case 'review':
112
127
  return approved('review')
113
- ? step('finish', `morph-spec finish ${f} --pr|--merge`, 'Gate 3 aprovado: arquiva e integra num passo')
114
- : step('review', skill('morph-review'), 'relatórios do Gate 3 e gate-check review');
128
+ ? step('finish', `morph-spec finish ${f} --pr|--merge`, 'Gate 3 aprovado: arquiva e integra num passo', 'a sessão abre o PR e entrega.')
129
+ : step('review', skill('morph-review'), 'relatórios do Gate 3 e gate-check review', 'a revisão independente roda sozinha.');
115
130
 
116
131
  default:
117
- return step('status', `morph-spec status ${f}`, `fase desconhecida: ${s.phase ?? '—'}`);
132
+ return step('status', `morph-spec status ${f}`, `fase desconhecida: ${s.phase ?? '—'}`, 'conferir o estado da feature.');
118
133
  }
119
134
  }
120
135
 
121
- export function formatNext(n) {
136
+ export const SESSION_MARK = 'para a sessão:';
137
+
138
+ export function sessionLine(n) {
122
139
  const ids = n.checks?.length ? ` [${n.checks.join(', ')}]` : '';
123
- return `próximo: ${n.action}${ids} → ${n.command} — ${n.reason}`;
140
+ return `${SESSION_MARK} ${n.action}${ids} → ${n.command} — ${n.reason}`;
141
+ }
142
+
143
+ // Owner line first; the second line is the exact instruction the session runs.
144
+ export function formatNext(n) {
145
+ return `Próximo: ${n.say}\n ${sessionLine(n)}`;
146
+ }
147
+
148
+ export function retratoOf(signals, next) {
149
+ return retrato({
150
+ slug: signals.feature, feature: signals.featureJson, progress: signals.progress,
151
+ phase: signals.phase, next, hasDesign: signals.hasDesign,
152
+ });
124
153
  }
125
154
 
126
155
  /** Facts readable from `hooks/shared`; the CLI adds `verificationStale` (git) on top. Null without feature.json. */
@@ -139,9 +168,11 @@ export function collectNextSignals(featureName, cwd) {
139
168
  return {
140
169
  feature: featureName,
141
170
  workType: feature.workType ?? 'feature',
171
+ featureJson: feature,
142
172
  worktreePath: feature.worktree?.path ?? null,
143
173
  phase,
144
174
  progress: implementProgress(featureDir),
175
+ hasDesign: existsSync(join(featureDir, '1-design')),
145
176
  gates: feature.approvals || feature.approvalGates || {},
146
177
  verification: feature.verification ?? null,
147
178
  failStreak: feature.verifications?.feature?.failStreak ?? 0,