mergen-server 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/LICENSE +57 -0
  2. package/README.md +96 -0
  3. package/dist/__stubs__/calibration.js +471 -0
  4. package/dist/__stubs__/causal.js +601 -0
  5. package/dist/__stubs__/closed-source.js +150 -0
  6. package/dist/__stubs__/license.js +35 -0
  7. package/dist/__stubs__/plans.js +197 -0
  8. package/dist/app.js +467 -0
  9. package/dist/cli.js +250 -0
  10. package/dist/commands/agent-identity.js +79 -0
  11. package/dist/commands/gate.js +107 -0
  12. package/dist/commands/github.js +632 -0
  13. package/dist/commands/incident.js +644 -0
  14. package/dist/commands/policy.js +710 -0
  15. package/dist/commands/scan.js +243 -0
  16. package/dist/commands/setup.js +1218 -0
  17. package/dist/commands/shared.js +109 -0
  18. package/dist/commands/team.js +809 -0
  19. package/dist/datadog/blame-attribution.js +228 -0
  20. package/dist/datadog/client.js +159 -0
  21. package/dist/datadog/compactor.js +169 -0
  22. package/dist/datadog/fingerprinter.js +34 -0
  23. package/dist/datadog/incident-state.js +21 -0
  24. package/dist/datadog/line-matcher.js +56 -0
  25. package/dist/datadog/memory-store.js +399 -0
  26. package/dist/datadog/otel-trace.js +67 -0
  27. package/dist/index.js +505 -0
  28. package/dist/intelligence/action-risk.js +132 -0
  29. package/dist/intelligence/activity-feed.js +40 -0
  30. package/dist/intelligence/agent-identity.js +115 -0
  31. package/dist/intelligence/agent-pipeline.js +329 -0
  32. package/dist/intelligence/agent-profiles.js +81 -0
  33. package/dist/intelligence/ai-commit.js +16 -0
  34. package/dist/intelligence/approval-analytics.js +42 -0
  35. package/dist/intelligence/approval-events.js +5 -0
  36. package/dist/intelligence/arch-boundaries.js +94 -0
  37. package/dist/intelligence/arch-graph.js +117 -0
  38. package/dist/intelligence/autonomy.js +397 -0
  39. package/dist/intelligence/azure-broker.js +57 -0
  40. package/dist/intelligence/azure-proxy-sessions.js +49 -0
  41. package/dist/intelligence/baseline.js +1 -0
  42. package/dist/intelligence/behavior-baseline.js +134 -0
  43. package/dist/intelligence/billing.js +1 -0
  44. package/dist/intelligence/blast-radius.js +224 -0
  45. package/dist/intelligence/bypass.js +157 -0
  46. package/dist/intelligence/calibration-classifier.js +77 -0
  47. package/dist/intelligence/calibration-git-sync.js +74 -0
  48. package/dist/intelligence/calibration.js +1 -0
  49. package/dist/intelligence/cascade-detector.js +58 -0
  50. package/dist/intelligence/case-study-generator.js +126 -0
  51. package/dist/intelligence/causal-graph.js +126 -0
  52. package/dist/intelligence/causal.js +1 -0
  53. package/dist/intelligence/change-risk.js +102 -0
  54. package/dist/intelligence/compliance-report.js +134 -0
  55. package/dist/intelligence/confidence-report.js +85 -0
  56. package/dist/intelligence/corpus-to-policy.js +140 -0
  57. package/dist/intelligence/credential-broker.js +112 -0
  58. package/dist/intelligence/credential-misuse.js +39 -0
  59. package/dist/intelligence/debug-sessions.js +108 -0
  60. package/dist/intelligence/decision-escalation.js +36 -0
  61. package/dist/intelligence/decision-memory.js +47 -0
  62. package/dist/intelligence/decision-similarity.js +85 -0
  63. package/dist/intelligence/default-safety-tests.js +53 -0
  64. package/dist/intelligence/degradation-watcher.js +108 -0
  65. package/dist/intelligence/detector-plugins.js +70 -0
  66. package/dist/intelligence/detectors.js +1 -0
  67. package/dist/intelligence/device-auth.js +138 -0
  68. package/dist/intelligence/diff-size.js +42 -0
  69. package/dist/intelligence/ebpf-verify.js +45 -0
  70. package/dist/intelligence/enterprise-policy-engine.js +1122 -0
  71. package/dist/intelligence/error-fingerprint.js +1 -0
  72. package/dist/intelligence/execution-gate.js +100 -0
  73. package/dist/intelligence/execution-mode.js +22 -0
  74. package/dist/intelligence/gate-analytics.js +256 -0
  75. package/dist/intelligence/gate-decision.js +64 -0
  76. package/dist/intelligence/gcp-broker.js +50 -0
  77. package/dist/intelligence/git-adr-sync.js +207 -0
  78. package/dist/intelligence/hitl-hold.js +460 -0
  79. package/dist/intelligence/hypothesis-history.js +93 -0
  80. package/dist/intelligence/idp-identity.js +83 -0
  81. package/dist/intelligence/impl-critic.js +216 -0
  82. package/dist/intelligence/incident-autopilot.js +622 -0
  83. package/dist/intelligence/incident-replay.js +162 -0
  84. package/dist/intelligence/incident-result-cache.js +33 -0
  85. package/dist/intelligence/incident-similarity.js +58 -0
  86. package/dist/intelligence/infra-detectors.js +312 -0
  87. package/dist/intelligence/license.js +185 -0
  88. package/dist/intelligence/llm-spokesperson.js +62 -0
  89. package/dist/intelligence/mcp-prompts.js +320 -0
  90. package/dist/intelligence/mcp-resources.js +171 -0
  91. package/dist/intelligence/normalize.js +108 -0
  92. package/dist/intelligence/notifications.js +83 -0
  93. package/dist/intelligence/oidc-issuer.js +87 -0
  94. package/dist/intelligence/override-corpus.js +597 -0
  95. package/dist/intelligence/planning-gate.js +84 -0
  96. package/dist/intelligence/plans.js +223 -0
  97. package/dist/intelligence/platt-scaling.js +164 -0
  98. package/dist/intelligence/policy-proposals.js +84 -0
  99. package/dist/intelligence/policy-suggester.js +161 -0
  100. package/dist/intelligence/policy-sync.js +103 -0
  101. package/dist/intelligence/policy-test-runner.js +35 -0
  102. package/dist/intelligence/postmortem-parser.js +181 -0
  103. package/dist/intelligence/postmortem-retrieval.js +224 -0
  104. package/dist/intelligence/postmortem-store.js +596 -0
  105. package/dist/intelligence/pr-commenter.js +81 -0
  106. package/dist/intelligence/pr-policy-gate.js +38 -0
  107. package/dist/intelligence/pr-shadow-analyzer.js +229 -0
  108. package/dist/intelligence/process-tree.js +108 -0
  109. package/dist/intelligence/prompts.js +1 -0
  110. package/dist/intelligence/replay.js +38 -0
  111. package/dist/intelligence/repro-steps.js +1 -0
  112. package/dist/intelligence/resource-extractors.js +0 -0
  113. package/dist/intelligence/resource-file-context.js +138 -0
  114. package/dist/intelligence/risk-score.js +22 -0
  115. package/dist/intelligence/rollback.js +137 -0
  116. package/dist/intelligence/runbook-updater.js +143 -0
  117. package/dist/intelligence/sandbox.js +194 -0
  118. package/dist/intelligence/script-trust.js +104 -0
  119. package/dist/intelligence/session-metrics.js +67 -0
  120. package/dist/intelligence/session-threat-tracker.js +231 -0
  121. package/dist/intelligence/shadow-digest-cron.js +81 -0
  122. package/dist/intelligence/shadow-log.js +284 -0
  123. package/dist/intelligence/shell-ast.js +145 -0
  124. package/dist/intelligence/siem-forward.js +104 -0
  125. package/dist/intelligence/slack-digest.js +151 -0
  126. package/dist/intelligence/slack-override-loop.js +217 -0
  127. package/dist/intelligence/slack-routing.js +67 -0
  128. package/dist/intelligence/slack.js +900 -0
  129. package/dist/intelligence/sql-ast.js +31 -0
  130. package/dist/intelligence/team.js +1 -0
  131. package/dist/intelligence/telemetry.js +76 -0
  132. package/dist/intelligence/threshold-optimizer.js +75 -0
  133. package/dist/intelligence/token-budget.js +66 -0
  134. package/dist/intelligence/tool-guard.js +708 -0
  135. package/dist/intelligence/tool-manifest 2.js +74 -0
  136. package/dist/intelligence/tool-manifest.js +125 -0
  137. package/dist/intelligence/tools-analysis.js +857 -0
  138. package/dist/intelligence/tools-arch.js +152 -0
  139. package/dist/intelligence/tools-autonomy.js +495 -0
  140. package/dist/intelligence/tools-blast-radius.js +140 -0
  141. package/dist/intelligence/tools-browser.js +431 -0
  142. package/dist/intelligence/tools-change-timeline.js +154 -0
  143. package/dist/intelligence/tools-credentials.js +117 -0
  144. package/dist/intelligence/tools-datadog.js +233 -0
  145. package/dist/intelligence/tools-debug-sessions.js +209 -0
  146. package/dist/intelligence/tools-discovery.js +284 -0
  147. package/dist/intelligence/tools-infra.js +612 -0
  148. package/dist/intelligence/tools-intent.js +128 -0
  149. package/dist/intelligence/tools-memory.js +514 -0
  150. package/dist/intelligence/tools-runbook.js +951 -0
  151. package/dist/intelligence/tools-sessions.js +107 -0
  152. package/dist/intelligence/tools-state.js +232 -0
  153. package/dist/intelligence/tools-utility.js +430 -0
  154. package/dist/intelligence/tools-validate.js +215 -0
  155. package/dist/intelligence/tools.js +1 -0
  156. package/dist/intelligence/trace-context.js +11 -0
  157. package/dist/intelligence/unclassified-clusters.js +87 -0
  158. package/dist/intelligence/usage.js +195 -0
  159. package/dist/routes/active-authors.js +63 -0
  160. package/dist/routes/activity-feed.js +21 -0
  161. package/dist/routes/adr.js +117 -0
  162. package/dist/routes/agent-activity.js +184 -0
  163. package/dist/routes/agent-blunders.js +163 -0
  164. package/dist/routes/agents.js +175 -0
  165. package/dist/routes/api-keys.js +65 -0
  166. package/dist/routes/arch.js +75 -0
  167. package/dist/routes/audit-export.js +93 -0
  168. package/dist/routes/billing-dashboard.js +158 -0
  169. package/dist/routes/billing-outcome.js +77 -0
  170. package/dist/routes/calibration.js +305 -0
  171. package/dist/routes/ci-gate-history.js +20 -0
  172. package/dist/routes/ci-gate.js +232 -0
  173. package/dist/routes/ci.js +293 -0
  174. package/dist/routes/compliance-report.js +24 -0
  175. package/dist/routes/confidence.js +30 -0
  176. package/dist/routes/credentials.js +119 -0
  177. package/dist/routes/dashboard.js +1407 -0
  178. package/dist/routes/decision-memory.js +42 -0
  179. package/dist/routes/demo.js +844 -0
  180. package/dist/routes/device-auth-stub.js +173 -0
  181. package/dist/routes/explain-why.js +39 -0
  182. package/dist/routes/gate-analytics.js +213 -0
  183. package/dist/routes/gate.js +28 -0
  184. package/dist/routes/github-webhook.js +364 -0
  185. package/dist/routes/habituation.js +30 -0
  186. package/dist/routes/health-integrations.js +243 -0
  187. package/dist/routes/heartbeats.js +45 -0
  188. package/dist/routes/hitl.js +364 -0
  189. package/dist/routes/impact-report.js +645 -0
  190. package/dist/routes/incident-webhook.js +63 -0
  191. package/dist/routes/incidents.js +366 -0
  192. package/dist/routes/layers.js +62 -0
  193. package/dist/routes/license.js +187 -0
  194. package/dist/routes/oidc-issuer.js +30 -0
  195. package/dist/routes/onboarding.js +170 -0
  196. package/dist/routes/otel.js +67 -0
  197. package/dist/routes/otlp-receiver.js +179 -0
  198. package/dist/routes/overrides.js +241 -0
  199. package/dist/routes/pagerduty.js +258 -0
  200. package/dist/routes/policies.js +809 -0
  201. package/dist/routes/policy-nl.js +169 -0
  202. package/dist/routes/postmortem.js +102 -0
  203. package/dist/routes/pr-shadow.js +47 -0
  204. package/dist/routes/rbac.js +61 -0
  205. package/dist/routes/replay.js +17 -0
  206. package/dist/routes/risk-report.js +164 -0
  207. package/dist/routes/runbooks.js +125 -0
  208. package/dist/routes/safety-test.js +174 -0
  209. package/dist/routes/sdk.js +222 -0
  210. package/dist/routes/sensor.js +819 -0
  211. package/dist/routes/sentry.js +140 -0
  212. package/dist/routes/sessions.js +43 -0
  213. package/dist/routes/setup-ui.js +594 -0
  214. package/dist/routes/shadow-report.js +107 -0
  215. package/dist/routes/slack-routing.js +171 -0
  216. package/dist/routes/team-usage.js +71 -0
  217. package/dist/routes/telemetry.js +28 -0
  218. package/dist/routes/tenants.js +199 -0
  219. package/dist/routes/tickets.js +167 -0
  220. package/dist/routes/validate.js +13 -0
  221. package/dist/routes/war-room.js +113 -0
  222. package/dist/scripts/check-arch.js +22 -0
  223. package/dist/seeds/community-corpus.js +176 -0
  224. package/dist/seeds/corpus.js +1224 -0
  225. package/dist/sensor/action-ledger.js +327 -0
  226. package/dist/sensor/adr-store.js +140 -0
  227. package/dist/sensor/agent-blunder-store.js +370 -0
  228. package/dist/sensor/agent-context-store.js +225 -0
  229. package/dist/sensor/agent-memory-store.js +231 -0
  230. package/dist/sensor/audit-fetch.js +23 -0
  231. package/dist/sensor/audit-log.js +273 -0
  232. package/dist/sensor/buffer-schemas.js +225 -0
  233. package/dist/sensor/buffer.js +599 -0
  234. package/dist/sensor/bypass-tracker.js +93 -0
  235. package/dist/sensor/ci-gate-history.js +70 -0
  236. package/dist/sensor/cloud-auth.js +183 -0
  237. package/dist/sensor/commit-context-store.js +235 -0
  238. package/dist/sensor/docker-log-stream.js +164 -0
  239. package/dist/sensor/docker-monitor.js +122 -0
  240. package/dist/sensor/extended-buffer.js +46 -0
  241. package/dist/sensor/feedback-token.js +41 -0
  242. package/dist/sensor/file-lock.js +6 -0
  243. package/dist/sensor/fs-watcher.js +106 -0
  244. package/dist/sensor/gate-heartbeat.js +122 -0
  245. package/dist/sensor/git-suspect.js +136 -0
  246. package/dist/sensor/habituation-store.js +77 -0
  247. package/dist/sensor/heartbeat-monitor.js +133 -0
  248. package/dist/sensor/incident-store.js +340 -0
  249. package/dist/sensor/infra-normalizer.js +513 -0
  250. package/dist/sensor/ingest.js +339 -0
  251. package/dist/sensor/jest-reporter.js +52 -0
  252. package/dist/sensor/k8s-events.js +132 -0
  253. package/dist/sensor/layer2-store.js +111 -0
  254. package/dist/sensor/layer3-store.js +230 -0
  255. package/dist/sensor/layer4-store.js +147 -0
  256. package/dist/sensor/logger.js +13 -0
  257. package/dist/sensor/otel-exporter.js +161 -0
  258. package/dist/sensor/paths.js +71 -0
  259. package/dist/sensor/policy-history.js +147 -0
  260. package/dist/sensor/pr-shadow-store.js +83 -0
  261. package/dist/sensor/process-watcher.js +162 -0
  262. package/dist/sensor/rbac.js +92 -0
  263. package/dist/sensor/redact.js +114 -0
  264. package/dist/sensor/redis-store.js +191 -0
  265. package/dist/sensor/route-reachability.js +64 -0
  266. package/dist/sensor/security-utils.js +18 -0
  267. package/dist/sensor/service-graph.js +170 -0
  268. package/dist/sensor/service-topology.js +227 -0
  269. package/dist/sensor/session-history.js +74 -0
  270. package/dist/sensor/session-persist.js +38 -0
  271. package/dist/sensor/shadow-promote.js +122 -0
  272. package/dist/sensor/sourcemap.js +281 -0
  273. package/dist/sensor/sqlite-store.js +205 -0
  274. package/dist/sensor/sso.js +164 -0
  275. package/dist/sensor/vitest-reporter.js +65 -0
  276. package/dist/sensor/watcher.js +48 -0
  277. package/dist/storage/interfaces.js +0 -0
  278. package/dist/storage/pg/pg-action-ledger.js +138 -0
  279. package/dist/storage/pg/pg-approval-store.js +107 -0
  280. package/dist/storage/pg/pg-blunder-store.js +193 -0
  281. package/dist/storage/pg/pg-ci-gate-history.js +83 -0
  282. package/dist/storage/pg/pg-client.js +24 -0
  283. package/dist/storage/pg/pg-event-store.js +63 -0
  284. package/dist/storage/pg/pg-incident-store.js +190 -0
  285. package/dist/storage/pg/pg-migrations.js +26 -0
  286. package/dist/storage/pg/pg-override-corpus.js +447 -0
  287. package/dist/storage/pg/pg-shadow-log.js +129 -0
  288. package/dist/storage/sqlite/sqlite-action-ledger.js +18 -0
  289. package/dist/storage/sqlite/sqlite-approval-store.js +37 -0
  290. package/dist/storage/sqlite/sqlite-blunder-store.js +27 -0
  291. package/dist/storage/sqlite/sqlite-ci-gate-history.js +19 -0
  292. package/dist/storage/sqlite/sqlite-event-store.js +29 -0
  293. package/dist/storage/sqlite/sqlite-incident-store.js +34 -0
  294. package/dist/storage/sqlite/sqlite-override-corpus.js +75 -0
  295. package/dist/storage/sqlite/sqlite-shadow-log.js +36 -0
  296. package/dist/storage/store-factory.js +55 -0
  297. package/dist/storage/store-registry.js +31 -0
  298. package/dist/update-checker.js +107 -0
  299. package/dist/workers/autopilot-worker.js +28 -0
  300. package/dist/workers/notification-worker.js +28 -0
  301. package/dist/workers/queues.js +58 -0
  302. package/dist/workers/validation-worker.js +24 -0
  303. package/dist/workers/worker-registry.js +18 -0
  304. package/package.json +123 -0
  305. package/sdk/mergen-inject.js +260 -0
  306. package/sdk/node.js +313 -0
  307. package/sdk/vite-plugin.ts +57 -0
  308. package/sdk/webpack-plugin.js +106 -0
@@ -0,0 +1,819 @@
1
+ import { Router } from "express";
2
+ import { store } from "../sensor/buffer.js";
3
+ import { getMetricCounters } from "../sensor/otel-exporter.js";
4
+ import { startProcessWatcher, stopProcessWatcher, listProcessWatchers } from "../sensor/process-watcher.js";
5
+ import { startDockerLogStream, stopDockerLogStream, listStreamedContainers } from "../sensor/docker-log-stream.js";
6
+ import { saveSessionToHistory } from "../sensor/session-history.js";
7
+ import { historyStore } from "../sensor/sqlite-store.js";
8
+ import { getStores } from "../storage/store-registry.js";
9
+ import { buildCausalChain } from "../intelligence/causal.js";
10
+ import { buildCausalGraph } from "../intelligence/causal-graph.js";
11
+ import { serviceTopology } from "../sensor/service-topology.js";
12
+ import { hypothesisHistory } from "../intelligence/hypothesis-history.js";
13
+ import { getCostGuardStats } from "../intelligence/incident-autopilot.js";
14
+ import { getUsageSnapshot, recordExplainWhyFeedback } from "../intelligence/usage.js";
15
+ import { toolCallCounts, lastMcpCallAt, firstAnalyzeAt, lastTimeToFirstAnalysisMs } from "../intelligence/tools.js";
16
+ import { listActiveSessions } from "../intelligence/debug-sessions.js";
17
+ import { getTeamState, isTeamEnabled } from "../intelligence/team.js";
18
+ import { getStats } from "../intelligence/calibration.js";
19
+ import { getDegradationState } from "../intelligence/degradation-watcher.js";
20
+ import { getPendingBypasses } from "../intelligence/tool-guard.js";
21
+ import { getPendingHolds } from "../intelligence/hitl-hold.js";
22
+ import { getGateHeartbeatStatus } from "../sensor/gate-heartbeat.js";
23
+ import { getRecentActivity } from "../intelligence/activity-feed.js";
24
+ import { loadEnterprisePolicy, IMMUTABLE_RULE_IDS, getGateCoverageSummary, getLastEvalLatencyMs } from "../intelligence/enterprise-policy-engine.js";
25
+ import { getRuleFirings, getBlockedActionCount } from "../intelligence/gate-analytics.js";
26
+ import { agentCallCount } from "../intelligence/tools-state.js";
27
+ import { getBypassStats } from "../sensor/bypass-tracker.js";
28
+ import { getEbpfCapability } from "../intelligence/ebpf-verify.js";
29
+ import { getMacSandboxCapability } from "../intelligence/sandbox.js";
30
+ function createSensorRouter(serverVersion) {
31
+ const router = Router();
32
+ router.get("/health", async (req, res) => {
33
+ const tid = req.tenantId;
34
+ const teamState = getTeamState();
35
+ const counters = store.getCounters(tid);
36
+ const buffered = store.size(tid);
37
+ const signals = store.getSignals(tid);
38
+ const allClear = counters.errors === 0 && counters.networkErrors === 0 && signals.length === 0 && buffered > 0;
39
+ res.json({
40
+ ok: true,
41
+ buffered,
42
+ errors: counters.errors,
43
+ warnings: counters.warnings,
44
+ networkErrors: counters.networkErrors,
45
+ websocketConnections: store.getWebSocketCount(tid),
46
+ lastEventAt: store.lastEventAt(tid),
47
+ clearedAt: store.clearedAt(),
48
+ mcpLastCallAt: lastMcpCallAt,
49
+ firstAnalyzeAt,
50
+ lastTimeToFirstAnalysisMs,
51
+ metrics: getMetricCounters(),
52
+ signals,
53
+ allClear,
54
+ allClearMessage: allClear ? `\u2705 0 errors in the last session (${buffered} events captured)` : null,
55
+ allClearSince: allClear ? store.clearedAt() ?? store.lastEventAt() : null,
56
+ name: "mergen",
57
+ version: serverVersion,
58
+ teamSync: isTeamEnabled() ? { enabled: true, memberName: teamState?.memberName, connectedPeers: 0 } : { enabled: false },
59
+ costGuard: getCostGuardStats(),
60
+ degradation: getDegradationState(),
61
+ gateHeartbeat: getGateHeartbeatStatus(),
62
+ pendingBypassesCount: (getPendingBypasses() ?? []).length + getPendingHolds().length,
63
+ blockedActionsCount: getBlockedActionCount(),
64
+ // Linux-only, opt-in (MERGEN_EBPF_VERIFY=true) syscall-level BLOCK
65
+ // verification — explicit here so a team relying on it can see at a
66
+ // glance whether it's actually active on this host, not silently no-op.
67
+ ebpfCapability: getEbpfCapability(),
68
+ // macOS-only, opt-in (MERGEN_SANDBOX=seatbelt) native sandbox-exec
69
+ // execution guard — surfaced for the same reason as ebpfCapability
70
+ // above: a team relying on it should be able to see at a glance
71
+ // whether it's actually active on this host.
72
+ macSandboxCapability: getMacSandboxCapability()
73
+ });
74
+ });
75
+ router.post("/clear", (req, res) => {
76
+ const tid = req.tenantId;
77
+ const was = store.size(tid);
78
+ const events = store.serialize(tid);
79
+ saveSessionToHistory(events, "manual-clear");
80
+ store.clear();
81
+ historyStore.clear();
82
+ hypothesisHistory.clear();
83
+ res.json({ ok: true, cleared: was });
84
+ });
85
+ router.post("/checkpoint", (req, res) => {
86
+ const { label } = req.body ?? {};
87
+ const name = typeof label === "string" && label.trim() ? label.trim().slice(0, 120) : "checkpoint";
88
+ store.push({
89
+ type: "console",
90
+ level: "log",
91
+ args: [`[mergen:checkpoint] ${name}`],
92
+ url: "mergen://checkpoint",
93
+ timestamp: Date.now()
94
+ }, req.tenantId);
95
+ const signals = store.getSignals(req.tenantId);
96
+ res.json({
97
+ ok: true,
98
+ label: name,
99
+ buffered: store.size(req.tenantId),
100
+ signals: signals.length,
101
+ topSignal: signals[0] ?? null
102
+ });
103
+ });
104
+ router.get("/diagnose", async (req, res) => {
105
+ const tid = req.tenantId;
106
+ const logs = store.getLogs(200, void 0, void 0, tid);
107
+ const network = store.getNetwork(200, void 0, void 0, tid);
108
+ const contexts = store.getContext(20, void 0, tid);
109
+ const terminal = store.getTerminalOutput(100, void 0, void 0, tid);
110
+ const processExits = store.getProcessExits(20, void 0, void 0, tid);
111
+ const ciEvents = store.getCIEvents(20, void 0, void 0, tid);
112
+ const deployments = store.getDeployments(10, void 0, void 0, tid);
113
+ const causal = await buildCausalChain(logs, network, contexts, void 0, terminal, processExits, ciEvents, deployments);
114
+ const SYSTEM = [
115
+ "You are a concise runtime-debug assistant.",
116
+ 'You will receive a structured telemetry report called a "Context Pack".',
117
+ "Your job is to identify the root cause of the bug and the exact fix.",
118
+ "",
119
+ "Rules:",
120
+ "1. Respond with a single JSON object only \u2014 no surrounding prose, no markdown fences.",
121
+ "2. Be maximally specific: name the endpoint, field, or code path that is broken.",
122
+ "3. The fix must be a concrete, immediately-applicable action (a code line, not a concept).",
123
+ "4. If you are not confident, say so in missing_signals \u2014 do not hallucinate."
124
+ ].join("\n");
125
+ const USER = [
126
+ causal.contextPack,
127
+ "",
128
+ "Return a single JSON object with exactly these fields:",
129
+ " root_cause \u2014 one sentence naming what broke and why (be specific: endpoint/field/line)",
130
+ " fix \u2014 one concrete action: a code line, config change, or exact command",
131
+ " confidence \u2014 HIGH | MEDIUM | LOW",
132
+ " missing_signals \u2014 what telemetry would make this HIGH confidence, or null"
133
+ ].join("\n");
134
+ const openaiRequest = {
135
+ model: process.env.MERGEN_MODEL ?? "gpt-4o",
136
+ temperature: 0,
137
+ response_format: { type: "json_object" },
138
+ messages: [
139
+ { role: "system", content: SYSTEM },
140
+ { role: "user", content: USER }
141
+ ]
142
+ };
143
+ res.json({
144
+ ok: true,
145
+ buffered: store.size(tid),
146
+ hypotheses: causal.hypotheses.length,
147
+ contextPack: causal.contextPack,
148
+ openai_request: openaiRequest,
149
+ prompt: { system: SYSTEM, user: USER }
150
+ });
151
+ });
152
+ router.get("/usage", (_req, res) => {
153
+ res.json({ ...getUsageSnapshot(), toolCallCounts });
154
+ });
155
+ router.post("/explain-why/feedback", (req, res) => {
156
+ const { id, helpful } = req.body;
157
+ if (typeof helpful !== "boolean") {
158
+ res.status(400).json({ error: '"helpful" must be a boolean' });
159
+ return;
160
+ }
161
+ recordExplainWhyFeedback(helpful);
162
+ res.json({ ok: true, id: id ?? null, helpful });
163
+ });
164
+ router.get("/last-pack", (_req, res) => {
165
+ const latest = hypothesisHistory.latest();
166
+ if (!latest) {
167
+ res.json({ ok: true, hasPack: false });
168
+ return;
169
+ }
170
+ const statsByTag = new Map(getStats().map((s) => [s.tag, s]));
171
+ const enrich = (h) => h ? { ...h, calibration: statsByTag.get(h.tag) ?? null } : h;
172
+ res.json({
173
+ ok: true,
174
+ hasPack: true,
175
+ builtAt: latest.builtAt,
176
+ builtAtIso: latest.builtAtIso,
177
+ triggerMessage: latest.triggerMessage,
178
+ reason: latest.reason,
179
+ topHypothesis: enrich(latest.topHypothesis),
180
+ hypotheses: latest.chain.hypotheses.map((h) => enrich(h)),
181
+ contextPack: latest.chain.contextPack,
182
+ hypothesesCount: latest.chain.hypotheses.length,
183
+ errorsCount: latest.chain.errors.length
184
+ });
185
+ });
186
+ router.get("/history", (req, res) => {
187
+ const limit = Math.min(20, Math.max(1, Number(req.query.limit ?? 10)));
188
+ const statsByTag = new Map(getStats().map((s) => [s.tag, s]));
189
+ const entries = hypothesisHistory.list(limit).map((e) => ({
190
+ ...e,
191
+ topHypothesis: e.topHypothesis ? { ...e.topHypothesis, calibration: statsByTag.get(e.topHypothesis.tag) ?? null } : null
192
+ }));
193
+ res.json({ ok: true, entries });
194
+ });
195
+ router.get("/graph", async (req, res) => {
196
+ const seconds = Math.min(600, Math.max(1, Number(req.query.seconds ?? 60)));
197
+ const since = Date.now() - seconds * 1e3;
198
+ const logs = store.getLogs(200, void 0, since);
199
+ const network = store.getNetwork(200, void 0, since);
200
+ const contexts = store.getContext(20, since);
201
+ const terminal = store.getTerminalOutput(100, void 0, since);
202
+ const processExits = store.getProcessExits(20, void 0, since);
203
+ const ciEvents = store.getCIEvents(20, void 0, since);
204
+ const deployments = store.getDeployments(10, void 0, since);
205
+ const causal = await buildCausalChain(logs, network, contexts, since, terminal, processExits, ciEvents, deployments);
206
+ const graph = buildCausalGraph(causal);
207
+ res.json({ ok: true, windowSeconds: seconds, graph });
208
+ });
209
+ router.get("/topology", (_req, res) => {
210
+ res.json({ ok: true, ...serviceTopology.snapshot() });
211
+ });
212
+ router.get("/timeline", (req, res) => {
213
+ const seconds = Math.min(600, Math.max(1, Number(req.query.seconds ?? 60)));
214
+ const limit = Math.min(500, Math.max(1, Number(req.query.limit ?? 200)));
215
+ const since = Date.now() - seconds * 1e3;
216
+ const logs = store.getLogs(limit, void 0, since);
217
+ const network = store.getNetwork(limit, void 0, since);
218
+ const ctx = store.getContext(20, since);
219
+ const terminal = store.getTerminalOutput(limit, void 0, since);
220
+ const processExits = store.getProcessExits(limit, void 0, since);
221
+ const rows = [];
222
+ for (const e of logs) {
223
+ const summary = e.args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ").slice(0, 200);
224
+ rows.push({ ts: e.timestamp, isoTs: new Date(e.timestamp).toISOString(), kind: e.level, summary });
225
+ }
226
+ for (const n of network) {
227
+ const isFail = n.status >= 400 || n.status === 0 || !!n.error;
228
+ const label = n.status === 0 ? `network error (${n.error ?? "\u2014"})` : `${n.status} ${n.statusText}`;
229
+ rows.push({
230
+ ts: n.timestamp,
231
+ isoTs: new Date(n.timestamp).toISOString(),
232
+ kind: "request",
233
+ summary: `${n.method} ${n.url} \u2192 ${label} (${n.duration}ms)${isFail ? " \u26A0" : ""}`
234
+ });
235
+ }
236
+ for (const c of ctx) {
237
+ rows.push({
238
+ ts: c.timestamp,
239
+ isoTs: new Date(c.timestamp).toISOString(),
240
+ kind: "context",
241
+ summary: `[${c.trigger}] ${c.url}`
242
+ });
243
+ }
244
+ for (const t of terminal) {
245
+ rows.push({
246
+ ts: t.timestamp,
247
+ isoTs: new Date(t.timestamp).toISOString(),
248
+ kind: "terminal",
249
+ summary: t.data.slice(0, 200),
250
+ source: t.terminalName
251
+ });
252
+ }
253
+ for (const p of processExits) {
254
+ rows.push({
255
+ ts: p.timestamp,
256
+ isoTs: new Date(p.timestamp).toISOString(),
257
+ kind: "process_exit",
258
+ summary: `[${p.process}] exited ${p.exitCode} (${p.reason})${p.signal ? " \xB7 " + p.signal : ""}`,
259
+ source: p.process
260
+ });
261
+ }
262
+ rows.sort((a, b) => a.ts - b.ts);
263
+ res.json({ ok: true, windowSeconds: seconds, count: rows.length, rows: rows.slice(-limit) });
264
+ });
265
+ router.get("/current-version", (_req, res) => {
266
+ const deploys = store.getDeployments(5);
267
+ const latest = deploys.find((d) => d.status === "success") ?? deploys[0] ?? null;
268
+ res.json({
269
+ ok: true,
270
+ sha: latest?.sha ?? null,
271
+ shortSha: latest?.shortSha ?? (latest?.sha?.slice(0, 7) ?? null),
272
+ environment: latest?.environment ?? null,
273
+ service: latest?.service ?? null,
274
+ deployedAt: latest ? new Date(latest.timestamp).toISOString() : null
275
+ });
276
+ });
277
+ router.get("/timeline/unified", (req, res) => {
278
+ const seconds = Math.min(3600, Math.max(1, Number(req.query.seconds ?? 300)));
279
+ const limit = Math.min(200, Math.max(1, Number(req.query.limit ?? 50)));
280
+ const since = Date.now() - seconds * 1e3;
281
+ const rows = [];
282
+ for (const e of store.getLogs(limit, void 0, since)) {
283
+ rows.push({
284
+ ts: e.timestamp,
285
+ isoTs: new Date(e.timestamp).toISOString(),
286
+ kind: e.level === "error" ? "error" : e.level === "warn" ? "warn" : "log",
287
+ summary: e.args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ").slice(0, 200),
288
+ source: "browser"
289
+ });
290
+ }
291
+ for (const n of store.getNetwork(limit, void 0, since)) {
292
+ const fail = n.status >= 400 || n.status === 0 || !!n.error;
293
+ if (!fail) continue;
294
+ rows.push({
295
+ ts: n.timestamp,
296
+ isoTs: new Date(n.timestamp).toISOString(),
297
+ kind: "request",
298
+ summary: `${n.method} ${n.url} \u2192 ${n.status || "ERR"} ${n.statusText} (${n.duration}ms)${n.error ? " \u2014 " + n.error : ""}`,
299
+ source: "browser"
300
+ });
301
+ }
302
+ const BACKEND_ERROR_RE = /error|exception|traceback|panic|fatal|killed|oom/i;
303
+ for (const t of store.getTerminalOutput(limit, void 0, since)) {
304
+ if (!BACKEND_ERROR_RE.test(t.data)) continue;
305
+ rows.push({
306
+ ts: t.timestamp,
307
+ isoTs: new Date(t.timestamp).toISOString(),
308
+ kind: "terminal",
309
+ summary: `[${t.terminalName}] ${t.data.slice(0, 200)}`,
310
+ source: "backend"
311
+ });
312
+ }
313
+ for (const p of store.getProcessExits(20, void 0, since)) {
314
+ if (p.reason === "normal") continue;
315
+ rows.push({
316
+ ts: p.timestamp,
317
+ isoTs: new Date(p.timestamp).toISOString(),
318
+ kind: "process_exit",
319
+ summary: `[${p.process}] exited ${p.exitCode} (${p.reason})${p.signal ? " \xB7 " + p.signal : ""}`,
320
+ source: "backend"
321
+ });
322
+ }
323
+ for (const c of store.getCIEvents(50, void 0, since)) {
324
+ rows.push({
325
+ ts: c.timestamp,
326
+ isoTs: new Date(c.timestamp).toISOString(),
327
+ kind: c.status === "failure" ? "ci_failure" : "ci_success",
328
+ summary: c.status === "failure" ? `CI failed: ${c.job}${c.workflow ? " (" + c.workflow + ")" : ""}${c.failedTests && c.failedTests.length > 0 ? " \u2014 " + c.failedTests.slice(0, 3).map((t) => t.name).join(", ") : ""}` : `CI passed: ${c.job}${c.workflow ? " (" + c.workflow + ")" : ""}`,
329
+ source: "ci",
330
+ sha: c.shortSha ?? c.sha.slice(0, 7)
331
+ });
332
+ }
333
+ for (const d of store.getDeployments(20, void 0, since)) {
334
+ rows.push({
335
+ ts: d.timestamp,
336
+ isoTs: new Date(d.timestamp).toISOString(),
337
+ kind: "deployment",
338
+ summary: `Deploy to ${d.environment}: ${d.status}${d.service ? " (" + d.service + ")" : ""}${d.actor ? " by " + d.actor : ""}`,
339
+ source: "deploy",
340
+ sha: d.shortSha ?? d.sha.slice(0, 7)
341
+ });
342
+ }
343
+ const browserTraceIds = new Set(
344
+ store.getNetwork(200, void 0, since).filter((n) => n.traceId).map((n) => n.traceId)
345
+ );
346
+ for (const s of store.getBackendSpans(limit, void 0, since)) {
347
+ const joined = browserTraceIds.has(s.traceId);
348
+ rows.push({
349
+ ts: s.timestamp,
350
+ isoTs: new Date(s.timestamp).toISOString(),
351
+ kind: "backend_span",
352
+ summary: `[${s.service}] ${s.method} ${s.route} \u2192 ${s.statusCode} (${s.durationMs}ms)${s.error ? " \u2014 " + s.error : ""}`,
353
+ source: "backend",
354
+ confidence: joined ? 1 : 0.5,
355
+ traceId: s.traceId
356
+ });
357
+ }
358
+ rows.sort((a, b) => a.ts - b.ts);
359
+ const latest = hypothesisHistory.latest();
360
+ const topHyp = latest?.topHypothesis ?? null;
361
+ const statsByTag = new Map(getStats().map((s) => [s.tag, s]));
362
+ const rootCause = topHyp ? {
363
+ hypothesis: topHyp.summary,
364
+ tag: topHyp.tag,
365
+ confidence: topHyp.confidenceScore,
366
+ fixHint: topHyp.fixHint,
367
+ builtAt: latest?.builtAt,
368
+ calibration: statsByTag.get(topHyp.tag) ?? null
369
+ } : null;
370
+ res.json({
371
+ ok: true,
372
+ windowSeconds: seconds,
373
+ count: rows.length,
374
+ rootCause,
375
+ rows: rows.slice(-limit)
376
+ });
377
+ });
378
+ router.get("/unified-dashboard", async (req, res) => {
379
+ const tid = req.tenantId;
380
+ const teamState = getTeamState();
381
+ const counters = store.getCounters(tid);
382
+ const buffered = store.size(tid);
383
+ const signals = store.getSignals(tid);
384
+ const allClear = counters.errors === 0 && counters.networkErrors === 0 && signals.length === 0 && buffered > 0;
385
+ const health = {
386
+ ok: true,
387
+ buffered,
388
+ errors: counters.errors,
389
+ warnings: counters.warnings,
390
+ networkErrors: counters.networkErrors,
391
+ websocketConnections: store.getWebSocketCount(tid),
392
+ lastEventAt: store.lastEventAt(tid),
393
+ clearedAt: store.clearedAt(),
394
+ mcpLastCallAt: lastMcpCallAt,
395
+ firstAnalyzeAt,
396
+ lastTimeToFirstAnalysisMs,
397
+ metrics: getMetricCounters(),
398
+ signals,
399
+ allClear,
400
+ allClearMessage: allClear ? `\u2705 0 errors in the last session (${buffered} events captured)` : null,
401
+ allClearSince: allClear ? store.clearedAt() ?? store.lastEventAt() : null,
402
+ name: "mergen",
403
+ version: serverVersion,
404
+ teamSync: isTeamEnabled() ? { enabled: true, memberName: teamState?.memberName, connectedPeers: 0 } : { enabled: false },
405
+ costGuard: getCostGuardStats(),
406
+ pendingBypassesCount: (getPendingBypasses() ?? []).length + getPendingHolds().length,
407
+ blockedActionsCount: getBlockedActionCount()
408
+ };
409
+ const usage = getUsageSnapshot();
410
+ const latest = hypothesisHistory.latest();
411
+ const stats = getStats();
412
+ const statsByTag = new Map(stats.map((s) => [s.tag, s]));
413
+ const enrich = (h) => h ? { ...h, calibration: statsByTag.get(h.tag) ?? null } : h;
414
+ const lastPack = latest ? {
415
+ ok: true,
416
+ hasPack: true,
417
+ builtAt: latest.builtAt,
418
+ builtAtIso: latest.builtAtIso,
419
+ triggerMessage: latest.triggerMessage,
420
+ reason: latest.reason,
421
+ topHypothesis: enrich(latest.topHypothesis),
422
+ hypotheses: latest.chain.hypotheses.map((h) => enrich(h)),
423
+ contextPack: latest.chain.contextPack,
424
+ hypothesesCount: latest.chain.hypotheses.length,
425
+ errorsCount: latest.chain.errors.length
426
+ } : { ok: true, hasPack: false };
427
+ const history = hypothesisHistory.list(5).map((e) => ({
428
+ ...e,
429
+ topHypothesis: e.topHypothesis ? { ...e.topHypothesis, calibration: statsByTag.get(e.topHypothesis.tag) ?? null } : null
430
+ }));
431
+ const trusted = stats.filter((s) => s.trusted);
432
+ const totalVerdicts = trusted.reduce((sum, s) => sum + s.verdicts, 0);
433
+ const overall = totalVerdicts > 0 ? trusted.reduce((sum, s) => sum + s.accuracy * s.verdicts, 0) / totalVerdicts : null;
434
+ const calibration = {
435
+ ok: true,
436
+ overallAccuracy: overall,
437
+ trustedDetectors: trusted.length,
438
+ totalDetectors: stats.length,
439
+ perDetector: stats
440
+ };
441
+ const seconds = 300;
442
+ const limit = 12;
443
+ const since = Date.now() - seconds * 1e3;
444
+ const rows = [];
445
+ for (const e of store.getLogs(limit, void 0, since)) {
446
+ rows.push({
447
+ ts: e.timestamp,
448
+ isoTs: new Date(e.timestamp).toISOString(),
449
+ kind: e.level === "error" ? "error" : e.level === "warn" ? "warn" : "log",
450
+ summary: e.args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ").slice(0, 200),
451
+ source: "browser"
452
+ });
453
+ }
454
+ for (const n of store.getNetwork(limit, void 0, since)) {
455
+ const fail = n.status >= 400 || n.status === 0 || !!n.error;
456
+ if (!fail) continue;
457
+ rows.push({
458
+ ts: n.timestamp,
459
+ isoTs: new Date(n.timestamp).toISOString(),
460
+ kind: "request",
461
+ summary: `${n.method} ${n.url} \u2192 ${n.status || "ERR"} ${n.statusText} (${n.duration}ms)${n.error ? " \u2014 " + n.error : ""}`,
462
+ source: "browser"
463
+ });
464
+ }
465
+ const BACKEND_ERROR_RE = /error|exception|traceback|panic|fatal|killed|oom/i;
466
+ for (const t of store.getTerminalOutput(limit, void 0, since)) {
467
+ if (!BACKEND_ERROR_RE.test(t.data)) continue;
468
+ rows.push({
469
+ ts: t.timestamp,
470
+ isoTs: new Date(t.timestamp).toISOString(),
471
+ kind: "terminal",
472
+ summary: `[${t.terminalName}] ${t.data.slice(0, 200)}`,
473
+ source: "backend"
474
+ });
475
+ }
476
+ for (const p of store.getProcessExits(20, void 0, since)) {
477
+ if (p.reason === "normal") continue;
478
+ rows.push({
479
+ ts: p.timestamp,
480
+ isoTs: new Date(p.timestamp).toISOString(),
481
+ kind: "process_exit",
482
+ summary: `[${p.process}] exited ${p.exitCode} (${p.reason})${p.signal ? " \xB7 " + p.signal : ""}`,
483
+ source: "backend"
484
+ });
485
+ }
486
+ for (const c of store.getCIEvents(50, void 0, since)) {
487
+ rows.push({
488
+ ts: c.timestamp,
489
+ isoTs: new Date(c.timestamp).toISOString(),
490
+ kind: c.status === "failure" ? "ci_failure" : "ci_success",
491
+ summary: c.status === "failure" ? `CI failed: ${c.job}${c.workflow ? " (" + c.workflow + ")" : ""}${c.failedTests && c.failedTests.length > 0 ? " \u2014 " + c.failedTests.slice(0, 3).map((t) => t.name).join(", ") : ""}` : `CI passed: ${c.job}${c.workflow ? " (" + c.workflow + ")" : ""}`,
492
+ source: "ci",
493
+ sha: c.shortSha ?? c.sha.slice(0, 7)
494
+ });
495
+ }
496
+ for (const d of store.getDeployments(20, void 0, since)) {
497
+ rows.push({
498
+ ts: d.timestamp,
499
+ isoTs: new Date(d.timestamp).toISOString(),
500
+ kind: "deployment",
501
+ summary: `Deploy to ${d.environment}: ${d.status}${d.service ? " (" + d.service + ")" : ""}${d.actor ? " by " + d.actor : ""}`,
502
+ source: "deploy",
503
+ sha: d.shortSha ?? d.sha.slice(0, 7)
504
+ });
505
+ }
506
+ const browserTraceIds = new Set(
507
+ store.getNetwork(200, void 0, since).filter((n) => n.traceId).map((n) => n.traceId)
508
+ );
509
+ for (const s of store.getBackendSpans(limit, void 0, since)) {
510
+ const joined = browserTraceIds.has(s.traceId);
511
+ rows.push({
512
+ ts: s.timestamp,
513
+ isoTs: new Date(s.timestamp).toISOString(),
514
+ kind: "backend_span",
515
+ summary: `[${s.service}] ${s.method} ${s.route} \u2192 ${s.statusCode} (${s.durationMs}ms)${s.error ? " \u2014 " + s.error : ""}`,
516
+ source: "backend",
517
+ confidence: joined ? 1 : 0.5,
518
+ traceId: s.traceId
519
+ });
520
+ }
521
+ rows.sort((a, b) => a.ts - b.ts);
522
+ const topHyp = latest?.topHypothesis ?? null;
523
+ const rootCause = topHyp ? {
524
+ hypothesis: topHyp.summary,
525
+ tag: topHyp.tag,
526
+ confidence: topHyp.confidenceScore,
527
+ fixHint: topHyp.fixHint,
528
+ builtAt: latest?.builtAt,
529
+ calibration: statsByTag.get(topHyp.tag) ?? null
530
+ } : null;
531
+ const timelineUnified = {
532
+ ok: true,
533
+ windowSeconds: seconds,
534
+ count: rows.length,
535
+ rootCause,
536
+ rows: rows.slice(-limit)
537
+ };
538
+ const edges = await getStores().incidents.getInteractionGraph(void 0, req.tenantId);
539
+ const interactionServices = [...new Set(edges.flatMap((e) => [e.source, e.target]))];
540
+ const interactions = {
541
+ edges,
542
+ services: interactionServices
543
+ };
544
+ const services = getSdkServices();
545
+ const policy = loadEnterprisePolicy();
546
+ const firings = getRuleFirings();
547
+ const policies = {
548
+ enabled: policy.enabled,
549
+ rules: policy.rules.map((r) => ({
550
+ id: r.id,
551
+ name: r.name,
552
+ description: r.description,
553
+ action: r.action,
554
+ triggerCount: firings.get(r.id) ?? 0,
555
+ immutable: IMMUTABLE_RULE_IDS.has(r.id)
556
+ }))
557
+ };
558
+ const gateCovers = getGateCoverageSummary();
559
+ const activity = getRecentActivity(20);
560
+ const bypassStats = getBypassStats();
561
+ const securityMetrics = {
562
+ protectedActions: agentCallCount,
563
+ // getBlockedActionCount() = real-time in-memory count of BLOCK verdicts from the gate.
564
+ blockedActions: getBlockedActionCount(),
565
+ // approvalsRequested = outstanding human-approval queue across both mechanisms:
566
+ // • HITL bypass requests (warn-rule triggers awaiting approve/deny)
567
+ // • HITL holds (policy holds awaiting quorum approval)
568
+ approvalsRequested: (getPendingBypasses() ?? []).length + getPendingHolds().length,
569
+ // shadowViolations = bypasses actually granted (agent got through a warn gate)
570
+ shadowViolations: bypassStats.totalBypasses,
571
+ latencyMs: getLastEvalLatencyMs()
572
+ };
573
+ res.json({
574
+ health,
575
+ usage,
576
+ lastPack,
577
+ history,
578
+ calibration,
579
+ timelineUnified,
580
+ services,
581
+ interactions,
582
+ pendingBypasses: getPendingBypasses(),
583
+ activity,
584
+ policies,
585
+ gateCovers,
586
+ securityMetrics
587
+ });
588
+ });
589
+ function getSdkServices() {
590
+ const logs = store.getLogs(500);
591
+ const spans = store.getBackendSpans(200);
592
+ const services = /* @__PURE__ */ new Map();
593
+ for (const e of logs) {
594
+ if (!e.url?.startsWith("mergen://node/") && !e.url?.startsWith("mergen://python/")) continue;
595
+ const parts = e.url.split("/");
596
+ const sdk = parts[2] ?? "unknown";
597
+ const name = parts[3] ?? "unknown";
598
+ const key = `${sdk}/${name}`;
599
+ const prev = services.get(key);
600
+ services.set(key, {
601
+ sdk,
602
+ lastSeen: Math.max(e.timestamp, prev?.lastSeen ?? 0),
603
+ errorCount: (prev?.errorCount ?? 0) + (e.level === "error" ? 1 : 0),
604
+ spanCount: prev?.spanCount ?? 0
605
+ });
606
+ }
607
+ for (const s of spans) {
608
+ const key = `${s.sdk}/${s.service}`;
609
+ const prev = services.get(key);
610
+ services.set(key, {
611
+ sdk: s.sdk,
612
+ lastSeen: Math.max(s.timestamp, prev?.lastSeen ?? 0),
613
+ errorCount: (prev?.errorCount ?? 0) + (s.statusCode >= 400 ? 1 : 0),
614
+ spanCount: (prev?.spanCount ?? 0) + 1
615
+ });
616
+ }
617
+ return Object.fromEntries(services);
618
+ }
619
+ router.get("/watchers", (_req, res) => {
620
+ res.json({
621
+ ok: true,
622
+ processes: listProcessWatchers(),
623
+ containers: listStreamedContainers()
624
+ });
625
+ });
626
+ router.post("/watchers/start", (req, res) => {
627
+ const { name, command, args, cwd } = req.body ?? {};
628
+ if (!command || typeof command !== "string") {
629
+ res.status(400).json({ error: "command is required" });
630
+ return;
631
+ }
632
+ const watcherName = typeof name === "string" && name.trim() ? name.trim() : command;
633
+ startProcessWatcher({ name: watcherName, command, args, cwd });
634
+ res.json({ ok: true, name: watcherName });
635
+ });
636
+ router.post("/watchers/stop", (req, res) => {
637
+ const { name } = req.body ?? {};
638
+ if (!name || typeof name !== "string") {
639
+ res.status(400).json({ error: "name is required" });
640
+ return;
641
+ }
642
+ stopProcessWatcher(name);
643
+ res.json({ ok: true });
644
+ });
645
+ router.post("/watchers/docker", async (_req, res) => {
646
+ await startDockerLogStream();
647
+ res.json({ ok: true, containers: listStreamedContainers() });
648
+ });
649
+ router.delete("/watchers/docker", (_req, res) => {
650
+ stopDockerLogStream();
651
+ res.json({ ok: true });
652
+ });
653
+ let _captureMarkTs = null;
654
+ router.post("/mark", (_req, res) => {
655
+ _captureMarkTs = Date.now();
656
+ res.json({ ok: true, timestamp: _captureMarkTs, iso: new Date(_captureMarkTs).toISOString() });
657
+ });
658
+ router.get("/mark", (_req, res) => {
659
+ res.json({ ok: true, timestamp: _captureMarkTs, iso: _captureMarkTs ? new Date(_captureMarkTs).toISOString() : null });
660
+ });
661
+ router.get("/sessions", (_req, res) => {
662
+ const sessions = listActiveSessions().map((s) => {
663
+ const last = s.iterations.length > 0 ? s.iterations[s.iterations.length - 1] : null;
664
+ return {
665
+ id: s.id,
666
+ description: s.description,
667
+ targetComponent: s.targetComponent ?? null,
668
+ startedAt: s.startedAt,
669
+ iterationCount: s.iterations.length,
670
+ baselineErrorCount: s.baseline.errors.length,
671
+ baselineNetworkFailureCount: s.baseline.networkFailures.length,
672
+ latestDiff: last ? {
673
+ resolved: last.diff.resolved.length,
674
+ persisted: last.diff.persisted.length,
675
+ newErrors: last.diff.newErrors.length,
676
+ isFixed: last.diff.isFixed
677
+ } : null
678
+ };
679
+ });
680
+ res.json({ ok: true, sessions });
681
+ });
682
+ router.get("/export/incident", async (req, res) => {
683
+ const from = Number(req.query.from) || Date.now() - 60 * 60 * 1e3;
684
+ const to = Number(req.query.to) || Date.now();
685
+ const sha = typeof req.query.sha === "string" ? req.query.sha : void 0;
686
+ const format = req.query.format === "json" ? "json" : "md";
687
+ const window = { from, to };
688
+ const since = window.from;
689
+ const logs = store.getLogs(500, void 0, since).filter((e) => e.timestamp <= to);
690
+ const network = store.getNetwork(500, void 0, since).filter((e) => e.timestamp <= to);
691
+ const terminal = store.getTerminalOutput(200, void 0, since).filter((e) => e.timestamp <= to);
692
+ const ciEvents = store.getCIEvents(50, void 0, since).filter((e) => e.timestamp <= to);
693
+ const deployments = store.getDeployments(20, void 0, since).filter((e) => e.timestamp <= to);
694
+ const exits = store.getProcessExits(20, void 0, since).filter((e) => e.timestamp <= to);
695
+ const filteredDeploy = sha ? deployments.filter((d) => d.sha?.startsWith(sha) || sha.startsWith(d.sha?.slice(0, 7) ?? "")) : deployments;
696
+ const latest = hypothesisHistory.latest();
697
+ const topHyp = latest?.topHypothesis ?? null;
698
+ const errors = logs.filter((e) => e.level === "error");
699
+ const warns = logs.filter((e) => e.level === "warn");
700
+ const netFail = network.filter((n) => n.status >= 400 || n.status === 0);
701
+ const affectedServices = [
702
+ .../* @__PURE__ */ new Set([
703
+ ...netFail.map((n) => {
704
+ try {
705
+ return new URL(n.url).hostname;
706
+ } catch {
707
+ return n.url;
708
+ }
709
+ }),
710
+ ...terminal.filter((t) => /error|exception|fatal/i.test(t.data)).map((t) => t.terminalName)
711
+ ])
712
+ ];
713
+ if (format === "json") {
714
+ res.json({
715
+ ok: true,
716
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
717
+ window: { from: new Date(from).toISOString(), to: new Date(to).toISOString() },
718
+ sha,
719
+ topHypothesis: topHyp,
720
+ affectedServices,
721
+ summary: { errors: errors.length, warnings: warns.length, networkFailures: netFail.length },
722
+ deployments: filteredDeploy,
723
+ ciEvents,
724
+ timeline: logs.concat(network).sort((a, b) => a.timestamp - b.timestamp)
725
+ });
726
+ return;
727
+ }
728
+ const lines = [];
729
+ const startIso = new Date(from).toISOString();
730
+ const endIso = new Date(to).toISOString();
731
+ const depRef = filteredDeploy[0];
732
+ lines.push(`# Incident Postmortem \u2014 ${startIso.slice(0, 10)}`);
733
+ lines.push("");
734
+ if (topHyp) {
735
+ lines.push(`**Root Cause**`);
736
+ lines.push(`${topHyp.summary}`);
737
+ if (topHyp.evidence && topHyp.evidence.length > 0) {
738
+ lines.push("");
739
+ lines.push(`**Evidence**`);
740
+ for (const ev of topHyp.evidence) lines.push(`- ${ev}`);
741
+ }
742
+ }
743
+ lines.push("");
744
+ lines.push(`**Window:** ${startIso.slice(11, 19)} \u2192 ${endIso.slice(11, 19)} UTC`);
745
+ if (depRef) lines.push(`**SHA:** \`${depRef.shortSha ?? depRef.sha.slice(0, 7)}\` \u2014 deployed to ${depRef.environment}${depRef.actor ? " by " + depRef.actor : ""}`);
746
+ if (topHyp?.fixHint) lines.push(`**Fix:** ${topHyp.fixHint}`);
747
+ lines.push("");
748
+ lines.push("## Summary");
749
+ lines.push("");
750
+ lines.push(`| Signal | Count |`);
751
+ lines.push(`|--------|-------|`);
752
+ lines.push(`| Browser errors | ${errors.length} |`);
753
+ lines.push(`| Warnings | ${warns.length} |`);
754
+ lines.push(`| Network failures | ${netFail.length} |`);
755
+ lines.push(`| CI failures | ${ciEvents.filter((c) => c.status === "failure").length} |`);
756
+ lines.push(`| Deployments | ${filteredDeploy.length} |`);
757
+ lines.push("");
758
+ if (affectedServices.length > 0) {
759
+ lines.push("## Affected Services");
760
+ lines.push("");
761
+ for (const svc of affectedServices) lines.push(`- ${svc}`);
762
+ lines.push("");
763
+ }
764
+ lines.push("## Timeline");
765
+ lines.push("");
766
+ lines.push("| Time | Source | Event |");
767
+ lines.push("|------|--------|-------|");
768
+ const rows = [];
769
+ for (const c of ciEvents) rows.push({ ts: c.timestamp, src: "CI", msg: `${c.status === "failure" ? "\u274C" : "\u2705"} ${c.job}${c.failedTests?.length ? " \u2014 " + c.failedTests.slice(0, 2).map((t) => t.name).join(", ") : ""}` });
770
+ for (const d of filteredDeploy) rows.push({ ts: d.timestamp, src: "Deploy", msg: `\u{1F680} Deployed to ${d.environment}: ${d.status}${d.actor ? " by " + d.actor : ""}` });
771
+ for (const e of errors) rows.push({ ts: e.timestamp, src: "Browser", msg: `\u{1F534} ${e.args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ").slice(0, 100)}` });
772
+ for (const n of netFail) rows.push({ ts: n.timestamp, src: "Network", msg: `${n.method} ${n.url} \u2192 ${n.status} (${n.duration}ms)` });
773
+ for (const t of terminal.filter((t2) => /error|exception|fatal/i.test(t2.data))) rows.push({ ts: t.timestamp, src: t.terminalName, msg: t.data.slice(0, 100) });
774
+ for (const p of exits.filter((p2) => p2.reason !== "normal")) rows.push({ ts: p.timestamp, src: p.process, msg: `\u{1F4A5} Exited ${p.exitCode} (${p.reason})` });
775
+ rows.sort((a, b) => a.ts - b.ts);
776
+ for (const r of rows) {
777
+ const t = new Date(r.ts).toISOString().slice(11, 19);
778
+ lines.push(`| ${t} | ${r.src} | ${r.msg.replace(/\|/g, "/")} |`);
779
+ }
780
+ lines.push("");
781
+ if (topHyp?.evidence?.length) {
782
+ lines.push("## Evidence");
783
+ lines.push("");
784
+ for (const e of topHyp.evidence) lines.push(`- ${e}`);
785
+ lines.push("");
786
+ }
787
+ lines.push("---");
788
+ lines.push(`*Generated by Mergen at ${(/* @__PURE__ */ new Date()).toISOString()}*`);
789
+ res.setHeader("Content-Type", "text/markdown; charset=utf-8");
790
+ res.send(lines.join("\n"));
791
+ });
792
+ router.get("/replay", (req, res) => {
793
+ const since = Number(req.query["since"]) || 0;
794
+ const limit = Math.min(Number(req.query["limit"]) || 500, 2e3);
795
+ const level = typeof req.query["level"] === "string" ? req.query["level"] : void 0;
796
+ const type = typeof req.query["type"] === "string" ? req.query["type"] : void 0;
797
+ const events = historyStore.query({ since, limit, level, type });
798
+ res.json({ ok: true, count: events.length, events });
799
+ });
800
+ router.get("/sdk-status", (_req, res) => {
801
+ res.json({ ok: true, services: getSdkServices() });
802
+ });
803
+ router.get("/trace/:traceId", (req, res) => {
804
+ const traceId = req.params["traceId"]?.toLowerCase();
805
+ if (!traceId || !/^[0-9a-f]{32}$/.test(traceId)) {
806
+ res.status(400).json({ error: "invalid traceId \u2014 must be 32 hex chars" });
807
+ return;
808
+ }
809
+ const browserNet = store.getNetwork(200).filter((n) => n.traceId?.toLowerCase() === traceId);
810
+ const backendSpans = store.getBackendSpans(50).filter((s) => s.traceId.toLowerCase() === traceId);
811
+ const backendLogs = store.getTerminalOutput(200).filter((t) => t.traceId?.toLowerCase() === traceId);
812
+ const found = browserNet.length + backendSpans.length + backendLogs.length > 0;
813
+ res.json({ ok: true, traceId, found, browserNet, backendSpans, backendLogs });
814
+ });
815
+ return router;
816
+ }
817
+ export {
818
+ createSensorRouter
819
+ };