@polymorphism-tech/morph-spec 10.8.1 → 10.10.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.
@@ -1,18 +1,37 @@
1
1
  import { readFileSync } from 'fs';
2
- import { PROOF_KINDS, RISK_KINDS, REUSE_VERDICTS } from '../plan/plan-parser.js';
3
2
  import { renderRecapHtml } from '../recap/recap.js';
3
+ import { ADR_PLAIN_LABELS } from '../plan/plan-parser.js';
4
4
  import { stateMachineSvg } from './flow-svg.js';
5
+ import { layeredFlowSvg } from './flow-layers.js';
5
6
 
6
7
  export const TOKENS_CSS = readFileSync(new URL('./tokens.css', import.meta.url), 'utf8');
7
8
  const PAGE_CSS = readFileSync(new URL('./feature-page.css', import.meta.url), 'utf8');
8
9
  const CLIENT_JS = readFileSync(new URL('./feature-page.client.js', import.meta.url), 'utf8');
9
10
 
10
11
  const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
11
- const WORK_LABEL = { feature: 'Feature', bug: 'Correção de bug', chore: 'Manutenção', hotfix: 'Hotfix' };
12
- const STATUS_LABEL = { pendente: 'Pendente', feito: 'Feito', bloqueado: 'Bloqueado' };
13
- const RUNG_TONE = { migrar: 'warn', 'irreversível': 'bad', irreversivel: 'bad' };
12
+ const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
13
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
14
+ const clean = (text) => String(text ?? '').replace(/<!--[\s\S]*?-->/g, '').trim();
14
15
  const NONE_RE = /^(nenhum|nenhuma)\.?$/i;
15
16
 
17
+ const WORK_LABEL = { feature: 'Funcionalidade nova', bug: 'Correção de bug', chore: 'Manutenção', hotfix: 'Correção urgente' };
18
+ const PROOF_LABEL = {
19
+ teste: 'teste automático', e2e: 'teste do fluxo completo, como um usuário', eval: 'avaliação da resposta da IA',
20
+ manual: 'conferência manual', leitura: 'leitura do código',
21
+ };
22
+ const RISK_LABEL = {
23
+ regra: 'regra de negócio', dinheiro: 'dinheiro', contrato: 'integração com outro sistema',
24
+ 'concorrência': 'duas coisas ao mesmo tempo', dado: 'integridade dos dados', 'regressão': 'bug que já aconteceu',
25
+ };
26
+ const RUNG = {
27
+ desfazer: { label: 'Dá trabalho para desfazer', why: 'Dá para voltar atrás, mas não só desfazendo o código.', tone: 'warn' },
28
+ migrar: { label: 'Mexe na estrutura do banco', why: 'Voltar atrás exige outra migração; desfazer o código não basta.', tone: 'warn' },
29
+ 'irreversível': { label: 'Não tem volta', why: 'Depois que rodar, o que mudou não se recupera.', tone: 'bad' },
30
+ };
31
+ const rungOf = (c) => RUNG[String(c.rung ?? '').toLowerCase().replace('irreversivel', 'irreversível')] ?? null;
32
+ const REUSE_LABEL = { REUSAR: 'usa o que já existe', ESTENDER: 'amplia o que já existe', CRIAR: 'novo' };
33
+ const REVIEW_LABEL = { verifier: 'Conferência das entregas', reviewer: 'Revisão do código', security: 'Revisão de segurança' };
34
+
16
35
  function linkifier(plan) {
17
36
  const known = new Set([...plan.scenarios.map((c) => c.id), ...plan.adrs.map((a) => a.id)]);
18
37
  const defaults = new Set(plan.defaults.items.map((d) => d.n));
@@ -29,6 +48,29 @@ function inline(text, link) {
29
48
  }).join('');
30
49
  }
31
50
 
51
+ const LONG_PARAGRAPH = 320;
52
+
53
+ /** Sentences of a paragraph, never cut inside a code span. */
54
+ export function sentences(text) {
55
+ const out = [''];
56
+ const parts = String(text).split(/(`[^`]+`)/);
57
+ parts.forEach((part, i) => {
58
+ if (i % 2) { out[out.length - 1] += part; return; }
59
+ part.split(/(?<=[.!?])\s+(?=[A-ZÀ-Ý"(])/).forEach((piece, k) => {
60
+ if (k) out.push('');
61
+ out[out.length - 1] += piece;
62
+ });
63
+ if (/[.!?]\s+$/.test(part) && i < parts.length - 1) out.push('');
64
+ });
65
+ return out.map((s) => s.trim()).filter(Boolean);
66
+ }
67
+
68
+ // A wall of text reads as one sentence per line; a short paragraph stays a paragraph.
69
+ function paragraph(text, link) {
70
+ const parts = text.length > LONG_PARAGRAPH ? sentences(text) : [];
71
+ return parts.length >= 3 ? `<ul class="sentences">${parts.map((s) => `<li>${inline(s, link)}</li>`).join('')}</ul>` : `<p>${inline(text, link)}</p>`;
72
+ }
73
+
32
74
  function blocks(markdown, link) {
33
75
  const text = String(markdown ?? '').replace(/<!--[\s\S]*?-->/g, '');
34
76
  const out = [];
@@ -36,7 +78,7 @@ function blocks(markdown, link) {
36
78
  let list = null;
37
79
  let table = null;
38
80
  let fence = null;
39
- const closePara = () => { if (para.length) out.push(`<p>${inline(para.join(' '), link)}</p>`); para = []; };
81
+ const closePara = () => { if (para.length) out.push(paragraph(para.join(' '), link)); para = []; };
40
82
  const closeList = () => { if (list) out.push(`<ul>${list.map((i) => `<li>${inline(i, link)}</li>`).join('')}</ul>`); list = null; };
41
83
  const closeTable = () => {
42
84
  if (!table) return;
@@ -65,7 +107,7 @@ function blocks(markdown, link) {
65
107
  if (list && /^\s+\S/.test(line)) { list[list.length - 1] += ` ${line.trim()}`; continue; }
66
108
  closeList();
67
109
  const heading = /^#{1,6}\s+(.*)$/.exec(line);
68
- if (heading) { closePara(); out.push(`<h3>${inline(heading[1], link)}</h3>`); continue; }
110
+ if (heading) { closePara(); out.push(`<h4>${inline(heading[1], link)}</h4>`); continue; }
69
111
  para.push(line.trim());
70
112
  }
71
113
  if (fence) out.push(`<pre><code>${esc(fence.join('\n'))}</code></pre>`);
@@ -74,179 +116,317 @@ function blocks(markdown, link) {
74
116
  }
75
117
 
76
118
  export function splitProblem(text) {
77
- const m = /^\s*\**\s*Resultado buscado\s*:\s*\**\s*(.+)$/im.exec(text ?? '');
78
- const outcome = m ? m[1].replace(/\*\*/g, '').trim() : null;
119
+ const m = /^\s*\**\s*Resultado buscado\s*:\s*\**\s*(.+(?:\r?\n(?!\s*$).+)*)/im.exec(text ?? '');
120
+ const outcome = m ? m[1].replace(/\*\*/g, '').replace(/\s*\r?\n\s*/g, ' ').trim() : null;
79
121
  return { outcome, problem: m ? text.replace(m[0], '').trim() : text ?? '' };
80
122
  }
81
123
 
82
- const bulletsOf = (text) => String(text ?? '').replace(/<!--[\s\S]*?-->/g, '').split(/\r?\n/)
83
- .map((l) => /^\s*[-*]\s+(.+)$/.exec(l)?.[1]).filter((l) => l && !NONE_RE.test(l.trim()));
124
+ /** "Dado X, quando Y, então Z" in its three parts; null when the scenario is not written that way. */
125
+ export function splitScenario(text) {
126
+ const m = /^Dad[oa]s?\s+(.+?),\s+quando\s+(.+?),\s+então\s+(.+)$/is.exec(String(text ?? '').trim());
127
+ return m ? { given: m[1], when: m[2], then: m[3] } : null;
128
+ }
129
+
130
+ const bulletsOf = (text) => clean(text).split(/\r?\n/).reduce((items, line) => {
131
+ const bullet = /^\s*[-*]\s+(.+)$/.exec(line);
132
+ if (bullet) items.push(bullet[1]);
133
+ else if (items.length && /^\s+\S/.test(line)) items[items.length - 1] += ` ${line.trim()}`;
134
+ return items;
135
+ }, []).filter((item) => !NONE_RE.test(item.trim()));
84
136
 
85
137
  const conflictsOf = (plan) => {
86
- const text = plan.conflicts?.text?.replace(/<!--[\s\S]*?-->/g, '').trim();
138
+ const text = clean(plan.conflicts?.text);
87
139
  return text && !NONE_RE.test(text) ? text : null;
88
140
  };
89
141
 
90
- export function pendingAsks(view) {
91
- const { plan } = view;
92
- const asks = [];
93
- for (const c of plan.scenarios) {
94
- if (c.rung && c.rung.toLowerCase() !== 'refazer') asks.push({ id: c.id, verb: 'Revisar', action: 'Pedir ajuste', anchor: `ask-${c.id}`, text: `Não se desfaz com revert (degrau: ${c.rung}). ${c.text}`, tag: 'Degrau' });
95
- if (c.status === 'bloqueado') asks.push({ id: c.id, verb: 'Destravar', action: 'Decidir', anchor: `ask-${c.id}-b`, text: `Bloqueado na implementação. ${c.evidence || c.text}`, tag: 'Bloqueio' });
96
- }
97
- bulletsOf(plan.text.assumptions).forEach((text, i) => asks.push({ id: `suposição ${i + 1}`, verb: 'Corrigir', action: 'Corrigir', anchor: `S${i + 1}`, text, tag: 'Suposição sem prova' }));
98
- for (const d of plan.defaults.items) asks.push({ id: `padrão ${d.n}`, verb: 'Vetar', action: 'Vetar', anchor: `P${d.n}`, text: d.text, tag: `Padrão ${d.n}` });
99
- return asks;
100
- }
101
142
 
102
- function askRow(a, link) {
103
- return `<li id="${esc(a.anchor)}" data-ask="${esc(a.id)}" data-verb="${esc(a.verb)}"><div><p>${inline(a.text, link)}</p><span class="tag">${esc(a.tag)}</span></div><button type="button" class="toggle" aria-pressed="false">${esc(a.action)}</button></li>`;
143
+ export function firstSentence(text) {
144
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
145
+ return /^(.+?[.!?])\s+(?=[A-ZÀ-Ý"`(])/.exec(flat)?.[1] ?? flat;
104
146
  }
105
147
 
106
- function segmented(title, entries, filterable = true) {
107
- const used = entries.filter((e) => e.n > 0);
108
- if (!used.length) return '';
109
- const total = used.reduce((sum, e) => sum + e.n, 0);
110
- const attrs = (e) => (filterable ? `data-filter="${esc(e.key)}" data-jump` : 'disabled');
111
- return `<div class="chart"><h3>${esc(title)}</h3><div class="seg" role="img" aria-label="${esc(used.map((e) => `${e.label}: ${e.n}`).join(', '))}">${used.map((e) => `<button type="button" ${attrs(e)} style="--n:${e.n};--c:var(--s${e.slot})" title="${esc(e.label)}: ${e.n} de ${total}" aria-label="${esc(e.label)}: ${e.n}"></button>`).join('')}</div><ul class="legend">${used.map((e) => `<li><i style="--c:var(--s${e.slot})"></i>${esc(e.label)} ${e.n}</li>`).join('')}</ul></div>`;
148
+ const titleOf = (c) => c.title || firstSentence(cap(splitScenario(c.text)?.then ?? c.text));
149
+
150
+ /** The before and after the page opens with: the plan's own plain lines, else its technical text cut short. */
151
+ export function story(plan) {
152
+ const { outcome, problem } = splitProblem(plan.text.problem);
153
+ const s = plan.summary ?? {};
154
+ return { today: s.today ?? (firstSentence(clean(problem)) || null), after: s.after ?? outcome, plain: Boolean(s.today && s.after), outcome, problem, rest: clean(s.rest) };
112
155
  }
113
156
 
114
- function riskBars(scenarios) {
115
- const rows = RISK_KINDS.map((r) => ({ r, n: scenarios.filter((c) => c.risk?.toLowerCase() === r).length })).filter((x) => x.n);
116
- if (!rows.length) return '';
117
- const max = Math.max(...rows.map((x) => x.n));
118
- return `<div class="chart"><h3>Risco que os cenários protegem</h3><ul class="bars">${rows.map((x) => `<li><button type="button" data-filter="${esc(x.r)}" data-jump title="Ver cenários de ${esc(x.r)}"><span>${esc(x.r)}</span><span class="track"><span class="fill" style="--share:${x.n / max}"></span></span><span>${x.n}</span></button></li>`).join('')}</ul></div>`;
157
+ /** What deserves a careful look, heaviest first: the plan's own warnings, no way back, stuck, failed, flagged, assumed. */
158
+ export function attentionPoints(view) {
159
+ const { plan, reviews, verification } = view;
160
+ const points = [];
161
+ for (const text of plan.summary?.watch ?? []) points.push({ kind: 'note', tone: 'warn', glyph: '!', tag: 'Aviso do plano', text: cap(text) });
162
+ for (const c of plan.scenarios) {
163
+ const rung = rungOf(c);
164
+ if (rung) points.push({ kind: 'rung', tone: rung.tone, glyph: '!', tag: rung.label, why: rung.why, text: titleOf(c), ref: c.id, ask: c.id, verb: 'Rever', anchor: `ponto-${c.id}` });
165
+ }
166
+ for (const c of plan.scenarios) {
167
+ if (c.status === 'bloqueado') points.push({ kind: 'blocked', tone: 'bad', glyph: '✕', tag: 'Travado na construção', why: 'Precisa de uma decisão para continuar.', text: c.evidence || titleOf(c), ref: c.id, ask: `${c.id} (travado)`, verb: 'Decidir', anchor: `ponto-${c.id}-travado` });
168
+ }
169
+ if (verification && verification.status !== 'pass') points.push({ kind: 'verify', tone: 'bad', glyph: '✕', tag: 'Checagem automática falhou', text: 'O build ou os testes não passaram na última rodada.' });
170
+ for (const [role, r] of Object.entries(reviews ?? {})) {
171
+ for (const b of r.blockers ?? []) points.push({ kind: 'review', tone: 'bad', glyph: '✕', tag: `${REVIEW_LABEL[role] ?? 'Revisão'} apontou`, text: b.evidence || b.where || b.id });
172
+ }
173
+ if (conflictsOf(plan)) points.push({ kind: 'conflict', tone: 'warn', glyph: '!', tag: 'Contraria uma decisão anterior', text: 'Este plano muda algo que já tinha sido decidido no projeto.', href: '#conflitos' });
174
+ bulletsOf(plan.text.assumptions).forEach((text, i) => points.push({ kind: 'assumption', tone: 'warn', glyph: '?', tag: 'Suposição não confirmada', why: 'Foi assumido sem prova. Se estiver errado, o plano muda.', text, ask: `suposição ${i + 1}`, verb: 'Corrigir', anchor: `S${i + 1}` }));
175
+ return points;
119
176
  }
120
177
 
121
- function panorama(view, asks, link) {
122
- const { plan } = view;
123
- const { outcome, problem } = splitProblem(plan.text.problem);
124
- const rungs = plan.scenarios.filter((c) => c.rung && c.rung.toLowerCase() !== 'refazer').length;
125
- const proofs = PROOF_KINDS.map((k, i) => ({ key: k, label: k, slot: i + 1, n: plan.scenarios.filter((c) => c.proof?.toLowerCase() === k).length }));
126
- const reuse = REUSE_VERDICTS.map((v, i) => ({ key: v, label: v.toLowerCase(), slot: i + 1, n: plan.reuse.filter((r) => r.verdict === v).length }));
127
- const num = (href, n, label, alert = false) => `<li${alert ? ' class="alert"' : ''}><a href="${href}"><b>${n}</b>${esc(label)}</a></li>`;
128
- return `<section id="panorama">
129
- ${outcome ? `<p class="outcome">${inline(outcome, link)}</p>` : ''}
130
- <ul class="numbers">
131
- ${num('#cenarios', plan.scenarios.length, plan.scenarios.length === 1 ? 'cenário define o pronto' : 'cenários definem o pronto')}
132
- ${num('#decisoes', plan.adrs.length, plan.adrs.length === 1 ? 'decisão registrada' : 'decisões registradas')}
133
- ${num('#decidir', asks.length, asks.length === 1 ? 'ponto para você olhar' : 'pontos para você olhar')}
134
- ${rungs ? num('#decidir', rungs, 'sem volta por revert', true) : ''}
135
- </ul>
136
- ${problem ? `<details class="fold" open><summary>O problema hoje</summary><div class="prose">${blocks(problem, link)}</div></details>` : ''}
137
- ${segmented('Como cada cenário será provado', proofs)}
138
- ${riskBars(plan.scenarios)}
139
- ${segmented('Reaproveitar ou criar', reuse, false)}
140
- </section>`;
178
+ const approved = (g) => g === true || g?.approved === true;
179
+ // After the plan gate there is nothing left to veto: the points stay as a record, and only what is stuck still asks.
180
+ const settled = (view) => approved(view.gates?.plan);
181
+ const LIVE_KINDS = ['blocked', 'verify', 'review'];
182
+
183
+ const toggle = (label = 'Quero mudar') => `<button type="button" class="toggle" aria-pressed="false">${esc(label)}</button>`;
184
+
185
+ function pointGroups(points, link) {
186
+ const groups = [];
187
+ for (const p of points) {
188
+ const last = groups[groups.length - 1];
189
+ if (last?.tag === p.tag) last.items.push(p); else groups.push({ ...p, items: [p] });
190
+ }
191
+ const item = (p) => {
192
+ const ask = p.ask ? ` data-ask="${esc(p.ask)}" data-verb="${esc(p.verb)}"` : '';
193
+ const where = p.ref ? `<a class="id" href="#${esc(p.ref)}" data-ref="${esc(p.ref)}">${esc(p.ref)}</a>` : p.href ? `<a class="id" href="${esc(p.href)}">ver</a>` : '';
194
+ return `<li${p.anchor ? ` id="${esc(p.anchor)}"` : ''}${LIVE_KINDS.includes(p.kind) ? ' class="live"' : ''}${ask}>${where}<p>${inline(p.text, link)}</p>${p.ask ? toggle(p.kind === 'blocked' ? 'Decidir' : 'Quero mudar') : ''}</li>`;
195
+ };
196
+ return `<ul class="groups plain">${groups.map((g) => `<li class="group ${g.tone}"><div class="group-head"><i class="ico ${g.tone}" aria-hidden="true">${g.glyph}</i><div><h3>${esc(g.tag)}${g.items.length > 1 ? `<span class="n">${g.items.length}</span>` : ''}</h3>${g.why ? `<p class="why">${esc(g.why)}</p>` : ''}</div></div><ul class="items">${g.items.map(item).join('')}</ul></li>`).join('')}</ul>`;
141
197
  }
142
198
 
143
- function gateSign(view) {
199
+ // The hook that records an approval reads an answer that starts with this word.
200
+ const APPROVAL_ANSWER = 'Aprovado.';
201
+
202
+ export function headline(view) {
144
203
  const g = view.gate;
145
204
  if (g?.pause && g.resolver !== 'session') {
146
- return `<div class="sign"><h3>O ${esc(g.label.toLowerCase())} espera sua decisão</h3><p>${inline(g.reason ?? 'Leia os pontos abaixo e responda no terminal.', (s) => s)}</p></div>`;
205
+ return { tone: 'wait', title: 'Esperando a sua decisão', text: g.reason ?? `A etapa "${g.label}" só segue com o seu ok.`, hint: 'Para seguir como está, cole a resposta no terminal. Para mudar algo, marque "Quero mudar" nos itens abaixo e cole a resposta do rodapé.', answer: APPROVAL_ANSWER };
147
206
  }
148
- const approved = Object.values(view.gates).filter((x) => x === true || x?.approved === true).length;
149
- return `<div class="sign clear"><h3>${approved ? 'Nenhuma decisão parada' : 'Gate ainda não chamado'}</h3><p>Você pode vetar qualquer padrão abaixo a qualquer momento.</p></div>`;
207
+ const now = view.stations.find((s) => s.state === 'now');
208
+ const p = view.progress;
209
+ if (!now) return { tone: 'ok', title: 'Entregue', text: 'Tudo o que foi prometido foi construído, conferido e entregue.' };
210
+ if (now.id === 'plan') return { tone: 'info', title: 'Plano escrito, nada construído ainda', text: 'A construção começa quando o plano for aprovado.' };
211
+ if (now.id === 'uiux') return { tone: 'info', title: 'Desenhando as telas', text: 'Plano aprovado. As telas vêm antes da construção.' };
212
+ if (now.id === 'implement') {
213
+ const stuck = p?.blocked ? ` ${plural(p.blocked, 'está travada', 'estão travadas')}.` : '';
214
+ return { tone: p?.blocked ? 'wait' : 'info', title: 'Em construção', text: p?.total ? `${p.done} de ${plural(p.total, 'entrega pronta', 'entregas prontas')}.${stuck}` : 'A construção começou.' };
215
+ }
216
+ if (now.id === 'review') return { tone: 'info', title: 'Construído, em conferência', text: 'Cada entrega é conferida antes de ir para o ar.' };
217
+ return { tone: 'ok', title: 'Conferido, falta entregar', text: 'A revisão aprovou. Falta só integrar ao projeto.' };
150
218
  }
151
219
 
152
- function decide(view, asks, link) {
153
- const conflicts = conflictsOf(view.plan);
154
- return `<section id="decidir"><h2>O que precisa de você</h2><p class="sub">Marque o que quer mudar. O que ficar sem marca está aceito. A resposta pronta aparece no rodapé para colar no terminal.</p>
155
- ${gateSign(view)}
156
- ${asks.length ? `<ul class="asks">${asks.map((a) => askRow(a, link)).join('')}</ul>` : '<p class="empty">Nenhum ponto em aberto neste plano.</p>'}
157
- ${conflicts ? `<h3>Conflitos com decisões anteriores</h3><div class="prose">${blocks(conflicts, link)}</div>` : ''}
158
- ${view.critique ? `<details class="fold"><summary>Ler a crítica independente do plano</summary><div class="prose">${blocks(view.critique, link)}</div></details>` : ''}
159
- </section>`;
220
+ function scenarioState(c) {
221
+ if (c.proved === 'PROVADO') return { tone: 'ok', glyph: '✓', label: 'Conferido', done: true };
222
+ if (c.proved === 'FALHA') return { tone: 'bad', glyph: '✕', label: 'Falhou na conferência' };
223
+ if (c.status === 'bloqueado') return { tone: 'bad', glyph: '✕', label: 'Travado' };
224
+ if (c.proved) return { tone: 'warn', glyph: '!', label: 'Ainda não conferido' };
225
+ if (c.status === 'feito') return { tone: 'ok', glyph: '✓', label: 'Construído', done: true };
226
+ return { tone: 'todo', glyph: '', label: 'A fazer' };
160
227
  }
161
228
 
162
- function scenarioItem(c, cites, link) {
163
- const state = c.proved === 'PROVADO' ? 'provado' : c.proved === 'FALHA' ? 'falha' : c.status;
164
- const label = c.proved ?? STATUS_LABEL[c.status];
165
- const tone = c.proved === 'PROVADO' || c.status === 'feito' ? 'ok' : c.proved === 'FALHA' || c.status === 'bloqueado' ? 'bad' : '';
166
- const tags = [c.proof, c.risk, c.status, c.rung].filter(Boolean).map((t) => String(t).toLowerCase());
167
- const rung = c.rung && c.rung.toLowerCase() !== 'refazer' ? `<span class="${RUNG_TONE[c.rung.toLowerCase()] ?? ''}">Degrau: ${esc(c.rung)}</span>` : '';
168
- const adrs = cites.length ? `<span>${cites.map((id) => `<a href="#${id}" data-ref="${id}">${id}</a>`).join(', ')}</span>` : '';
169
- const evidence = c.proof_note || c.evidence;
170
- return `<li id="${esc(c.id)}" data-state="${state}" data-tags="${esc(tags.join(' '))}"><p><span class="id">${esc(c.id)}</span>${inline(c.text, link)}</p><div class="tags"><span class="${tone}">${esc(label)}</span>${c.proof ? `<span>Prova: ${esc(c.proof)}</span>` : ''}${c.risk ? `<span>Risco: ${esc(c.risk)}</span>` : ''}${rung}${adrs}</div>${evidence ? `<p class="evidence">${inline(evidence, link)}</p>` : ''}</li>`;
229
+ /** One stop per delivery, in plan order, painted by its state; a diamond marks what has no way back. */
230
+ function stopsLine(scenarios) {
231
+ return `<nav class="stops" aria-label="As ${scenarios.length} entregas">${scenarios.map((c, i) => {
232
+ const state = scenarioState(c);
233
+ const rung = rungOf(c);
234
+ return `<a class="stop ${state.tone}${rung ? ' rung' : ''}" style="--i:${i}" href="#${esc(c.id)}" data-ref="${esc(c.id)}" aria-label="${esc(`${c.id}: ${state.label}${rung ? `, ${rung.label.toLowerCase()}` : ''}`)}"><i aria-hidden="true"></i><span>${esc(c.id)}</span></a>`;
235
+ }).join('')}</nav>`;
171
236
  }
172
237
 
173
- function scenariosSection(view, citesOf, link) {
174
- const { scenarios } = view.plan;
175
- const keys = (list) => [...new Set(list.filter(Boolean).map((k) => k.toLowerCase()))];
176
- const filters = ['todos', ...keys(scenarios.map((c) => c.proof)), ...keys(scenarios.map((c) => c.risk)), ...keys(scenarios.map((c) => c.status))];
177
- return `<section id="cenarios"><h2>O que vai estar pronto</h2><p class="sub">Cada ponto da linha é um comportamento que o verificador executa antes da entrega.</p>
178
- <div class="filters" role="group" aria-label="Filtrar cenários">${filters.map((f, i) => `<button type="button" data-filter="${esc(f)}" aria-pressed="${i === 0}">${esc(f)}</button>`).join('')}</div>
179
- <ol class="line">${scenarios.map((c) => scenarioItem(c, citesOf(c.id), link)).join('')}</ol></section>`;
180
- }
238
+ const fold = (title, body) => (body ? `<details class="fold"><summary>${title}</summary><div class="prose">${body}</div></details>` : '');
181
239
 
182
- const adrBody = (a) => a.body.replace(/^\s*\*\*Alcance:\*\*.*$/im, '').trim();
240
+ const number = (n) => n.toLocaleString('pt-BR');
183
241
 
184
- function matrix(view, cited) {
185
- const adrs = view.plan.adrs.filter((a) => cited.get(a.id).length);
186
- if (!adrs.length) return '';
187
- const ids = view.plan.scenarios.map((c) => c.id);
188
- return `<h3>Qual decisão sustenta qual cenário</h3><div class="scroll-x"><table class="matrix"><thead><tr><th></th>${ids.map((id) => `<th><a href="#${id}" data-ref="${id}">${id}</a></th>`).join('')}</tr></thead><tbody>${adrs.map((a) => `<tr><th><a href="#${a.id}" data-ref="${a.id}">${a.id}</a></th>${ids.map((id) => `<td>${cited.get(a.id).includes(id) ? `<a href="#${id}" aria-label="${a.id} sustenta ${id}"></a>` : ''}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`;
242
+ export function span(startedAt, endedAt) {
243
+ const ms = Date.parse(endedAt ?? '') - Date.parse(startedAt ?? '');
244
+ if (!Number.isFinite(ms) || ms < 0) return null;
245
+ const minutes = Math.round(ms / 60000);
246
+ if (minutes < 90) return `${Math.max(1, minutes)} min`;
247
+ const hours = Math.round(minutes / 60);
248
+ return hours < 48 ? `${hours} h` : `${Math.round(hours / 24)} dias`;
189
249
  }
190
250
 
191
- function decisions(view, cited, link) {
192
- const { adrs } = view.plan;
193
- return `<section id="decisoes"><h2>Decisões</h2><p class="sub">Abra uma decisão para ver o motivo. Os links levam aos cenários que dependem dela.</p>
194
- ${adrs.length ? adrs.map((a) => `<details class="adr" id="${esc(a.id)}"><summary>${esc(a.id)}: ${esc(a.title)}${a.scope ? `<small>vale para ${a.scope === 'projeto' ? 'o projeto' : 'esta feature'}</small>` : ''}</summary><div class="prose">${blocks(adrBody(a), link)}</div></details>`).join('') : '<p class="empty">Este plano não registrou decisões de arquitetura.</p>'}
195
- ${matrix(view, cited)}</section>`;
251
+ const tokenCount = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1).replace('.', ',')} mi` : n >= 1e3 ? `${Math.round(n / 1e3)} mil` : String(n));
252
+ const dayOf = (iso) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso ?? ''); return m ? `${m[3]}/${m[2]}/${m[1]}` : null; };
253
+
254
+ function linkLabel(url) {
255
+ const gh = /github\.com\/[^/]+\/[^/]+\/(issues|pull)\/(\d+)/.exec(url);
256
+ if (gh) return `${gh[1] === 'pull' ? 'PR' : 'Issue'} #${gh[2]}`;
257
+ try { return new URL(url).hostname; } catch { return 'link do pedido'; }
196
258
  }
197
259
 
198
- function howItWorks(view, link) {
199
- const { plan } = view;
200
- const flow = plan.flow?.transitions ?? [];
201
- const states = plan.states?.transitions ?? [];
202
- const reuse = plan.reuse.length ? `<h3>O que aproveita e o que nasce</h3><div class="scroll-x"><table><thead><tr><th>Conceito</th><th>Veredito</th><th>Onde</th></tr></thead><tbody>${plan.reuse.map((r) => `<tr><td>${inline(r.concept, link)}</td><td>${esc(r.verdict.toLowerCase())}</td><td>${inline(r.target, link)}${r.why ? `<br><small>${inline(r.why, link)}</small>` : ''}</td></tr>`).join('')}</tbody></table></div>` : '';
203
- const out = plan.text.outOfScope;
204
- return `<section id="como"><h2>Como funciona</h2>
205
- ${flow.length ? `<h3>Fluxo</h3><div class="diagram">${stateMachineSvg(flow, 'Fluxo', 'flow')}</div>` : ''}
206
- ${states.length ? `<h3>Estados</h3><div class="diagram">${stateMachineSvg(states, 'Máquina de estados', 'states')}</div>` : ''}
207
- ${plan.text.architecture ? `<h3>Arquitetura</h3><div class="prose">${blocks(plan.text.architecture, link)}</div>` : ''}
208
- ${reuse}
209
- ${out ? `<h3>Fora de escopo</h3><div class="prose">${blocks(out, link)}</div>` : ''}
210
- ${plan.text.contract ? `<details class="fold"><summary>Contrato de implementação</summary><div class="prose">${blocks(plan.text.contract, link)}</div></details>` : ''}
211
- ${plan.errata ? `<h3>Errata</h3><div class="prose">${blocks(plan.errata, link)}</div>` : ''}
212
- </section>`;
260
+ function originStrip(view) {
261
+ const o = view.origin ?? {};
262
+ const items = [
263
+ o.link && `<li>Pedido: <a href="${esc(o.link)}" rel="noreferrer">${esc(linkLabel(o.link))}</a></li>`,
264
+ dayOf(o.startedAt) && `<li>Começou em ${dayOf(o.startedAt)}</li>`,
265
+ dayOf(o.endedAt) && `<li>Entregue em ${dayOf(o.endedAt)}</li>`,
266
+ o.branch && `<li>Branch <code>${esc(o.branch)}</code></li>`,
267
+ ].filter(Boolean);
268
+ return items.length ? `<ul class="origin">${items.join('')}</ul>` : '';
213
269
  }
214
270
 
215
- const REVIEW_LABEL = { verifier: 'Verificador', reviewer: 'Revisor', security: 'Segurança' };
271
+ function sizeFacts(view) {
272
+ const stat = view.changes?.stat;
273
+ const took = span(view.origin?.startedAt, view.origin?.endedAt);
274
+ const facts = [
275
+ stat && `<li><b>${number(stat.files)}</b> ${stat.files === 1 ? 'arquivo alterado' : 'arquivos alterados'}</li>`,
276
+ stat && `<li><b>+${number(stat.added)}</b> linhas, <b>−${number(stat.removed)}</b></li>`,
277
+ took && `<li><b>${took}</b> do início à entrega</li>`,
278
+ view.tokens && `<li><b>${tokenCount(view.tokens)}</b> de tokens</li>`,
279
+ ].filter(Boolean);
280
+ return facts.length ? `<ul class="legend facts">${facts.join('')}</ul>` : '';
281
+ }
216
282
 
217
- function execution(view, link) {
218
- const { progress, verification, reviews, design, changes } = view;
283
+ function progressBlock(view, link) {
284
+ const { progress, verification, reviews, design } = view;
219
285
  const started = progress?.done > 0 || progress?.blocked > 0 || verification || Object.values(reviews).some((r) => r.status !== 'missing');
220
286
  if (!started && !design.length) return '';
221
- const share = progress?.total ? progress.done / progress.total : 0;
222
- const ring = progress?.total ? `<div class="gauge"><svg class="ring" viewBox="0 0 112 112" role="img" aria-label="${progress.done} de ${progress.total} cenários feitos"><circle class="base" cx="56" cy="56" r="45"/><circle class="part" cx="56" cy="56" r="45" style="--share:${share}"/></svg><div><b>${progress.done} de ${progress.total}</b>cenários feitos${progress.blocked ? `, ${progress.blocked} bloqueado${progress.blocked > 1 ? 's' : ''}` : ''}</div></div>` : '';
223
- const stat = changes?.stat ? `<div class="gauge"><div><b>${changes.stat.files}</b>arquivos alterados, +${changes.stat.added} e −${changes.stat.removed} linhas</div></div>` : '';
287
+ const row = (tone, glyph, title, text, extra = '') => `<li><i class="ico ${tone}" aria-hidden="true">${glyph}</i><div><b>${title}</b><span>${text}</span>${extra ? `<small>${extra}</small>` : ''}</div></li>`;
224
288
  const rows = [];
289
+ if (progress?.total) {
290
+ const all = progress.done === progress.total;
291
+ rows.push(row(progress.blocked ? 'bad' : all ? 'ok' : 'todo', progress.blocked ? '✕' : all ? '✓' : '', 'Construção', `${progress.done} de ${plural(progress.total, 'entrega pronta', 'entregas prontas')}${progress.blocked ? `, ${plural(progress.blocked, 'travada', 'travadas')}` : ''}`));
292
+ }
225
293
  if (verification) {
226
294
  const ok = verification.status === 'pass';
227
- rows.push(`<li>Verify: <span class="${ok ? 'ok' : 'bad'}">${ok ? 'passou' : 'falhou'}</span>${verification.sha ? ` em <code>${esc(String(verification.sha).slice(0, 8))}</code>` : ''}</li>`);
295
+ rows.push(row(ok ? 'ok' : 'bad', ok ? '✓' : '✕', 'Checagem automática', ok ? 'build e testes passaram' : 'build ou testes falharam', verification.sha ? `versão <code>${esc(String(verification.sha).slice(0, 8))}</code>` : ''));
228
296
  }
229
297
  for (const [role, r] of Object.entries(reviews)) {
230
298
  if (r.status === 'missing') continue;
231
- const tone = r.verdict === 'SHIP' ? 'ok' : r.verdict === 'FIX' ? 'bad' : 'wait';
232
- rows.push(`<li>${REVIEW_LABEL[role]}: <span class="${tone}">${esc(r.verdict ?? 'em andamento')}</span>${r.blockers?.length ? `, ${r.blockers.length} bloqueador${r.blockers.length > 1 ? 'es' : ''}` : ''}</li>`);
299
+ const tone = r.verdict === 'SHIP' ? 'ok' : r.verdict === 'FIX' ? 'bad' : 'todo';
300
+ const word = r.verdict === 'SHIP' ? 'aprovou' : r.verdict === 'FIX' ? 'pediu correções' : 'em andamento';
301
+ rows.push(row(tone, tone === 'ok' ? '✓' : tone === 'bad' ? '✕' : '', REVIEW_LABEL[role] ?? esc(role), word, r.blockers?.length ? plural(r.blockers.length, 'problema apontado', 'problemas apontados') : ''));
233
302
  }
234
303
  const blockers = Object.values(reviews).flatMap((r) => r.blockers ?? []);
235
- return `<section id="execucao"><h2>Execução e provas</h2>
236
- <div class="gauges">${ring}${stat}${rows.length ? `<ul class="status-list">${rows.join('')}</ul>` : ''}</div>
237
- ${blockers.length ? `<h3>Bloqueadores da revisão</h3><div class="prose"><ul>${blockers.map((b) => `<li>${inline(`${b.id}: ${b.evidence || b.where}`, link)}</li>`).join('')}</ul></div>` : ''}
304
+ return `<div id="andamento"><h2>Como está andando</h2>
305
+ ${rows.length ? `<ul class="timeline">${rows.join('')}</ul>` : ''}
306
+ ${blockers.length ? `<h3>O que a revisão apontou</h3><div class="prose"><ul>${blockers.map((b) => `<li>${inline(`${b.id}: ${b.evidence || b.where}`, link)}</li>`).join('')}</ul></div>` : ''}
238
307
  ${design.length ? `<h3>Telas</h3><ul class="shots">${design.map((d) => `<li><a href="${esc(d.href)}">${d.shot ? `<img src="${esc(d.shot)}" alt="" loading="lazy">` : ''}${esc(d.name)}${d.kind === 'opcoes' ? ' (opções)' : ''}</a></li>`).join('')}</ul>` : ''}
308
+ </div>`;
309
+ }
310
+
311
+ function summaryPanel(view, points, link) {
312
+ const { plan } = view;
313
+ const st = story(plan);
314
+ const h = headline(view);
315
+ const out = bulletsOf(plan.text.outOfScope);
316
+ const done = plan.scenarios.filter((c) => scenarioState(c).done).length;
317
+ const total = plan.scenarios.length;
318
+ const noReturn = plan.scenarios.filter(rungOf).length;
319
+ const choices = plan.defaults.items.length;
320
+ const live = points.some((p) => LIVE_KINDS.includes(p.kind));
321
+ const beforeAfter = st.today || st.after ? `<div class="shift${st.plain ? ' plain' : ''}">
322
+ <div class="before"><span class="tag">Hoje</span><p>${st.today ? inline(cap(st.today), link) : '—'}</p></div>
323
+ <div class="after"><span class="tag">Depois</span><p>${st.after ? inline(cap(st.after), link) : '—'}</p></div>
324
+ </div>` : '';
325
+ return `<section class="panel on" id="resumo">
326
+ ${beforeAfter}
327
+ <div class="status ${h.tone}"><div><h2>${esc(h.title)}</h2><p>${inline(h.text, link)}</p>${h.hint ? `<p class="hint">${esc(h.hint)}</p>` : ''}</div>${h.answer ? `<button type="button" class="act" data-copy="${esc(h.answer)}">Copiar "${esc(h.answer)}"</button>` : ''}</div>
328
+ ${total ? `<div class="board">${stopsLine(plan.scenarios)}
329
+ <ul class="legend"><li><b>${done} de ${total}</b> ${total === 1 ? 'entrega pronta' : 'entregas prontas'}</li>${noReturn ? `<li class="rung"><i aria-hidden="true"></i><b>${noReturn}</b> sem volta fácil</li>` : ''}<li><a href="#decisoes"><b>${plan.adrs.length}</b> ${plan.adrs.length === 1 ? 'decisão de projeto' : 'decisões de projeto'}</a></li>${choices ? `<li><a href="#escolhas"><b>${choices}</b> ${choices === 1 ? 'escolha técnica' : 'escolhas técnicas'}</a></li>` : ''}</ul>
330
+ ${sizeFacts(view)}</div>` : ''}
331
+ <h2 id="atencao">${settled(view) && !live ? 'O risco que este plano carrega' : 'Olhe com carinho'}</h2>
332
+ ${points.length ? `${pointGroups(points, link)}<p class="tip">"Quero mudar" monta a resposta no rodapé, pronta para colar no terminal.</p>` : '<p class="calm"><i class="ico ok" aria-hidden="true">✓</i>Nada fora do comum: nenhuma mudança sem volta, nada travado, nenhuma suposição em aberto.</p>'}
333
+ ${progressBlock(view, link)}
334
+ ${out.length ? `<h2>Fica de fora</h2><ul class="out">${out.map((o) => `<li><p>${inline(o, link)}</p></li>`).join('')}</ul>` : ''}
335
+ <h2>Quer o contexto inteiro?</h2>
336
+ ${fold('O problema, em detalhe', blocks(st.problem, link))}
337
+ ${fold('O que mais o resumo diz', st.rest ? blocks(st.rest, link) : '')}
338
+ ${st.plain && st.outcome ? fold('Como saber que deu certo', `<p>${inline(st.outcome, link)}</p>`) : ''}
339
+ ${fold('O pedido original', view.description ? `<p>${esc(view.description)}</p>` : '')}
340
+ </section>`;
341
+ }
342
+
343
+ function scenarioRow(c, cites, link) {
344
+ const state = scenarioState(c);
345
+ const parts = splitScenario(c.text);
346
+ const rung = rungOf(c);
347
+ const steps = parts
348
+ ? `<div class="steps"><div><b>Situação</b><p>${inline(cap(parts.given), link)}</p></div><i aria-hidden="true">→</i><div><b>Ação</b><p>${inline(cap(parts.when), link)}</p></div><i aria-hidden="true">→</i><div class="res"><b>Resultado</b><p>${inline(cap(parts.then), link)}</p></div></div>`
349
+ : `<div class="prose"><p>${inline(c.text, link)}</p></div>`;
350
+ const proof = c.proof ? PROOF_LABEL[c.proof.toLowerCase()] ?? c.proof : null;
351
+ const risk = c.risk ? RISK_LABEL[c.risk.toLowerCase()] ?? c.risk : null;
352
+ const meta = [
353
+ proof && `<li><b>Como se confere</b>${esc(proof)}</li>`,
354
+ risk && `<li><b>O que protege</b>${esc(risk)}</li>`,
355
+ rung && `<li><b>Cuidado</b>${esc(rung.why)}</li>`,
356
+ cites.length && `<li><b>Decisão por trás</b>${cites.map((id) => `<a href="#${id}" data-ref="${id}">${id}</a>`).join(', ')}</li>`,
357
+ ].filter(Boolean).join('');
358
+ const evidence = c.proof_note || c.evidence;
359
+ // The title is the author's paraphrase and nothing checks it: what has no way back shows its real text unasked.
360
+ return `<li><details class="row ${state.tone}" id="${esc(c.id)}"${rung ? ' open' : ''}><summary><i class="ico ${state.tone}" title="${esc(state.label)}" aria-hidden="true">${state.glyph}</i><span class="id">${esc(c.id)}</span><span class="t plain">${inline(titleOf(c), link)}</span>${rung ? `<span class="pill ${rung.tone}">${esc(rung.label)}</span>` : ''}<span class="pill ${state.tone}">${esc(state.label)}</span></summary><div class="row-body">${steps}${meta ? `<ul class="meta">${meta}</ul>` : ''}${evidence ? fold('A prova, para quem quer conferir', `<p>${inline(evidence, link)}</p>`) : ''}</div></details></li>`;
361
+ }
362
+
363
+ function deliveriesPanel(view, citesOf, link) {
364
+ const { scenarios } = view.plan;
365
+ const states = scenarios.map(scenarioState);
366
+ const tally = [...new Set(states.map((s) => s.label))].map((label) => {
367
+ const s = states.find((x) => x.label === label);
368
+ return `<li><i class="ico ${s.tone}" aria-hidden="true">${s.glyph}</i>${states.filter((x) => x.label === label).length} ${esc(label.toLowerCase())}</li>`;
369
+ }).join('');
370
+ return `<section class="panel" id="entregas"><h2>O que será entregue</h2><p class="sub">Cada linha é algo que precisa funcionar para a feature estar pronta. Clique para ver em que situação.</p>
371
+ ${scenarios.length ? `<ul class="tally">${tally}</ul><ol class="line">${scenarios.map((c) => scenarioRow(c, citesOf(c.id), link)).join('')}</ol>` : '<p class="calm">O plano ainda não lista entregas.</p>'}</section>`;
372
+ }
373
+
374
+ // The page shows the plain lines and what a decision holds up by itself; the body keeps only the technical rest.
375
+ const adrBody = (a) => a.body
376
+ .replace(/^\s*\*\*(?:Alcance|Decidimos|Por qu[eê]|O que custa):\*\*.*$/gim, '')
377
+ .replace(/\s*Sustenta\s+(?:C\d+(?:,\s*|\s+e\s+)?)+\.?\s*$/i, '')
378
+ .trim();
379
+
380
+ function decisionCard(a, holds, link) {
381
+ const head = `<span class="id">${esc(a.id)}</span><span class="t plain">${inline(a.title, link)}</span>${a.scope === 'projeto' ? '<span class="pill">vale para o projeto todo</span>' : ''}`;
382
+ const sustains = holds.length ? `<p class="holds">Sustenta ${holds.map((id) => `<a href="#${id}" data-ref="${id}">${id}</a>`).join(', ')}</p>` : '';
383
+ const body = adrBody(a);
384
+ const lines = Object.entries(ADR_PLAIN_LABELS).filter(([key]) => a.plain?.[key]);
385
+ if (!lines.length) return `<details class="adr" id="${esc(a.id)}"><summary>${head}</summary><div class="prose">${blocks(body, link)}</div>${sustains}</details>`;
386
+ return `<article class="adr said" id="${esc(a.id)}"><h3>${head}</h3><dl class="plain">${lines.map(([key, label]) => `<dt>${label}</dt><dd>${inline(cap(a.plain[key]), link)}</dd>`).join('')}</dl>${sustains}${fold('O detalhe técnico', body ? blocks(body, link) : '')}</article>`;
387
+ }
388
+
389
+ function decisionsPanel(view, cited, link) {
390
+ const { adrs } = view.plan;
391
+ const conflicts = conflictsOf(view.plan);
392
+ return `<section class="panel" id="decisoes">
393
+ <h2>Decisões de projeto</h2><p class="sub">O caminho escolhido, o motivo e o que ele custa.</p>
394
+ ${adrs.length ? adrs.map((a) => decisionCard(a, cited.get(a.id), link)).join('') : '<p class="calm">Este plano não precisou de decisão de arquitetura.</p>'}
395
+ ${conflicts ? `<h2 id="conflitos">Mudanças em decisões anteriores</h2><div class="prose">${blocks(conflicts, link)}</div>` : ''}
396
+ ${fold('Segunda opinião sobre o plano', view.critique ? blocks(view.critique, link) : '')}
397
+ </section>`;
398
+ }
399
+
400
+ function insidePanel(view, link) {
401
+ const { plan } = view;
402
+ const flow = plan.flow?.transitions ?? [];
403
+ const states = plan.states?.transitions ?? [];
404
+ const reuse = plan.reuse.length ? `<h2>O que aproveita e o que é novo</h2><div class="scroll-x"><table><thead><tr><th>Peça</th><th>Situação</th><th>Onde</th></tr></thead><tbody>${plan.reuse.map((r) => `<tr><td>${inline(r.concept, link)}</td><td><span class="pill ${r.verdict === 'CRIAR' ? 'warn' : 'ok'}">${esc(REUSE_LABEL[r.verdict] ?? r.verdict.toLowerCase())}</span></td><td>${inline(r.target, link)}${r.why ? `<br><small>${inline(r.why, link)}</small>` : ''}</td></tr>`).join('')}</tbody></table></div>` : '';
405
+ const choices = plan.defaults.items.length
406
+ ? `<h2 id="escolhas">Escolhas técnicas feitas sem perguntar</h2><p class="sub">Valores de baixo risco, decididos para não parar o trabalho. Sem marca = aceito.</p><ul class="choices">${plan.defaults.items.map((d) => `<li id="P${d.n}" data-ask="padrão ${d.n}" data-verb="Vetar"><span class="n">${d.n}</span><p>${inline(d.text, link)}</p>${toggle()}</li>`).join('')}</ul>`
407
+ : '';
408
+ const parts = [
409
+ flow.length ? `<h2>O caminho pelo sistema</h2><div class="diagram">${layeredFlowSvg(flow, 'Fluxo', 'flow')}</div>` : '',
410
+ states.length ? `<h2>Estados</h2><div class="diagram">${stateMachineSvg(states, 'Máquina de estados', 'states')}</div>` : '',
411
+ plan.text.architecture ? `<h2>Onde o código entra</h2><div class="prose">${blocks(plan.text.architecture, link)}</div>` : '',
412
+ reuse,
413
+ choices,
414
+ clean(plan.errata) ? `<h2>Correções feitas depois da aprovação</h2><div class="prose">${blocks(plan.errata, link)}</div>` : '',
415
+ ].filter(Boolean);
416
+ if (!parts.length) return '';
417
+ return `<section class="panel" id="por-dentro"><p class="calm">A parte técnica, para quem vai abrir o código. Dá para aprovar o plano sem ler esta aba.</p>
418
+ ${parts.join('\n')}
239
419
  </section>`;
240
420
  }
241
421
 
242
- function recapSection(view) {
422
+ function recapPanel(view) {
243
423
  if (!view.recap) return '';
244
- return `<section id="recap"><h2>A história da feature</h2><p class="sub">Toque para ouvir o que foi feito, cena por cena.</p><iframe class="recap" title="Recap narrado" loading="lazy" srcdoc="${esc(renderRecapHtml(view.recap))}"></iframe></section>`;
424
+ return `<section class="panel" id="recap"><h2>A história da feature</h2><p class="sub">Toque para ouvir o que foi feito, cena por cena.</p><iframe class="recap" title="Recap narrado" loading="lazy" srcdoc="${esc(renderRecapHtml(view.recap))}"></iframe></section>`;
245
425
  }
246
426
 
247
427
  function refsOf(plan) {
248
428
  const refs = {};
249
- for (const c of plan.scenarios) refs[c.id] = c.text.replace(/`/g, '');
429
+ for (const c of plan.scenarios) refs[c.id] = (c.title || c.text).replace(/`/g, '');
250
430
  for (const a of plan.adrs) refs[a.id] = a.title;
251
431
  for (const d of plan.defaults.items) refs[`P${d.n}`] = d.text.replace(/`/g, '');
252
432
  return JSON.stringify(refs).replace(/</g, '\\u003c');
@@ -255,47 +435,46 @@ function refsOf(plan) {
255
435
  export function renderFeatureHtml(view) {
256
436
  const { plan } = view;
257
437
  const link = linkifier(plan);
258
- const asks = pendingAsks(view);
438
+ const points = attentionPoints(view);
259
439
  const ids = plan.scenarios.map((c) => c.id);
260
440
  const cited = new Map(plan.adrs.map((a) => [a.id, ids.filter((id) => new RegExp(`\\b${id}\\b`).test(a.body))]));
261
441
  const citesOf = (id) => plan.adrs.filter((a) => cited.get(a.id).includes(id)).map((a) => a.id);
262
- const done = view.stations.filter((s) => s.done).length;
263
- const exec = execution(view, link);
264
- const recap = recapSection(view);
265
- const nav = [
266
- ['panorama', 'Panorama'], ['decidir', 'Decidir', asks.length], ['cenarios', 'Cenários'], ['decisoes', 'Decisões'], ['como', 'Como funciona'],
267
- ...(exec ? [['execucao', 'Execução']] : []), ...(recap ? [['recap', 'Recap']] : []),
442
+ const inside = insidePanel(view, link);
443
+ const recap = recapPanel(view);
444
+ const tabs = [
445
+ ['resumo', 'Resumo', settled(view) ? points.filter((p) => LIVE_KINDS.includes(p.kind)).length : points.length],
446
+ ['entregas', 'Entregas'],
447
+ ['decisoes', 'Decisões'],
448
+ ...(inside ? [['por-dentro', 'Por dentro']] : []),
449
+ ...(recap ? [['recap', 'Recap']] : []),
268
450
  ];
269
451
  const key = `${view.feature}:${(view.planHash ?? '').slice(0, 12)}`;
452
+ const name = plan.summary?.name;
270
453
  return `<!doctype html>
271
454
  <html lang="pt-BR">
272
455
  <head>
273
456
  <meta charset="utf-8">
274
457
  <meta name="viewport" content="width=device-width, initial-scale=1">
275
- <title>${esc(view.feature)}</title>
458
+ <title>${esc(name ?? view.feature)}</title>
276
459
  <style>
277
460
  ${TOKENS_CSS}${PAGE_CSS}</style>
278
461
  </head>
279
- <body data-key="${esc(key)}" data-feature="${esc(view.feature)}">
462
+ <body data-key="${esc(key)}" data-feature="${esc(view.feature)}"${settled(view) ? ' class="settled"' : ''}>
280
463
  <header class="top">
281
- <p class="kind">${esc(WORK_LABEL[view.workType] ?? 'Feature')}</p>
282
- <h1>${esc(view.feature)}</h1>
283
- ${view.description ? `<p class="ask">${esc(view.description)}</p>` : ''}
284
- <ol class="route" style="--done:${Math.min(1, done / Math.max(1, view.stations.length - 1)).toFixed(3)}">${view.stations.map((s) => `<li class="stop ${s.state}"${s.state === 'now' ? ' aria-current="step"' : ''}>${esc(s.label)}${s.note ? `<small>${esc(s.note)}</small>` : ''}</li>`).join('')}</ol>
464
+ <p class="kind">${esc(WORK_LABEL[view.workType] ?? 'Funcionalidade nova')}${name ? ` <code>${esc(view.feature)}</code>` : ''}</p>
465
+ <h1>${esc(name ?? view.feature)}</h1>
466
+ <ol class="route">${view.stations.map((s) => `<li class="${s.state}"${s.state === 'now' ? ' aria-current="step"' : ''}><i aria-hidden="true"></i><span>${esc(s.label)}${s.note ? `<small>${esc(s.note)}</small>` : ''}</span></li>`).join('')}</ol>
467
+ ${originStrip(view)}
285
468
  </header>
286
- <div class="shell">
287
- <nav class="side" aria-label="Seções">${nav.map(([id, label, badge]) => `<a href="#${id}">${esc(label)}${badge ? `<b>${badge}</b>` : ''}</a>`).join('')}</nav>
469
+ <nav class="tabs" aria-label="Partes da página"><div>${tabs.map(([id, label, badge], i) => `<a href="#${id}"${i === 0 ? ' class="on"' : ''}>${esc(label)}${badge ? `<b>${badge}</b>` : ''}</a>`).join('')}</div></nav>
288
470
  <main>
289
- ${panorama(view, asks, link)}
290
- ${decide(view, asks, link)}
291
- ${scenariosSection(view, citesOf, link)}
292
- ${decisions(view, cited, link)}
293
- ${howItWorks(view, link)}
294
- ${exec}
471
+ ${summaryPanel(view, points, link)}
472
+ ${deliveriesPanel(view, citesOf, link)}
473
+ ${decisionsPanel(view, cited, link)}
474
+ ${inside}
295
475
  ${recap}
296
- <p class="source">Gerada pelo morph-spec a partir de plan.md${view.planHash ? ` (${esc(view.planHash.slice(0, 12))})` : ''} e dos relatórios da feature. Atualize a aba para ver o estado mais recente. Para mudar o plano, edite o plan.md.</p>
476
+ <p class="source">Página gerada pelo morph-spec a partir do plano${view.planHash ? ` (${esc(view.planHash.slice(0, 12))})` : ''} e dos relatórios da feature. Recarregue para ver o estado mais recente.</p>
297
477
  </main>
298
- </div>
299
478
  <div id="peek" role="tooltip"></div>
300
479
  <div id="tray" role="region" aria-label="Sua resposta"><span class="count"></span><button type="button" class="copy">Copiar resposta</button><button type="button" class="clear">Limpar</button></div>
301
480
  <script type="application/json" id="refs">${refsOf(plan)}</script>