Add OpsProof incident evidence view
Homelab Main / validate (push) Failing after 1m28s Details
Homelab Main / running-update (push) Has been skipped Details
Homelab Main / debian-ops (push) Has been skipped Details

This commit is contained in:
juvenal.diaz 2026-12-04 15:59:12 -06:00
parent de7024935b
commit 193f07b044
10 changed files with 484 additions and 44 deletions

View File

@ -57,6 +57,14 @@ OpsProof fails closed and labels the overview unavailable instead of presenting
stale data as current. Warning and failing checks show a read-only focused
Doctor command but cannot submit it.
Unhealthy Kubernetes applications link to
`/incidents/cluster/{application}`. The incident page runs the exact focused
Doctor target with `--json`, assigns stable evidence IDs to the returned rows,
and presents bounded command-output excerpts, observed state, missing evidence,
and root-cause hypotheses. Route input is restricted to Kubernetes application
names and cannot become arbitrary Jeannie arguments. The page deliberately has
no mitigation control.
## Security boundary
OpsProof is not a shell console.
@ -79,7 +87,8 @@ Each slice should be a small, independently testable commit:
1. architecture decision and API contract;
2. Laravel Go/Inertia application shell and health page;
3. read-only homelab overview backed by Jeannie status;
4. incident evidence page backed by Doctor output;
4. incident evidence page backed by Doctor output (implemented for Kubernetes
applications);
5. remediation proposal with risk and rollback details;
6. Dex login and operator authorization;
7. approval-gated execution and live progress;

View File

@ -0,0 +1,41 @@
package incident
import (
"log"
"net/http"
laravel "go.laravel.com"
"go.laravel.com/inertia"
"go.laravel.com/web"
"app/services"
)
type view struct {
Available bool `json:"available"`
Message string `json:"message"`
Incident services.IncidentSnapshot `json:"incident"`
}
func Show(request *web.Request) *web.Response {
scope := request.PathValue("scope")
target := request.PathValue("target")
if !services.ValidDoctorTarget(scope, target) {
return web.Abort(http.StatusNotFound)
}
result := view{Message: "Focused Doctor evidence is temporarily unavailable."}
incident, err := services.From(request.Context()).Jeannie.Doctor(request.Context(), scope, target)
if err != nil {
log.Printf("OpsProof could not collect Doctor evidence for %s/%s: %v", scope, target, err)
} else {
result.Available = true
result.Message = "Read-only evidence collected by the focused Jeannie Doctor."
result.Incident = incident
}
return inertia.Render("Incident", inertia.Props{
"laravelVersion": laravel.Version,
"view": result,
})
}

View File

@ -0,0 +1,157 @@
interface Evidence {
id: string;
status: string;
area: string;
check: string;
summary: string;
output: string;
cause: string;
}
interface Incident {
scope: string;
target: string;
title: string;
executionId: string;
evidence: Evidence[];
missingEvidence: string[];
nextCommand: string;
collectedAt: string;
}
interface Props {
laravelVersion: string;
view: {
available: boolean;
message: string;
incident: Incident;
};
}
const tone: Record<string, string> = {
ok: 'border-emerald-300/20 bg-emerald-300/10 text-emerald-200',
warn: 'border-amber-300/20 bg-amber-300/10 text-amber-200',
fail: 'border-rose-300/20 bg-rose-300/10 text-rose-200',
skip: 'border-slate-500/20 bg-slate-500/10 text-slate-400',
};
export default function IncidentPage({ laravelVersion, view }: Props) {
const incident = view.incident;
return (
<main className="min-h-screen bg-[#071019] text-slate-100 selection:bg-cyan-300 selection:text-slate-950">
<div className="pointer-events-none fixed inset-0 bg-[radial-gradient(circle_at_15%_10%,rgba(34,211,238,0.10),transparent_25%),radial-gradient(circle_at_85%_20%,rgba(99,102,241,0.12),transparent_28%)]" />
<div className="relative mx-auto max-w-6xl px-5 py-6 sm:px-8 lg:px-10">
<header className="flex items-center justify-between border-b border-white/10 pb-5">
<div>
<a href="/" className="text-xs text-cyan-300 hover:text-cyan-200">
← Homelab overview
</a>
<p className="mt-3 font-semibold tracking-tight">OpsProof incident evidence</p>
</div>
<span className="rounded-full border border-cyan-300/30 bg-cyan-300/10 px-3 py-1.5 text-xs text-cyan-200">
Read-only investigation
</span>
</header>
{!view.available ? (
<section className="mt-10 rounded-3xl border border-rose-300/20 bg-rose-300/[0.06] p-7">
<p className="text-xs uppercase tracking-[0.2em] text-rose-300">Evidence unavailable</p>
<h1 className="mt-3 text-2xl font-semibold text-white">Doctor could not complete this investigation</h1>
<p className="mt-3 max-w-2xl text-sm leading-6 text-slate-400">{view.message}</p>
<p className="mt-5 text-xs text-slate-500">
OpsProof does not reuse stale evidence and cannot submit a mitigation from this page.
</p>
</section>
) : (
<>
<section className="grid gap-6 py-10 lg:grid-cols-[1fr_auto] lg:items-end">
<div>
<p className="font-mono text-xs uppercase tracking-[0.2em] text-cyan-300">
{incident.scope} / {incident.target}
</p>
<h1 className="mt-3 text-3xl font-semibold tracking-tight text-white sm:text-5xl">
{incident.title || 'Focused Doctor investigation'}
</h1>
<p className="mt-4 max-w-3xl text-sm leading-6 text-slate-400">{view.message}</p>
</div>
<div className="rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3 font-mono text-[11px] text-slate-500">
<p>EXECUTION {incident.executionId}</p>
<p className="mt-1">COLLECTED {incident.collectedAt}</p>
</div>
</section>
<section className="space-y-4">
{incident.evidence.map((evidence) => (
<article key={evidence.id} className="overflow-hidden rounded-2xl border border-white/10 bg-[#0a141e]/95">
<div className="flex flex-col gap-3 border-b border-white/10 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-3">
<span className="font-mono text-xs text-cyan-300">{evidence.id}</span>
<div>
<h2 className="font-medium text-white">{evidence.check}</h2>
<p className="mt-1 text-xs text-slate-500">{evidence.area}</p>
</div>
</div>
<span className={`w-fit rounded-md border px-2 py-1 text-[10px] uppercase ${tone[evidence.status] ?? tone.skip}`}>
{evidence.status}
</span>
</div>
<div className="grid gap-px bg-white/10 lg:grid-cols-2">
<div className="bg-[#0b1621] p-5">
<p className="text-xs uppercase tracking-[0.18em] text-slate-600">Desired state</p>
<p className="mt-2 text-sm text-slate-300">The declared check passes without warning or failure.</p>
<p className="mt-5 text-xs uppercase tracking-[0.18em] text-slate-600">Observed state</p>
<p className="mt-2 text-sm text-slate-300">{evidence.summary || 'No summary was returned.'}</p>
</div>
<div className="bg-[#0b1621] p-5">
<p className="text-xs uppercase tracking-[0.18em] text-slate-600">Root-cause hypothesis</p>
<p className="mt-2 text-sm leading-6 text-slate-400">
{evidence.cause || 'Doctor did not establish a supported cause from this evidence.'}
</p>
<p className="mt-2 text-[11px] text-amber-200/70">A hypothesis is not proof until deterministic validation succeeds.</p>
</div>
</div>
<div className="p-5">
<p className="text-xs uppercase tracking-[0.18em] text-slate-600">Command output excerpt</p>
<pre className="mt-3 max-h-80 overflow-auto whitespace-pre-wrap rounded-xl border border-white/8 bg-black/20 p-4 font-mono text-xs leading-5 text-slate-400">
{evidence.output || 'No detailed output was returned for this evidence row.'}
</pre>
</div>
</article>
))}
</section>
<section className="mt-6 grid gap-5 lg:grid-cols-2">
<div className="rounded-2xl border border-amber-300/20 bg-amber-300/[0.05] p-5">
<p className="text-xs uppercase tracking-[0.18em] text-amber-200">Missing evidence</p>
{incident.missingEvidence.length === 0 ? (
<p className="mt-3 text-sm text-slate-400">No empty deterministic evidence rows were detected.</p>
) : (
<ul className="mt-3 space-y-2 text-sm text-slate-400">
{incident.missingEvidence.map((item) => (
<li key={item}>• {item}</li>
))}
</ul>
)}
</div>
<div className="rounded-2xl border border-cyan-300/20 bg-cyan-300/[0.05] p-5">
<p className="text-xs uppercase tracking-[0.18em] text-cyan-200">Read-only next command</p>
<code className="mt-3 block overflow-x-auto rounded-lg bg-black/20 p-3 text-xs text-cyan-100">
{incident.nextCommand}
</code>
<button type="button" disabled className="mt-4 w-full cursor-not-allowed rounded-lg bg-white/8 px-4 py-2.5 text-sm text-slate-500">
No mitigation in this slice
</button>
</div>
</section>
</>
)}
<footer className="flex flex-col gap-2 py-8 text-xs text-slate-600 sm:flex-row sm:items-center sm:justify-between">
<span>Laravel Go {laravelVersion} · Jeannie evidence retained server-side.</span>
<span>Raw execution output is not exposed as an action surface.</span>
</footer>
</div>
</main>
);
}

View File

@ -147,9 +147,19 @@ function LiveOverview({ overview }: { overview: Overview }) {
</span>
</div>
{(row.status === 'warn' || row.status === 'fail') && (
<code className="mt-3 block overflow-x-auto rounded-md bg-white/[0.03] px-2 py-1.5 text-[11px] text-cyan-200">
{doctorCommand(row)}
</code>
<div className="mt-3 flex flex-col gap-2">
<code className="block overflow-x-auto rounded-md bg-white/[0.03] px-2 py-1.5 text-[11px] text-cyan-200">
{doctorCommand(row)}
</code>
{row.area === 'Kubernetes apps' && (
<a
href={`/incidents/cluster/${encodeURIComponent(row.check)}`}
className="text-[11px] font-medium text-cyan-300 hover:text-cyan-200"
>
Open evidence →
</a>
)}
</div>
)}
</div>
))}

View File

@ -0,0 +1,21 @@
package routes
import (
"net/http"
"go.laravel.com/config"
"go.laravel.com/routing"
"go.laravel.com/web"
"app/handlers/incident"
"app/handlers/welcome"
)
func Web(route *routing.Router, cfg *config.Config) {
route.Get("/", welcome.Show)
route.Get("/incidents/{scope}/{target}", incident.Show)
route.Fallback(func(*web.Request) *web.Response {
return web.Abort(http.StatusNotFound)
})
}

View File

@ -9,12 +9,15 @@ import (
"io"
"net/http"
"os"
"regexp"
"strings"
"time"
)
const maxJeannieResponseBytes = 2 << 20
var kubernetesApplicationName = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$`)
type StatusRow struct {
Status string `json:"status"`
Area string `json:"area"`
@ -35,6 +38,27 @@ type StatusSnapshot struct {
CollectedAt string `json:"collectedAt"`
}
type IncidentEvidence struct {
ID string `json:"id"`
Status string `json:"status"`
Area string `json:"area"`
Check string `json:"check"`
Summary string `json:"summary"`
Output string `json:"output"`
Cause string `json:"cause"`
}
type IncidentSnapshot struct {
Scope string `json:"scope"`
Target string `json:"target"`
Title string `json:"title"`
ExecutionID string `json:"executionId"`
Evidence []IncidentEvidence `json:"evidence"`
MissingEvidence []string `json:"missingEvidence"`
NextCommand string `json:"nextCommand"`
CollectedAt string `json:"collectedAt"`
}
type JeannieClient struct {
BaseURL string
Token string
@ -63,51 +87,44 @@ func (client *JeannieClient) Status(ctx context.Context) (StatusSnapshot, error)
return StatusSnapshot{}, errors.New("Jeannie API connection is not configured")
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
payload, err := json.Marshal(map[string]any{
"command": "status",
"args": []string{"all", "--json"},
})
completed, err := client.execute(ctx, "status", []string{"all", "--json"}, 30*time.Second)
if err != nil {
return StatusSnapshot{}, fmt.Errorf("encode status request: %w", err)
return StatusSnapshot{}, err
}
snapshot, err := decodeStatusOutput(completed.Output)
if err != nil {
return StatusSnapshot{}, err
}
snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339)
return snapshot, nil
}
func (client *JeannieClient) Doctor(ctx context.Context, scope string, target string) (IncidentSnapshot, error) {
if scope != "cluster" || !kubernetesApplicationName.MatchString(target) {
return IncidentSnapshot{}, errors.New("unsupported Doctor target")
}
if client.BaseURL == "" || client.Token == "" {
return IncidentSnapshot{}, errors.New("Jeannie API connection is not configured")
}
var submitted execution
if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil {
return StatusSnapshot{}, fmt.Errorf("submit status request: %w", err)
completed, err := client.execute(ctx, "doctor", []string{scope, target, "--json"}, 60*time.Second)
if err != nil {
return IncidentSnapshot{}, err
}
if submitted.ID == "" {
return StatusSnapshot{}, errors.New("Jeannie API returned an empty execution ID")
snapshot, err := decodeDoctorOutput(completed.Output)
if err != nil {
return IncidentSnapshot{}, err
}
snapshot.Scope = scope
snapshot.Target = target
snapshot.ExecutionID = completed.ID
snapshot.NextCommand = "./jeannie doctor cluster " + target + " --details"
snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339)
return snapshot, nil
}
for {
var current execution
if err := client.request(ctx, http.MethodGet, "/v1/executions/"+submitted.ID, nil, &current); err != nil {
return StatusSnapshot{}, fmt.Errorf("read status execution: %w", err)
}
switch current.Status {
case "queued", "running":
timer := time.NewTimer(client.PollInterval)
select {
case <-ctx.Done():
timer.Stop()
return StatusSnapshot{}, fmt.Errorf("wait for status execution: %w", ctx.Err())
case <-timer.C:
}
case "succeeded", "failed":
snapshot, err := decodeStatusOutput(current.Output)
if err != nil {
return StatusSnapshot{}, err
}
snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339)
return snapshot, nil
default:
return StatusSnapshot{}, fmt.Errorf("Jeannie API returned unknown execution state %q", current.Status)
}
}
func ValidDoctorTarget(scope string, target string) bool {
return scope == "cluster" && kubernetesApplicationName.MatchString(target)
}
type execution struct {
@ -116,6 +133,44 @@ type execution struct {
Output string `json:"output"`
}
func (client *JeannieClient) execute(ctx context.Context, command string, args []string, timeout time.Duration) (execution, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
payload, err := json.Marshal(map[string]any{"command": command, "args": args})
if err != nil {
return execution{}, fmt.Errorf("encode %s request: %w", command, err)
}
var submitted execution
if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil {
return execution{}, fmt.Errorf("submit %s request: %w", command, err)
}
if submitted.ID == "" {
return execution{}, errors.New("Jeannie API returned an empty execution ID")
}
for {
var current execution
if err := client.request(ctx, http.MethodGet, "/v1/executions/"+submitted.ID, nil, &current); err != nil {
return execution{}, fmt.Errorf("read %s execution: %w", command, err)
}
switch current.Status {
case "queued", "running":
timer := time.NewTimer(client.PollInterval)
select {
case <-ctx.Done():
timer.Stop()
return execution{}, fmt.Errorf("wait for %s execution: %w", command, ctx.Err())
case <-timer.C:
}
case "succeeded", "failed":
return current, nil
default:
return execution{}, fmt.Errorf("Jeannie API returned unknown execution state %q", current.Status)
}
}
}
func (client *JeannieClient) request(ctx context.Context, method string, path string, body io.Reader, target any) error {
request, err := http.NewRequestWithContext(ctx, method, client.BaseURL+path, body)
if err != nil {
@ -156,3 +211,62 @@ func decodeStatusOutput(output string) (StatusSnapshot, error) {
}
return snapshot, nil
}
func decodeDoctorOutput(output string) (IncidentSnapshot, error) {
type doctorRow struct {
Status string `json:"status"`
Area string `json:"area"`
Check string `json:"check"`
Summary string `json:"summary"`
Detail string `json:"detail"`
Cause string `json:"cause"`
}
var report struct {
Title string `json:"title"`
Rows []doctorRow `json:"rows"`
}
start := strings.Index(output, "{")
if start < 0 {
return IncidentSnapshot{}, errors.New("Jeannie Doctor output did not contain JSON")
}
if err := json.Unmarshal([]byte(output[start:]), &report); err != nil {
return IncidentSnapshot{}, fmt.Errorf("decode Jeannie Doctor output: %w", err)
}
if report.Rows == nil {
return IncidentSnapshot{}, errors.New("Jeannie Doctor output did not contain rows")
}
snapshot := IncidentSnapshot{Title: report.Title, Evidence: make([]IncidentEvidence, 0, len(report.Rows))}
for index, row := range report.Rows {
snapshot.Evidence = append(snapshot.Evidence, IncidentEvidence{
ID: fmt.Sprintf("C%02d", index+1),
Status: row.Status,
Area: row.Area,
Check: row.Check,
Summary: cleanExcerpt(row.Summary, 800),
Output: cleanExcerpt(row.Detail, 4000),
Cause: cleanExcerpt(row.Cause, 1200),
})
if strings.TrimSpace(row.Detail) == "" {
snapshot.MissingEvidence = append(snapshot.MissingEvidence, fmt.Sprintf("C%02d has no detailed command output.", index+1))
}
}
if len(report.Rows) == 0 {
snapshot.MissingEvidence = append(snapshot.MissingEvidence, "Doctor returned no evidence rows.")
}
return snapshot, nil
}
func cleanExcerpt(value string, limit int) string {
value = strings.Map(func(character rune) rune {
if character == '\n' || character == '\t' || character >= 32 {
return character
}
return -1
}, strings.TrimSpace(value))
characters := []rune(value)
if len(characters) <= limit {
return value
}
return string(characters[:limit]) + "\n[excerpt truncated by OpsProof]"
}

View File

@ -65,3 +65,47 @@ func TestDecodeStatusOutputRejectsNonJSON(t *testing.T) {
t.Fatal("expected invalid output to fail")
}
}
func TestDoctorNormalizesEvidenceAndRejectsArbitraryTargets(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/v1/execute":
var payload struct {
Command string `json:"command"`
Args []string `json:"args"`
}
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
if payload.Command != "doctor" || len(payload.Args) != 3 || payload.Args[0] != "cluster" || payload.Args[1] != "n8n" || payload.Args[2] != "--json" {
t.Fatalf("unexpected Doctor payload: %#v", payload)
}
response.WriteHeader(http.StatusAccepted)
_, _ = response.Write([]byte(`{"id":"doctor-1","status":"queued"}`))
case "/v1/executions/doctor-1":
_, _ = response.Write([]byte(`{"id":"doctor-1","status":"failed","output":"config loaded\n{\"title\":\"Jeannie Doctor: cluster / n8n\",\"rows\":[{\"status\":\"fail\",\"area\":\"Kubernetes apps\",\"check\":\"n8n\",\"summary\":\"health=Progressing\",\"detail\":\"$ kubectl get pod\\nCrashLoopBackOff\",\"cause\":\"The container exits during startup.\",\"fix\":\"kubectl delete pod\"}]}"}`))
default:
http.NotFound(response, request)
}
}))
defer server.Close()
client := NewJeannieClient(server.URL, "test-token")
client.PollInterval = time.Millisecond
incident, err := client.Doctor(context.Background(), "cluster", "n8n")
if err != nil {
t.Fatal(err)
}
if incident.ExecutionID != "doctor-1" || incident.NextCommand != "./jeannie doctor cluster n8n --details" {
t.Fatalf("unexpected incident metadata: %#v", incident)
}
if len(incident.Evidence) != 1 || incident.Evidence[0].ID != "C01" || incident.Evidence[0].Cause == "" {
t.Fatalf("unexpected normalized evidence: %#v", incident.Evidence)
}
if _, err := client.Doctor(context.Background(), "cluster", "n8n;shutdown"); err == nil {
t.Fatal("expected unsafe target to be rejected")
}
if ValidDoctorTarget("debian", "docker") {
t.Fatal("only the cluster application drill-down is enabled in this slice")
}
}

View File

@ -0,0 +1,29 @@
package feature_test
import (
"net/http"
"net/http/httptest"
"testing"
"app/services"
"app/tests"
)
func TestIncidentPageRendersDeterministicDoctorEvidence(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/v1/execute":
response.WriteHeader(http.StatusAccepted)
_, _ = response.Write([]byte(`{"id":"doctor-1","status":"queued"}`))
case "/v1/executions/doctor-1":
_, _ = response.Write([]byte(`{"id":"doctor-1","status":"failed","output":"{\"title\":\"Jeannie Doctor: cluster / n8n\",\"rows\":[{\"status\":\"fail\",\"area\":\"Kubernetes apps\",\"check\":\"n8n\",\"summary\":\"health=Progressing\",\"detail\":\"CrashLoopBackOff\",\"cause\":\"The container exits during startup.\"}]}"}`))
default:
http.NotFound(response, request)
}
}))
defer server.Close()
client := tests.New(t)
services.From(client.Context()).Jeannie = services.NewJeannieClient(server.URL, "test-token")
client.Get("/incidents/cluster/n8n").AssertOK().AssertInertia("Incident")
}

View File

@ -65,6 +65,9 @@ confirmed by deterministic validation.
differs from the proposal.
- Collect the overview through Jeannie's authenticated, read-only status
command and expose only sanitized status fields to browser props.
- Constrain incident routes to known target types, collect focused Doctor JSON
server-side, and expose bounded evidence excerpts rather than executable
commands or the complete private response.
## Why not Laravel Rust now?

View File

@ -107,15 +107,27 @@ class OpsProofPipelineTests(unittest.TestCase):
self.assertIn("Live read-only inventory", page)
self.assertIn("Desired: declared intent satisfied", page)
self.assertIn("bearer token retained server-side", page)
self.assertIn("/incidents/cluster/", page)
self.assertIn("Open evidence", page)
self.assertIn("./jeannie doctor opi5 --repair-k3s", page)
client = (ROOT / "apps/opsproof/overlay/services/jeannie.go").read_text(
encoding="utf-8"
)
self.assertIn('"command": "status"', client)
self.assertIn('client.execute(ctx, "status"', client)
self.assertIn('[]string{"all", "--json"}', client)
self.assertIn('[]string{scope, target, "--json"}', client)
self.assertIn("unsupported Doctor target", client)
self.assertNotIn("Detail string", client)
incident = (ROOT / "apps/opsproof/overlay/resources/js/pages/Incident.tsx").read_text(
encoding="utf-8"
)
self.assertIn("Command output excerpt", incident)
self.assertIn("Root-cause hypothesis", incident)
self.assertIn("No mitigation in this slice", incident)
self.assertNotIn("fetch('/v1/execute", incident)
if __name__ == "__main__":
unittest.main()