forjajs 5.1.0 → 5.3.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/CHANGELOG.md +76 -0
- package/README.md +37 -4
- package/README.pt-BR.md +39 -4
- package/dist/apps/cli/src/index.d.ts +0 -1
- package/dist/apps/cli/src/index.js +43 -32
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
- package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
- package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
- package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
- package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
- package/dist/apps/server/src/forja-nest.module.js +55 -0
- package/dist/apps/server/src/main.d.ts +21 -4
- package/dist/apps/server/src/main.js +79 -57
- package/dist/apps/server/src/task-planning-service.d.ts +29 -0
- package/dist/apps/server/src/task-planning-service.js +195 -0
- package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
- package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
- package/dist/bin/forja.js +3 -2
- package/dist/lib/agent-evals.d.ts +138 -0
- package/dist/lib/agent-evals.js +349 -0
- package/dist/lib/cli-output.js +14 -2
- package/dist/lib/code-context.d.ts +33 -5
- package/dist/lib/code-context.js +70 -5
- package/dist/lib/context-builder.d.ts +49 -4
- package/dist/lib/context-builder.js +114 -47
- package/dist/lib/core/coverage-gate.d.ts +59 -0
- package/dist/lib/core/coverage-gate.js +58 -0
- package/dist/lib/core/doc-graph.d.ts +38 -0
- package/dist/lib/core/doc-graph.js +83 -0
- package/dist/lib/core/health.js +286 -5
- package/dist/lib/core/journey.js +26 -0
- package/dist/lib/core/registry.js +81 -6
- package/dist/lib/docs-reference.d.ts +35 -0
- package/dist/lib/docs-reference.js +57 -0
- package/dist/lib/project-wiring.js +6 -2
- package/dist/lib/session-memory.d.ts +38 -0
- package/dist/lib/session-memory.js +206 -0
- package/dist/lib/spec-trace.d.ts +46 -0
- package/dist/lib/spec-trace.js +184 -0
- package/dist/packages/adapter-nest/src/index.d.ts +2 -1
- package/dist/packages/adapter-nest/src/index.js +59 -1
- package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
- package/dist/packages/adapter-sqlite/src/index.js +61 -1
- package/dist/packages/context/src/index.d.ts +2 -0
- package/dist/packages/context/src/index.js +36 -15
- package/dist/packages/contracts/src/index.d.ts +64 -0
- package/dist/packages/core/src/index.d.ts +9 -1
- package/dist/packages/core/src/index.js +28 -3
- package/dist/packages/graph/src/index.js +14 -5
- package/dist/packages/mcp/src/index.d.ts +8 -0
- package/dist/packages/mcp/src/index.js +12 -1
- package/dist/packages/observability/src/index.d.ts +11 -0
- package/dist/packages/observability/src/index.js +3 -0
- package/dist/packages/orchestration/src/index.d.ts +15 -1
- package/dist/packages/orchestration/src/index.js +127 -21
- package/dist/packages/planner/src/index.d.ts +7 -1
- package/dist/packages/planner/src/index.js +67 -10
- package/dist/packages/planner/src/proposal-store.d.ts +30 -0
- package/dist/packages/planner/src/proposal-store.js +109 -0
- package/dist/packages/policy/src/index.d.ts +9 -16
- package/dist/packages/policy/src/index.js +114 -31
- package/dist/packages/runtime/src/index.d.ts +16 -2
- package/dist/packages/runtime/src/index.js +176 -61
- package/dist/scripts/build-smart-context.d.ts +2 -0
- package/dist/scripts/build-smart-context.js +12 -3
- package/dist/scripts/code-context.d.ts +3 -1
- package/dist/scripts/code-context.js +13 -3
- package/dist/scripts/coverage-gate.d.ts +2 -0
- package/dist/scripts/coverage-gate.js +101 -0
- package/dist/scripts/eval-agents.d.ts +11 -0
- package/dist/scripts/eval-agents.js +96 -0
- package/dist/scripts/gen-commands-doc.d.ts +2 -0
- package/dist/scripts/gen-commands-doc.js +18 -0
- package/dist/scripts/hook-session-memory.d.ts +9 -0
- package/dist/scripts/hook-session-memory.js +20 -0
- package/dist/scripts/hook-session-start.js +34 -0
- package/dist/scripts/spec-trace.d.ts +10 -0
- package/dist/scripts/spec-trace.js +73 -0
- package/dist/scripts/sync-universal-memory.js +69 -4
- package/dist/scripts/token-benchmark.d.ts +33 -1
- package/dist/scripts/token-benchmark.js +179 -5
- package/dist/scripts/token-economy.js +3 -1
- package/dist/scripts/tools-doctor.d.ts +16 -1
- package/dist/scripts/tools-doctor.js +58 -17
- package/docs/commands.md +155 -0
- package/docs/fluxo.md +11 -7
- package/docs/init-project.md +3 -1
- package/docs/llm-fit-loop.md +20 -0
- package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
- package/docs/produto/factsheet-marketing.md +7 -5
- package/docs/produto/roteiro-demo.md +14 -5
- package/docs/quick-reference.md +3 -3
- package/docs/token-optimization.md +10 -6
- package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
- package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
- package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
- package/package.json +4 -2
- package/specs/avaliacoes-de-agentes/spec.md +52 -0
- package/specs/criterios-ligados-a-testes/spec.md +42 -0
- package/specs/memoria-de-sessao/spec.md +48 -0
- package/specs/v6-agent-runtime-portable/spec.md +83 -0
- package/specs/v6-core-consolidation/spec.md +70 -0
- package/specs/v6-docs-drift/spec.md +85 -0
- package/specs/v6-quality-gates/spec.md +99 -0
- package/specs/v6-token-economy/spec.md +84 -0
- package/templates/evals/agents/adr.json +25 -0
- package/templates/evals/agents/memoria.json +32 -0
- package/templates/evals/agents/proxima-acao.json +29 -0
- package/templates/evals/agents/spec-nova.json +26 -0
- package/templates/evals/agents/teste-do-criterio.json +29 -0
- package/templates/project/AGENTS.md +7 -0
- package/templates/project/CLAUDE.md +3 -2
- package/templates/project/skills/testing/SKILL.md +1 -1
|
@@ -1,62 +1,627 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
3
|
-
import { useEffect, useState } from 'react';
|
|
4
|
-
const
|
|
3
|
+
import { useEffect, useRef, useState } from 'react';
|
|
4
|
+
const api = '/api/forja';
|
|
5
|
+
/** Sentinela que `scripts/cost-economy.ts` usa para observação sem `model` — não é um modelo real. */
|
|
6
|
+
const NO_MODEL = '(sem modelo)';
|
|
7
|
+
const TABS = [
|
|
8
|
+
{ id: 'visao', label: 'Visão' },
|
|
9
|
+
{ id: 'rastreio', label: 'Rastreio' },
|
|
10
|
+
{ id: 'custo', label: 'Custo' },
|
|
11
|
+
{ id: 'gates', label: 'Gates' },
|
|
12
|
+
{ id: 'operacao', label: 'Operação' },
|
|
13
|
+
];
|
|
5
14
|
export default function DashboardClient() {
|
|
6
|
-
const
|
|
15
|
+
const [access, setAccess] = useState({ state: 'checking' });
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
let alive = true;
|
|
18
|
+
void probeAccess().then((next) => { if (alive)
|
|
19
|
+
setAccess(next); });
|
|
20
|
+
return () => { alive = false; };
|
|
21
|
+
}, []);
|
|
22
|
+
if (access.state !== 'open')
|
|
23
|
+
return <AccessScreen access={access} onChange={setAccess}/>;
|
|
24
|
+
return <Panel onDisconnect={() => { document.cookie = 'forja_dashboard_token=; path=/; max-age=0'; setAccess({ state: 'locked' }); }}/>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* O proxy falha fechado: sem o token no cookie, toda requisição é 403. Antes esse estado aparecia
|
|
28
|
+
* como cinco banners de erro sem nenhuma forma de resolver pela tela; agora é um portão explícito,
|
|
29
|
+
* e "servidor fora do ar" se distingue de "credencial recusada".
|
|
30
|
+
*/
|
|
31
|
+
async function probeAccess() {
|
|
32
|
+
try {
|
|
33
|
+
const response = await fetch(`${api}/control-plane/metrics`, { cache: 'no-store' });
|
|
34
|
+
if (response.status === 403)
|
|
35
|
+
return { state: 'locked' };
|
|
36
|
+
if (response.ok)
|
|
37
|
+
return { state: 'open' };
|
|
38
|
+
return { state: 'unreachable', message: await failureOf(response, `O servidor respondeu HTTP ${response.status}.`) };
|
|
39
|
+
}
|
|
40
|
+
catch (reason) {
|
|
41
|
+
return { state: 'unreachable', message: reason instanceof Error ? reason.message : 'Não foi possível alcançar o servidor.' };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function AccessScreen({ access, onChange }) {
|
|
45
|
+
const [token, setToken] = useState('');
|
|
46
|
+
const [busy, setBusy] = useState(false);
|
|
7
47
|
const [error, setError] = useState(undefined);
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
48
|
+
async function connect() {
|
|
49
|
+
setBusy(true);
|
|
50
|
+
setError(undefined);
|
|
51
|
+
document.cookie = `forja_dashboard_token=${encodeURIComponent(token.trim())}; path=/; max-age=86400; samesite=lax`;
|
|
52
|
+
const next = await probeAccess();
|
|
53
|
+
setBusy(false);
|
|
54
|
+
if (next.state === 'open') {
|
|
55
|
+
onChange(next);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
document.cookie = 'forja_dashboard_token=; path=/; max-age=0';
|
|
59
|
+
setError(next.state === 'unreachable' ? next.message : 'Token recusado. Confira o FORJA_DASHBOARD_TOKEN com que o painel foi iniciado.');
|
|
60
|
+
}
|
|
61
|
+
return <div className="access">
|
|
62
|
+
<div className="access__inner">
|
|
63
|
+
<div className="brand">
|
|
64
|
+
<span className="brand__mark" aria-hidden="true">F</span>
|
|
65
|
+
<span className="brand__text">
|
|
66
|
+
<span className="brand__title">Forja Control Plane</span>
|
|
67
|
+
<span className="brand__sub">autonomia supervisionada</span>
|
|
68
|
+
</span>
|
|
69
|
+
</div>
|
|
70
|
+
|
|
71
|
+
{access.state === 'checking' && <article className="card"><Skeleton lines={3}/></article>}
|
|
72
|
+
|
|
73
|
+
{access.state === 'unreachable' && <article className="card">
|
|
74
|
+
<Head title="Servidor indisponível" hint="o painel não conseguiu falar com a API"/>
|
|
75
|
+
<div className="banner"><span className="dot dot--crit"/><span>{access.message}</span></div>
|
|
76
|
+
<p className="card__hint">Suba a API com <code>npm run dashboard:api</code> e confira <code>FORJA_API_URL</code>. O painel roda em <code>:3001</code> e a API em <code>:3000</code>.</p>
|
|
77
|
+
<div className="inline">
|
|
78
|
+
<button className="btn btn--primary" disabled={busy} onClick={() => { setBusy(true); void probeAccess().then((next) => { setBusy(false); onChange(next); }); }}>{busy ? 'Tentando…' : 'Tentar de novo'}</button>
|
|
79
|
+
</div>
|
|
80
|
+
</article>}
|
|
81
|
+
|
|
82
|
+
{access.state === 'locked' && <form className="card" onSubmit={(event) => { event.preventDefault(); void connect(); }}>
|
|
83
|
+
<Head title="Conectar ao servidor" hint="credencial local do painel"/>
|
|
84
|
+
<p className="card__hint">O proxy só encaminha requisições autenticadas. Informe o <code>FORJA_DASHBOARD_TOKEN</code> com que o painel foi iniciado — ele guarda um cookie de sessão neste navegador.</p>
|
|
85
|
+
<input className="field" type="password" aria-label="Token do painel" placeholder="FORJA_DASHBOARD_TOKEN" autoComplete="off" value={token} onChange={(event) => setToken(event.target.value)}/>
|
|
86
|
+
{error !== undefined && <div className="banner" role="alert"><span className="dot dot--crit"/><span>{error}</span></div>}
|
|
87
|
+
<div className="inline">
|
|
88
|
+
<button className="btn btn--primary" type="submit" disabled={busy || token.trim().length === 0}>{busy ? 'Verificando…' : 'Conectar'}</button>
|
|
89
|
+
</div>
|
|
90
|
+
</form>}
|
|
91
|
+
</div>
|
|
92
|
+
</div>;
|
|
93
|
+
}
|
|
94
|
+
function Panel({ onDisconnect }) {
|
|
95
|
+
const [tab, setTab] = useState('visao');
|
|
96
|
+
return <>
|
|
97
|
+
<Topbar onDisconnect={onDisconnect}/>
|
|
98
|
+
<nav className="tabs" role="tablist" aria-label="Seções do painel">
|
|
99
|
+
{TABS.map((entry) => <button key={entry.id} role="tab" className="tab" aria-selected={tab === entry.id} onClick={() => setTab(entry.id)}>{entry.label}</button>)}
|
|
100
|
+
</nav>
|
|
101
|
+
{tab === 'visao' && <VisaoTab />}
|
|
102
|
+
{tab === 'rastreio' && <RastreioTab />}
|
|
103
|
+
{tab === 'custo' && <CustoTab />}
|
|
104
|
+
{tab === 'gates' && <GatesTab />}
|
|
105
|
+
{tab === 'operacao' && <OperacaoTab />}
|
|
106
|
+
</>;
|
|
107
|
+
}
|
|
108
|
+
/* ── Topo ──────────────────────────────────────────────────────────────── */
|
|
109
|
+
function Topbar({ onDisconnect }) {
|
|
110
|
+
const queryClient = useQueryClient();
|
|
111
|
+
const [busy, setBusy] = useState(false);
|
|
112
|
+
const [live, setLive] = useState(false);
|
|
11
113
|
useEffect(() => {
|
|
12
|
-
const source = new EventSource(`${
|
|
13
|
-
|
|
14
|
-
|
|
114
|
+
const source = new EventSource(`${api}/events`);
|
|
115
|
+
// O Nest emite `event: observation.recorded`; `onmessage` só pega eventos sem nome, então os
|
|
116
|
+
// dois caminhos são necessários para o painel reagir a uma execução registrada.
|
|
117
|
+
const refresh = () => { setLive(true); void queryClient.invalidateQueries(); };
|
|
118
|
+
source.onopen = () => setLive(true);
|
|
119
|
+
source.onmessage = refresh;
|
|
120
|
+
source.addEventListener('observation.recorded', refresh);
|
|
121
|
+
// Não fecha no erro: o EventSource reconecta sozinho e `onopen` reacende o indicador.
|
|
122
|
+
source.onerror = () => setLive(false);
|
|
15
123
|
return () => source.close();
|
|
16
124
|
}, [queryClient]);
|
|
17
|
-
|
|
125
|
+
return <header className="topbar">
|
|
126
|
+
<div className="brand">
|
|
127
|
+
<span className="brand__mark" aria-hidden="true">F</span>
|
|
128
|
+
<span className="brand__text">
|
|
129
|
+
<span className="brand__title">Forja Control Plane</span>
|
|
130
|
+
<span className="brand__sub">autonomia supervisionada</span>
|
|
131
|
+
</span>
|
|
132
|
+
</div>
|
|
133
|
+
<div className="topbar__actions">
|
|
134
|
+
<span className={`pill ${live ? 'pill--live' : ''}`}>
|
|
135
|
+
<span className={`dot ${live ? 'dot--live' : ''}`}/>
|
|
136
|
+
{live ? 'tempo real' : 'sem stream'}
|
|
137
|
+
</span>
|
|
138
|
+
<button className="btn btn--primary" disabled={busy} onClick={() => { setBusy(true); void queryClient.invalidateQueries().finally(() => setBusy(false)); }}>{busy ? 'Atualizando…' : 'Atualizar'}</button>
|
|
139
|
+
<button className="btn btn--ghost" onClick={onDisconnect}>Sair</button>
|
|
140
|
+
</div>
|
|
141
|
+
</header>;
|
|
142
|
+
}
|
|
143
|
+
/* ── Aba: Visão ────────────────────────────────────────────────────────── */
|
|
144
|
+
function VisaoTab() {
|
|
145
|
+
const status = useQuery({ queryKey: ['capability', 'forja.status'], queryFn: () => capability('forja.status') });
|
|
146
|
+
const next = useQuery({ queryKey: ['capability', 'forja.next'], queryFn: () => capability('forja.next') });
|
|
147
|
+
const data = status.data;
|
|
148
|
+
const sprint = sub(data?.sprint);
|
|
149
|
+
const specs = sub(data?.specs) ?? [];
|
|
150
|
+
const runs = sub(data?.orchestrate)?.runs ?? [];
|
|
151
|
+
const handoffs = sub(data?.handoffs) ?? [];
|
|
152
|
+
const recent = sub(data?.recentRuns) ?? [];
|
|
153
|
+
return <Section title="Visão" hint={data === undefined ? 'retrato único do estado (forja status)' : data.workspace.root}>
|
|
154
|
+
<Failure error={status.error}/>
|
|
155
|
+
<div className="grid grid--metrics">
|
|
156
|
+
<Metric label="Memória" value={data?.workspace.memoryIndexed === true ? 'indexada' : 'ausente'} hint={`${data?.workspace.source ?? '—'} · ${data?.workspace.exists === true ? 'workspace existe' : 'sem workspace'}`} accent={data?.workspace.memoryIndexed === true} loading={status.isPending}/>
|
|
157
|
+
<Metric label="Sprint" value={sprint === undefined || sprint === null ? '—' : `${sprint.done}/${sprint.items}`} hint={sprint?.title ?? reasonOf(data?.sprint) ?? 'sem sprint'} loading={status.isPending}/>
|
|
158
|
+
<Metric label="Specs" value={specs.length} hint={`${specs.filter((spec) => spec.status === 'done').length} concluídas`} loading={status.isPending}/>
|
|
159
|
+
<Metric label="Corridas" value={runs.length} hint={`${runs.filter((run) => !run.concluded).length} abertas`} loading={status.isPending}/>
|
|
160
|
+
</div>
|
|
161
|
+
|
|
162
|
+
<div className="grid grid--split">
|
|
163
|
+
<div className="grid">
|
|
164
|
+
<article className="card">
|
|
165
|
+
<Head title="Próxima ação" hint="forja.next">
|
|
166
|
+
{next.data !== undefined && <span className="pill pill--info">{next.data.action}</span>}
|
|
167
|
+
</Head>
|
|
168
|
+
{next.isPending && <Skeleton lines={2}/>}
|
|
169
|
+
<Failure error={next.error}/>
|
|
170
|
+
{next.data !== undefined && <>
|
|
171
|
+
<p className="card__hint">{next.data.reason}</p>
|
|
172
|
+
<Cmd value={next.data.command}/>
|
|
173
|
+
</>}
|
|
174
|
+
</article>
|
|
175
|
+
|
|
176
|
+
<article className="card">
|
|
177
|
+
<Head title="Corridas" hint="orchestrate"/>
|
|
178
|
+
{runs.length === 0 && <Empty text="Nenhuma corrida registrada." detail="Abra uma com forja orchestrate:start <slug>."/>}
|
|
179
|
+
<div className="rows">
|
|
180
|
+
{runs.map((run) => <Row key={run.slug} title={run.slug} meta={run.goal} dot={run.concluded ? 'ok' : run.openVerdict === null ? 'info' : 'warn'} aside={<span className={`pill ${run.concluded ? 'pill--ok' : 'pill--info'}`}>{run.concluded ? 'concluída' : run.openStage ?? 'aberta'}</span>}/>)}
|
|
181
|
+
</div>
|
|
182
|
+
</article>
|
|
183
|
+
</div>
|
|
184
|
+
|
|
185
|
+
<div className="grid">
|
|
186
|
+
<article className="card">
|
|
187
|
+
<Head title="Handoffs abertos" hint={`${handoffs.length} no workspace`}/>
|
|
188
|
+
{handoffs.length === 0 && <Empty text="Nenhum handoff aberto."/>}
|
|
189
|
+
<div className="rows">
|
|
190
|
+
{handoffs.slice(0, 6).map((handoff) => <Row key={handoff.id} title={`#${handoff.id} · ${handoff.from} → ${handoff.to}`} meta={handoff.intent} aside={<span className="pill">{handoff.slug === '' ? 'sem slug' : handoff.slug}</span>}/>)}
|
|
191
|
+
</div>
|
|
192
|
+
</article>
|
|
193
|
+
|
|
194
|
+
<article className="card">
|
|
195
|
+
<Head title="Execuções recentes" hint="auditoria append-only"/>
|
|
196
|
+
{recent.length === 0 && <Empty text="Nenhuma execução registrada neste workspace."/>}
|
|
197
|
+
<div className="rows">
|
|
198
|
+
{recent.slice(0, 6).map((run, index) => <Row key={`${run.ts}-${index}`} title={run.cmd} meta={new Date(run.ts).toLocaleString('pt-BR')} dot={run.exitCode === 0 ? 'ok' : 'crit'} aside={<span className={`pill ${run.exitCode === 0 ? 'pill--ok' : 'pill--crit'}`}>exit {run.exitCode}</span>}/>)}
|
|
199
|
+
</div>
|
|
200
|
+
</article>
|
|
201
|
+
|
|
202
|
+
<article className="card">
|
|
203
|
+
<Head title="Specs" hint="estado por artefato"/>
|
|
204
|
+
{specs.length === 0 && <Empty text="Nenhuma spec em specs/."/>}
|
|
205
|
+
<div className="rows">
|
|
206
|
+
{specs.slice(0, 6).map((spec) => <Row key={spec.slug} title={spec.slug} meta={`plan ${spec.plan} · tasks ${spec.tasks}`} aside={<span className={`pill ${pillOfStatus(spec.status)}`}>{spec.status}</span>}/>)}
|
|
207
|
+
</div>
|
|
208
|
+
</article>
|
|
209
|
+
</div>
|
|
210
|
+
</div>
|
|
211
|
+
</Section>;
|
|
212
|
+
}
|
|
213
|
+
/* ── Aba: Rastreio ─────────────────────────────────────────────────────── */
|
|
214
|
+
function RastreioTab() {
|
|
215
|
+
const [filter, setFilter] = useState('');
|
|
216
|
+
const trace = useQuery({ queryKey: ['capability', 'spec.trace'], queryFn: () => capability('spec.trace') });
|
|
217
|
+
const totals = trace.data?.totals;
|
|
218
|
+
const ratio = totals === undefined || totals.criteria === 0 ? 0 : totals.covered / totals.criteria;
|
|
219
|
+
const needle = filter.trim().toLowerCase();
|
|
220
|
+
const specs = (trace.data?.specs ?? []).filter((spec) => needle.length === 0 || spec.slug.toLowerCase().includes(needle) || (spec.specId ?? '').toLowerCase().includes(needle));
|
|
221
|
+
return <Section title="Rastreio" hint="critérios de aceite × testes que os citam (SPEC-053)">
|
|
222
|
+
<Failure error={trace.error}/>
|
|
223
|
+
<div className="grid grid--metrics">
|
|
224
|
+
<Metric label="Cobertura" value={`${Math.round(ratio * 100)}%`} hint={`${totals?.covered ?? 0} de ${totals?.criteria ?? 0} critérios`} accent={ratio >= 0.8} loading={trace.isPending}/>
|
|
225
|
+
<Metric label="Specs com AC" value={totals?.specs ?? 0} hint="declaram critérios AC-N" loading={trace.isPending}/>
|
|
226
|
+
<Metric label="Arquivos de teste" value={totals?.testFiles ?? 0} hint="lidos na varredura" loading={trace.isPending}/>
|
|
227
|
+
<Metric label="Citações ambíguas" value={trace.data?.ambiguous.length ?? 0} hint="AC-N sem spec identificável" loading={trace.isPending}/>
|
|
228
|
+
</div>
|
|
229
|
+
|
|
230
|
+
<article className="card">
|
|
231
|
+
<Head title="Por spec" hint={`${specs.length} listadas`}>
|
|
232
|
+
<input className="field" aria-label="Filtrar por slug ou SPEC-NNN" placeholder="filtrar por slug ou SPEC-NNN…" value={filter} onChange={(event) => setFilter(event.target.value)}/>
|
|
233
|
+
</Head>
|
|
234
|
+
{trace.isPending && <Skeleton lines={5}/>}
|
|
235
|
+
{trace.data !== undefined && specs.length === 0 && <Empty text="Nenhuma spec corresponde ao filtro."/>}
|
|
236
|
+
<div className="rows">
|
|
237
|
+
{specs.map((spec) => {
|
|
238
|
+
const covered = spec.criteria.length - spec.uncovered.length;
|
|
239
|
+
const clean = spec.uncovered.length === 0 && spec.orphans.length === 0;
|
|
240
|
+
return <div className="row row--stack" key={spec.slug}>
|
|
241
|
+
<div className="row__line">
|
|
242
|
+
<span className={`dot ${clean ? 'dot--ok' : covered === 0 ? 'dot--crit' : 'dot--warn'}`}/>
|
|
243
|
+
<span className="row__main">
|
|
244
|
+
<span className="row__title">{spec.specId ?? '—'} · {spec.slug}</span>
|
|
245
|
+
<span className="row__meta">
|
|
246
|
+
{covered}/{spec.criteria.length} critérios com teste
|
|
247
|
+
{spec.uncovered.length > 0 && ` · sem teste: ${spec.uncovered.slice(0, 6).join(', ')}${spec.uncovered.length > 6 ? '…' : ''}`}
|
|
248
|
+
{spec.orphans.length > 0 && ` · ${spec.orphans.length} órfã(s)`}
|
|
249
|
+
</span>
|
|
250
|
+
</span>
|
|
251
|
+
<span className="row__aside"><span className={`pill ${pillOfStatus(spec.status)}`}>{spec.status}</span></span>
|
|
252
|
+
</div>
|
|
253
|
+
<Gauge value={spec.criteria.length === 0 ? 0 : covered / spec.criteria.length} tone={clean ? 'ok' : covered === 0 ? 'crit' : 'warn'}/>
|
|
254
|
+
</div>;
|
|
255
|
+
})}
|
|
256
|
+
</div>
|
|
257
|
+
</article>
|
|
258
|
+
</Section>;
|
|
259
|
+
}
|
|
260
|
+
/* ── Aba: Custo ────────────────────────────────────────────────────────── */
|
|
261
|
+
function CustoTab() {
|
|
262
|
+
const cost = useQuery({ queryKey: ['capability', 'cost.economy'], queryFn: () => capability('cost.economy') });
|
|
263
|
+
const models = Object.entries(cost.data?.byModel ?? {}).sort((left, right) => right[1].costUsd - left[1].costUsd);
|
|
264
|
+
const peak = models.reduce((max, [, entry]) => Math.max(max, entry.costUsd), 0);
|
|
265
|
+
// `cost:economy` agrega toda observação, inclusive execução de capacidade sem modelo/tokens. Um
|
|
266
|
+
// gráfico de barras zerado pareceria quebrado; ele só aparece quando há uso de modelo de fato.
|
|
267
|
+
const hasUsage = models.some(([, entry]) => entry.costUsd > 0 || entry.inputTokens + entry.outputTokens > 0);
|
|
268
|
+
const namedModels = models.filter(([model]) => model !== NO_MODEL).length;
|
|
269
|
+
return <Section title="Custo" hint={cost.data === undefined ? 'custo real acumulado das execuções LLM (SPEC-029)' : `${cost.data.workspace} · ${cost.data.currency}`}>
|
|
270
|
+
<Failure error={cost.error}/>
|
|
271
|
+
<div className="grid grid--metrics">
|
|
272
|
+
<Metric label="Custo acumulado" value={cost.data === undefined ? '—' : `$${cost.data.totalCostUsd.toFixed(4)}`} hint="tabela de preço local" accent loading={cost.isPending}/>
|
|
273
|
+
<Metric label="Observações" value={cost.data?.observationCount ?? 0} hint="registradas no workspace" loading={cost.isPending}/>
|
|
274
|
+
<Metric label="Modelos" value={namedModels} hint="com uso identificado" loading={cost.isPending}/>
|
|
275
|
+
<Metric label="Sem preço" value={cost.data?.unknownPricingCount ?? 0} hint="observações fora da tabela" loading={cost.isPending}/>
|
|
276
|
+
</div>
|
|
277
|
+
|
|
278
|
+
<article className="card">
|
|
279
|
+
<Head title="Por modelo" hint="custo em USD, maior primeiro"/>
|
|
280
|
+
{cost.isPending && <Skeleton lines={3}/>}
|
|
281
|
+
{cost.data !== undefined && models.length === 0 && <Empty text="Nenhuma execução LLM registrada neste workspace." detail="Rode forja llm:run para gerar observações com custo."/>}
|
|
282
|
+
{cost.data !== undefined && models.length > 0 && !hasUsage && <Empty text="Nenhuma observação traz modelo ou tokens." detail={`As ${cost.data.observationCount} observações deste workspace são execuções de capacidade, não chamadas LLM — por isso o custo é $0. Rode forja llm:run para registrar uso real.`}/>}
|
|
283
|
+
{hasUsage && <div className="bars" role="img" aria-label="Custo por modelo">
|
|
284
|
+
{models.map(([model, entry]) => <div className="bars__col" key={model}>
|
|
285
|
+
<div className="bars__fill" style={{ height: `${Math.max(2, (entry.costUsd / peak) * 100)}%` }}/>
|
|
286
|
+
<span className="bars__label">{model}</span>
|
|
287
|
+
</div>)}
|
|
288
|
+
</div>}
|
|
289
|
+
{models.length > 0 && <div className="rows">
|
|
290
|
+
{models.map(([model, entry]) => <Row key={model} title={model} meta={`${entry.inputTokens.toLocaleString('pt-BR')} tokens de entrada · ${entry.outputTokens.toLocaleString('pt-BR')} de saída · ${entry.count} observação(ões)`} dot={entry.priceKnown ? 'ok' : 'warn'} aside={<span className={`pill ${entry.priceKnown ? '' : 'pill--warn'}`}>${entry.costUsd.toFixed(4)}</span>}/>)}
|
|
291
|
+
</div>}
|
|
292
|
+
</article>
|
|
293
|
+
</Section>;
|
|
294
|
+
}
|
|
295
|
+
/* ── Aba: Gates ────────────────────────────────────────────────────────── */
|
|
296
|
+
function GatesTab() {
|
|
297
|
+
const doctor = useQuery({ queryKey: ['capability', 'system.doctor'], queryFn: () => capability('system.doctor') });
|
|
298
|
+
const core = doctor.data?.core ?? [];
|
|
299
|
+
const flagged = core.filter((check) => check.status === 'fail' || check.status === 'warn');
|
|
300
|
+
const healthy = core.filter((check) => check.status === 'ok' || check.status === 'skipped');
|
|
301
|
+
return <Section title="Gates" hint="raio-x do núcleo (SPEC-009) e ferramentas de processo (ADR-0018)">
|
|
302
|
+
<Failure error={doctor.error}/>
|
|
303
|
+
{doctor.error !== null && doctor.error !== undefined && <div className="banner">
|
|
304
|
+
<span className="dot dot--crit"/>
|
|
305
|
+
<span>Com o núcleo reprovado o comando sai em erro e o detalhe dos checks não chega pela API. Rode <code>forja tools:doctor</code> no terminal para ver as falhas críticas.</span>
|
|
306
|
+
</div>}
|
|
307
|
+
<div className="grid grid--metrics">
|
|
308
|
+
<Metric label="Veredito" value={doctor.data?.verdict ?? '—'} hint="decidido só pelo núcleo" accent={doctor.data?.verdict === 'ok'} loading={doctor.isPending}/>
|
|
309
|
+
<Metric label="Ressalvas" value={flagged.length} hint="checks em aviso ou falha" loading={doctor.isPending}/>
|
|
310
|
+
<Metric label="Ferramentas" value={doctor.data === undefined ? '—' : `${doctor.data.toolsAvailable}/${doctor.data.toolsTotal}`} hint="ausentes nunca travam" loading={doctor.isPending}/>
|
|
311
|
+
<Metric label="Checks" value={core.length} hint="catálogo do núcleo" loading={doctor.isPending}/>
|
|
312
|
+
</div>
|
|
313
|
+
|
|
314
|
+
<div className="grid grid--cards">
|
|
315
|
+
<article className="card">
|
|
316
|
+
<Head title="Núcleo" hint="o que impede o framework de trabalhar"/>
|
|
317
|
+
{doctor.isPending && <Skeleton lines={4}/>}
|
|
318
|
+
{doctor.data !== undefined && flagged.length === 0 && <Empty text="Nenhuma ressalva no núcleo."/>}
|
|
319
|
+
<div className="rows">
|
|
320
|
+
{flagged.map((check) => <Row key={check.id} title={check.id} meta={check.fix === null ? check.detail ?? '' : `${check.detail ?? ''} · corrigir: ${check.fix}`} dot={check.status === 'fail' ? 'crit' : 'warn'} aside={<span className={`pill ${check.status === 'fail' ? 'pill--crit' : 'pill--warn'}`}>{check.severity ?? check.status}</span>}/>)}
|
|
321
|
+
</div>
|
|
322
|
+
{healthy.length > 0 && <p className="card__hint">{healthy.length} check(s) verde(s): {healthy.map((check) => check.id).join(', ')}</p>}
|
|
323
|
+
</article>
|
|
324
|
+
|
|
325
|
+
<article className="card">
|
|
326
|
+
<Head title="Ferramentas" hint="potencializam o harness, nunca travam"/>
|
|
327
|
+
{doctor.isPending && <Skeleton lines={4}/>}
|
|
328
|
+
<div className="rows">
|
|
329
|
+
{(doctor.data?.tools ?? []).map((tool) => <Row key={tool.name} title={tool.name} meta={tool.ok ? tool.gate : `instalar: ${tool.install}`} dot={tool.ok ? 'ok' : undefined} aside={<span className={`pill ${tool.ok ? 'pill--ok' : ''}`}>{tool.ok ? tool.version ?? 'instalada' : 'ausente'}</span>}/>)}
|
|
330
|
+
</div>
|
|
331
|
+
{doctor.data?.project !== undefined && <>
|
|
332
|
+
<h3 className="card__title">Projeto</h3>
|
|
333
|
+
<div className="rows">
|
|
334
|
+
{doctor.data.project.checks.map((check) => <Row key={check.id} title={check.id} meta={check.detail} dot={toneOf(check.status)} aside={<span className={`pill ${pillOf(check.status)}`}>{check.status}</span>}/>)}
|
|
335
|
+
</div>
|
|
336
|
+
</>}
|
|
337
|
+
</article>
|
|
338
|
+
</div>
|
|
339
|
+
</Section>;
|
|
340
|
+
}
|
|
341
|
+
/* ── Aba: Operação ─────────────────────────────────────────────────────── */
|
|
342
|
+
function OperacaoTab() {
|
|
343
|
+
const queryClient = useQueryClient();
|
|
344
|
+
const [notice, setNotice] = useState(undefined);
|
|
345
|
+
const [origin, setOrigin] = useState('');
|
|
346
|
+
// Separado do campo: digitar não dispara consulta a cada tecla, e clicar num nó da lista
|
|
347
|
+
// consulta o impacto dele na hora sem o usuário copiar um hash de 64 caracteres.
|
|
348
|
+
const [target, setTarget] = useState('');
|
|
349
|
+
const snapshot = useQuery({ queryKey: ['control-plane', 'snapshot'], queryFn: loadSnapshot });
|
|
350
|
+
const impact = useQuery({ queryKey: ['graph', 'impact', target], queryFn: () => loadImpact(target), enabled: target.length > 0 });
|
|
351
|
+
const metrics = snapshot.data?.metrics;
|
|
352
|
+
async function act(label, path, body) {
|
|
18
353
|
try {
|
|
19
|
-
const response = await fetch(`${
|
|
354
|
+
const response = await fetch(`${api}${path}`, {
|
|
355
|
+
method: 'POST',
|
|
356
|
+
...(body === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
|
|
357
|
+
});
|
|
20
358
|
if (!response.ok)
|
|
21
|
-
throw new Error(
|
|
359
|
+
throw new Error(await failureOf(response, `${label} recusada`));
|
|
22
360
|
await queryClient.invalidateQueries({ queryKey: ['control-plane', 'snapshot'] });
|
|
23
|
-
|
|
361
|
+
setNotice(undefined);
|
|
24
362
|
}
|
|
25
363
|
catch (reason) {
|
|
26
|
-
|
|
364
|
+
setNotice(reason instanceof Error ? reason.message : `Falha em ${label}`);
|
|
27
365
|
}
|
|
28
366
|
}
|
|
29
|
-
|
|
367
|
+
return <Section title="Operação" hint="execuções, aprovações e grafo">
|
|
368
|
+
{notice !== undefined && <div className="banner" role="alert"><span className="dot dot--crit"/><span>{notice}</span></div>}
|
|
369
|
+
<Failure error={snapshot.error}/>
|
|
370
|
+
<div className="grid grid--metrics">
|
|
371
|
+
<Metric label="Execuções" value={metrics?.runCount ?? 0} loading={snapshot.isPending}/>
|
|
372
|
+
<Metric label="Taxa de sucesso" value={`${((metrics?.successRate ?? 0) * 100).toFixed(1)}%`} accent loading={snapshot.isPending}/>
|
|
373
|
+
<Metric label="Tokens de entrada" value={(metrics?.totalInputTokens ?? 0).toLocaleString('pt-BR')} loading={snapshot.isPending}/>
|
|
374
|
+
<Metric label="Observações" value={metrics?.observationCount ?? 0} loading={snapshot.isPending}/>
|
|
375
|
+
</div>
|
|
376
|
+
|
|
377
|
+
<div className="grid grid--cards">
|
|
378
|
+
<article className="card">
|
|
379
|
+
<Head title="Aprovações" hint="identidade configurada no servidor"/>
|
|
380
|
+
{snapshot.data?.approvals.length === 0 && <Empty text="Nenhuma aprovação registrada."/>}
|
|
381
|
+
<div className="rows">
|
|
382
|
+
{(snapshot.data?.approvals ?? []).map((approval) => <Row key={approval.id} title={approval.action} meta={approval.impact} dot={approval.decision === 'approved' ? 'ok' : approval.decision === 'rejected' ? 'crit' : 'warn'} aside={approval.decision === undefined
|
|
383
|
+
? <>
|
|
384
|
+
<button className="btn btn--sm btn--primary" onClick={() => void act('aprovação', `/approvals/${encodeURIComponent(approval.id)}/decide`, { decision: 'approved' })}>Aprovar</button>
|
|
385
|
+
<button className="btn btn--sm btn--danger" onClick={() => void act('rejeição', `/approvals/${encodeURIComponent(approval.id)}/decide`, { decision: 'rejected' })}>Rejeitar</button>
|
|
386
|
+
</>
|
|
387
|
+
: <span className={`pill ${approval.decision === 'approved' ? 'pill--ok' : 'pill--crit'}`}>{approval.decision}</span>}/>)}
|
|
388
|
+
</div>
|
|
389
|
+
</article>
|
|
390
|
+
|
|
391
|
+
<article className="card">
|
|
392
|
+
<Head title="GraphLoop" hint={`${snapshot.data?.graphNodes.length ?? 0} nós indexados`}/>
|
|
393
|
+
<div className="inline">
|
|
394
|
+
<input className="field" aria-label="ID do nó de impacto" placeholder="ID do nó para impacto" value={origin} onChange={(event) => setOrigin(event.target.value)}/>
|
|
395
|
+
<button className="btn" disabled={origin.trim().length === 0} onClick={() => setTarget(origin.trim())}>Impacto</button>
|
|
396
|
+
</div>
|
|
397
|
+
{snapshot.data?.graphNodes.length === 0 && <Empty text="Nenhum nó indexado." detail="Rode forja graph:sync para indexar o workspace."/>}
|
|
398
|
+
<div className="rows">
|
|
399
|
+
{(snapshot.data?.graphNodes ?? []).slice(0, 8).map((node) => <Row key={node.id} title={node.label} meta={`${node.id.slice(0, 12)}…`} dot={node.status === 'verified' ? 'ok' : 'info'} aside={<>
|
|
400
|
+
<span className="pill">{node.type}</span>
|
|
401
|
+
<button className="btn btn--sm btn--ghost" onClick={() => { setOrigin(node.id); setTarget(node.id); }}>Impacto</button>
|
|
402
|
+
</>}/>)}
|
|
403
|
+
</div>
|
|
404
|
+
{impact.isFetching && <Skeleton lines={3}/>}
|
|
405
|
+
<Failure error={impact.error}/>
|
|
406
|
+
{impact.data !== undefined && <>
|
|
407
|
+
<p className="card__hint">Impacto de <code>{target.slice(0, 12)}…</code></p>
|
|
408
|
+
<pre className="dump"><code>{JSON.stringify(impact.data, null, 2)}</code></pre>
|
|
409
|
+
</>}
|
|
410
|
+
</article>
|
|
411
|
+
</div>
|
|
412
|
+
|
|
413
|
+
<article className="card">
|
|
414
|
+
<Head title="Atividade recente" hint={snapshot.isFetching ? 'sincronizando' : 'estado remoto'}/>
|
|
415
|
+
{snapshot.data?.observations.length === 0 && <Empty text="Nenhuma observação registrada."/>}
|
|
416
|
+
<div className="rows">
|
|
417
|
+
{(snapshot.data?.observations ?? []).slice(-10).reverse().map((observation) => <Row key={observation.id} title={observation.capabilityId ?? 'operação do Control Plane'} meta={observation.traceId} dot={toneOf(observation.outcome)} aside={<>
|
|
418
|
+
<span className={`pill ${pillOf(observation.outcome)}`}>{observation.outcome}</span>
|
|
419
|
+
{observation.runId !== undefined && <>
|
|
420
|
+
<button className="btn btn--sm btn--ghost" onClick={() => void act('pausa', `/executions/${observation.runId}/pause`)}>Pausar</button>
|
|
421
|
+
<button className="btn btn--sm btn--danger" onClick={() => void act('cancelamento', `/executions/${observation.runId}/cancel`)}>Cancelar</button>
|
|
422
|
+
</>}
|
|
423
|
+
</>}/>)}
|
|
424
|
+
</div>
|
|
425
|
+
</article>
|
|
426
|
+
</Section>;
|
|
427
|
+
}
|
|
428
|
+
/* ── Peças de apresentação ─────────────────────────────────────────────── */
|
|
429
|
+
function Section({ title, hint, children }) {
|
|
430
|
+
return <section className="section" aria-label={title}>
|
|
431
|
+
<div className="section__head">
|
|
432
|
+
<div className="section__title"><h2>{title}</h2>{hint !== undefined && <span className="card__hint">{hint}</span>}</div>
|
|
433
|
+
</div>
|
|
434
|
+
{children}
|
|
435
|
+
</section>;
|
|
436
|
+
}
|
|
437
|
+
function Head({ title, hint, children }) {
|
|
438
|
+
return <div className="card__head">
|
|
439
|
+
<div className="card__head-text">
|
|
440
|
+
<h3 className="card__title">{title}</h3>
|
|
441
|
+
{hint !== undefined && <span className="card__hint">{hint}</span>}
|
|
442
|
+
</div>
|
|
443
|
+
{children !== undefined && <div className="topbar__actions">{children}</div>}
|
|
444
|
+
</div>;
|
|
445
|
+
}
|
|
446
|
+
function Metric({ label, value, hint, accent, loading }) {
|
|
447
|
+
return <article className={`card metric${accent === true ? ' metric--accent' : ''}`}>
|
|
448
|
+
<span className="metric__label">{label}</span>
|
|
449
|
+
{loading === true ? <span className="skeleton skeleton--value"/> : <strong className="metric__value">{value}</strong>}
|
|
450
|
+
{hint !== undefined && <span className="metric__hint">{hint}</span>}
|
|
451
|
+
</article>;
|
|
452
|
+
}
|
|
453
|
+
function Row({ title, meta, dot, aside }) {
|
|
454
|
+
return <div className="row">
|
|
455
|
+
{dot !== undefined && <span className={`dot dot--${dot}`}/>}
|
|
456
|
+
<span className="row__main">
|
|
457
|
+
<span className="row__title">{title}</span>
|
|
458
|
+
{meta !== undefined && meta.length > 0 && <span className="row__meta">{meta}</span>}
|
|
459
|
+
</span>
|
|
460
|
+
{aside !== undefined && <span className="row__aside">{aside}</span>}
|
|
461
|
+
</div>;
|
|
462
|
+
}
|
|
463
|
+
function Gauge({ value, tone }) {
|
|
464
|
+
const percent = Math.round(Math.min(1, Math.max(0, value)) * 100);
|
|
465
|
+
return <span className={`gauge${tone === undefined ? '' : ` gauge--${tone}`}`} role="img" aria-label={`${percent}%`}>
|
|
466
|
+
<span className="gauge__fill" style={{ width: `${percent}%` }}/>
|
|
467
|
+
</span>;
|
|
468
|
+
}
|
|
469
|
+
function Cmd({ value }) {
|
|
470
|
+
const [state, setState] = useState('idle');
|
|
471
|
+
const code = useRef(null);
|
|
472
|
+
async function copy() {
|
|
30
473
|
try {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
throw new Error('Decisão recusada pelo Control Plane');
|
|
34
|
-
await queryClient.invalidateQueries({ queryKey: ['control-plane', 'snapshot'] });
|
|
35
|
-
setError(undefined);
|
|
474
|
+
await navigator.clipboard.writeText(value);
|
|
475
|
+
setState('copied');
|
|
36
476
|
}
|
|
37
|
-
catch
|
|
38
|
-
|
|
477
|
+
catch {
|
|
478
|
+
// A API de clipboard exige documento focado e contexto seguro; sem isso ela rejeita. Em vez
|
|
479
|
+
// de engolir o erro num botão que nunca muda, seleciona o comando para o usuário copiar.
|
|
480
|
+
const node = code.current;
|
|
481
|
+
if (node !== null) {
|
|
482
|
+
const range = document.createRange();
|
|
483
|
+
range.selectNodeContents(node);
|
|
484
|
+
const selection = window.getSelection();
|
|
485
|
+
selection?.removeAllRanges();
|
|
486
|
+
selection?.addRange(range);
|
|
487
|
+
}
|
|
488
|
+
setState('manual');
|
|
39
489
|
}
|
|
490
|
+
setTimeout(() => setState('idle'), 2400);
|
|
491
|
+
}
|
|
492
|
+
return <div className="cmd">
|
|
493
|
+
<code ref={code}>{value}</code>
|
|
494
|
+
<button className="btn btn--sm btn--ghost" onClick={() => void copy()}>
|
|
495
|
+
{state === 'copied' ? 'copiado' : state === 'manual' ? 'selecionado — copie' : 'copiar'}
|
|
496
|
+
</button>
|
|
497
|
+
</div>;
|
|
498
|
+
}
|
|
499
|
+
function Empty({ text, detail }) {
|
|
500
|
+
return <div className="empty"><span>{text}</span>{detail !== undefined && <span>{detail}</span>}</div>;
|
|
501
|
+
}
|
|
502
|
+
function Skeleton({ lines }) {
|
|
503
|
+
return <div className="grid">{Array.from({ length: lines }, (_, index) => <span className="skeleton skeleton--row" key={index}/>)}</div>;
|
|
504
|
+
}
|
|
505
|
+
function Failure({ error }) {
|
|
506
|
+
if (error === null || error === undefined)
|
|
507
|
+
return null;
|
|
508
|
+
return <div className="banner" role="alert"><span className="dot dot--crit"/><span>{textOf(error)}</span></div>;
|
|
509
|
+
}
|
|
510
|
+
function toneOf(status) {
|
|
511
|
+
if (status === 'ok' || status === 'succeeded' || status === 'done' || status === 'verified' || status === 'approved')
|
|
512
|
+
return 'ok';
|
|
513
|
+
if (status === 'warn' || status === 'pending' || status === 'implementing' || status === 'degraded')
|
|
514
|
+
return 'warn';
|
|
515
|
+
if (status === 'fail' || status === 'failed' || status === 'error' || status === 'abandoned' || status === 'rejected')
|
|
516
|
+
return 'crit';
|
|
517
|
+
return 'info';
|
|
518
|
+
}
|
|
519
|
+
function pillOf(status) {
|
|
520
|
+
const tone = toneOf(status);
|
|
521
|
+
return tone === 'info' ? 'pill--info' : `pill--${tone}`;
|
|
522
|
+
}
|
|
523
|
+
function pillOfStatus(status) {
|
|
524
|
+
if (status === 'done' || status === 'approved')
|
|
525
|
+
return 'pill--ok';
|
|
526
|
+
if (status === 'abandoned' || status === 'rejected')
|
|
527
|
+
return 'pill--crit';
|
|
528
|
+
if (status === 'draft')
|
|
529
|
+
return '';
|
|
530
|
+
return 'pill--info';
|
|
531
|
+
}
|
|
532
|
+
/* ── Acesso a dados ────────────────────────────────────────────────────── */
|
|
533
|
+
/**
|
|
534
|
+
* Executa uma capacidade de leitura e devolve o payload do contrato `--json` que o script escreveu
|
|
535
|
+
* no stdout (ADR-0082). Pela HTTP volta o `ExecutionResult` cru, com o JSON do comando como texto em
|
|
536
|
+
* `output.payload.stdout` — o parse acontece aqui, e um contrato `error` vira exceção com a mensagem
|
|
537
|
+
* do próprio comando em vez de um "falhou" genérico.
|
|
538
|
+
*/
|
|
539
|
+
async function capability(id, payload = { json: true }) {
|
|
540
|
+
const response = await fetch(`${api}/capabilities/${id}/execute`, {
|
|
541
|
+
method: 'POST',
|
|
542
|
+
headers: { 'content-type': 'application/json' },
|
|
543
|
+
// `categories` é o que a política do servidor avalia: sem ela a regra `local-read-only` não
|
|
544
|
+
// casa e o default-deny bloqueia a execução. O proxy confere a declaração independentemente.
|
|
545
|
+
body: JSON.stringify({ payload, categories: ['read'] }),
|
|
546
|
+
cache: 'no-store',
|
|
547
|
+
});
|
|
548
|
+
const body = await response.json().catch(() => undefined);
|
|
549
|
+
if (!response.ok)
|
|
550
|
+
throw new Error(textOf(body, `Execução recusada (HTTP ${response.status})`));
|
|
551
|
+
const execution = body;
|
|
552
|
+
const contract = parseContract(execution.output?.payload?.stdout ?? '');
|
|
553
|
+
if (contract !== undefined && contract.status === 'error')
|
|
554
|
+
throw new Error(textOf(contract.error, 'Comando falhou sem mensagem'));
|
|
555
|
+
if (contract !== undefined)
|
|
556
|
+
return contract;
|
|
557
|
+
if (execution.status !== 'succeeded')
|
|
558
|
+
throw new Error(execution.error?.message ?? `Capacidade falhou: ${id}`);
|
|
559
|
+
throw new Error(`Saída de ${id} não é o contrato --json`);
|
|
560
|
+
}
|
|
561
|
+
function parseContract(stdout) {
|
|
562
|
+
const text = stdout.trim();
|
|
563
|
+
if (!text.startsWith('{'))
|
|
564
|
+
return undefined;
|
|
565
|
+
try {
|
|
566
|
+
const parsed = JSON.parse(text);
|
|
567
|
+
if (typeof parsed !== 'object' || parsed === null || !('status' in parsed))
|
|
568
|
+
return undefined;
|
|
569
|
+
return parsed;
|
|
570
|
+
}
|
|
571
|
+
catch {
|
|
572
|
+
return undefined;
|
|
40
573
|
}
|
|
41
|
-
const metrics = snapshot.data?.metrics;
|
|
42
|
-
return <>
|
|
43
|
-
<header className="header"><div><p className="eyebrow">FORJAJS 2.0</p><h1>Control Plane</h1><p className="muted">Autonomia supervisionada, evidência e execução auditável.</p></div><button onClick={() => void snapshot.refetch()} disabled={snapshot.isFetching}>{snapshot.isFetching ? 'Atualizando…' : 'Atualizar'}</button></header>
|
|
44
|
-
{(error !== undefined || snapshot.error !== null) && <div className="alert" role="alert">{error ?? 'Control Plane indisponível'}</div>}
|
|
45
|
-
<section className="grid" aria-label="Métricas operacionais"><Metric label="Execuções" value={metrics?.runCount ?? 0}/><Metric label="Taxa de sucesso" value={`${((metrics?.successRate ?? 0) * 100).toFixed(1)}%`}/><Metric label="Tokens de entrada" value={metrics?.totalInputTokens ?? 0}/><Metric label="Observações" value={metrics?.observationCount ?? 0}/></section>
|
|
46
|
-
<section className="panel"><div className="panel-title"><h2>GraphLoop</h2><span className="muted">nós com origem no backend</span></div><div className="graph-controls"><input aria-label="ID do nó de impacto" value={impactOrigin} onChange={(event) => setImpactOrigin(event.target.value)} placeholder="ID do nó para impacto"/><button onClick={() => void impact.refetch()} disabled={impactOrigin.trim().length === 0}>Calcular impacto</button></div><div className="graph-grid">{snapshot.data?.graphNodes.slice(0, 12).map((node) => <span key={node.id} className="node"><strong>{node.label}</strong><small>{node.type} · {node.status}</small></span>)}</div>{impact.data !== undefined && <pre className="impact">{JSON.stringify(impact.data, null, 2)}</pre>}</section>
|
|
47
|
-
<section className="panel"><div className="panel-title"><h2>Approvals</h2><span className="muted">identidade configurada no servidor</span></div>{snapshot.data?.approvals.length === 0 && <p className="muted">Nenhuma aprovação registrada.</p>}<ul className="events">{snapshot.data?.approvals.map((approval) => <li key={approval.id}><span className="dot"/><span><strong>{approval.decision ?? 'pending'}</strong> · {approval.action}<small>{approval.impact}</small></span>{approval.decision === undefined && <span className="actions"><button onClick={() => void decideApproval(approval.id, 'approved')}>Aprovar</button><button onClick={() => void decideApproval(approval.id, 'rejected')}>Rejeitar</button></span>}</li>)}</ul></section>
|
|
48
|
-
<section className="panel"><div className="panel-title"><h2>Atividade recente</h2><span className="muted">{snapshot.isFetching ? 'sincronizando' : 'estado remoto'}</span></div>
|
|
49
|
-
{snapshot.data?.observations.length === 0 && <p className="muted">Nenhuma observação registrada.</p>}
|
|
50
|
-
<ul className="events">{snapshot.data?.observations.slice(-8).reverse().map((observation) => <li key={observation.id}><span className={`dot ${observation.outcome}`}/><span><strong>{observation.outcome}</strong> · {observation.capabilityId ?? 'operação do Control Plane'}<small>{observation.traceId}</small></span>{observation.runId !== undefined && <span className="actions"><button onClick={() => void execute(`/executions/${observation.runId}/pause`)}>Pausar</button><button onClick={() => void execute(`/executions/${observation.runId}/cancel`)}>Cancelar</button></span>}</li>)}</ul>
|
|
51
|
-
</section>
|
|
52
|
-
</>;
|
|
53
574
|
}
|
|
54
575
|
async function loadSnapshot() {
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
576
|
+
const responses = await Promise.all([
|
|
577
|
+
fetch(`${api}/control-plane/metrics`, { cache: 'no-store' }),
|
|
578
|
+
fetch(`${api}/observability/observations`, { cache: 'no-store' }),
|
|
579
|
+
fetch(`${api}/graph/query`, { cache: 'no-store' }),
|
|
580
|
+
fetch(`${api}/approvals`, { cache: 'no-store' }),
|
|
581
|
+
]);
|
|
582
|
+
for (const response of responses) {
|
|
583
|
+
if (response.ok)
|
|
584
|
+
continue;
|
|
585
|
+
throw new Error(await failureOf(response, 'Control Plane indisponível'));
|
|
586
|
+
}
|
|
587
|
+
const [metrics, observations, graphNodes, approvals] = await Promise.all(responses.map((response) => response.json()));
|
|
588
|
+
return {
|
|
589
|
+
metrics: metrics,
|
|
590
|
+
observations: observations,
|
|
591
|
+
graphNodes: graphNodes,
|
|
592
|
+
approvals: approvals,
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
async function loadImpact(origin) {
|
|
596
|
+
const response = await fetch(`${api}/graph/impact?origin=${encodeURIComponent(origin)}`, { cache: 'no-store' });
|
|
597
|
+
if (!response.ok)
|
|
598
|
+
throw new Error(await failureOf(response, 'Impacto não disponível'));
|
|
599
|
+
return response.json();
|
|
600
|
+
}
|
|
601
|
+
async function failureOf(response, fallback) {
|
|
602
|
+
const body = await response.json().catch(() => undefined);
|
|
603
|
+
return textOf(body, `${fallback} (HTTP ${response.status})`);
|
|
604
|
+
}
|
|
605
|
+
/** Mensagem legível de uma falha já materializada: `{error:{message}}`, `{message}`, Error ou texto. */
|
|
606
|
+
function textOf(source, fallback = 'Falha sem detalhe') {
|
|
607
|
+
if (typeof source === 'string' && source.length > 0)
|
|
608
|
+
return source;
|
|
609
|
+
if (source instanceof Error)
|
|
610
|
+
return source.message;
|
|
611
|
+
if (typeof source === 'object' && source !== null) {
|
|
612
|
+
const record = source;
|
|
613
|
+
if (typeof record.error?.message === 'string')
|
|
614
|
+
return record.error.message;
|
|
615
|
+
if (typeof record.message === 'string')
|
|
616
|
+
return record.message;
|
|
617
|
+
}
|
|
618
|
+
return fallback;
|
|
619
|
+
}
|
|
620
|
+
/** `{available:true,value}` → valor; qualquer outra forma → `undefined`. */
|
|
621
|
+
function sub(entry) {
|
|
622
|
+
return entry !== undefined && entry.available ? entry.value : undefined;
|
|
623
|
+
}
|
|
624
|
+
/** O motivo de um coletor indisponível — só aparece quando é o caso. */
|
|
625
|
+
function reasonOf(entry) {
|
|
626
|
+
return entry !== undefined && !entry.available ? entry.reason : undefined;
|
|
627
|
+
}
|