package main import ( "bufio" "context" "encoding/json" "flag" "fmt" "io" "os" "os/exec" "sort" "strings" "sync" "time" ) type reportRow struct { Status string `json:"status"` Area string `json:"area"` Check string `json:"check"` Summary string `json:"summary"` Detail string `json:"detail"` Fix string `json:"fix"` Graph string `json:"graph"` Query string `json:"query"` Cause string `json:"cause,omitempty"` Mitigate string `json:"mitigate,omitempty"` Redesign string `json:"redesign,omitempty"` Evidence string `json:"evidence,omitempty"` Impact string `json:"impact,omitempty"` ImpactScore int `json:"impact_score,omitempty"` } type reportDiagnosis struct { Cause string Mitigate string Redesign string Evidence string } type reportImpact struct { Label string Score int } func main() { if len(os.Args) < 2 { usage(os.Stderr) os.Exit(2) } switch os.Args[1] { case "report-render": if err := runReportRender(os.Args[2:], os.Stdin, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } case "run-dag": if err := runDAG(os.Args[2:], os.Stdout, os.Stderr); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } case "help", "-h", "--help": usage(os.Stdout) default: usage(os.Stderr) os.Exit(2) } } func usage(out io.Writer) { fmt.Fprintln(out, "Usage: jeannie-core {report-render|run-dag}") } type dagSpec struct { Tasks []dagTask `json:"tasks"` Parallelism int `json:"parallelism"` } type dagTask struct { ID string `json:"id"` Title string `json:"title"` Command []string `json:"command"` Needs []string `json:"needs"` } type dagTaskResult struct { id string exitCode int err error } func runDAG(args []string, out io.Writer, errOut io.Writer) error { flags := flag.NewFlagSet("run-dag", flag.ContinueOnError) flags.SetOutput(io.Discard) specPath := flags.String("spec", "", "") if err := flags.Parse(args); err != nil { return err } if *specPath == "" { return fmt.Errorf("run-dag requires --spec") } specData, err := os.ReadFile(*specPath) if err != nil { return err } var spec dagSpec if err := json.Unmarshal(specData, &spec); err != nil { return err } return executeDAG(context.Background(), spec, out, errOut) } func executeDAG(ctx context.Context, spec dagSpec, out io.Writer, errOut io.Writer) error { if spec.Parallelism <= 0 { spec.Parallelism = 4 } taskByID := map[string]dagTask{} dependents := map[string][]string{} remainingNeeds := map[string]int{} for _, task := range spec.Tasks { if task.ID == "" { return fmt.Errorf("dag task has empty id") } if _, exists := taskByID[task.ID]; exists { return fmt.Errorf("duplicate dag task id %q", task.ID) } if len(task.Command) == 0 { return fmt.Errorf("dag task %q has empty command", task.ID) } taskByID[task.ID] = task remainingNeeds[task.ID] = len(task.Needs) for _, need := range task.Needs { dependents[need] = append(dependents[need], task.ID) } } for _, task := range spec.Tasks { for _, need := range task.Needs { if _, exists := taskByID[need]; !exists { return fmt.Errorf("dag task %q depends on unknown task %q", task.ID, need) } } } ctx, cancel := context.WithCancel(ctx) defer cancel() ready := make(chan string, len(spec.Tasks)) results := make(chan dagTaskResult, len(spec.Tasks)) sem := make(chan struct{}, spec.Parallelism) var writersMu sync.Mutex var wg sync.WaitGroup started := map[string]bool{} completed := map[string]bool{} for id, count := range remainingNeeds { if count == 0 { ready <- id } } failed := false for len(completed) < len(spec.Tasks) { select { case id := <-ready: if started[id] || failed { continue } started[id] = true task := taskByID[id] wg.Add(1) go func() { defer wg.Done() sem <- struct{}{} defer func() { <-sem }() results <- runDAGTask(ctx, task, out, errOut, &writersMu) }() case result := <-results: completed[result.id] = true if result.err != nil || result.exitCode != 0 { failed = true cancel() wg.Wait() if result.err != nil { return result.err } return fmt.Errorf("dag task %q failed with exit code %d", result.id, result.exitCode) } for _, dependent := range dependents[result.id] { remainingNeeds[dependent]-- if remainingNeeds[dependent] == 0 { ready <- dependent } } } } wg.Wait() return nil } func runDAGTask(ctx context.Context, task dagTask, out io.Writer, errOut io.Writer, writersMu *sync.Mutex) dagTaskResult { title := task.Title if title == "" { title = task.ID } started := time.Now() writeDAGLine(out, writersMu, task.ID, "started "+title) cmd := exec.CommandContext(ctx, task.Command[0], task.Command[1:]...) cmd.Env = os.Environ() stdout, err := cmd.StdoutPipe() if err != nil { return dagTaskResult{id: task.ID, exitCode: 1, err: err} } cmd.Stderr = cmd.Stdout if err := cmd.Start(); err != nil { return dagTaskResult{id: task.ID, exitCode: 1, err: err} } scanner := bufio.NewScanner(stdout) scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) for scanner.Scan() { writeDAGLine(out, writersMu, task.ID, scanner.Text()) } if scanErr := scanner.Err(); scanErr != nil { writeDAGLine(errOut, writersMu, task.ID, "output read error: "+scanErr.Error()) } err = cmd.Wait() elapsed := time.Since(started).Round(time.Second) exitCode := 0 if err != nil { if ctx.Err() != nil { writeDAGLine(out, writersMu, task.ID, fmt.Sprintf("cancelled after %s", elapsed)) return dagTaskResult{id: task.ID, exitCode: 0, err: ctx.Err()} } exitCode = 1 if exitErr, ok := err.(*exec.ExitError); ok { exitCode = exitErr.ExitCode() } writeDAGLine(out, writersMu, task.ID, fmt.Sprintf("failed after %s", elapsed)) return dagTaskResult{id: task.ID, exitCode: exitCode, err: nil} } writeDAGLine(out, writersMu, task.ID, fmt.Sprintf("completed in %s", elapsed)) return dagTaskResult{id: task.ID, exitCode: 0, err: nil} } func writeDAGLine(out io.Writer, writersMu *sync.Mutex, id string, line string) { writersMu.Lock() defer writersMu.Unlock() fmt.Fprintf(out, "[%s] %s\n", id, line) } func runReportRender(args []string, in io.Reader, out io.Writer) error { flags := flag.NewFlagSet("report-render", flag.ContinueOnError) flags.SetOutput(io.Discard) title := flags.String("title", envDefault("REPORT_TITLE", "Jeannie Report"), "") details := flags.Bool("details", false, "") only := flags.String("only", "all", "") asJSON := flags.Bool("json", false, "") if err := flags.Parse(args); err != nil { usage(os.Stderr) return err } rows, err := parseReportRows(in) if err != nil { return err } rows = filterReportRows(rows, *only) if *asJSON { encoder := json.NewEncoder(out) encoder.SetIndent("", " ") return encoder.Encode(map[string]any{"title": *title, "rows": rows}) } renderReportText(out, *title, rows, *details, *only) return nil } func envDefault(name, fallback string) string { if value := os.Getenv(name); value != "" { return value } return fallback } func parseReportRows(in io.Reader) ([]reportRow, error) { data, err := io.ReadAll(in) if err != nil { return nil, err } var rows []reportRow for _, raw := range strings.Split(string(data), "\n") { raw = strings.TrimSuffix(raw, "\r") if strings.TrimSpace(raw) == "" { continue } parts := strings.Split(raw, "\t") for len(parts) < 8 { parts = append(parts, "") } row := reportRow{ Status: normalizeStatus(parts[0]), Area: strings.TrimSpace(parts[1]), Check: strings.TrimSpace(parts[2]), Summary: strings.TrimSpace(parts[3]), Detail: strings.TrimSpace(parts[4]), Fix: strings.TrimSpace(parts[5]), Graph: strings.TrimSpace(parts[6]), Query: strings.TrimSpace(parts[7]), } if row.Area == "" { row.Area = "General" } if row.Status == "ok" { row.Graph = "" row.Query = "" } if row.Status == "fail" || row.Status == "warn" { diagnosis := diagnoseReportRow(row) row.Cause = diagnosis.Cause row.Mitigate = diagnosis.Mitigate row.Redesign = diagnosis.Redesign row.Evidence = diagnosis.Evidence impact := assessReportImpact(row) row.Impact = impact.Label row.ImpactScore = impact.Score } rows = append(rows, row) } return rows, nil } func normalizeStatus(value string) string { status := strings.ToLower(strings.TrimSpace(value)) if status == "" { return "skip" } return status } func filterReportRows(rows []reportRow, only string) []reportRow { var filtered []reportRow for _, row := range rows { if includeReportRow(row, only) { filtered = append(filtered, row) } } return filtered } func includeReportRow(row reportRow, only string) bool { switch only { case "all": return true case "failures": return row.Status == "fail" case "warnings": return row.Status == "warn" case "problems": return row.Status == "fail" || row.Status == "warn" default: return true } } func renderReportText(out io.Writer, title string, rows []reportRow, details bool, only string) { counts := map[string]int{"fail": 0, "warn": 0, "ok": 0, "skip": 0} for _, row := range rows { counts[row.Status]++ } fmt.Fprintln(out, title) fmt.Fprintln(out, strings.Repeat("=", len(title))) fmt.Fprintf(out, "fail=%d warn=%d ok=%d skip=%d\n", counts["fail"], counts["warn"], counts["ok"], counts["skip"]) if len(rows) == 0 { switch only { case "problems": fmt.Fprintln(out, "\nNo failing or warning items.") case "failures": fmt.Fprintln(out, "\nNo failing items.") case "warnings": fmt.Fprintln(out, "\nNo warning items.") default: fmt.Fprintln(out, "\nNo report rows.") } return } if focus, ok := highestImpactReportRow(rows); ok { fmt.Fprintln(out, "\n== Highest Impact Focus ==") fmt.Fprintf(out, "%s / %s: %s\n", focus.Area, focus.Check, focus.Summary) if focus.Impact != "" { fmt.Fprintf(out, "impact: %s\n", focus.Impact) } if focus.Cause != "" { fmt.Fprintf(out, "likely: %s\n", focus.Cause) } if focus.Fix != "" { fmt.Fprintf(out, "first action: %s\n", focus.Fix) } if focus.Mitigate != "" { fmt.Fprintf(out, "mitigate: %s\n", focus.Mitigate) } } for _, area := range orderedReportAreas(rows) { fmt.Fprintf(out, "\n== %s ==\n", area) areaRows := rowsForReportArea(rows, area) sort.SliceStable(areaRows, func(i, j int) bool { leftRank := reportStatusRank(areaRows[i].Status) rightRank := reportStatusRank(areaRows[j].Status) if leftRank != rightRank { return leftRank < rightRank } return areaRows[i].Check < areaRows[j].Check }) for _, row := range areaRows { fmt.Fprintf(out, "%-5s %-30s %s\n", row.Status, truncate(row.Check, 30), row.Summary) if details || row.Status == "fail" || row.Status == "warn" { if row.Detail != "" { fmt.Fprintf(out, " detail: %s\n", row.Detail) } if row.Evidence != "" { fmt.Fprintf(out, " evidence: %s\n", row.Evidence) } if row.Impact != "" { fmt.Fprintf(out, " impact: %s\n", row.Impact) } if row.Cause != "" { fmt.Fprintf(out, " likely: %s\n", row.Cause) } if row.Fix != "" { fmt.Fprintf(out, " fix: %s\n", row.Fix) } if row.Mitigate != "" { fmt.Fprintf(out, " mitigate: %s\n", row.Mitigate) } if row.Redesign != "" { fmt.Fprintf(out, " redesign: %s\n", row.Redesign) } if row.Graph != "" { fmt.Fprintf(out, " graph: %s\n", row.Graph) } if row.Query != "" { fmt.Fprintf(out, " query: %s\n", row.Query) } } } } for _, row := range rows { if row.Status == "fail" || row.Status == "warn" { fmt.Fprintln(out, "\nNext Fix") if row.Fix != "" { fmt.Fprintln(out, row.Fix) } else { fmt.Fprintf(out, "Investigate %s / %s\n", row.Area, row.Check) } if row.Mitigate != "" { fmt.Fprintf(out, "Mitigate: %s\n", row.Mitigate) } return } } } func highestImpactReportRow(rows []reportRow) (reportRow, bool) { var focus reportRow found := false for _, row := range rows { if row.Status != "fail" && row.Status != "warn" { continue } if !found || row.ImpactScore > focus.ImpactScore || (row.ImpactScore == focus.ImpactScore && reportStatusRank(row.Status) < reportStatusRank(focus.Status)) { focus = row found = true } } return focus, found } func diagnoseReportRow(row reportRow) reportDiagnosis { text := strings.ToLower(strings.Join([]string{row.Area, row.Check, row.Summary, row.Detail}, " ")) diagnosis := reportDiagnosis{ Evidence: evidenceFromRow(row), } switch { case containsAny(text, "connection refused", "connect: connection refused", "couldn't connect to server", "no route to host", "network is unreachable", "timed out", "i/o timeout"): diagnosis.Cause = "The target is not accepting traffic from this network path. The usual break is service down, wrong backend IP/port, route advertisement, firewall/NAT, or MetalLB address ownership." diagnosis.Mitigate = "Test the next hop directly from the host that failed, then restart or reapply the owning layer shown by the check. For public URL failures, compare Debian -> Traefik and OCI edge -> Traefik before changing app code." diagnosis.Redesign = "Keep backend IPs and edge routes inventory-driven and prefer one routed entry point per service to reduce stale hardcoded targets." case containsAny(text, "tls handshake timeout", "bad record mac", "certificate", "x509", "ssl"): diagnosis.Cause = "TLS is failing before the application response is usable. Common causes are API server load, proxy/cache corruption, stale certificates, or HTTPS being attempted against an HTTP-only backend." diagnosis.Mitigate = "Validate the same endpoint with a direct HTTP/TLS probe from the closest hop, then restart/reapply the proxy or control-plane component that owns TLS termination." diagnosis.Redesign = "Terminate TLS at a single intentional layer and keep cache/proxy compression disabled for identity/control-plane paths." case containsAny(text, "imagepullbackoff", "errimagepull", "server gave http response to https client", "failed to pull", "manifest unknown", "pull access denied"): diagnosis.Cause = "A node cannot pull the image it was scheduled to run. Likely causes are unsigned/stale tag, missing image, insecure registry config drift, or the registry endpoint not reachable from Pimox workers." diagnosis.Mitigate = "Run the apps pipeline to rebuild/sign/push the image, verify worker access to the registry, and restart only the affected deployment." diagnosis.Redesign = "Make registry endpoint, insecure registry setup, signing policy, and image overrides generated from the same profile inputs." case containsAny(text, "containerstatusunknown", "evicted"): diagnosis.Cause = "Kubernetes has stale or unhealthy pod records, usually after node disruption, kubelet/container runtime restart, disk or memory pressure, or an interrupted local-registry rollout." diagnosis.Mitigate = "Focus on the current owner first: verify nodes are Ready, then delete stale Evicted/ContainerStatusUnknown pods and confirm the deployment/daemonset recreates healthy replicas." diagnosis.Redesign = "Add cleanup for stale terminated pods after disruptive Pimox/node recovery and keep local-registry replicas/storage sized for node pressure events." case containsAny(text, "pending", "didn't match pod's node affinity", "insufficient", "taint", "unbound immediate persistentvolumeclaims"): diagnosis.Cause = "The scheduler cannot place the pod. The usual cause is node affinity/selector drift, missing labels, taints, resource pressure, or storage claims not bound." diagnosis.Mitigate = "Describe the pod and compare requested selectors/tolerations/resources with current node labels and capacity; reapply the profile/policy that owns those labels." diagnosis.Redesign = "Keep node labels and workload placement policy generated per cluster profile so migration does not strand workloads." case containsAny(text, "notready", "node(s) not ready", "node pressure", "diskpressure", "memorypressure", "pidpressure"): diagnosis.Cause = "A Kubernetes node is unhealthy or under pressure. On Pimox this often points to VM health, CPU pinning, storage health, kubelet/containerd, or CNI readiness." diagnosis.Mitigate = "Check the specific node condition, kubelet status, and Pimox VM state before restarting workloads; recover the node first." diagnosis.Redesign = "Add capacity guardrails and profile-specific VM sizing/pinning so the cluster stays inside OPI5/Pimox limits." case containsAny(text, "qemu guest agent is not running", "guest agent", "pimox", "input/output error"): diagnosis.Cause = "The virtualization layer is unhealthy or unreachable. Likely causes are Pimox storage trouble, stopped/stuck VM, guest-agent failure, or CPU/storage pressure." diagnosis.Mitigate = "Check Pimox storage and VM status first; avoid rebuilding Kubernetes until the VM and disk layer are healthy." diagnosis.Redesign = "Keep VM CPU affinity, storage checks, and backup/restore drills as first-class profile checks." case containsAny(text, "http 502", "http 503", "http 504", "no available server", "err_read_error"): diagnosis.Cause = "A proxy reached the edge path but could not get a healthy backend response. This usually means stale cache/backend routing, dead upstream, or app ingress unavailable." diagnosis.Mitigate = "Flush edge caches only after direct backend checks show healthy; if direct backend fails, fix Traefik/app first." diagnosis.Redesign = "Separate cacheable website traffic from identity/API/control-plane traffic and generate edge backend targets from inventory." case containsAny(text, "http 404", "not found"): diagnosis.Cause = "The route exists but the requested path/host is not owned by the expected backend. Common causes are wrong host header, stale ingress, or provider/application path mismatch." diagnosis.Mitigate = "Check ingress host/path and backend service target, then reapply the app or edge layer that owns routing." diagnosis.Redesign = "Centralize public hostnames and callback/root URLs so app, ingress, and edge config cannot diverge." case containsAny(text, "unauthorized", "forbidden", "permission denied", "authentication required"): diagnosis.Cause = "The service is reachable, but credentials, RBAC, or token state does not authorize the operation." diagnosis.Mitigate = "Rotate or re-sync the relevant SOPS/runner/API secret through the pipeline and validate the exact service account/user." diagnosis.Redesign = "Prefer declarative secret inventory and automated restore drills over manual token creation." case strings.Contains(text, "backup"): diagnosis.Cause = "Backup freshness or restore validation is outside the expected window." diagnosis.Mitigate = "Run the backup command and inspect the restore drill output before deleting old state." diagnosis.Redesign = "Schedule profile-aware backup and restore-drill checks after each major topology change." default: diagnosis.Cause = "The check failed at this layer, but the output is not specific enough to isolate one root cause automatically." diagnosis.Mitigate = "Run the suggested fix command with --verbose or use the related focused doctor to collect layer-specific evidence." diagnosis.Redesign = "If this repeats, add a narrower check that verifies the dependency immediately upstream and downstream of this layer." } return diagnosis } func assessReportImpact(row reportRow) reportImpact { text := strings.ToLower(strings.Join([]string{row.Area, row.Check, row.Summary, row.Detail}, " ")) score := 10 label := "low - limited or advisory impact" if row.Status == "fail" { score += 30 } else if row.Status == "warn" { score += 10 } switch { case containsAny(text, "public", "edge", "website public", "gitea public", "grafana public", "argocd public", "dex public", "traefik loadbalancer", "no available server", "http 502", "http 503", "http 504"): score += 45 label = "critical - public access or edge ingress is affected" case containsAny(text, "kubernetes", "api ready", "nodes ready", "notready", "control-plane", "pimox runtime"): score += 40 label = "critical - cluster control plane or node availability is affected" case containsAny(text, "registry", "imagepullbackoff", "errimagepull", "failed to pull", "containerstatusunknown", "evicted"): score += 35 label = "high - deployments cannot recover or roll out reliably" case containsAny(text, "backup", "restore"): score += 30 label = "high - recovery confidence is reduced" case containsAny(text, "gitea", "runner", "git"): score += 25 label = "medium - GitOps or CI/CD path may be degraded" case containsAny(text, "dns", "pi-hole", "rpi"): score += 25 label = "medium - local name resolution or supporting services may be degraded" case containsAny(text, "ollama", "n8n", "uptime kuma"): score += 15 label = "medium - optional application service is degraded" } if score >= 80 { label = "critical - fix first; downstream checks may be noisy until this is healthy" } else if score >= 60 { label = "high - fix before lower-priority application symptoms" } else if score >= 35 { label = "medium - investigate after critical path checks" } return reportImpact{Label: label, Score: score} } func containsAny(text string, needles ...string) bool { for _, needle := range needles { if strings.Contains(text, needle) { return true } } return false } func evidenceFromRow(row reportRow) string { if row.Detail != "" { return truncate(row.Detail, 140) } if row.Summary != "" { return truncate(row.Summary, 140) } return "" } func orderedReportAreas(rows []reportRow) []string { seen := map[string]bool{} var areas []string for _, row := range rows { if !seen[row.Area] { seen[row.Area] = true areas = append(areas, row.Area) } } return areas } func rowsForReportArea(rows []reportRow, area string) []reportRow { var areaRows []reportRow for _, row := range rows { if row.Area == area { areaRows = append(areaRows, row) } } return areaRows } func reportStatusRank(status string) int { switch status { case "fail": return 0 case "warn": return 1 case "skip": return 2 case "ok": return 3 default: return 9 } } func truncate(value string, max int) string { if len(value) <= max { return value } if max <= 3 { return value[:max] } return value[:max-3] + "..." }