Files
Duriin-API/public/admin/assets/js/ops/sql.js
T
ImBenjiandClaude Opus 5 0a5b30ab63 feat: new ops console for the admin surface
The old admin was five separate html pages, so every navigation was a full
reload and the operational picture was scattered across all of them. Worth
saying: the api was never the problem, every endpoint answers in under 200ms.
It felt slow because of the architecture, not the backend.

This is a single page console. React and htm from a cdn, no bundler and no
babel-in-the-browser, because a runtime transpiler on every load is exactly the
slowness we are trying to get rid of. Hash routing, polling that keeps the last
good payload on screen instead of flashing a spinner, and stale responses are
dropped so a slow request cannot overwrite a newer one.

/admin/api/ops/overview answers the whole dashboard in one call rather than
making the browser fan out and stitch. It carries the things that actually
matter and were not visible anywhere before: when live evidence matures, why a
cohort does or does not clear the trade gate, which stage of the pipeline has
gone quiet, and what is sitting in dead letters.

Controls, all of which change production and all of which ask twice:
- requeue dead letters, which only ever moves dead_letter back to pending
- execution mode and a kill switch, now read from autonomy_settings on every
  poll instead of only from AUTONOMY_EXECUTION_MODE, so halting no longer needs
  a redeploy first
- run the reaction analysis and read its output

The d3 graph is framed rather than ported. It works, and rewriting it would risk
something valuable for nothing the operator can see.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WnNxwxfXSbeNtjvtz5gayb
2026-09-01 20:17:36 +01:00

107 lines
4.4 KiB
JavaScript

import { html, api, useState, num } from './core.js';
import { Card, Pill, Empty } from './ui.js';
const SAMPLES = [
{ label: 'live prediction maturity', db: 'intelligence', sql:
`SELECT horizon_days, COUNT(*) AS n,
MIN(date(information_cutoff, '+' || horizon_days || ' days')) AS first_matures
FROM autonomy_predictions
WHERE origin='live' AND status='open'
GROUP BY horizon_days ORDER BY horizon_days` },
{ label: 'accuracy by origin', db: 'intelligence', sql:
`SELECT p.origin, COUNT(*) AS n,
ROUND(100.0*AVG(o.direction_correct),1) AS acc_pct,
ROUND(100.0*AVG(o.excess_return),2) AS mean_excess_pct
FROM autonomy_predictions p JOIN autonomy_outcomes o ON o.prediction_id=p.id
GROUP BY p.origin` },
{ label: 'dead letters', db: 'intelligence', sql:
`SELECT job_type, lane, COUNT(*) AS n, substr(MAX(last_error),1,80) AS err
FROM autonomy_jobs WHERE status='dead_letter' GROUP BY job_type, lane` },
{ label: 'content backlog', db: 'archive', sql:
`SELECT COALESCE(content_status,'unfetched') AS status, COUNT(*) AS n
FROM articles GROUP BY status ORDER BY n DESC` },
];
export function Sql({ notify }) {
const [sql, setSql] = useState(SAMPLES[0].sql);
const [database, setDatabase] = useState('intelligence');
const [result, setResult] = useState(null);
const [busy, setBusy] = useState(false);
const run = async () => {
setBusy(true);
const started = performance.now();
try {
const response = await api('/admin/api/sql', { method: 'POST', body: { sql, database } });
setResult({ ...response, clientMs: Math.round(performance.now() - started) });
} catch (error) {
console.error('[ops] sql failed:', error.message);
notify({ tone: 'bad', message: error.message, sticky: true });
setResult(null);
} finally {
setBusy(false);
}
};
const first = result && result.results && result.results[0];
const rows = (first && first.rows) || [];
const columns = rows.length ? Object.keys(rows[0]) : [];
return html`
<div class="grid" style="gap:14px">
<${Card} title="Query"
right=${html`
<div class="row" style="gap:8px">
<select value=${database} onChange=${(e) => setDatabase(e.target.value)}>
<option value="intelligence">intelligence</option>
<option value="archive">archive</option>
</select>
<button class="primary sm" disabled=${busy} onClick=${run}>
${busy ? 'running…' : 'run'}
</button>
</div>`}>
<textarea rows="9" spellcheck="false" value=${sql}
onInput=${(e) => setSql(e.target.value)}
onKeyDown=${(e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') run(); }}></textarea>
<div class="row" style="gap:8px; margin-top:10px; flex-wrap:wrap">
<span class="muted small">samples:</span>
${SAMPLES.map((s) => html`
<button class="sm" key=${s.label}
onClick=${() => { setSql(s.sql); setDatabase(s.db); }}>${s.label}</button>`)}
<span class="grow"></span>
<span class="muted small mono">⌘/ctrl + enter</span>
</div>
<//>
${result && html`
<${Card} title="Result"
right=${html`<span class="row" style="gap:8px">
<${Pill}>${num(rows.length)} rows<//>
<${Pill}>${num(result.elapsed)}ms server<//>
<${Pill}>${num(result.clientMs)}ms total<//>
</span>`}>
${first && first.error
? html`<div class="muted small" style="color:var(--bad)">${first.error}</div>`
: !rows.length
? html`<${Empty}>No rows.<//>`
: html`
<div class="table-scroll">
<table>
<thead><tr>${columns.map((c) => html`<th key=${c}>${c}</th>`)}</tr></thead>
<tbody>
${rows.slice(0, 500).map((row, i) => html`
<tr key=${i}>
${columns.map((c) => html`
<td key=${c} class="mono small">${row[c] === null ? '—' : String(row[c])}</td>`)}
</tr>`)}
</tbody>
</table>
</div>
${rows.length > 500 && html`
<div class="muted small" style="margin-top:10px">
Showing the first 500 of ${num(rows.length)} rows.
</div>`}`}
<//>`}
</div>`;
}