import express from "express"; import { acknowledgeAgentMessage, enrichStoryEvidenceDocuments, getOpportunity, getStoryThread, listAgentMessages, listOpportunities, listStoryThreads, markOpportunity, markStoryThreadStatus, migrate, pool, seedInitialStoryThread, seedSources } from "./db.js"; import { beginWebLogin, finishWebLogin, logoutWeb, protectedResourceMetadata, requireMcpAuth, requireWebAuth } from "./auth.js"; import { handleMcp } from "./mcp.js"; import { SOURCES } from "./sources.js"; import { syncAll } from "./sync.js"; const app = express(); app.set("trust proxy", true); app.use(express.json({ limit: "2mb" })); app.use(express.urlencoded({ extended: false })); function escapeHtml(value: unknown) { return String(value ?? "") .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } function nzTime(value: unknown) { if (!value) return ""; try { return new Intl.DateTimeFormat("en-NZ", { timeZone: "Pacific/Auckland", dateStyle: "medium", timeStyle: "short" }).format(new Date(String(value))); } catch { return String(value); } } function storyGraphSvg(story: any) { const nodes = Array.isArray(story.nodes) ? story.nodes : []; const edges = Array.isArray(story.edges) ? story.edges : []; const width = 1000; const height = 640; const cx = width / 2; const cy = height / 2 + 20; const rx = 390; const ry = 235; const positions = new Map(); nodes.forEach((node: any, index: number) => { const angle = -Math.PI / 2 + (Math.PI * 2 * index) / Math.max(nodes.length, 1); positions.set(node.id, { x: cx + Math.cos(angle) * rx, y: cy + Math.sin(angle) * ry }); }); const edgeSvg = edges.map((edge: any) => { const from = positions.get(edge.from_node_id); const to = positions.get(edge.to_node_id); if (!from || !to) return ""; const mx = (from.x + to.x) / 2; const my = (from.y + to.y) / 2; return ` ${escapeHtml(edge.relationship)} `; }).join(""); const nodeSvg = nodes.map((node: any) => { const p = positions.get(node.id)!; const title = String(node.title ?? ""); const short = title.length > 36 ? title.slice(0, 33) + "…" : title; return ` ${escapeHtml(node.title)} — ${escapeHtml(node.node_type)} ${escapeHtml(node.node_type)} ${escapeHtml(short)} `; }).join(""); return ` STORY THREAD ${escapeHtml(String(story.title).slice(0, 38))} ${edgeSvg} ${nodeSvg} `; } app.get("/health", async (_req, res) => { try { await pool.query("SELECT 1"); res.json({ ok: true, service: "media-intelligence", version: "0.1.0" }); } catch (error) { res.status(503).json({ ok: false, error: error instanceof Error ? error.message : String(error) }); } }); app.get("/ready", async (_req, res) => { try { const result = await pool.query( `SELECT s.id, s.name, s.last_synced_at, s.last_error, COUNT(sig.id)::int AS signal_count FROM sources s LEFT JOIN signals sig ON sig.source_id=s.id GROUP BY s.id,s.name,s.last_synced_at,s.last_error,s.baseline_complete ORDER BY s.id` ); const missing = result.rows .filter((row: any) => Number(row.signal_count) < 1) .map((row: any) => row.id); const errored = result.rows .filter((row: any) => row.last_error) .map((row: any) => row.id); if (missing.length || errored.length) { return res.status(503).json({ ok: false, missing_sources: missing, errored_sources: errored, sources: result.rows }); } return res.json({ ok: true, sources: result.rows }); } catch (error) { return res.status(503).json({ ok: false, error: error instanceof Error ? error.message : String(error) }); } }); app.get("/.well-known/oauth-protected-resource", (req, res) => res.json(protectedResourceMetadata(req)) ); app.get("/.well-known/oauth-protected-resource/api/mcp", (req, res) => res.json(protectedResourceMetadata(req)) ); app.get("/auth/login", beginWebLogin); app.get("/auth/callback", finishWebLogin); app.get("/auth/logout", logoutWeb); app.post("/api/mcp", requireMcpAuth, handleMcp); app.get("/api/mcp", requireMcpAuth, (_req, res) => { res.status(405).setHeader("Allow", "POST").json({ error: "Use POST for MCP JSON-RPC requests" }); }); app.post("/stories/:id/status", requireWebAuth, async (req, res) => { const user = (req as any).user ?? {}; const identity = String(user.preferred_username ?? user.email ?? user.name ?? user.sub ?? "web-user"); try { await markStoryThreadStatus(String(req.params.id), String(req.body.status ?? ""), `web:${identity}`); return res.redirect(`/stories/${encodeURIComponent(String(req.params.id))}`); } catch (error) { return res.status(400).type("text").send(error instanceof Error ? error.message : String(error)); } }); app.get("/stories/:id", requireWebAuth, async (req, res) => { const story = await getStoryThread(String(req.params.id)); if (!story) return res.status(404).send("Story thread not found"); const user = (req as any).user ?? {}; const identity = user.name || user.preferred_username || user.email || "Signed-in user"; const nodes = Array.isArray(story.nodes) ? story.nodes : []; const edges = Array.isArray(story.edges) ? story.edges : []; const checks = Array.isArray(story.research_checks) ? story.research_checks : []; const counter = checks.find((c:any)=>c.check_type === "counter_evidence"); res.type("html").send(` ${escapeHtml(story.title)} — Story Research
← Story Threads

${escapeHtml(story.title)}

${escapeHtml(story.question)}

${escapeHtml(identity)} · Sign out
Status: ${escapeHtml(story.status)} · Nodes: ${nodes.length} · Edges: ${edges.length}
${["researching","review","develop","closed"].map(s=>`
`).join("")}
Mandatory counter-evidence pass: ${counter ? `${escapeHtml(counter.result)} · sources checked: ${escapeHtml((counter.sources_checked ?? []).join(", "))}

${escapeHtml(counter.summary)}

` : "not completed"}
${storyGraphSvg(story)}

Research nodes

${nodes.map((n:any)=>`
${escapeHtml(n.node_type)}

${escapeHtml(n.title)}

${escapeHtml(n.summary)}

${n.provenance_source_id ? `source ${escapeHtml(n.provenance_source_id)} · ` : ""}${n.confidence != null ? `confidence ${escapeHtml(n.confidence)} · ` : ""}${escapeHtml(n.created_by_name)}
${n.evidence_url ? `

Open evidence ↗

` : ""}
`).join("")}

Relationships

${edges.length ? edges.map((e:any)=>`
${escapeHtml(e.relationship)}
${escapeHtml(e.from_node_id.slice(0,8))} → ${escapeHtml(e.to_node_id.slice(0,8))}

${escapeHtml(e.reason)}

`).join("") : '
No graph edges yet.
'} `); }); app.get("/stories", requireWebAuth, async (req, res) => { const stories = await listStoryThreads({ limit: 100 }); const user = (req as any).user ?? {}; const identity = user.name || user.preferred_username || user.email || "Signed-in user"; res.type("html").send(` Story Threads — Media Intelligence
← Dashboard

360° Story Threads

Evidence networks that require an explicit counter-evidence pass before editorial review.

${escapeHtml(identity)} · Sign out
${stories.length ? stories.map((s:any)=>`
${escapeHtml(s.title)}

${escapeHtml(s.question)}

${escapeHtml(s.status)} · ${s.node_count} nodes · ${s.edge_count} edges · counter-evidence: ${escapeHtml(s.counter_evidence_result ?? "pending")}
`).join("") : '
No story threads yet.
'} `); }); app.post("/messages/:id/ack", requireWebAuth, async (req, res) => { const user = (req as any).user ?? {}; const identity = String( user.preferred_username ?? user.email ?? user.name ?? user.sub ?? "web-user" ); await acknowledgeAgentMessage(String(req.params.id), `web:${identity}`); return res.redirect("/"); }); app.post("/opportunities/:id/status", requireWebAuth, async (req, res) => { const id = String(req.params.id); const status = String(req.body.status ?? ""); await markOpportunity(id, status); return res.redirect(req.body.returnTo === "detail" ? `/opportunities/${encodeURIComponent(id)}` : "/opportunities"); }); app.get("/opportunities/:id", requireWebAuth, async (req, res) => { const opportunity = await getOpportunity(String(req.params.id)); if (!opportunity) return res.status(404).send("Opportunity not found"); const user = (req as any).user ?? {}; const identity = user.name || user.preferred_username || user.email || "Signed-in user"; const evidence = Array.isArray(opportunity.evidence) ? opportunity.evidence : []; const notes = Array.isArray(opportunity.notes) ? opportunity.notes : []; res.type("html").send(` ${escapeHtml(opportunity.title)} — Media Intelligence
← Opportunities

${escapeHtml(opportunity.title)}

${escapeHtml(identity)} · Sign out
${escapeHtml(opportunity.source_id)} · ${escapeHtml(nzTime(opportunity.published_at || opportunity.detected_at))}

${escapeHtml(opportunity.summary)}

Status: ${escapeHtml(opportunity.status)} · Score: ${escapeHtml(opportunity.score)}

Why surfaced: ${escapeHtml((opportunity.reasons ?? []).join(" · "))}

Open original source ↗

${["watch","investigate","develop","ignore","closed"].map(status=>`
`).join("")}

Evidence

${evidence.length ? evidence.map((e:any)=>`
${escapeHtml(nzTime(e.retrieved_at))} · ${escapeHtml(e.content_hash?.slice(0,12))}
${escapeHtml(e.excerpt)}
Source ↗
`).join("") : '
No evidence stored.
'}

Notes

${notes.length ? notes.map((n:any)=>`
${escapeHtml(nzTime(n.created_at))}

${escapeHtml(n.note)}

`).join("") : '
No notes yet.
'} `); }); app.get("/opportunities", requireWebAuth, async (req, res) => { const requested = String(req.query.status ?? ""); const valid = new Set(["new","watch","investigate","develop","ignore","closed"]); const status = valid.has(requested) ? requested : undefined; const opportunities = await listOpportunities({ status, limit: 100 }); const user = (req as any).user ?? {}; const identity = user.name || user.preferred_username || user.email || "Signed-in user"; res.type("html").send(` Opportunities — Media Intelligence
← Dashboard

Media Opportunities

Human triage queue. No release drafting or distribution happens here.

${escapeHtml(identity)} · Sign out
Active ${["new","watch","investigate","develop","ignore","closed"].map(s=>`${s}`).join("")}
${opportunities.length ? opportunities.map((o:any)=>`
${escapeHtml(o.title)}
${escapeHtml(o.source_id)} · ${escapeHtml(nzTime(o.published_at || o.detected_at))} · status ${escapeHtml(o.status)} · score ${escapeHtml(o.score)}

${escapeHtml(o.summary)}

${escapeHtml((o.reasons ?? []).join(" · "))}
${["watch","investigate","develop","ignore"].map(s=>`
`).join("")}
`).join("") : '
No opportunities in this view.
'} `); }); app.get("/", requireWebAuth, async (req, res) => { const sourceRows = await pool.query( `SELECT s.id,s.name,s.last_synced_at,s.last_error,s.baseline_complete, COUNT(sig.id)::int AS signal_count FROM sources s LEFT JOIN signals sig ON sig.source_id=s.id GROUP BY s.id,s.name,s.last_synced_at,s.last_error,s.baseline_complete ORDER BY s.id` ); const counts = await pool.query(` SELECT (SELECT COUNT(*) FROM signals) AS signals, (SELECT COUNT(*) FROM opportunities WHERE status <> 'closed') AS opportunities, (SELECT COUNT(*) FROM opportunities WHERE status='new') AS new_opportunities, (SELECT COUNT(*) FROM agent_messages WHERE acknowledged_at IS NULL) AS unread_messages, (SELECT COUNT(*) FROM story_threads WHERE status <> 'closed') AS story_threads `); const messages = await listAgentMessages({ acknowledged: false, limit: 10 }); const c = counts.rows[0] ?? {}; const user = (req as any).user ?? {}; const identity = user.name || user.preferred_username || user.email || "Signed-in user"; res.type("html").send(` Media Intelligence

Media Intelligence MVP

Human-led NZ public-source monitoring behind a dedicated MCP.

Open Opportunities → · Open 360° Story Threads →

${escapeHtml(identity)}
Sign out
${c.signals ?? 0}signals
${c.opportunities ?? 0}opportunities
${c.new_opportunities ?? 0}new
${c.unread_messages ?? 0}agent messages
${c.story_threads ?? 0}story threads

Agent Activity

${messages.length ? messages.map((m:any)=>`
${escapeHtml(m.title)}
${escapeHtml(m.kind)} · ${escapeHtml(m.severity)}
${escapeHtml(nzTime(m.created_at))}

${escapeHtml(m.body)}

From ${escapeHtml(m.actor_name)} via ${escapeHtml(m.actor_client_id)}${m.related_type ? ` · ${escapeHtml(m.related_type)} ${escapeHtml(m.related_id ?? "")}` : ""}
`).join("") : '
No unread agent messages.
'}

Sources

${sourceRows.rows.map((s:any)=>`
${s.name}
${s.id} · ${s.baseline_complete ? 'baseline ready' : 'awaiting baseline'}
${s.signal_count} stored signals
${s.last_error ? 'Error: '+s.last_error : (s.last_synced_at ? 'Last sync '+new Date(s.last_synced_at).toLocaleString() : 'Waiting for first sync')}
`).join("")}

MCP endpoint: /api/mcp — OAuth protected separately from this browser session.

`); }); async function start() { await migrate(); await seedSources(SOURCES); await seedInitialStoryThread(); const port = Number(process.env.PORT ?? 3000); app.listen(port, "0.0.0.0", () => { console.log(JSON.stringify({ event: "server_started", port, version: "0.1.0" })); }); const intervalMinutes = Math.max( Number(process.env.SYNC_INTERVAL_MINUTES ?? 15), 5 ); setTimeout( () => enrichStoryEvidenceDocuments() .then((result) => console.log(JSON.stringify({ event: "story_evidence_enrichment", result })) ) .catch((error) => console.error(error)), 2500 ); setTimeout( () => syncAll() .then((r) => console.log(JSON.stringify({ event: "initial_sync", result: r })) ) .catch((e) => console.error(e)), 5000 ); setInterval( () => syncAll() .then((r) => console.log(JSON.stringify({ event: "scheduled_sync", result: r })) ) .catch((e) => console.error(e)), intervalMinutes * 60_000 ); } start().catch((error) => { console.error(error); process.exit(1); });