fleet(tower): 0.18 — Tasks-View (Spool/Dead-Letter/Alarm) + Task-Detail-Modal + /healthz + /api/status; Fleet-Views 0.13-0.18 erstmals versioniert

This commit is contained in:
Hermes CEO
2026-10-30 04:55:35 +00:00
parent fa3d5d0a8f
commit 9e94512214
33 changed files with 3498 additions and 3 deletions
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server"
import { readJournalTail } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/escalations — HITL-/Escalation-Historie (Kernfeature 4):
* Journal-Filter auf type=escalation + rejected-Events (Quarantine).
* Kein psql — Escalations sind Spool-Envelopes, die DB bleibt reiner Index.
*/
export async function GET() {
try {
const tail = readJournalTail(500)
const escalations = tail.filter(
(l) => l.event === "accepted" && l.type === "escalation"
)
const rejected = tail.filter((l) => l.event === "rejected")
return NextResponse.json(
{
escalations: escalations.reverse(),
rejected: rejected.reverse(),
counts: { escalations: escalations.length, rejected: rejected.length },
},
{ headers: { "Cache-Control": "no-store" } }
)
} catch (err) {
return NextResponse.json(
{ error: `FLEET_ESCALATIONS_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+36
View File
@@ -0,0 +1,36 @@
import { NextResponse } from "next/server"
import { mcpCallTool, FLEET_BOARD_MCP_URL, cached } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/kanban — VS-Liste + Kanban je VS (Kernfeature 3) als Proxy
* auf board-service-MCP (get_kanban / list_value_streams).
* Tower schreibt NIE direkt aufs Board-PVC (Single-Writer board-service).
* Cache 3 s (Karten-Statuswechsel erscheinen ohne Reload <=10 s, §8).
*/
export async function GET() {
try {
const data = await cached("fleet-kanban", 3000, async () => {
const vsList = await mcpCallTool(FLEET_BOARD_MCP_URL, "list_value_streams")
if (!vsList.ok) throw new Error(`list_value_streams: ${vsList.error}`)
const vsIds = ((vsList.data as { value_streams?: Array<{ vs_id: string }> }).value_streams || []).map(
(v) => v.vs_id
)
const boards = await Promise.all(
vsIds.map(async (vs) => {
const board = await mcpCallTool(FLEET_BOARD_MCP_URL, "get_kanban", { vs })
if (!board.ok) throw new Error(`get_kanban(${vs}): ${board.error}`)
return { vs, board: board.data }
})
)
return { value_streams: vsIds, boards, generated_at: new Date().toISOString() }
})
return NextResponse.json(data, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `FLEET_KANBAN_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+31
View File
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server"
import { readJournalTail } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/messages?limit=200&cursor=<epoch>
* Rollierendes Spool-Journal (Kernfeature 2): accepted/rejected/run_* je task_id.
* `cursor` = time_epoch des letzten sichtbaren Eintrags; geliefert werden nur
* neuere Eintraege (Aufsteigend), der Client haelt die Liste selbst.
*/
export async function GET(request: Request) {
try {
const url = new URL(request.url)
const limit = Math.min(Number(url.searchParams.get("limit") || 200), 500)
const cursor = Number(url.searchParams.get("cursor") || 0)
const tail = readJournalTail(limit)
const filtered = cursor > 0 ? tail.filter((l) => Number(l.time_epoch || 0) > cursor) : tail
// absteigend fuer die Anzeige (neueste oben), Cursor bleibt epoch-basiert
filtered.reverse()
return NextResponse.json(
{ messages: filtered, count: filtered.length },
{ headers: { "Cache-Control": "no-store" } }
)
} catch (err) {
return NextResponse.json(
{ error: `FLEET_MESSAGES_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+56
View File
@@ -0,0 +1,56 @@
import { NextResponse } from "next/server"
import {
loadOrg,
loadVkMapping,
loadTokenRates,
loadHeartbeatAges,
countInbox,
cached,
} from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/overview — aggregierter Org-Chart-Datensatz (Kernfeature 1).
* Alle Quellen fail-loud: eine tote Quelle -> 500 mit Klartext (Design §5.5),
* KEIN teilweises Rendering mit stillen Nullen.
* Cache 2 s (Views pollen 5 s -> max 1 upstream call je Quelle je Zyklus).
*/
export async function GET() {
try {
const data = await cached("fleet-overview", 2000, async () => {
const [org, vks, rates, hearts] = await Promise.all([
loadOrg(),
loadVkMapping(),
loadTokenRates(),
loadHeartbeatAges(),
])
const inbox = countInbox()
const vkByAgent = new Map(vks.map((v) => [v.agent_id, v]))
const agents = org.members.map((m) => {
const vk = vkByAgent.get(m.agent_id)
const rate = vk ? rates[vk.vk_name] || { in: 0, out: 0 } : { in: 0, out: 0 }
const hbAge = hearts[m.agent_id]
return {
...m,
vk_name: vk?.vk_name || null,
model: vk?.model || null,
profile: vk?.profile || null,
tok_in_per_s: rate.in,
tok_out_per_s: rate.out,
inbox: inbox[m.agent_id] || 0,
heartbeat_age_s: typeof hbAge === "number" ? hbAge : null,
}
})
return { agents, generated_at: new Date().toISOString() }
})
return NextResponse.json(data, {
headers: { "Cache-Control": "no-store" },
})
} catch (err) {
return NextResponse.json(
{ error: `FLEET_OVERVIEW_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+63
View File
@@ -0,0 +1,63 @@
import { NextResponse } from "next/server"
import { mcpCallTool, FLEET_BOARD_MCP_URL, readChatThreads } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/owner/chat — Thread-Liste + Nachrichten (Kernfeature 5).
* POST /api/fleet/owner/chat — neue Owner-Nachricht in einen Thread via
* board-service submit_owner_task (type=chat, thread_id, topic) — der Tower
* schreibt NIE direkt in den Spool (Single-Writer-Disziplin via board-service).
* from=tower-owner, to=ceo; CEO-Antworten erscheinen als ceo->tower-owner?
* NEIN: to muss 9er-Org sein -> CEO-Antworten sind Tasks von ceo mit
* thread_id + reply_to; der Chat-View rendert alle type=chat-Tasks eines
* thread_id unabhaengig von from/to (solange from in 9er-Org oder tower-owner).
*/
export async function GET() {
try {
const threads = readChatThreads()
return NextResponse.json(
{ threads, count: threads.length },
{ headers: { "Cache-Control": "no-store" } }
)
} catch (err) {
return NextResponse.json(
{ error: `OWNER_CHAT_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
export async function POST(request: Request) {
try {
const body = (await request.json()) as { thread_id?: string; topic?: string; message?: string }
const thread_id = String(body.thread_id || "").trim()
const topic = String(body.topic || "").trim()
const message = String(body.message || "").trim()
if (!thread_id || !message) {
return NextResponse.json({ error: "thread_id und message sind Pflicht" }, { status: 400 })
}
const res = await mcpCallTool(FLEET_BOARD_MCP_URL, "submit_owner_task", {
to: "ceo",
type: "chat",
priority: "P3",
topic: topic || thread_id,
thread_id,
body: message,
requires_ack: false,
})
if (!res.ok) {
return NextResponse.json({ error: `submit_owner_task: ${res.error}` }, { status: 500 })
}
return NextResponse.json(res.data, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
getErrLog(err)
}
}
function getErrLog(err: unknown) {
return NextResponse.json(
{ error: `OWNER_CHAT_POST_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
+37
View File
@@ -0,0 +1,37 @@
import { NextResponse } from "next/server"
import { mcpCallTool, FLEET_BOARD_MCP_URL } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* POST /api/fleet/owner/decide — Owner-Entscheidung über einen NAR/Owner-Inbox-Task
* via board-service decide_owner_task (approve|decline). Der Tower schreibt nie
* direkt in den Spool — alles läuft über den board-service (Single-Writer).
* Response enthält folge_task (an den Antragsteller).
*/
export async function POST(request: Request) {
try {
const body = (await request.json()) as { task_id?: string; decision?: string; note?: string }
const task_id = String(body.task_id || "").trim()
const decision = String(body.decision || "").trim()
const note = String(body.note || "")
if (!task_id || !decision) {
return NextResponse.json({ error: "task_id und decision sind Pflicht" }, { status: 400 })
}
const res = await mcpCallTool(FLEET_BOARD_MCP_URL, "decide_owner_task", {
task_id,
decision,
note,
})
if (!res.ok) {
return NextResponse.json({ error: `decide_owner_task: ${res.error}` }, { status: 500 })
}
const payload = typeof res.data === "string" ? JSON.parse(res.data) : res.data
return NextResponse.json(payload, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `OWNER_DECIDE_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+46
View File
@@ -0,0 +1,46 @@
import { NextResponse } from "next/server"
import { mcpCallTool, FLEET_BOARD_MCP_URL } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* POST /api/fleet/owner/idea — Owner-Idee -> board-service add_backlog_card
* (ursprung=owner, immer markiert). Kernfeature 5, E-V3: "Ideen -> VS-Backlog".
* Fail loud: unbekannte VS / ungueltige Werte -> 500 mit Klartext.
*/
export async function POST(request: Request) {
try {
const body = (await request.json()) as {
vs?: string
karte_id?: string
titel?: string
wert?: number
machbarkeit?: number
}
const vs = String(body.vs || "").trim()
const karte_id = String(body.karte_id || "").trim()
const titel = String(body.titel || "").trim()
const wert = Number(body.wert)
const machbarkeit = Number(body.machbarkeit)
if (!vs || !karte_id || !titel) {
return NextResponse.json({ error: "vs, karte_id und titel sind Pflicht" }, { status: 400 })
}
const res = await mcpCallTool(FLEET_BOARD_MCP_URL, "add_backlog_card", {
vs,
karte_id,
titel,
wert,
machbarkeit,
ursprung: "owner",
})
if (!res.ok) {
return NextResponse.json({ error: `add_backlog_card: ${res.error}` }, { status: 500 })
}
return NextResponse.json(res.data, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `OWNER_IDEA_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server"
import { mcpCallTool, FLEET_BOARD_MCP_URL } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/owner/inbox — Owner-Inbox (NAR-Verfahren §1.3):
* Alle Tasks an 'tower-owner' via board-service list_owner_inbox.
* status=submitted = wartet auf Owner-Entscheidung.
*/
export async function GET() {
try {
const res = await mcpCallTool(FLEET_BOARD_MCP_URL, "list_owner_inbox", {})
if (!res.ok) {
return NextResponse.json({ error: `list_owner_inbox: ${res.error}` }, { status: 500 })
}
const payload = typeof res.data === "string" ? JSON.parse(res.data) : res.data
return NextResponse.json(payload, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `OWNER_INBOX_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+38
View File
@@ -0,0 +1,38 @@
import { NextResponse } from "next/server"
import { mcpCallTool, FLEET_BOARD_MCP_URL } from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* POST /api/fleet/owner/new-vs — "Neuer Value Stream" -> CEO-Task (type=build, P2)
* via board-service submit_owner_task (neuer Tool, Phase 0.13). E-V3:
* Owner-Chat verdraengt nie den Task-Flow; VS-Gruendung ist ein formaler Task.
* Fail loud bei unbekanntem CEO oder Spool-Fehler.
*/
export async function POST(request: Request) {
try {
const body = (await request.json()) as { topic?: string; ziel?: string }
const topic = String(body.topic || "").trim()
const ziel = String(body.ziel || "").trim()
if (!topic || topic.length > 200) {
return NextResponse.json({ error: "topic Pflicht (max 200 Zeichen)" }, { status: 400 })
}
const res = await mcpCallTool(FLEET_BOARD_MCP_URL, "submit_owner_task", {
to: "ceo",
type: "build",
priority: "P2",
topic,
body: ziel || topic,
requires_ack: true,
})
if (!res.ok) {
return NextResponse.json({ error: `submit_owner_task: ${res.error}` }, { status: 500 })
}
return NextResponse.json(res.data, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `OWNER_NEW_VS_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+65
View File
@@ -0,0 +1,65 @@
import { NextResponse } from "next/server"
import {
loadOrg,
loadSandboxFacts,
loadHeartbeatAges,
cached,
} from "@/app/lib/fleet/fleetSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/sandboxes — fleet-native Sandbox-View (Kernfeature-Ergänzung,
* Design §2 Datenquellen-Adapter). Zeigt die K8s-Realität der 9 Agenten-Sandboxes:
* Phase, Restarts, Age, Node, Requests, Image-Digest (kube-state-metrics via
* Prometheus) + Worker-/Heartbeat-Status aus Spool/Beacon.
* KEIN kubectl / KEINE Host-CLI im Tower (macOS-Design des Upstream ersetzt).
* Fail-loud: tote Quelle -> 500 mit Klartext, kein stilles Leeren (§5.5).
* Cache 2 s (View pollt 5 s -> max 1 Upstream-Call je Quelle je Zyklus).
*/
export async function GET() {
try {
const data = await cached("fleet-sandboxes", 2000, async () => {
const [org, facts, hearts] = await Promise.all([
loadOrg(),
loadSandboxFacts(),
loadHeartbeatAges(),
])
const sandboxByAgent = new Map(facts.sandboxes.map((s) => [s.agent_id, s]))
const agents = org.members.map((m) => {
const sb = sandboxByAgent.get(m.agent_id)
const hbAge = hearts[m.agent_id]
return {
agent_id: m.agent_id,
role: m.role,
title: m.title ?? null,
exists: Boolean(sb),
phase: sb?.phase ?? null,
ready: sb?.ready ?? null,
restarts: sb?.restarts ?? null,
pod_age_s: sb?.pod_age_s ?? null,
node: sb?.node ?? null,
cpu_request_milli: sb?.cpu_request_milli ?? null,
mem_request_mb: sb?.mem_request_mb ?? null,
image_digest: sb?.image_digest ?? null,
heartbeat_age_s: typeof hbAge === "number" ? hbAge : null,
}
})
const healthy =
facts.sandboxes.length === org.members.length &&
facts.sandboxes.every((s) => s.phase === "Running" && s.ready)
return {
agents,
fleet_image_digest: facts.fleet_image_digest,
all_running: healthy,
generated_at: new Date().toISOString(),
}
})
return NextResponse.json(data, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `FLEET_SANDBOXES_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from "next/server"
import { getTaskDetail } from "@/app/lib/fleet/taskSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/task-detail?id=<task_id>[&kind=spool|dead-letter|alarm]
* Voller Task-Envelope fuer die Detailansicht (Karte tower-task-detail).
*
* Garantien aus der Change-Order: nie 5xx fuer unbekannte/leere ids (found:false),
* fehlende Felder als "-", Body unveraendert. Nur ein kaputter Lesepfad liefert
* degraded:true mit 200 — die Ansicht bleibt bedienbar.
*/
export async function GET(req: Request) {
const url = new URL(req.url)
const id = (url.searchParams.get("id") || "").trim()
const kind = (url.searchParams.get("kind") || "").trim()
try {
const data = getTaskDetail(id, kind)
return NextResponse.json(data, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `FLEET_TASK_DETAIL_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+26
View File
@@ -0,0 +1,26 @@
import { NextResponse } from "next/server"
import { loadTaskOverview } from "@/app/lib/fleet/taskSource"
export const dynamic = "force-dynamic"
/**
* GET /api/fleet/tasks — Listen der Task-Detail-Ansicht (Karte tower-task-detail).
* Liefert Spool-Reifegrad (offene Envelopes), Dead-Letter (failed, 7 Tage) und
* Alarm-Feed (Stoerungsereignisse aus dem Journal) in einem Datensatz.
* Cache 10 s (Panel pollt 30 s).
*
* Abweichung zur Change-Order: Pfad /api/fleet/tasks statt /api/spool|/api/alarm-feed
* — konsistent mit den uebrigen Fleet-Routen (/api/fleet/overview, /sandboxes, ...).
* Degradierte Quelle -> 200 mit degraded:true (Panel zeigt Banner statt Crash).
*/
export async function GET() {
try {
const data = loadTaskOverview()
return NextResponse.json(data, { headers: { "Cache-Control": "no-store" } })
} catch (err) {
return NextResponse.json(
{ error: `FLEET_TASKS_FAILED: ${err instanceof Error ? err.message : String(err)}` },
{ status: 500 }
)
}
}
+60
View File
@@ -0,0 +1,60 @@
import { NextResponse } from "next/server"
import { probe, uptimeSeconds, TOWER_VERSION } from "@/app/lib/fleet/health"
import {
FLEET_BEACON_URL,
FLEET_PROM_URL,
FLEET_SPOOL_DIR,
loadOrg,
} from "@/app/lib/fleet/fleetSource"
import { existsSync } from "node:fs"
export const dynamic = "force-dynamic"
/**
* GET /api/status — maschinenlesbarer Betriebszustand (Karte it1-tower-03).
* Version, Uptime, Datenquellen-Zustand mit Latenz + Klartext-Fehler.
* Immer 200 (Monitoring braucht eine Antwort); Degradation steht im Body.
*/
export async function GET() {
const t0 = Date.now()
let orgOk = false
let orgError = ""
try {
const org = loadOrg()
orgOk = org.members.length > 0
} catch (e) {
orgError = e instanceof Error ? e.message : String(e)
}
const [prom, beacon] = await Promise.all([
probe(`${FLEET_PROM_URL}/-/healthy`),
probe(`${FLEET_BEACON_URL}/metrics`),
])
const sources = {
spool: {
ok: existsSync(FLEET_SPOOL_DIR),
latency_ms: 0,
error: existsSync(FLEET_SPOOL_DIR) ? "" : `fehlt: ${FLEET_SPOOL_DIR}`,
},
org_yaml: { ok: orgOk, latency_ms: 0, error: orgError },
prometheus: prom,
beacon: beacon,
}
const coreOk = sources.spool.ok && sources.org_yaml.ok
const allOk = coreOk && prom.ok && beacon.ok
return NextResponse.json(
{
status: allOk ? "ok" : coreOk ? "degraded" : "down",
version: TOWER_VERSION,
uptime_seconds: uptimeSeconds(),
generated_at: new Date().toISOString(),
response_ms: Date.now() - t0,
sources,
},
{ headers: { "Cache-Control": "no-store" } }
)
}