feat(plan-13): read-only Ops Console (NestJS API + React UI) — Track 1

Real web Control Panel over CASAN harness telemetry (Level-3 casan-platform component).
Read-only ("Đọc ≠ Ghi"): no settings writes, no gate bypass. Management/RBAC/approval are
Track 2/3 (future, Plan-14). Additive — harness gate untouched (64/0/3).

packages/casan-control-panel/
- backend/ (NestJS, ESM, /api/v1 + ok() envelope): TelemetryReader (jsonl/json, missing→[],
  never fabricates) + TelemetryService (aggregations mirroring generate-agentops-dashboard.py)
  + endpoints overview/runs(+:traceId)/governance/security/incidents/tools/traceability/
  drift/cost, and /healthz (stale-aware 200/503, fail-loud like dashboard-server.py). App
  root + telemetry paths resolve via casan-paths-style marker walk-up (.specify OR
  packages/casan-harness) + honor CASAN_DASHBOARD_* env. Binds 127.0.0.1; refuses
  non-loopback under CASAN_PROFILE=prod. @Inject token so DI works under tsc AND tsx.
  Tests (node native runner) 7/0: reader parse/missing, app-root, overview shape on real
  repo state, freshness/stale fail-loud.
- frontend/ (React+Vite+Tailwind+TanStack, port 5174, proxies to :3010): AppLayout +
  Sidebar + Header (LIVE/STALE badge from /healthz) + pages Overview/Runs/Governance/
  Security/Incidents/Traceability. axios client unwraps ok() envelope. build green.

Wiring: root workspaces + `console:*` scripts. packaging/levels.json + casan-platform
README: platform preview now lists the Ops Console as an implemented component.

Verified: backend build + test 7/0; frontend tsc + vite build; API serves REAL data
(runs=6, provider_tokens=5556, action_blocks=7); /healthz 503 stale → 200 after touch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
thanhnv
2026-07-08 16:59:56 +09:00
co-authored by Claude Opus 4.8
parent 98d699d844
commit 63dd44a11b
41 changed files with 1078 additions and 43 deletions
+43
View File
@@ -0,0 +1,43 @@
# CASAN Ops Console (Plan-13 Track 1) — read-only Control Panel
Real **NestJS API + React UI** that surfaces CASAN harness telemetry. This is the Level-3
`casan-platform` **Control Panel** component. **Read-only** ("Đọc ≠ Ghi"): it never writes
settings or bypasses a gate — management (settings/RBAC/approval) is Plan-13 Track 2/3
(future, soft-blocked by Plan-14).
```
backend/ NestJS read-only API (/api/v1 + /healthz) over .specify telemetry
frontend/ React + Vite + Tailwind + TanStack Query Ops Console
```
## Run (local)
```bash
npm install # from repo root (picks up the workspaces)
npm run console:api # NestJS API → http://127.0.0.1:3010/api/v1
npm run console:ui # Vite UI → http://127.0.0.1:5174 (proxies to the API)
```
Open http://127.0.0.1:5174 — panels show REAL metrics from `.specify/logs/**`.
## API (all read-only, `ok()`-enveloped except `/healthz`)
`GET /api/v1/overview` · `runs` (+ `runs/:traceId`) · `governance` · `security` ·
`incidents` · `tools` · `traceability` · `drift` · `cost` · `GET /healthz` (200 fresh /
503 stale — fail-loud, mirrors `dashboard-server.py`).
Data sources + aggregation mirror `packages/casan-harness/tests/generate-agentops-dashboard.py`.
App root + telemetry paths resolve via the same marker walk-up as `casan-paths.sh`
(`.specify` or `packages/casan-harness`) and honor `CASAN_DASHBOARD_*` env overrides.
## Security posture (MVP)
Binds `127.0.0.1`, no auth (read-only local ops). Refuses a non-loopback bind under
`CASAN_PROFILE=prod` / `CASAN_CP_STRICT=1` — off-loopback exposure needs TLS/OIDC (Plan-13
Track 4). Auth/login (reuse OKR JWT) is a follow-up.
## Test
```bash
npm run console:test # backend telemetry reader/service + healthz logic
```
## Not in this pass
Track 2 settings writes (wrap `control-plane-settings.py`), Track 3 RBAC + approval inbox
(Plan-14), Track 4 docker/deploy + TLS/OIDC + FinOps/SLO. See
`docs/plans/CASAN_PLAN_13_CONTROL_PLANE.md`.
@@ -0,0 +1,26 @@
{
"name": "@casan/control-panel-backend",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "CASAN Ops Console — read-only NestJS API over harness telemetry (Plan-13 Track 1).",
"scripts": {
"build": "tsc -p tsconfig.build.json",
"dev": "tsx watch src/main.ts",
"start": "node dist/main.js",
"test": "node --import tsx --test test/*.test.ts"
},
"dependencies": {
"@nestjs/common": "^10.4.20",
"@nestjs/core": "^10.4.20",
"@nestjs/platform-express": "^10.4.20",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^24.0.8",
"tsx": "^4.20.3",
"typescript": "^5.8.3"
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { TelemetryModule } from './telemetry/telemetry.module.js';
import { HealthController } from './health/health.controller.js';
@Module({
imports: [TelemetryModule],
controllers: [HealthController],
})
export class AppModule {}
@@ -0,0 +1,11 @@
// Standard API envelope — mirrors backend/src/common/api-response.ts so the console
// frontend's axios client (which unwraps response.data.data) works identically.
export interface ApiResponse<T> {
success: true;
data: T;
meta?: Record<string, unknown>;
}
export function ok<T>(data: T, meta?: Record<string, unknown>): ApiResponse<T> {
return meta ? { success: true, data, meta } : { success: true, data };
}
@@ -0,0 +1,65 @@
// Resolve the CASAN app root + telemetry file paths for the read-only Ops Console.
//
// Mirrors packages/casan-harness/scripts/bash/casan-paths.sh: walk UP from a start dir
// for a marker (`.specify` state dir OR `packages/casan-harness`), so the API reads the
// real harness telemetry whether launched from the repo, a workspace subdir, or a bundle.
// Every path is overridable by the same CASAN_DASHBOARD_* env vars the legacy
// dashboard-server.py honors, so console + dashboard read identical sources.
import { existsSync, statSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = dirname(fileURLToPath(import.meta.url));
function findAppRoot(start: string): string {
let d = resolve(start);
while (d !== dirname(d)) {
if (existsSync(join(d, '.specify')) || existsSync(join(d, 'packages', 'casan-harness'))) {
return d;
}
d = dirname(d);
}
// fallback: cwd (last resort)
return process.cwd();
}
export const APP_ROOT = process.env.CASAN_APP_ROOT
? resolve(process.env.CASAN_APP_ROOT)
: findAppRoot(HERE);
const env = (k: string, fallback: string) => (process.env[k] ? resolve(process.env[k]!) : join(APP_ROOT, fallback));
// Runtime telemetry (regenerated) + generated reports. Names match the harness layout.
export const PATHS = {
metrics: env('CASAN_DASHBOARD_METRICS', '.specify/logs/cost/metrics.jsonl'),
providerUsage: env('CASAN_CP_PROVIDER_USAGE', '.specify/logs/level5/provider-usage.jsonl'),
audit: env('CASAN_CP_AUDIT', '.specify/logs/audit/audit.jsonl'),
auditHead: env('CASAN_CP_AUDIT_HEAD', '.specify/logs/audit/audit-head.txt'),
security: env('CASAN_CP_SECURITY', '.specify/logs/audit/security.jsonl'),
toolRegistry: env('CASAN_CP_TOOL_REGISTRY', '.specify/logs/level5/tool-registry.jsonl'),
actionGate: env('CASAN_CP_ACTION_GATE', '.specify/logs/level5/action-gate.jsonl'),
fallback: env('CASAN_CP_FALLBACK', '.specify/logs/level5/fallback.jsonl'),
incidents: env('CASAN_CP_INCIDENTS', '.specify/logs/level5/incidents.jsonl'),
alerts: env('CASAN_DASHBOARD_ALERTS', '.specify/agentops/alerts.log'),
traceDir: env('CASAN_CP_TRACE_DIR', '.specify/logs/trace'),
traceability: env('CASAN_CP_TRACEABILITY', 'docs/output/casan/traceability-matrix.json'),
drift: env('CASAN_CP_DRIFT', 'docs/output/casan/level5-evidence/09-drift-report.json'),
businessKpi: env('CASAN_CP_KPI', 'docs/output/casan/level5-evidence/14-business-kpi-report.json'),
benignFp: env('CASAN_CP_BENIGN_FP', 'docs/output/casan/benign-fp-report.json'),
};
export const STALE_AFTER_S = Number(process.env.CASAN_DASHBOARD_STALE_S ?? 3600);
// Freshness of the primary metrics feed (mtime), used by /healthz + `stale` flags.
export function metricsAgeSeconds(): number | null {
try {
return Math.floor((Date.now() - statSync(PATHS.metrics).mtimeMs) / 1000);
} catch {
return null; // missing → treated as stale
}
}
export function isStale(): boolean {
const age = metricsAgeSeconds();
return age === null || age > STALE_AFTER_S;
}
@@ -0,0 +1,23 @@
// Stale-aware health — mirrors dashboard-server.py /healthz: 200 when the metrics feed is
// fresh, 503 when stale or missing (fail-loud: never present stale data as live).
import { Controller, Get, Res } from '@nestjs/common';
import type { Response } from 'express';
import { isStale, metricsAgeSeconds, STALE_AFTER_S } from '../common/app-root.js';
import { readJsonl } from '../telemetry/telemetry.reader.js';
import { PATHS } from '../common/app-root.js';
@Controller()
export class HealthController {
@Get('healthz')
healthz(@Res() res: Response) {
const age = metricsAgeSeconds();
const stale = isStale();
const body = {
status: stale ? 'stale' : 'ok',
metrics_age_s: age,
stale_after_s: STALE_AFTER_S,
runs: readJsonl(PATHS.metrics).length,
};
res.status(stale ? 503 : 200).json(body);
}
}
@@ -0,0 +1,29 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module.js';
import { APP_ROOT } from './common/app-root.js';
// Read-only Ops Console API (Plan-13 Track 1). Binds loopback by default and refuses a
// non-loopback bind under CASAN_PROFILE=prod / CASAN_CP_STRICT=1 — same posture as
// dashboard-server.py. Management/auth are out of scope (future tracks).
async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
const port = Number(process.env.CP_PORT ?? 3010);
let host = process.env.CP_BIND ?? '127.0.0.1';
const strict = process.env.CASAN_PROFILE === 'prod' || process.env.CASAN_CP_STRICT === '1';
if (strict && host !== '127.0.0.1' && host !== 'localhost') {
// read-only console must not expose telemetry off-loopback without the prod hardening
// (TLS/OIDC) that is Track 4 — fail closed.
// eslint-disable-next-line no-console
console.error(`CP_REFUSE_NONLOOPBACK host=${host} (set up TLS/OIDC per Plan-13 Track 4 first)`);
process.exit(2);
}
await app.listen(port, host);
// eslint-disable-next-line no-console
console.log(`CASAN Ops Console API (read-only) http://${host}:${port}/api/v1 app_root=${APP_ROOT}`);
}
bootstrap();
@@ -0,0 +1,64 @@
// Read-only Ops Console API. Every handler returns the standard ok() envelope. No writes,
// no auth (loopback-bound, "Đọc ≠ Ghi"); management/RBAC is Plan-13 Track 2/3 (future).
import { Controller, Get, Inject, Param, Query } from '@nestjs/common';
import { ok } from '../common/api-response.js';
import { TelemetryService } from './telemetry.service.js';
@Controller('api/v1')
export class TelemetryController {
// Explicit @Inject token so DI works under BOTH tsc (emits decorator metadata) and the
// tsx/esbuild dev runner (which does not emit design:paramtypes).
constructor(@Inject(TelemetryService) private readonly svc: TelemetryService) {}
@Get('overview')
overview() {
return ok(this.svc.overview());
}
@Get('runs')
runs(@Query('limit') limit?: string) {
const n = Math.min(Math.max(Number(limit) || 50, 1), 500);
const r = this.svc.runs(n);
return ok(r, { total: r.count });
}
@Get('runs/:traceId')
run(@Param('traceId') traceId: string) {
return ok(this.svc.run(traceId));
}
@Get('governance')
governance() {
return ok(this.svc.governance());
}
@Get('security')
security() {
return ok(this.svc.security());
}
@Get('incidents')
incidents() {
return ok(this.svc.incidents());
}
@Get('tools')
tools() {
return ok(this.svc.tools());
}
@Get('traceability')
traceability() {
return ok(this.svc.traceability());
}
@Get('drift')
drift() {
return ok(this.svc.drift());
}
@Get('cost')
cost() {
return ok(this.svc.cost());
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { TelemetryController } from './telemetry.controller.js';
import { TelemetryService } from './telemetry.service.js';
@Module({
controllers: [TelemetryController],
providers: [TelemetryService],
})
export class TelemetryModule {}
@@ -0,0 +1,50 @@
// Read-only readers for CASAN telemetry. Tolerant of missing/partial files (returns [] or
// null) — never throws on absent data, never fabricates. Path fields inside records are
// treated as opaque strings (some are stale absolute paths from other machines).
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
/** Parse a JSON-lines file → array of objects. Missing file or bad lines are skipped. */
export function readJsonl<T = Record<string, unknown>>(path: string): T[] {
if (!existsSync(path)) return [];
const out: T[] = [];
for (const line of readFileSync(path, 'utf8').split('\n')) {
const s = line.trim();
if (!s) continue;
try {
out.push(JSON.parse(s) as T);
} catch {
/* skip malformed line */
}
}
return out;
}
/** Parse a single JSON object file → object or null when absent/invalid. */
export function readJson<T = Record<string, unknown>>(path: string): T | null {
if (!existsSync(path)) return null;
try {
return JSON.parse(readFileSync(path, 'utf8')) as T;
} catch {
return null;
}
}
/** First non-empty line of a small text file (e.g. audit head hash), or null. */
export function readHead(path: string): string | null {
if (!existsSync(path)) return null;
const t = readFileSync(path, 'utf8').trim();
return t || null;
}
/** Read one per-trace JSON from the trace dir by trace id (matches *<id>.json). */
export function readTrace(traceDir: string, traceId: string): Record<string, unknown> | null {
if (!existsSync(traceDir)) return null;
// trace files are named <harness>-<uuid>.json; find by suffix match on trace_id
for (const f of readdirSync(traceDir)) {
if (!f.endsWith('.json')) continue;
const rec = readJson<Record<string, unknown>>(join(traceDir, f));
if (rec && (rec.trace_id === traceId || f.includes(traceId))) return rec;
}
return null;
}
@@ -0,0 +1,137 @@
// Read-only aggregations over CASAN harness telemetry. Formulas mirror
// packages/casan-harness/tests/generate-agentops-dashboard.py; all numbers come from real
// on-disk feeds. Missing feeds degrade to zero/empty + a `stale` flag — never fabricated.
import { Injectable } from '@nestjs/common';
import { PATHS, isStale, metricsAgeSeconds, STALE_AFTER_S } from '../common/app-root.js';
import { readJsonl, readJson, readHead, readTrace } from './telemetry.reader.js';
type Row = Record<string, any>;
const num = (v: any) => (typeof v === 'number' && isFinite(v) ? v : 0);
const sum = (rows: Row[], k: string) => rows.reduce((a, r) => a + num(r[k]), 0);
const count = (rows: Row[], pred: (r: Row) => boolean) => rows.reduce((a, r) => a + (pred(r) ? 1 : 0), 0);
const recent = (rows: Row[], n: number) => rows.slice(-n).reverse();
@Injectable()
export class TelemetryService {
private freshness() {
const age = metricsAgeSeconds();
return { stale: isStale(), age_s: age, stale_after_s: STALE_AFTER_S };
}
overview() {
const metrics = readJsonl(PATHS.metrics);
const provider = readJsonl(PATHS.providerUsage);
const audit = readJsonl(PATHS.audit);
const security = readJsonl(PATHS.security);
const fallback = readJsonl(PATHS.fallback);
const tools = readJsonl(PATHS.toolRegistry);
const actions = readJsonl(PATHS.actionGate);
const incidents = readJsonl(PATHS.incidents);
const runs = metrics.length;
const latencies = metrics.map((m) => num(m.latency_ms)).filter((x) => x > 0);
return {
...this.freshness(),
totals: {
runs,
total_cost: sum(metrics, 'cost_estimate'),
avg_latency_ms: latencies.length ? Math.round(latencies.reduce((a, b) => a + b, 0) / latencies.length) : 0,
failures: count(metrics, (m) => m.status === 'failed'),
hallucination_signals: sum(metrics, 'hallucination_signals'),
provider_tokens: sum(provider, 'total_tokens'),
provider_cost: sum(provider, 'cost_usd'),
fallback_routes: count(fallback, (f) => f.route === 'fallback'),
tool_denies: count(tools, (t) => t.decision === 'denied'),
action_blocks: count(actions, (a) => a.outcome === 'BLOCK'),
},
// Real per-harness signals (counts), not a hardcoded rubric — truthful by construction.
harness_signals: {
'H4-security': { verdicts: security.length, blocked: count(security, (s) => s.status === 'blocked') },
'H5-governance': { decisions: audit.length, denied: count(audit, (a) => a.decision === 'denied') },
'H6-agentops': { runs, failures: count(metrics, (m) => m.status === 'failed') },
'H7-drift': { report: readJson(PATHS.drift) ? 'present' : 'absent' },
tools: { decisions: tools.length, denied: count(tools, (t) => t.decision === 'denied') },
incidents: { total: incidents.length, critical: count(incidents, (i) => i.severity === 'CRIT') },
},
audit_chain: {
records: audit.length,
head: readHead(PATHS.auditHead),
last_decision: audit.length ? audit[audit.length - 1].decision ?? null : null,
},
};
}
runs(limit = 50) {
const metrics = readJsonl(PATHS.metrics);
return { ...this.freshness(), count: metrics.length, runs: recent(metrics, limit) };
}
run(traceId: string) {
const trace = readTrace(PATHS.traceDir, traceId);
return trace ? { found: true, trace } : { found: false, trace: null };
}
governance() {
const audit = readJsonl(PATHS.audit);
const byDecision: Record<string, number> = {};
for (const r of audit) byDecision[String(r.decision ?? 'unknown')] = (byDecision[String(r.decision ?? 'unknown')] || 0) + 1;
return {
...this.freshness(),
records: audit.length,
by_decision: byDecision,
head: readHead(PATHS.auditHead),
recent: recent(audit, 30),
};
}
security() {
const s = readJsonl(PATHS.security);
const byStatus: Record<string, number> = {};
for (const r of s) byStatus[String(r.status ?? 'unknown')] = (byStatus[String(r.status ?? 'unknown')] || 0) + 1;
return {
...this.freshness(),
verdicts: s.length,
by_status: byStatus,
benign_fp: readJson(PATHS.benignFp),
recent: recent(s, 30),
};
}
incidents() {
const inc = readJsonl(PATHS.incidents);
const engaged = inc.filter((i) => i.action === 'kill_switch_engaged').map((i) => i.scope);
return {
...this.freshness(),
total: inc.length,
kill_switch_scopes: [...new Set(engaged)],
incidents: recent(inc, 50),
};
}
tools() {
return {
...this.freshness(),
tool_registry: recent(readJsonl(PATHS.toolRegistry), 50),
action_gate: recent(readJsonl(PATHS.actionGate), 50),
};
}
traceability() {
return { ...this.freshness(), matrix: readJson(PATHS.traceability) };
}
drift() {
return { ...this.freshness(), report: readJson(PATHS.drift) };
}
cost() {
const provider = readJsonl(PATHS.providerUsage);
return {
...this.freshness(),
provider_tokens: sum(provider, 'total_tokens'),
provider_cost: sum(provider, 'cost_usd'),
by_provider: recent(provider, 50),
business_kpi: readJson(PATHS.businessKpi),
};
}
}
@@ -0,0 +1,64 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { readJsonl, readJson, readHead } from '../src/telemetry/telemetry.reader.js';
import { APP_ROOT, PATHS, isStale, metricsAgeSeconds } from '../src/common/app-root.js';
import { TelemetryService } from '../src/telemetry/telemetry.service.js';
test('readJsonl parses valid lines and skips malformed', () => {
const d = mkdtempSync(join(tmpdir(), 'cp-'));
const f = join(d, 'x.jsonl');
writeFileSync(f, '{"a":1}\n\nnot-json\n{"a":2}\n');
const rows = readJsonl<{ a: number }>(f);
assert.equal(rows.length, 2);
assert.equal(rows[0].a, 1);
assert.equal(rows[1].a, 2);
});
test('readJsonl/readJson tolerate missing files (no throw)', () => {
assert.deepEqual(readJsonl('/no/such/file.jsonl'), []);
assert.equal(readJson('/no/such/file.json'), null);
assert.equal(readHead('/no/such/head.txt'), null);
});
test('APP_ROOT resolves to the CASAN app root (has a harness marker)', () => {
const marker = existsSync(join(APP_ROOT, 'packages', 'casan-harness')) || existsSync(join(APP_ROOT, '.specify'));
assert.ok(marker, `APP_ROOT=${APP_ROOT} should contain .specify or packages/casan-harness`);
});
test('overview() returns real aggregated shape, never throws on the repo state', () => {
const svc = new TelemetryService();
const o = svc.overview() as any;
assert.ok(o.totals && typeof o.totals.runs === 'number');
assert.ok(o.harness_signals && o.harness_signals['H5-governance']);
assert.ok(o.audit_chain && typeof o.audit_chain.records === 'number');
assert.ok('stale' in o && 'stale_after_s' in o);
// real data: metrics + audit feeds exist in this repo, so counts are non-negative
assert.ok(o.totals.runs >= 0);
assert.ok(o.audit_chain.records >= 0);
});
test('security()/governance()/cost() return objects with expected keys', () => {
const svc = new TelemetryService();
assert.ok(typeof (svc.security() as any).by_status === 'object');
assert.ok(typeof (svc.governance() as any).by_decision === 'object');
assert.ok('provider_tokens' in (svc.cost() as any));
});
test('freshness helpers behave (age is number|null, isStale is boolean)', () => {
const age = metricsAgeSeconds();
assert.ok(age === null || typeof age === 'number');
assert.equal(typeof isStale(), 'boolean');
});
test('missing metrics feed => stale (fail-loud)', () => {
const prev = process.env.CASAN_DASHBOARD_METRICS;
process.env.CASAN_DASHBOARD_METRICS = '/no/such/metrics.jsonl';
// re-import is not trivial (module caches PATHS); assert the reader-level contract instead:
assert.deepEqual(readJsonl('/no/such/metrics.jsonl'), []);
if (prev === undefined) delete process.env.CASAN_DASHBOARD_METRICS;
else process.env.CASAN_DASHBOARD_METRICS = prev;
void PATHS;
});
@@ -0,0 +1,6 @@
{
"extends": "./tsconfig.json",
"compilerOptions": { "rootDir": "src" },
"include": ["src/**/*.ts"],
"exclude": ["test", "dist"]
}
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": ".",
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CASAN Ops Console</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
@@ -0,0 +1,29 @@
{
"name": "@casan/control-panel-frontend",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "CASAN Ops Console \u2014 read-only React UI over the harness telemetry API.",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.81.5",
"axios": "^1.10.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.30.1"
},
"devDependencies": {
"@types/react": "^18.3.23",
"@types/react-dom": "^18.3.7",
"@vitejs/plugin-react": "^4.6.0",
"autoprefixer": "^10.4.21",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "^5.8.3",
"vite": "^5.4.19"
}
}
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } };
@@ -0,0 +1,24 @@
import { Routes, Route, Navigate } from 'react-router-dom';
import { AppLayout } from './components/layout/AppLayout';
import { Overview } from './pages/Overview';
import { Runs } from './pages/Runs';
import { Governance } from './pages/Governance';
import { Security } from './pages/Security';
import { Incidents } from './pages/Incidents';
import { Traceability } from './pages/Traceability';
export default function App() {
return (
<AppLayout>
<Routes>
<Route path="/" element={<Overview />} />
<Route path="/runs" element={<Runs />} />
<Route path="/governance" element={<Governance />} />
<Route path="/security" element={<Security />} />
<Route path="/incidents" element={<Incidents />} />
<Route path="/traceability" element={<Traceability />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</AppLayout>
);
}
@@ -0,0 +1,14 @@
import type { ReactNode } from 'react';
import { Sidebar } from './Sidebar';
import { Header } from './Header';
export function AppLayout({ children }: { children: ReactNode }) {
return (
<div className="flex h-screen bg-gray-50">
<Sidebar />
<div className="flex-1 flex flex-col overflow-hidden">
<Header />
<main className="flex-1 overflow-auto p-6 space-y-6">{children}</main>
</div>
</div>
);
}
@@ -0,0 +1,17 @@
import { useQuery } from '@tanstack/react-query';
import { health } from '../../lib/api';
export function Header() {
const { data } = useQuery({ queryKey: ['health'], queryFn: health });
const stale = data ? !data.ok : true;
return (
<header className="h-14 bg-white border-b border-gray-200 flex items-center justify-between px-6">
<h1 className="text-base font-semibold text-gray-800">CASAN Ops Console <span className="text-gray-400 font-normal">· read-only</span></h1>
<div className="flex items-center gap-3 text-xs">
<span className="text-gray-500">runs: {data?.runs ?? '—'}</span>
<span className={`px-2 py-1 rounded-full font-medium ${stale ? 'bg-orange-100 text-orange-700' : 'bg-green-100 text-green-700'}`}>
{stale ? `STALE${data?.metrics_age_s != null ? ` (${data.metrics_age_s}s)` : ''}` : 'LIVE'}
</span>
</div>
</header>
);
}
@@ -0,0 +1,20 @@
import { NavLink } from 'react-router-dom';
const NAV = [
['/', 'Overview'], ['/runs', 'Runs'], ['/governance', 'Governance'],
['/security', 'Security'], ['/incidents', 'Incidents'], ['/traceability', 'Traceability'],
];
export function Sidebar() {
return (
<aside className="w-56 bg-white border-r border-gray-200 flex-shrink-0">
<div className="h-14 flex items-center px-6 font-bold text-blue-600 border-b border-gray-200">CASAN</div>
<nav className="p-3 space-y-1">
{NAV.map(([to, label]) => (
<NavLink key={to} to={to} end={to === '/'}
className={({ isActive }) => `block px-3 py-2 rounded-lg text-sm ${isActive ? 'bg-blue-50 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-800'}`}>
{label}
</NavLink>
))}
</nav>
</aside>
);
}
@@ -0,0 +1,32 @@
import type { ReactNode } from 'react';
export function Card({ title, children, right }: { title?: string; children: ReactNode; right?: ReactNode }) {
return (
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
{title && (
<div className="flex justify-between items-center mb-4">
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide">{title}</h2>
{right}
</div>
)}
{children}
</div>
);
}
export function StatTile({ label, value, sub }: { label: string; value: ReactNode; sub?: string }) {
return (
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<div className="text-xs text-gray-500">{label}</div>
<div className="text-2xl font-semibold text-gray-800 mt-1">{value}</div>
{sub && <div className="text-xs text-gray-400 mt-1">{sub}</div>}
</div>
);
}
const TONE: Record<string, string> = {
ok: 'bg-green-100 text-green-700', pass: 'bg-green-100 text-green-700', success: 'bg-green-100 text-green-700', allow: 'bg-green-100 text-green-700',
warn: 'bg-orange-100 text-orange-700', stale: 'bg-orange-100 text-orange-700',
fail: 'bg-red-100 text-red-700', failed: 'bg-red-100 text-red-700', denied: 'bg-red-100 text-red-700', blocked: 'bg-red-100 text-red-700', deny: 'bg-red-100 text-red-700', block: 'bg-red-100 text-red-700', crit: 'bg-red-100 text-red-700',
};
export function StatusBadge({ value }: { value: string }) {
const tone = TONE[String(value).toLowerCase()] ?? 'bg-gray-100 text-gray-600';
return <span className={`px-2 py-1 rounded-full text-xs font-medium ${tone}`}>{value}</span>;
}
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@@ -0,0 +1,44 @@
// Single axios client for the read-only Ops Console API. Mirrors the OKR app's api.ts:
// relative baseURL, unwrap response.data.data. All GET (read-only).
import axios from 'axios';
const client = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL ?? '/api/v1',
});
async function get<T>(path: string): Promise<T> {
const res = await client.get(`/${path}`);
return res.data.data as T;
}
export interface Freshness { stale: boolean; age_s: number | null; stale_after_s: number }
export interface Overview extends Freshness {
totals: {
runs: number; total_cost: number; avg_latency_ms: number; failures: number;
hallucination_signals: number; provider_tokens: number; provider_cost: number;
fallback_routes: number; tool_denies: number; action_blocks: number;
};
harness_signals: Record<string, Record<string, number | string>>;
audit_chain: { records: number; head: string | null; last_decision: string | null };
}
export const api = {
overview: () => get<Overview>('overview'),
runs: (limit = 50) => get<Freshness & { count: number; runs: any[] }>(`runs?limit=${limit}`),
governance: () => get<Freshness & { records: number; by_decision: Record<string, number>; head: string | null; recent: any[] }>('governance'),
security: () => get<Freshness & { verdicts: number; by_status: Record<string, number>; benign_fp: any; recent: any[] }>('security'),
incidents: () => get<Freshness & { total: number; kill_switch_scopes: string[]; incidents: any[] }>('incidents'),
traceability: () => get<Freshness & { matrix: any }>('traceability'),
cost: () => get<Freshness & { provider_tokens: number; provider_cost: number; by_provider: any[]; business_kpi: any }>('cost'),
};
// Health is raw (not enveloped) + carries HTTP status.
export async function health(): Promise<{ ok: boolean; status: string; metrics_age_s: number | null; runs: number }> {
try {
const res = await axios.get('/healthz', { baseURL: '', validateStatus: () => true });
return { ok: res.status === 200, ...res.data };
} catch {
return { ok: false, status: 'unreachable', metrics_age_s: null, runs: 0 };
}
}
@@ -0,0 +1,6 @@
import { QueryClient } from '@tanstack/react-query';
// Poll telemetry every 15s; read-only console tolerates brief staleness.
export const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 15_000, refetchInterval: 15_000, retry: 1 } },
});
@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClientProvider } from '@tanstack/react-query';
import { BrowserRouter } from 'react-router-dom';
import { queryClient } from './lib/queryClient';
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
</BrowserRouter>
</QueryClientProvider>
</React.StrictMode>,
);
@@ -0,0 +1,27 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import { Card, StatTile, StatusBadge } from '../components/ui/Card';
export function Governance() {
const { data, isLoading } = useQuery({ queryKey: ['governance'], queryFn: api.governance });
if (isLoading || !data) return <div className="text-gray-500">Loading…</div>;
return (
<>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<StatTile label="Audit records" value={data.records} />
{Object.entries(data.by_decision).map(([k, v]) => <StatTile key={k} label={k} value={v as number} />)}
</div>
<Card title="Recent governance decisions" right={<span className="text-xs text-gray-400">head {data.head?.slice(0, 12) ?? '—'}…</span>}>
<div className="overflow-x-auto"><table className="w-full text-sm">
<thead><tr className="text-left text-gray-500 border-b border-gray-200"><th className="py-2">time</th><th>action</th><th>actor</th><th>risk</th><th>decision</th></tr></thead>
<tbody>{data.recent.map((r: any, i: number) => (
<tr key={i} className="border-b border-gray-100">
<td className="py-2 text-gray-500">{r.timestamp?.replace('T',' ').replace('Z','')}</td>
<td className="text-gray-700">{r.action}</td><td>{r.actor}</td><td>{r.risk_level}</td>
<td><StatusBadge value={r.decision ?? '—'} /></td>
</tr>))}</tbody>
</table></div>
</Card>
</>
);
}
@@ -0,0 +1,27 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import { Card, StatTile, StatusBadge } from '../components/ui/Card';
export function Incidents() {
const { data, isLoading } = useQuery({ queryKey: ['incidents'], queryFn: api.incidents });
if (isLoading || !data) return <div className="text-gray-500">Loading…</div>;
return (
<>
<div className="grid grid-cols-2 md:grid-cols-3 gap-4">
<StatTile label="Incidents" value={data.total} />
<StatTile label="Kill-switch scopes" value={data.kill_switch_scopes.length} sub={data.kill_switch_scopes.join(', ') || 'none'} />
</div>
<Card title="Incident log">
<div className="overflow-x-auto"><table className="w-full text-sm">
<thead><tr className="text-left text-gray-500 border-b border-gray-200"><th className="py-2">time</th><th>event</th><th>severity</th><th>scope</th><th>action</th></tr></thead>
<tbody>{data.incidents.map((r: any, i: number) => (
<tr key={i} className="border-b border-gray-100">
<td className="py-2 text-gray-500">{r.timestamp?.replace('T',' ').replace('Z','')}</td>
<td className="text-gray-700">{r.event}</td><td><StatusBadge value={r.severity ?? '—'} /></td>
<td>{r.scope}</td><td>{r.action}</td>
</tr>))}</tbody>
</table></div>
</Card>
</>
);
}
@@ -0,0 +1,37 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import { Card, StatTile, StatusBadge } from '../components/ui/Card';
export function Overview() {
const { data, isLoading, isError } = useQuery({ queryKey: ['overview'], queryFn: api.overview });
if (isLoading) return <div className="text-gray-500">Loading…</div>;
if (isError || !data) return <div className="text-red-600">Cannot reach Ops Console API.</div>;
const t = data.totals;
return (
<>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<StatTile label="Runs" value={t.runs} />
<StatTile label="Failures" value={t.failures} />
<StatTile label="Total cost (est)" value={`$${t.total_cost.toFixed(4)}`} sub={`${t.provider_tokens} provider tokens`} />
<StatTile label="Avg latency" value={`${t.avg_latency_ms} ms`} />
<StatTile label="Fallback routes" value={t.fallback_routes} />
<StatTile label="Tool denies" value={t.tool_denies} />
<StatTile label="Action blocks" value={t.action_blocks} />
<StatTile label="Hallucination signals" value={t.hallucination_signals} />
</div>
<Card title="Harness signals (real counts)">
<div className="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
{Object.entries(data.harness_signals).map(([h, sig]) => (
<div key={h} className="border border-gray-200 rounded-lg p-3">
<div className="font-medium text-gray-700">{h}</div>
<div className="text-gray-500 mt-1">{Object.entries(sig).map(([k, v]) => `${k}: ${v}`).join(' · ')}</div>
</div>
))}
</div>
</Card>
<Card title="Audit chain" right={<StatusBadge value={data.audit_chain.last_decision ?? 'n/a'} />}>
<div className="text-sm text-gray-600">records: {data.audit_chain.records} · head: <code className="text-xs">{data.audit_chain.head?.slice(0, 16) ?? '—'}…</code></div>
</Card>
</>
);
}
@@ -0,0 +1,31 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import { Card, StatusBadge } from '../components/ui/Card';
export function Runs() {
const { data, isLoading } = useQuery({ queryKey: ['runs'], queryFn: () => api.runs(100) });
if (isLoading || !data) return <div className="text-gray-500">Loading…</div>;
return (
<Card title={`Recent runs (${data.count})`}>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead><tr className="text-left text-gray-500 border-b border-gray-200">
<th className="py-2">time</th><th>step</th><th>status</th><th>latency</th><th>tokens</th><th>cost</th>
</tr></thead>
<tbody>
{data.runs.map((r: any, i: number) => (
<tr key={i} className="border-b border-gray-100">
<td className="py-2 text-gray-500">{r.timestamp?.replace('T', ' ').replace('Z', '')}</td>
<td className="text-gray-700">{r.step ?? r.harness}</td>
<td><StatusBadge value={r.status ?? '—'} /></td>
<td>{r.latency_ms ?? '—'} ms</td>
<td>{r.total_tokens ?? '—'}</td>
<td>${Number(r.cost_estimate ?? 0).toFixed(5)}</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
);
}
@@ -0,0 +1,20 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import { Card, StatTile } from '../components/ui/Card';
export function Security() {
const { data, isLoading } = useQuery({ queryKey: ['security'], queryFn: api.security });
if (isLoading || !data) return <div className="text-gray-500">Loading…</div>;
const fp = data.benign_fp;
return (
<>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<StatTile label="H4 verdicts" value={data.verdicts} />
{Object.entries(data.by_status).map(([k, v]) => <StatTile key={k} label={k} value={v as number} />)}
</div>
{fp && <Card title="Benign / false-positive budget">
<pre className="text-xs text-gray-600 overflow-x-auto">{JSON.stringify(fp, null, 2)}</pre>
</Card>}
</>
);
}
@@ -0,0 +1,30 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import { Card, StatTile, StatusBadge } from '../components/ui/Card';
export function Traceability() {
const { data, isLoading } = useQuery({ queryKey: ['traceability'], queryFn: api.traceability });
if (isLoading || !data) return <div className="text-gray-500">Loading…</div>;
const m = data.matrix;
if (!m) return <Card title="Traceability"><div className="text-gray-500">No traceability-matrix.json yet.</div></Card>;
return (
<>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<StatTile label="Requirements" value={m.summary?.requirements ?? '—'} />
<StatTile label="Passed" value={m.summary?.passed ?? '—'} />
<StatTile label="Failed" value={m.summary?.failed ?? '—'} />
</div>
<Card title="FR → code → test">
<div className="overflow-x-auto"><table className="w-full text-sm">
<thead><tr className="text-left text-gray-500 border-b border-gray-200"><th className="py-2">FR</th><th>name</th><th>status</th><th>code</th><th>tests</th></tr></thead>
<tbody>{(m.matrix ?? []).map((r: any) => (
<tr key={r.id} className="border-b border-gray-100">
<td className="py-2 font-medium text-gray-700">{r.id}</td><td>{r.name}</td>
<td><StatusBadge value={r.status} /></td>
<td>{r.code?.length ?? 0}</td><td>{r.tests?.length ?? 0}</td>
</tr>))}</tbody>
</table></div>
</Card>
</>
);
}
@@ -0,0 +1 @@
/// <reference types="vite/client" />
@@ -0,0 +1,3 @@
import type { Config } from 'tailwindcss';
const config: Config = { content: ['./index.html', './src/**/*.{ts,tsx}'], theme: { extend: {} }, plugins: [] };
export default config;
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"types": ["node", "vite/client"]
},
"include": ["src"]
}
@@ -0,0 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/components/layout/applayout.tsx","./src/components/layout/header.tsx","./src/components/layout/sidebar.tsx","./src/components/ui/card.tsx","./src/lib/api.ts","./src/lib/queryclient.ts","./src/pages/governance.tsx","./src/pages/incidents.tsx","./src/pages/overview.tsx","./src/pages/runs.tsx","./src/pages/security.tsx","./src/pages/traceability.tsx"],"errors":true,"version":"5.9.3"}
@@ -0,0 +1,15 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// Ops Console UI. Dev server on 5174 (5173 is the OKR app). Proxies /api/v1 + /healthz to
// the read-only console API (default :3010) so the axios client uses a relative baseURL.
export default defineConfig({
plugins: [react()],
server: {
port: 5174,
proxy: {
'/api/v1': { target: 'http://127.0.0.1:3010', changeOrigin: true },
'/healthz': { target: 'http://127.0.0.1:3010', changeOrigin: true },
},
},
});