@igorjpimenta/manifold 0.0.0-bootstrap.1

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 (210) hide show
  1. package/.migrations/ops/0000_futuristic_karma.sql +111 -0
  2. package/.migrations/ops/0001_low_maximus.sql +7 -0
  3. package/.migrations/ops/meta/0000_snapshot.json +763 -0
  4. package/.migrations/ops/meta/0001_snapshot.json +173 -0
  5. package/.migrations/ops/meta/_journal.json +20 -0
  6. package/.migrations/runtime/0000_real_boomer.sql +180 -0
  7. package/.migrations/runtime/0001_hot_dakota_north.sql +2 -0
  8. package/.migrations/runtime/0002_breezy_vertigo.sql +8 -0
  9. package/.migrations/runtime/0003_dashing_jack_flag.sql +5 -0
  10. package/.migrations/runtime/0004_panoramic_ego.sql +1 -0
  11. package/.migrations/runtime/0005_tidy_ben_grimm.sql +10 -0
  12. package/.migrations/runtime/0006_wet_nightmare.sql +57 -0
  13. package/.migrations/runtime/0007_ambiguous_chronomancer.sql +8 -0
  14. package/.migrations/runtime/0008_wealthy_thundra.sql +301 -0
  15. package/.migrations/runtime/0009_lying_shocker.sql +96 -0
  16. package/.migrations/runtime/0010_solid_phantom_reporter.sql +160 -0
  17. package/.migrations/runtime/0011_windy_demogoblin.sql +175 -0
  18. package/.migrations/runtime/0012_restore_harness_fks.sql +103 -0
  19. package/.migrations/runtime/meta/0000_snapshot.json +1181 -0
  20. package/.migrations/runtime/meta/0001_snapshot.json +1209 -0
  21. package/.migrations/runtime/meta/0002_snapshot.json +1261 -0
  22. package/.migrations/runtime/meta/0003_snapshot.json +1292 -0
  23. package/.migrations/runtime/meta/0004_snapshot.json +1240 -0
  24. package/.migrations/runtime/meta/0006_snapshot.json +1310 -0
  25. package/.migrations/runtime/meta/0007_snapshot.json +1362 -0
  26. package/.migrations/runtime/meta/0008_snapshot.json +1742 -0
  27. package/.migrations/runtime/meta/0009_snapshot.json +2413 -0
  28. package/.migrations/runtime/meta/0010_snapshot.json +2562 -0
  29. package/.migrations/runtime/meta/0011_snapshot.json +2812 -0
  30. package/.migrations/runtime/meta/0012_snapshot.json +2812 -0
  31. package/.migrations/runtime/meta/_journal.json +97 -0
  32. package/README.md +1584 -0
  33. package/RELEASING.md +89 -0
  34. package/agent/fleet.js +100 -0
  35. package/bin/cli.js +854 -0
  36. package/bin/manifold.js +4 -0
  37. package/boot/flow-revival.js +536 -0
  38. package/budget/index.js +495 -0
  39. package/budget/lib.js +59 -0
  40. package/dashboard/cost.js +528 -0
  41. package/dashboard/dist/assets/index-CUfp63sj.css +1 -0
  42. package/dashboard/dist/assets/index-Qy9JMpma.js +371 -0
  43. package/dashboard/dist/index.html +13 -0
  44. package/dashboard/event-log.js +267 -0
  45. package/dashboard/index.html +12 -0
  46. package/dashboard/package-lock.json +2877 -0
  47. package/dashboard/package.json +37 -0
  48. package/dashboard/pipeline-graph.js +131 -0
  49. package/dashboard/postcss.config.js +6 -0
  50. package/dashboard/search.js +183 -0
  51. package/dashboard/server.js +1015 -0
  52. package/dashboard/src/App.tsx +42 -0
  53. package/dashboard/src/api/client.ts +118 -0
  54. package/dashboard/src/api/types.ts +510 -0
  55. package/dashboard/src/api/ws.tsx +112 -0
  56. package/dashboard/src/components/CancelButton.tsx +63 -0
  57. package/dashboard/src/components/ClickToCopy.tsx +68 -0
  58. package/dashboard/src/components/CopyButton.tsx +61 -0
  59. package/dashboard/src/components/DailyCostTrend.tsx +85 -0
  60. package/dashboard/src/components/DailyTimeTrend.tsx +94 -0
  61. package/dashboard/src/components/Funnel.tsx +149 -0
  62. package/dashboard/src/components/GateForm.tsx +158 -0
  63. package/dashboard/src/components/GraphView.tsx +302 -0
  64. package/dashboard/src/components/GroupPathsSummary.tsx +47 -0
  65. package/dashboard/src/components/Histogram.tsx +292 -0
  66. package/dashboard/src/components/Layout.tsx +28 -0
  67. package/dashboard/src/components/NeedsAttention.tsx +98 -0
  68. package/dashboard/src/components/NodeContextCard.tsx +132 -0
  69. package/dashboard/src/components/PathTrail.tsx +35 -0
  70. package/dashboard/src/components/PipelineCostBreakdown.tsx +277 -0
  71. package/dashboard/src/components/RerunButton.tsx +46 -0
  72. package/dashboard/src/components/RunComparison.tsx +53 -0
  73. package/dashboard/src/components/Sparkline.tsx +94 -0
  74. package/dashboard/src/components/StatStrip.tsx +147 -0
  75. package/dashboard/src/components/StateTree.tsx +84 -0
  76. package/dashboard/src/components/StatusBadge.tsx +18 -0
  77. package/dashboard/src/components/SubflowPathPills.tsx +38 -0
  78. package/dashboard/src/components/SubflowSummary.tsx +24 -0
  79. package/dashboard/src/components/SubflowsCard.tsx +327 -0
  80. package/dashboard/src/components/TodayStrip.tsx +86 -0
  81. package/dashboard/src/components/TranscriptPane.tsx +99 -0
  82. package/dashboard/src/components/TranscriptRow.tsx +69 -0
  83. package/dashboard/src/components/ui/badge.tsx +38 -0
  84. package/dashboard/src/components/ui/button.tsx +28 -0
  85. package/dashboard/src/components/ui/card.tsx +42 -0
  86. package/dashboard/src/components/ui/skeleton.tsx +9 -0
  87. package/dashboard/src/components/ui/table.tsx +62 -0
  88. package/dashboard/src/index.css +26 -0
  89. package/dashboard/src/lib/anomaly.ts +42 -0
  90. package/dashboard/src/lib/format.ts +30 -0
  91. package/dashboard/src/lib/step-history.ts +13 -0
  92. package/dashboard/src/lib/subflow.ts +154 -0
  93. package/dashboard/src/lib/use-click-outside.ts +28 -0
  94. package/dashboard/src/lib/use-ignored-clusters.ts +67 -0
  95. package/dashboard/src/lib/utils.ts +6 -0
  96. package/dashboard/src/main.tsx +10 -0
  97. package/dashboard/src/types/shims.d.ts +4 -0
  98. package/dashboard/src/views/Home.tsx +478 -0
  99. package/dashboard/src/views/PipelineDetail.tsx +1185 -0
  100. package/dashboard/src/views/PipelinesList.tsx +111 -0
  101. package/dashboard/src/views/RunDetail.tsx +248 -0
  102. package/dashboard/src/views/Search.tsx +196 -0
  103. package/dashboard/stats.js +668 -0
  104. package/dashboard/tailwind.config.ts +43 -0
  105. package/dashboard/tree-stats.js +12 -0
  106. package/dashboard/tsconfig.json +25 -0
  107. package/dashboard/views.js +231 -0
  108. package/dashboard/vite.config.ts +34 -0
  109. package/drizzle.config.js +12 -0
  110. package/drizzle.config.ops.js +12 -0
  111. package/elevation.js +116 -0
  112. package/engine/admission-promotion-resume.js +127 -0
  113. package/engine/agent-dispatch.js +64 -0
  114. package/engine/child-resume-trigger.js +315 -0
  115. package/engine/executor-budget.js +87 -0
  116. package/engine/executor-cancel.js +83 -0
  117. package/engine/executor-errors.js +122 -0
  118. package/engine/executor-helpers.js +254 -0
  119. package/engine/executor-nodes.js +292 -0
  120. package/engine/executor-persist.js +212 -0
  121. package/engine/executor-subflow-children.js +275 -0
  122. package/engine/executor.js +1013 -0
  123. package/engine/global-concurrency.js +33 -0
  124. package/engine/loader.js +528 -0
  125. package/engine/needs-resolver.js +229 -0
  126. package/engine/pipelines-watcher.js +133 -0
  127. package/engine/result-replay.js +34 -0
  128. package/engine/revival-messages.js +11 -0
  129. package/engine/spawn-child.js +55 -0
  130. package/engine/wait-for-flow-settlement.js +109 -0
  131. package/events/catalog.js +26 -0
  132. package/events/emit.js +44 -0
  133. package/events/kinds.js +118 -0
  134. package/events/serve-ws.js +74 -0
  135. package/events/stream.js +35 -0
  136. package/events/ws-dialog.js +257 -0
  137. package/events/ws-frame.js +194 -0
  138. package/events/ws-run-events.js +70 -0
  139. package/events.js +32 -0
  140. package/gates/gate-resolver.js +576 -0
  141. package/gates/paused-flows.js +55 -0
  142. package/graphql/columns.js +67 -0
  143. package/graphql/schema.js +333 -0
  144. package/index.js +49 -0
  145. package/mcp/http.js +159 -0
  146. package/mcp/identity.js +94 -0
  147. package/mcp/stdio.js +80 -0
  148. package/mcp/tools.js +245 -0
  149. package/mcp/wire-ops.js +178 -0
  150. package/package.json +51 -0
  151. package/routes/bearer-auth.js +57 -0
  152. package/routes/discuss-audio.js +87 -0
  153. package/routes/discuss-component.js +39 -0
  154. package/routes/discuss-draft.js +159 -0
  155. package/routes/discuss-helpers.js +20 -0
  156. package/routes/discuss.js +848 -0
  157. package/routes/failures.js +104 -0
  158. package/routes/graphql.js +61 -0
  159. package/routes/health.js +54 -0
  160. package/routes/operator-discuss.js +193 -0
  161. package/routes/operator-resume.js +32 -0
  162. package/routes/operator-retry.js +301 -0
  163. package/routes/operator.js +539 -0
  164. package/routes/pipelines.js +118 -0
  165. package/routes/runs.js +1129 -0
  166. package/scripts/ci/import-check.mjs +50 -0
  167. package/scripts/link-core-self.mjs +31 -0
  168. package/scripts/with-guard.sh +24 -0
  169. package/server/app.js +503 -0
  170. package/server/registry.js +53 -0
  171. package/server/serve.js +163 -0
  172. package/state/admission-queue-store.js +325 -0
  173. package/state/attribution-registries.js +102 -0
  174. package/state/batch-writer.js +162 -0
  175. package/state/db-guard.js +63 -0
  176. package/state/db-health.js +27 -0
  177. package/state/db.js +122 -0
  178. package/state/discuss-store.js +299 -0
  179. package/state/failure-store.js +427 -0
  180. package/state/migrate.js +104 -0
  181. package/state/node-cost.js +67 -0
  182. package/state/node-executions.js +775 -0
  183. package/state/node-health-store.js +124 -0
  184. package/state/ops-merge.js +93 -0
  185. package/state/paths.js +146 -0
  186. package/state/pipeline-dirs.js +99 -0
  187. package/state/pipeline-registry.js +449 -0
  188. package/state/run-store.js +697 -0
  189. package/state/schema.js +438 -0
  190. package/state/schema.ops.js +44 -0
  191. package/state/session-index.js +177 -0
  192. package/state/session-keys.js +39 -0
  193. package/state/state-store.js +311 -0
  194. package/state/subflow-state.js +126 -0
  195. package/state/tool-handoff.js +169 -0
  196. package/telemetry/budget-alert.js +353 -0
  197. package/telemetry/cli.js +331 -0
  198. package/telemetry/grammar.js +119 -0
  199. package/telemetry/http-budget.js +132 -0
  200. package/telemetry/http-cost.js +670 -0
  201. package/telemetry/http-helpers.js +134 -0
  202. package/telemetry/http-tree.js +349 -0
  203. package/telemetry/http.js +44 -0
  204. package/telemetry/index.js +307 -0
  205. package/telemetry/ingest.js +134 -0
  206. package/telemetry/labels.js +115 -0
  207. package/telemetry/pricer.js +77 -0
  208. package/telemetry/resolver.js +314 -0
  209. package/telemetry/store.js +147 -0
  210. package/utils/run-patch.js +43 -0
@@ -0,0 +1,1015 @@
1
+ // server.js — read-only HTTP dashboard for manifold.
2
+ //
3
+ // Bound to 127.0.0.1 only (no LAN exposure, no auth surface). All routes are
4
+ // read-only — actuation stays in the CLI and Telegram surfaces. Live updates
5
+ // are pushed over WebSocket from the event-bus (event-log.js), which fires
6
+ // on every store write — no polling lag, no per-client catch-up stream:
7
+ // the run-detail page reloads full state from REST after any reconnect.
8
+ //
9
+ // File-serving for the bundled SPA uses node:http only; no express/fastify.
10
+
11
+ import http from "node:http";
12
+ import { attachWsEndpoint } from "../events/ws-frame.js";
13
+ import { readFile, readdir, stat } from "node:fs/promises";
14
+ import path from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+ import { serializePipeline } from "./pipeline-graph.js";
17
+ import { computeGlobalStats, computePipelineStats, compareRunToMedian, computeNodeStats, resolveDisplayStep } from "./stats.js";
18
+ import { searchRuns } from "./search.js";
19
+ import { costForRun, costForPipeline, costForAllPipelines } from "./cost.js";
20
+ import { computeViews } from "./views.js";
21
+ import { stepsExecutedFromTree } from "./tree-stats.js";
22
+ import { TERMINAL_STATUS_SET } from "../state/run-store.js";
23
+ import { assembleState } from "../engine/executor-helpers.js";
24
+ import { getAllSubflowGroups } from "../state/subflow-state.js";
25
+ import { getNodeExecutionsStore } from "../state/node-executions.js";
26
+
27
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
28
+ // Static assets come from vite's build output under `dist/`. Run `npm run
29
+ // build` from this directory after editing the React sources to refresh.
30
+ const DIST_DIR = path.join(HERE, "dist");
31
+
32
+ const MIME = {
33
+ ".html": "text/html; charset=utf-8",
34
+ ".js": "application/javascript; charset=utf-8",
35
+ ".css": "text/css; charset=utf-8",
36
+ ".json": "application/json; charset=utf-8",
37
+ ".md": "text/markdown; charset=utf-8",
38
+ ".txt": "text/plain; charset=utf-8",
39
+ ".svg": "image/svg+xml",
40
+ ".png": "image/png",
41
+ ".jpg": "image/jpeg",
42
+ ".jpeg": "image/jpeg",
43
+ ".gif": "image/gif",
44
+ ".ico": "image/x-icon",
45
+ };
46
+
47
+ export function createDashboardServer({ writeStore, readStore, failureStore, discussStore, nodeExecutionsStore, pipelinesRef, pipelineRegistryStore, ensurePipelinesLoaded, executor, eventBus, port, host, logger, recordItemDecision }) {
48
+ let server = null;
49
+ // Live WS door (events/ws-frame.js) — opened in start(), drained on stop().
50
+ let door = null;
51
+ let unsubscribe = null;
52
+
53
+ // ── Direct store reads ────────────────────────────────────────────────────
54
+ // Every read below hits manifold's own stores with the same query logic
55
+ // the gateway's /manifold/* routes use — no gateway hop. Payload shapes
56
+ // match the old gateway responses field-for-field so the React app is untouched.
57
+
58
+ // Adapter-injected in production; process singleton otherwise (the same
59
+ // binding the gateway routes read through).
60
+ function nx() {
61
+ return nodeExecutionsStore ?? getNodeExecutionsStore();
62
+ }
63
+
64
+ // Normalize a listRunsPage row: *Ms suffix timestamps + synthesized
65
+ // stateJson so stats functions that access stateJson.pipelineId work.
66
+ function adaptRun(r) {
67
+ return {
68
+ ...r,
69
+ createdAt: r.createdAt ?? r.createdAtMs,
70
+ updatedAt: r.updatedAt ?? r.updatedAtMs,
71
+ endedAt: r.endedAt ?? r.endedAtMs,
72
+ stateJson: r.stateJson ?? { pipelineId: r.pipelineId },
73
+ };
74
+ }
75
+
76
+ // All top-level runs, trimmed to the same 500-row window the gateway's
77
+ // list endpoint served (limit=min(500, 9999), limit+1 fetch, pop).
78
+ async function fetchAllRuns({ pipelineId, status } = {}) {
79
+ const page = await readStore.listRunsPage({
80
+ pipelineId: pipelineId || null,
81
+ status: status || null,
82
+ limit: 501,
83
+ });
84
+ const rows = page.slice(0, 500);
85
+ const childSummaryMap = await nx().summarizeChildrenByFlowIds(rows.map((r) => r.flowId));
86
+ const EMPTY_SUBFLOWS = { total: 0, pending: 0, failed: 0, skipped: 0, succeeded: 0 };
87
+ const discussSummaries = discussStore ? await discussStore.getBulkSummaries(rows.map((r) => r.flowId)) : {};
88
+ const runs = rows.map((r) => {
89
+ const discuss = discussSummaries[r.flowId] ?? null;
90
+ const subflows = childSummaryMap.get(r.flowId) ?? EMPTY_SUBFLOWS;
91
+ return {
92
+ ...r,
93
+ subflowTotal: subflows.total,
94
+ subflowPending: subflows.pending,
95
+ subflowFailed: subflows.failed,
96
+ subflowSkipped: subflows.skipped,
97
+ subflowSucceeded: subflows.succeeded,
98
+ pendingDraftItemIds: discuss?.pendingItemIds ?? [],
99
+ };
100
+ });
101
+ return runs.map(adaptRun);
102
+ }
103
+
104
+ // Full run payload — same shape as the gateway's sendFullRun
105
+ // (routes/runs.js): assembleState-enriched stateJson, gate_records gates,
106
+ // failure_events errorEntries, *Ms timestamps, parent linkage. Returns
107
+ // null when the flow does not exist.
108
+ async function fetchFlow(flowId) {
109
+ const flow = await readStore.get(flowId);
110
+ if (!flow) return null;
111
+ return readFullRun(flow);
112
+ }
113
+
114
+ async function readFullRun(flow) {
115
+ const store = nx();
116
+ const enrichedState = await assembleState(flow.flowId, {
117
+ runStore: readStore, nodeExecutionsStore: store, baseState: flow.stateJson ?? {},
118
+ });
119
+ const gates = await store.listGateRecordsForFlow(flow.flowId);
120
+ const { loop: _loop, errors: _errors, gates: _staleGates, ...stateWithoutLegacy } = enrichedState;
121
+ let parentFlowId = null, parentNodeId = null, parentSubflowKey = null;
122
+ let resolvedPipelineId = flow.stateJson?.pipelineId ?? null;
123
+ if (flow.parentInvocationId) {
124
+ const invocation = await store.getInvocation(flow.parentInvocationId);
125
+ if (invocation) {
126
+ parentFlowId = invocation.flowId;
127
+ parentNodeId = invocation.nodeId;
128
+ parentSubflowKey = invocation.subflowKey;
129
+ const parentFlow = await readStore.get(parentFlowId);
130
+ if (parentFlow) resolvedPipelineId = parentFlow.pipelineId ?? resolvedPipelineId;
131
+ }
132
+ }
133
+ return {
134
+ flowId: flow.flowId,
135
+ pipelineId: resolvedPipelineId,
136
+ runId: flow.stateJson?.runId ?? null,
137
+ status: flow.status,
138
+ currentStep: flow.currentStep ?? null,
139
+ lastStep: flow.lastStep,
140
+ revision: flow.revision,
141
+ statusReason: flow.statusReason ?? null,
142
+ stateJson: { ...stateWithoutLegacy, gates },
143
+ waitJson: flow.waitJson ?? null,
144
+ errorEntries: failureStore ? await failureStore.queryErrorsByFlow(flow.flowId) : [],
145
+ createdAtMs: flow.createdAt ?? null,
146
+ updatedAtMs: flow.updatedAt ?? null,
147
+ endedAtMs: flow.endedAt ?? null,
148
+ parentFlowId,
149
+ nodeId: parentNodeId,
150
+ subflowKey: parentSubflowKey,
151
+ };
152
+ }
153
+
154
+ // Errors for a set of flowIds → Map<flowId, ErrorEntry[]> (same source as
155
+ // the gateway's /manifold/errors: failureStore.queryErrorsByFlowIds).
156
+ async function fetchErrors(flowIds) {
157
+ if (!flowIds.length) return new Map();
158
+ if (!failureStore) return new Map();
159
+ return failureStore.queryErrorsByFlowIds(flowIds);
160
+ }
161
+
162
+ // Batched "which top-level nodes did each flow visit" → Map<flowId,
163
+ // Set<nodeId>>, backing the auto-funnel visit check without one round-trip
164
+ // per run. Empty Map on error — the funnel then reports 0 for every
165
+ // stage, same as "no runs visited yet", rather than throwing.
166
+ async function fetchTreeSummary(flowIds) {
167
+ if (!flowIds.length) return new Map();
168
+ try {
169
+ const visitedMap = await nx().listVisitedNodeIdsByFlow(flowIds);
170
+ return new Map([...visitedMap.entries()].map(([flowId, nodeIds]) => [flowId, new Set(nodeIds ?? [])]));
171
+ } catch { return new Map(); }
172
+ }
173
+
174
+ // Subflow rows for a flow — same { subflows: [...] } envelope the
175
+ // gateway's sendSubflowsList serves (legacy errors column stripped).
176
+ async function fetchSubflows(flowId) {
177
+ try {
178
+ const grouped = await getAllSubflowGroups({
179
+ flowId, runStore: readStore, nodeExecutionsStore: nx(),
180
+ });
181
+ const subflows = Object.values(grouped).flatMap((group) =>
182
+ Object.values(group).map(({ errors: _errors, ...rest }) => rest)
183
+ );
184
+ return { subflows };
185
+ } catch { return {}; }
186
+ }
187
+
188
+ // This flow's own top-level node list — the same row shape the gateway's
189
+ // /tree root serves (one row per invocation, ordered by invokedAt).
190
+ // Empty array on error rather than throwing — callers treat "no tree
191
+ // data" the same as "flow has no history yet".
192
+ async function fetchTree(flowId) {
193
+ try {
194
+ const flow = await readStore.get(flowId);
195
+ if (!flow) return [];
196
+ return await buildTreeNodeRows(flow);
197
+ } catch { return []; }
198
+ }
199
+
200
+ // Ports routes/runs.js's buildTreeNodeRows (same flow-status fallback and
201
+ // point-in-time kind/agent reads, same shallow immediate-children rollup).
202
+ async function buildTreeNodeRows(flow) {
203
+ const store = nx();
204
+ const pipelineId = flow.stateJson?.pipelineId;
205
+ const invocations = await store.listInvocationsForFlow(flow.flowId);
206
+ const failedExecutionIds = new Set(
207
+ ((failureStore ? await failureStore.queryErrorsByFlow(flow.flowId) : []) ?? [])
208
+ .map((e) => e.executionId).filter(Boolean)
209
+ );
210
+ const versionRequests = invocations.map((inv) => ({ pipelineId, nodeName: inv.nodeId, atMs: inv.invokedAt }));
211
+ const versions = await pipelineRegistryStore.getNodeVersionsBatch(versionRequests);
212
+ const versionByInvocationId = new Map(invocations.map((inv, i) => [inv.invocationId, versions[i]]));
213
+ const subflowNodeIds = [
214
+ ...new Set(invocations.filter((inv) => versionByInvocationId.get(inv.invocationId)?.kind === "subflow").map((inv) => inv.nodeId)),
215
+ ];
216
+ const childrenByNodeId = new Map();
217
+ if (subflowNodeIds.length > 0) {
218
+ const invIdsByNodeId = await store.listInvocationIdsForNodes(flow.flowId, subflowNodeIds);
219
+ const allInvIds = [...invIdsByNodeId.values()].flat();
220
+ const allChildren = await readStore.listForParentInvocations(allInvIds);
221
+ const nodeIdByInvId = new Map();
222
+ for (const [nodeId, ids] of invIdsByNodeId) {
223
+ for (const id of ids) nodeIdByInvId.set(id, nodeId);
224
+ }
225
+ for (const child of allChildren) {
226
+ const nodeId = nodeIdByInvId.get(child.parentInvocationId);
227
+ if (!nodeId) continue;
228
+ if (!childrenByNodeId.has(nodeId)) childrenByNodeId.set(nodeId, []);
229
+ childrenByNodeId.get(nodeId).push(child);
230
+ }
231
+ }
232
+ const lastIdx = invocations.length - 1;
233
+ return invocations.map((inv, idx) => {
234
+ const version = versionByInvocationId.get(inv.invocationId);
235
+ const kind = version?.kind ?? null;
236
+ const isSubflowNode = kind === "subflow";
237
+ const kids = isSubflowNode ? (childrenByNodeId.get(inv.nodeId) ?? []) : [];
238
+ let status;
239
+ if (inv.latestExecutionId && failedExecutionIds.has(inv.latestExecutionId)) {
240
+ status = "failed";
241
+ } else if (idx === lastIdx) {
242
+ status = flow.status;
243
+ } else {
244
+ status = "succeeded";
245
+ }
246
+ const row = {
247
+ type: "node",
248
+ invocationId: inv.invocationId,
249
+ nodeId: inv.nodeId,
250
+ kind,
251
+ agent: version?.agent ?? null,
252
+ status,
253
+ enteredAt: inv.enteredAt,
254
+ exitedAt: inv.exitedAt,
255
+ execKind: inv.kind,
256
+ executionCount: inv.executionCount,
257
+ everRetriedOrRevived: inv.everRetriedOrRevived,
258
+ hasChildren: isSubflowNode && kids.length > 0,
259
+ };
260
+ if (isSubflowNode) row.rollup = bucketChildFlowsByStatus(kids);
261
+ return row;
262
+ });
263
+ }
264
+
265
+ // Shallow rollup (immediate children only) — same status-bucket shape
266
+ // summarizeChildrenByFlowIds uses.
267
+ function bucketChildFlowsByStatus(childFlowRows) {
268
+ const rollup = { succeeded: 0, failed: 0, pending: 0, skipped: 0, cancelled: 0 };
269
+ for (const c of childFlowRows) {
270
+ if (c.status === "succeeded") rollup.succeeded++;
271
+ else if (c.status === "failed") rollup.failed++;
272
+ else if (c.status === "skipped") rollup.skipped++;
273
+ else if (c.status === "cancelled") rollup.cancelled++;
274
+ else rollup.pending++;
275
+ }
276
+ return rollup;
277
+ }
278
+
279
+ // TTL cache for stats endpoints — these are polled by the SPA on a timer
280
+ // and can tolerate a few seconds of staleness. Keyed on fetch parameters;
281
+ // runs + errors are always fetched together and cached as a pair.
282
+ const _statsCache = new Map();
283
+ const STATS_TTL_MS = 5_000;
284
+
285
+ async function cachedRunsAndErrors(key, runsOpts = {}) {
286
+ const now = Date.now();
287
+ const hit = _statsCache.get(key);
288
+ if (hit && hit.expiresAt > now) return hit.data;
289
+ const runs = await fetchAllRuns(runsOpts);
290
+ const errorsByFlow = await fetchErrors(runs.map((r) => r.flowId));
291
+ const data = { runs, errorsByFlow };
292
+ _statsCache.set(key, { data, expiresAt: now + STATS_TTL_MS });
293
+ return data;
294
+ }
295
+
296
+ // Same /graph prefix strip as handle() below: the bundle is built with
297
+ // vite base `/graph/`, so the WS URL embeds the prefix when served
298
+ // under it and arrives bare on direct loopback.
299
+ function wsPathMatch(pathname) {
300
+ return pathname === "/api/events/ws" || pathname === "/graph/api/events/ws";
301
+ }
302
+
303
+ function dispatchWs(event) {
304
+ try {
305
+ door?.broadcast(event);
306
+ } catch { /* client gone; cleanup on close */ }
307
+ }
308
+
309
+ async function handle(req, res) {
310
+ const url = new URL(req.url, `http://${req.headers.host}`);
311
+ // The bundle is built with vite base `/graph/`, so all HTML references
312
+ // (assets, API client URLs) embed that prefix. We strip it here so the
313
+ // route table below stays prefix-agnostic. This works two ways:
314
+ // - Direct loopback: `127.0.0.1:7430/graph/...` arrives with the prefix.
315
+ // - Behind `tailscale serve --set-path=/graph`: tailscale already strips
316
+ // the mount prefix before forwarding, so backend sees the unprefixed
317
+ // path and the `if` is a no-op.
318
+ let pathname = url.pathname;
319
+ if (pathname.startsWith("/graph/")) {
320
+ pathname = pathname.slice("/graph".length);
321
+ }
322
+
323
+ try {
324
+ // ── API ────────────────────────────────────────────────────────────────
325
+ if (req.method === "GET" && pathname === "/api/health") {
326
+ return sendJson(res, 200, {
327
+ ok: true,
328
+ pipelines: pipelinesRef.value.size,
329
+ bus: eventBus.snapshot(),
330
+ });
331
+ }
332
+
333
+ if (req.method === "GET" && pathname === "/api/pipelines") {
334
+ await ensurePipelinesLoaded?.();
335
+ const implemented = [...pipelinesRef.value.values()].map((p) => ({
336
+ ...serializePipeline(p),
337
+ historical: false,
338
+ }));
339
+ // Augment with pipeline ids that exist only in flow_runs history — the
340
+ // operator may have run them in the past and then removed the
341
+ // definition file. We show them dimmed so the dashboard surfaces all
342
+ // runs in context, not just the ones whose source still exists.
343
+ const implementedIds = new Set(implemented.map((p) => p.id));
344
+ const runCounts = new Map();
345
+ for (const r of await fetchAllRuns()) {
346
+ const pid = r.stateJson?.pipelineId;
347
+ if (!pid || implementedIds.has(pid)) continue;
348
+ runCounts.set(pid, (runCounts.get(pid) ?? 0) + 1);
349
+ }
350
+ const historical = [...runCounts.entries()].map(([id, runs]) => ({
351
+ id, goal: null, file: null, dir: null,
352
+ nodes: [], edges: [],
353
+ historical: true, runs,
354
+ }));
355
+ return sendJson(res, 200, [...implemented, ...historical]);
356
+ }
357
+
358
+ const pipelineMatch = pathname.match(/^\/api\/pipelines\/([^/]+)$/);
359
+ if (req.method === "GET" && pipelineMatch) {
360
+ await ensurePipelinesLoaded?.();
361
+ const p = pipelinesRef.value.get(decodeURIComponent(pipelineMatch[1]));
362
+ if (!p) return sendJson(res, 404, { error: "pipeline not found" });
363
+ return sendJson(res, 200, serializePipeline(p));
364
+ }
365
+
366
+ if (req.method === "GET" && pathname === "/api/stats") {
367
+ const { runs, errorsByFlow } = await cachedRunsAndErrors("all");
368
+ return sendJson(res, 200, computeGlobalStats(runs, errorsByFlow));
369
+ }
370
+
371
+ // /api/stats/cost?sinceDays=N — cross-pipeline cost roll-up for the
372
+ // home-page sidebar. One disk walk per run (via costForRun); fine
373
+ // at <1k runs, revisit when it bites.
374
+ if (req.method === "GET" && pathname === "/api/stats/cost") {
375
+ const sinceDays = Number(url.searchParams.get("sinceDays") ?? "");
376
+ const sinceMs = Number.isFinite(sinceDays) && sinceDays > 0
377
+ ? Date.now() - sinceDays * 86_400_000
378
+ : null;
379
+ const cost = await costForAllPipelines(await fetchAllRuns(), { sinceMs });
380
+ return sendJson(res, 200, cost);
381
+ }
382
+
383
+ // Cost subroute must precede the broader pipelineStats match below —
384
+ // otherwise the `.+$` regex captures "<id>/cost" as the pipelineId
385
+ // and the more specific endpoint is never reached.
386
+ const pipeCostMatch = pathname.match(/^\/api\/stats\/pipelines\/(.+)\/cost$/);
387
+ if (req.method === "GET" && pipeCostMatch) {
388
+ const pipelineId = decodeURIComponent(pipeCostMatch[1]);
389
+ const sinceDays = Number(url.searchParams.get("sinceDays") ?? "");
390
+ const sinceMs = Number.isFinite(sinceDays) && sinceDays > 0
391
+ ? Date.now() - sinceDays * 86_400_000
392
+ : null;
393
+ const priorWindowMs = sinceMs ? Date.now() - sinceMs : null;
394
+ const cost = await costForPipeline(await fetchAllRuns({ pipelineId }), pipelineId, { sinceMs, priorWindowMs });
395
+ return sendJson(res, 200, cost);
396
+ }
397
+
398
+ // /api/stats/pipelines/:id/views?sinceDays=N — pipeline-declared
399
+ // view payloads. Each entry is the computed result for one
400
+ // `views[]` declaration (see views.js header for the
401
+ // declaration shape). Empty array when the pipeline declares
402
+ // none — caller skips rendering.
403
+ const pipeViewsMatch = pathname.match(/^\/api\/stats\/pipelines\/(.+)\/views$/);
404
+ if (req.method === "GET" && pipeViewsMatch) {
405
+ const pipelineId = decodeURIComponent(pipeViewsMatch[1]);
406
+ const pipeline = pipelinesRef.value.get(pipelineId);
407
+ if (!pipeline) return sendJson(res, 404, { error: "pipeline not loaded", pipelineId });
408
+ const sinceDays = Number(url.searchParams.get("sinceDays") ?? "");
409
+ const sinceMs = Number.isFinite(sinceDays) && sinceDays > 0
410
+ ? Date.now() - sinceDays * 86_400_000
411
+ : null;
412
+ const views = await computeViews(pipeline, { sinceMs });
413
+ return sendJson(res, 200, { sinceMs, views });
414
+ }
415
+
416
+ const pipelineStatsMatch = pathname.match(/^\/api\/stats\/pipelines\/(.+)$/);
417
+ if (req.method === "GET" && pipelineStatsMatch) {
418
+ const pipelineId = decodeURIComponent(pipelineStatsMatch[1]);
419
+ // Pass the pipeline def so the funnel + any future
420
+ // pipeline-declared metrics are read transparently rather than
421
+ // looked up in a hardcoded dashboard-side map.
422
+ const pipeline = pipelinesRef.value.get(pipelineId) ?? null;
423
+ const { runs, errorsByFlow } = await cachedRunsAndErrors("all");
424
+ const mine = runs.filter((r) => (r.stateJson?.pipelineId ?? "") === pipelineId);
425
+ const visitedByFlow = await fetchTreeSummary(mine.map((r) => r.flowId));
426
+ // Lets an older run's invocation under a since-renamed node id
427
+ // still count toward the auto-derived funnel's current stage —
428
+ // see pipeline-registry.js's getNodeLineageBatch.
429
+ const lineageByNodeId = await pipelineRegistryStore.getNodeLineageBatch(pipelineId, Object.keys(pipeline?.nodes ?? {}));
430
+ return sendJson(res, 200, await computePipelineStats(runs, pipelineId, pipeline, errorsByFlow, null, null, visitedByFlow, lineageByNodeId));
431
+ }
432
+
433
+ // /api/pipelines/:id/nodes/:nodeId/stats — per-node aggregation for the
434
+ // graph-view click panel. Scans the pipeline's runs and counts how many
435
+ // visited / failed at / blocked at / terminated at this node, plus the
436
+ // most-recent 10 runs that touched it.
437
+ const nodeStatsMatch = pathname.match(/^\/api\/pipelines\/([^/]+)\/nodes\/([^/]+)\/stats$/);
438
+ if (req.method === "GET" && nodeStatsMatch) {
439
+ const pipelineId = decodeURIComponent(nodeStatsMatch[1]);
440
+ const nodeId = decodeURIComponent(nodeStatsMatch[2]);
441
+ const { runs, errorsByFlow } = await cachedRunsAndErrors(`pipeline:${pipelineId}`, { pipelineId });
442
+ const nodeStatsMine = runs.filter((r) => (r.stateJson?.pipelineId ?? "") === pipelineId);
443
+ const nodeStatsVisited = await fetchTreeSummary(nodeStatsMine.map((r) => r.flowId));
444
+ const nodeStatsLineage = await pipelineRegistryStore.getNodeLineageBatch(pipelineId, [nodeId]);
445
+ return sendJson(res, 200, computeNodeStats(runs, pipelineId, nodeId, errorsByFlow, nodeStatsVisited, nodeStatsLineage));
446
+ }
447
+
448
+ // /api/search?q=<query>&status=<status>&limit=N — substring
449
+ // search over structured fields + errorEntries[] (flow_node_executions,
450
+ // covers both root and subflow errors) + top-level state keys.
451
+ // `status` is a structured filter applied before the free-text match
452
+ // (exact equality vs r.status). Both q and status are optional;
453
+ // status-only returns every run with that status, snippet-less. See
454
+ // search.js header for design call.
455
+ if (req.method === "GET" && pathname === "/api/search") {
456
+ const q = url.searchParams.get("q") ?? "";
457
+ const status = url.searchParams.get("status") ?? "";
458
+ const limitRaw = url.searchParams.get("limit");
459
+ const limit = limitRaw ? Math.max(1, Math.min(500, Number(limitRaw))) : 50;
460
+ const searchRunsList = await fetchAllRuns();
461
+ const errorsByFlow = await fetchErrors(searchRunsList.map((r) => r.flowId));
462
+ return sendJson(res, 200, searchRuns(searchRunsList, q, { limit, status, errorsByFlow }));
463
+ }
464
+
465
+ // /api/runs/:flowId/cost — sum usage.cost.total across every agent
466
+ // session the flow spawned. Disk-walks the agent session JSONLs
467
+ // (same data source as the transcript endpoint). See cost.js for
468
+ // the aggregation shape.
469
+ const runCostMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/cost$/i);
470
+ if (req.method === "GET" && runCostMatch) {
471
+ const cost = await costForRun(runCostMatch[1]);
472
+ return sendJson(res, 200, cost);
473
+ }
474
+
475
+ // /api/runs/:flowId/subflows — subflow rows grouped by groupId,
476
+ // shaped like the old stateJson.subflows mirror ({[groupId]:
477
+ // {[subflowKey]: SubflowData}}) so SubflowsCard can consume it
478
+ // without a shape change on the frontend.
479
+ const runSubflowsMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/subflows$/i);
480
+ if (req.method === "GET" && runSubflowsMatch) {
481
+ const flowId = runSubflowsMatch[1];
482
+ const grouped = await fetchSubflows(flowId);
483
+ return sendJson(res, 200, grouped);
484
+ }
485
+
486
+ // /api/runs/:flowId/tree — node-invocation tree, the same
487
+ // shape/endpoint companion clients already consume at the gateway
488
+ // level. Backs PathTrail/GraphView's executed-path rendering
489
+ // instead of stateJson._stepHistory.
490
+ const runTreeMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/tree$/i);
491
+ if (req.method === "GET" && runTreeMatch) {
492
+ const items = await fetchTree(runTreeMatch[1]);
493
+ return sendJson(res, 200, { items });
494
+ }
495
+
496
+ const runCompareMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/compare$/i);
497
+ if (req.method === "GET" && runCompareMatch) {
498
+ const flow = await fetchFlow(runCompareMatch[1]);
499
+ if (!flow) return sendJson(res, 404, { error: "run not found" });
500
+ const peers = (await fetchAllRuns({ pipelineId: flow.pipelineId })).map(adaptRun);
501
+ return sendJson(res, 200, compareRunToMedian(flow, peers));
502
+ }
503
+
504
+ if (req.method === "GET" && pathname === "/api/runs") {
505
+ const statusFilter = url.searchParams.get("status");
506
+ const pipelineFilter = url.searchParams.get("pipelineId");
507
+ // since/until filter by createdAt — used when the home pins a
508
+ // day on the runs/day chart. Lets the table show runs from
509
+ // older days that the default top-200-by-updatedAt window
510
+ // wouldn't otherwise include.
511
+ const sinceParam = parseInt(url.searchParams.get("since") ?? "", 10);
512
+ const untilParam = parseInt(url.searchParams.get("until") ?? "", 10);
513
+ const sinceMs = Number.isFinite(sinceParam) ? sinceParam : null;
514
+ const untilMs = Number.isFinite(untilParam) ? untilParam : null;
515
+ const limit = Math.min(parseInt(url.searchParams.get("limit") ?? "200", 10) || 200, 1000);
516
+ let rows = await fetchAllRuns({ pipelineId: pipelineFilter || undefined, status: statusFilter || undefined });
517
+ if (sinceMs != null) rows = rows.filter((r) => (r.createdAt ?? 0) >= sinceMs);
518
+ if (untilMs != null) rows = rows.filter((r) => (r.createdAt ?? 0) < untilMs);
519
+ rows.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
520
+ rows = rows.slice(0, limit);
521
+ const errorsByFlow = await fetchErrors(rows.map((r) => r.flowId));
522
+ rows = await Promise.all(rows.map((r) => summariseRun(r, errorsByFlow.get(r.flowId) ?? [])));
523
+ return sendJson(res, 200, rows);
524
+ }
525
+
526
+ const runMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)$/i);
527
+ if (req.method === "GET" && runMatch) {
528
+ const flow = await fetchFlow(runMatch[1]);
529
+ if (!flow) return sendJson(res, 404, { error: "run not found" });
530
+ return sendJson(res, 200, fullRun(flow, flow.errorEntries ?? []));
531
+ }
532
+
533
+ const runEventsMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/events$/i);
534
+ if (req.method === "GET" && runEventsMatch) {
535
+ return sendJson(res, 200, await eventBus.getEventsFor(runEventsMatch[1]));
536
+ }
537
+
538
+ const runSummaryMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/summary$/i);
539
+ if (req.method === "GET" && runSummaryMatch) {
540
+ return handleSummary(res, runSummaryMatch[1]);
541
+ }
542
+
543
+ const artifactsListMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/artifacts$/i);
544
+ if (req.method === "GET" && artifactsListMatch) {
545
+ return sendArtifactsList(res, artifactsListMatch[1]);
546
+ }
547
+
548
+ const transcriptsMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/transcripts$/i);
549
+ if (req.method === "GET" && transcriptsMatch) {
550
+ return sendTranscripts(res, transcriptsMatch[1]);
551
+ }
552
+
553
+ const artifactGetMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/artifacts\/(.+)$/i);
554
+ if (req.method === "GET" && artifactGetMatch) {
555
+ return sendArtifact(res, artifactGetMatch[1], decodeURIComponent(artifactGetMatch[2]));
556
+ }
557
+
558
+ // ── Actuation: respond to a gate item ───────────────────────────────
559
+ // Delegates to the shared recordItemDecision helper (same write site
560
+ // as TG callback, CLI, and the bridge's /manifold/gate/resolve).
561
+ // POST body: { itemId, decision: "approve"|"reject"|"edit", text? }.
562
+ const approveMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/approve$/i);
563
+ if (req.method === "POST" && approveMatch) {
564
+ return handleApprove(req, res, approveMatch[1]);
565
+ }
566
+
567
+ const cancelMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/cancel$/i);
568
+ if (req.method === "POST" && cancelMatch) {
569
+ return handleCancel(req, res, cancelMatch[1]);
570
+ }
571
+
572
+ const rerunMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/rerun$/i);
573
+ if (req.method === "POST" && rerunMatch) {
574
+ return handleRerun(req, res, rerunMatch[1]);
575
+ }
576
+
577
+ const pauseMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/pause$/i);
578
+ if (req.method === "POST" && pauseMatch) {
579
+ return handlePause(req, res, pauseMatch[1]);
580
+ }
581
+
582
+ const resumeMatch = pathname.match(/^\/api\/runs\/([0-9a-f-]+)\/resume$/i);
583
+ if (req.method === "POST" && resumeMatch) {
584
+ return handleResume(req, res, resumeMatch[1]);
585
+ }
586
+
587
+ if (req.method === "POST" && pathname === "/api/runs/bulk-cancel") {
588
+ return handleBulkCancel(req, res);
589
+ }
590
+
591
+ // ── Static SPA fallback ─────────────────────────────────────────────
592
+ // Live events moved to the WS door (/api/events/ws, attached in
593
+ // start()); there is no HTTP fallback — a client that cannot
594
+ // Upgrade must poll the REST history endpoints instead.
595
+ // Any unmatched GET maps to a file inside `dist/`. `/` and `/index.html`
596
+ // serve the SPA shell; vite-emitted `/assets/<hash>.{js,css}` URLs land
597
+ // here too. Path-traversal guarded by ensuring the resolved absolute
598
+ // path stays inside DIST_DIR.
599
+ if (req.method === "GET") {
600
+ const rel = pathname === "/" ? "index.html" : pathname.slice(1);
601
+ const resolved = path.resolve(DIST_DIR, rel);
602
+ if (!resolved.startsWith(DIST_DIR + path.sep) && resolved !== DIST_DIR) {
603
+ return sendJson(res, 403, { error: "forbidden" });
604
+ }
605
+ return serveFile(res, resolved);
606
+ }
607
+
608
+ return sendJson(res, 404, { error: "not found", path: pathname });
609
+ } catch (err) {
610
+ logger?.warn?.(`manifold dashboard handler error on ${pathname}: ${err?.message ?? err}`);
611
+ return sendJson(res, 500, { error: "internal", message: err?.message ?? String(err) });
612
+ }
613
+ }
614
+
615
+ async function sendArtifactsList(res, flowId) {
616
+ const flow = await fetchFlow(flowId);
617
+ if (!flow) return sendJson(res, 404, { error: "run not found" });
618
+ const pipelineId = flow.stateJson?.pipelineId;
619
+ const runId = flow.stateJson?.runId;
620
+ if (!pipelineId || !runId) return sendJson(res, 200, []);
621
+ const pipeline = pipelinesRef.value.get(pipelineId);
622
+ if (!pipeline?._dir) return sendJson(res, 200, []);
623
+ const runDir = path.join(pipeline._dir, "runs", runId);
624
+ try {
625
+ const entries = await readdir(runDir, { withFileTypes: true });
626
+ const out = [];
627
+ for (const ent of entries) {
628
+ if (!ent.isFile()) continue;
629
+ const full = path.join(runDir, ent.name);
630
+ const s = await stat(full);
631
+ out.push({ name: ent.name, size: s.size, mtime: s.mtimeMs });
632
+ }
633
+ return sendJson(res, 200, out);
634
+ } catch (err) {
635
+ if (err.code === "ENOENT") return sendJson(res, 200, []);
636
+ throw err;
637
+ }
638
+ }
639
+
640
+ // Sessions are opaque: transcript attribution comes from the session
641
+ // ledger, never from the session's shape.
642
+ async function sendTranscripts(res, flowId) {
643
+ const flow = await fetchFlow(flowId);
644
+ if (!flow) return sendJson(res, 404, { error: "run not found" });
645
+ return sendJson(res, 200, []);
646
+ }
647
+
648
+ async function readJsonBody(req, maxBytes = 64 * 1024) {
649
+ return new Promise((resolve, reject) => {
650
+ const chunks = [];
651
+ let total = 0;
652
+ req.on("data", (c) => {
653
+ total += c.length;
654
+ if (total > maxBytes) {
655
+ req.destroy();
656
+ reject(new Error("body too large"));
657
+ return;
658
+ }
659
+ chunks.push(c);
660
+ });
661
+ req.on("end", () => {
662
+ if (total === 0) return resolve({});
663
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf-8"))); }
664
+ catch (err) { reject(err); }
665
+ });
666
+ req.on("error", reject);
667
+ });
668
+ }
669
+
670
+ async function handleApprove(req, res, flowId) {
671
+ let body;
672
+ try { body = await readJsonBody(req); }
673
+ catch (err) { return sendJson(res, 400, { error: "invalid JSON body", message: err?.message ?? String(err) }); }
674
+ const { itemId, decision, text } = body ?? {};
675
+ if (typeof itemId !== "string" || !itemId) return sendJson(res, 400, { error: "itemId (string) required" });
676
+ if (!["approve", "reject", "edit"].includes(decision)) return sendJson(res, 400, { error: "decision must be approve|reject|edit" });
677
+ if (decision === "edit" && typeof text !== "string") return sendJson(res, 400, { error: "decision=edit requires text" });
678
+ if (!recordItemDecision) {
679
+ return sendJson(res, 500, { error: "gate resolver unavailable", message: "createDashboardServer was not given recordItemDecision" });
680
+ }
681
+
682
+ // Delegates to the shared recordItemDecision helper. Same write site as
683
+ // the CLI's `manifold approve` and the /manifold/gate/resolve route that
684
+ // companion harnesses POST to.
685
+ // Resolution -> state.approvalPending[itemId] = {decision, source: "dashboard"};
686
+ // the existing consolidator advances the flow when all items decide.
687
+ const result = await recordItemDecision({
688
+ flowId,
689
+ itemId,
690
+ decision,
691
+ source: "dashboard",
692
+ editedText: text,
693
+ });
694
+ if (!result.ok) {
695
+ const status = result.code === "flow_not_found" ? 404 : 409;
696
+ return sendJson(res, status, { error: result.code, code: result.code });
697
+ }
698
+ return sendJson(res, 200, { decision, itemId, status: result.status });
699
+ }
700
+
701
+ async function handleRerun(req, res, sourceFlowId) {
702
+ if (!executor?.rerun) {
703
+ return sendJson(res, 501, { error: "executor.rerun not available on this dashboard instance" });
704
+ }
705
+ let body;
706
+ try { body = await readJsonBody(req); }
707
+ catch (err) { return sendJson(res, 400, { error: "invalid JSON body", message: err?.message ?? String(err) }); }
708
+ const argsOverride = body && typeof body === "object" && "args" in body ? body.args : undefined;
709
+ if (argsOverride !== undefined && (argsOverride === null || typeof argsOverride !== "object" || Array.isArray(argsOverride))) {
710
+ return sendJson(res, 400, { error: "args must be a JSON object" });
711
+ }
712
+ let record;
713
+ try { record = executor.rerun(sourceFlowId, argsOverride); }
714
+ catch (err) {
715
+ const msg = err?.message ?? String(err);
716
+ // Singleton-guard rejection surfaces as "pipeline already has N active flow(s)";
717
+ // surface as 409 so the client can offer "cancel the active one first".
718
+ if (msg.includes("active flow")) return sendJson(res, 409, { error: msg });
719
+ if (msg.includes("not found")) return sendJson(res, 404, { error: msg });
720
+ logger?.warn?.(`manifold dashboard rerun: ${sourceFlowId.slice(0, 8)} failed: ${msg}`);
721
+ return sendJson(res, 500, { error: "rerun failed", message: msg });
722
+ }
723
+ // Fire the executor loop in the background; the HTTP response returns
724
+ // the new flowId immediately and the WS door drives the dashboard.
725
+ setImmediate(() => {
726
+ Promise.resolve()
727
+ .then(() => ensurePipelinesLoaded?.())
728
+ .then(() => executor.runFlow(record.flowId, "fresh"))
729
+ .catch((err) => logger?.warn?.(`manifold dashboard rerun: runFlow(${record.flowId.slice(0, 8)}) failed: ${err?.message ?? err}`));
730
+ });
731
+ return sendJson(res, 200, {
732
+ flowId: record.flowId,
733
+ pipelineId: record.stateJson?.pipelineId ?? null,
734
+ rerunOf: sourceFlowId,
735
+ });
736
+ }
737
+
738
+ async function handleCancel(req, res, flowId) {
739
+ const flow = await fetchFlow(flowId);
740
+ if (!flow) return sendJson(res, 404, { error: "flow not found" });
741
+ if (TERMINAL_STATUS_SET.has(flow.status)) {
742
+ return sendJson(res, 409, { error: `flow is already terminal (status=${flow.status}); nothing to cancel` });
743
+ }
744
+ if (!executor?.cancel) {
745
+ return sendJson(res, 501, { error: "executor.cancel not available on this dashboard instance" });
746
+ }
747
+ let body;
748
+ try { body = await readJsonBody(req); } catch { body = {}; }
749
+ const reason = typeof body?.reason === "string" && body.reason.trim() ? body.reason.trim() : null;
750
+ let result;
751
+ try { result = await executor.cancel(flowId, reason); }
752
+ catch (err) {
753
+ logger?.warn?.(`manifold dashboard cancel: executor.cancel(${flowId.slice(0, 8)}) failed: ${err?.message ?? err}`);
754
+ return sendJson(res, 500, { error: "cancel failed", message: err?.message ?? String(err) });
755
+ }
756
+ if (!result?.cancelled) {
757
+ return sendJson(res, 409, { error: "cancel did not apply", reason: result?.reason ?? "unknown" });
758
+ }
759
+ return sendJson(res, 200, { cancelled: true, wasStatus: flow.status });
760
+ }
761
+
762
+ async function handlePause(_req, res, flowId) {
763
+ const flow = await fetchFlow(flowId);
764
+ if (!flow) return sendJson(res, 404, { error: "flow not found" });
765
+ if (flow.status !== "running") {
766
+ return sendJson(res, 409, { error: `flow is ${flow.status}; only running flows can be paused` });
767
+ }
768
+ if (flow.stateJson?._paused) {
769
+ return sendJson(res, 200, { paused: true, already: true });
770
+ }
771
+ if (!writeStore) return sendJson(res, 501, { error: "writeStore not available" });
772
+ const nextState = { ...flow.stateJson, _paused: true };
773
+ const result = await writeStore.setRunning({
774
+ flowId, expectedRevision: flow.revision,
775
+ lastStep: flow.lastStep, stateJson: nextState,
776
+ });
777
+ if (!result?.applied) {
778
+ return sendJson(res, 409, { error: "pause did not apply", reason: result?.reason ?? "revision conflict" });
779
+ }
780
+ return sendJson(res, 200, { paused: true });
781
+ }
782
+
783
+ async function handleResume(_req, res, flowId) {
784
+ const flow = await fetchFlow(flowId);
785
+ if (!flow) return sendJson(res, 404, { error: "flow not found" });
786
+ if (flow.status !== "running" || !flow.stateJson?._paused) {
787
+ return sendJson(res, 409, { error: `flow is not paused (status=${flow.status})` });
788
+ }
789
+ if (!writeStore) return sendJson(res, 501, { error: "writeStore not available" });
790
+ const { _paused: _, ...nextState } = flow.stateJson;
791
+ const result = await writeStore.setRunning({
792
+ flowId, expectedRevision: flow.revision,
793
+ lastStep: flow.lastStep, stateJson: nextState,
794
+ });
795
+ if (!result?.applied) {
796
+ return sendJson(res, 409, { error: "resume did not apply", reason: result?.reason ?? "revision conflict" });
797
+ }
798
+ setImmediate(() => {
799
+ executor?.resume?.(flowId)?.catch?.((err) =>
800
+ logger?.warn?.(`manifold dashboard resume: runFlow(${flowId.slice(0, 8)}) failed: ${err?.message ?? err}`)
801
+ );
802
+ });
803
+ return sendJson(res, 200, { resumed: true });
804
+ }
805
+
806
+ async function handleBulkCancel(req, res) {
807
+ let body;
808
+ try { body = await readJsonBody(req); } catch { return sendJson(res, 400, { error: "invalid body" }); }
809
+ const { flowIds } = body ?? {};
810
+ const reason = typeof body?.reason === "string" && body.reason.trim() ? body.reason.trim() : null;
811
+ if (!Array.isArray(flowIds) || flowIds.length === 0) {
812
+ return sendJson(res, 400, { error: "flowIds must be a non-empty array" });
813
+ }
814
+ if (!executor?.cancel) return sendJson(res, 501, { error: "executor.cancel not available" });
815
+ const results = await Promise.all(
816
+ flowIds.map(async (flowId) => {
817
+ try {
818
+ const result = await executor.cancel(flowId, reason);
819
+ return { flowId, cancelled: !!result?.cancelled, reason: result?.reason ?? null };
820
+ } catch (err) {
821
+ return { flowId, cancelled: false, reason: err?.message ?? String(err) };
822
+ }
823
+ })
824
+ );
825
+ const cancelled = results.filter((r) => r.cancelled).length;
826
+ return sendJson(res, 200, { cancelled, total: flowIds.length, results });
827
+ }
828
+
829
+ async function handleSummary(res, flowId) {
830
+ const flow = await fetchFlow(flowId);
831
+ if (!flow) return sendJson(res, 404, { error: "flow not found" });
832
+ const state = flow.stateJson ?? {};
833
+ const pipelineId = state.pipelineId;
834
+ const pipeline = pipelineId ? pipelinesRef.value.get(pipelineId) : null;
835
+
836
+ // Try pipeline-declared runAudit.summarize first.
837
+ const audit = pipeline?.runAudit;
838
+ if (audit?.runsDir && typeof audit.summarize === "function" && state.runId) {
839
+ try {
840
+ const raw = await readFile(path.join(audit.runsDir, state.runId, "final-state.json"), "utf-8");
841
+ const finalState = JSON.parse(raw);
842
+ const summary = await Promise.resolve(audit.summarize(finalState));
843
+ return sendJson(res, 200, { flowId, status: flow.status, summary, source: "pipeline" });
844
+ } catch { /* fall through to system summary */ }
845
+ }
846
+
847
+ return sendJson(res, 200, { flowId, status: flow.status, summary: await deriveSystemSummary(state, flow, flowId), source: "system" });
848
+ }
849
+
850
+ async function deriveSystemSummary(state, flow, flowId) {
851
+ const out = {};
852
+
853
+ if (state.startedAt) {
854
+ const endedAt = flow.endedAt ?? flow.updatedAt ?? Date.now();
855
+ out.durationMs = endedAt - state.startedAt;
856
+ }
857
+
858
+ const stepsExecuted = stepsExecutedFromTree(await fetchTree(flowId));
859
+ if (stepsExecuted > 0) out.stepsExecuted = stepsExecuted;
860
+
861
+ const loop = await fetchSubflows(flowId);
862
+ if (loop && Object.keys(loop).length > 0) {
863
+ let items = 0, successes = 0, failures = 0;
864
+ for (const group of Object.values(loop)) {
865
+ if (!group || typeof group !== "object") continue;
866
+ for (const branch of Object.values(group)) {
867
+ items++;
868
+ if (branch?.doneAt) successes++;
869
+ else if (branch?.failedAt) failures++;
870
+ }
871
+ }
872
+ if (items > 0) {
873
+ out.loopItems = items;
874
+ if (successes > 0) out.loopSuccesses = successes;
875
+ if (failures > 0) out.loopFailures = failures;
876
+ }
877
+ }
878
+
879
+ const flowErrors = flow.errorEntries ?? [];
880
+ if (flowErrors.length > 0) {
881
+ out.errorCount = flowErrors.length;
882
+ out.recentErrors = flowErrors.slice(-3).map((e) => ({
883
+ node: e.nodeId,
884
+ message: e.message.slice(0, 120),
885
+ }));
886
+ }
887
+
888
+ if (typeof state.cost === "number") out.cost = state.cost;
889
+
890
+ return out;
891
+ }
892
+
893
+ async function sendArtifact(res, flowId, name) {
894
+ const flow = await fetchFlow(flowId);
895
+ if (!flow) return sendJson(res, 404, { error: "run not found" });
896
+ const pipelineId = flow.stateJson?.pipelineId;
897
+ const runId = flow.stateJson?.runId;
898
+ if (!pipelineId || !runId) return sendJson(res, 404, { error: "no run artifacts" });
899
+ const pipeline = pipelinesRef.value.get(pipelineId);
900
+ if (!pipeline?._dir) return sendJson(res, 404, { error: "pipeline dir unknown" });
901
+ const runDir = path.join(pipeline._dir, "runs", runId);
902
+ const resolved = path.resolve(runDir, name);
903
+ // Path-traversal guard: resolved must live inside runDir.
904
+ if (!resolved.startsWith(runDir + path.sep)) {
905
+ return sendJson(res, 403, { error: "forbidden" });
906
+ }
907
+ return serveFile(res, resolved);
908
+ }
909
+
910
+ return {
911
+ async start() {
912
+ if (server) return;
913
+
914
+ server = http.createServer((req, res) => { handle(req, res); });
915
+ door = attachWsEndpoint(server, { match: wsPathMatch, logger });
916
+ await new Promise((resolve, reject) => {
917
+ const onErr = (err) => { server = null; reject(err); };
918
+ server.once("error", onErr);
919
+ server.listen(port, host, () => {
920
+ server.off("error", onErr);
921
+ resolve();
922
+ });
923
+ });
924
+ unsubscribe = eventBus.subscribe(dispatchWs);
925
+ logger?.info?.(`manifold dashboard: listening on http://${host}:${port}`);
926
+ },
927
+ async stop() {
928
+ if (unsubscribe) { unsubscribe(); unsubscribe = null; }
929
+ if (door) { door.close(); door = null; }
930
+ if (server) {
931
+ await new Promise((resolve) => server.close(() => resolve()));
932
+ server = null;
933
+ }
934
+ },
935
+ url() { return `http://${host}:${port}`; },
936
+ };
937
+ }
938
+
939
+ // ─── helpers ─────────────────────────────────────────────────────────────────
940
+
941
+ async function summariseRun(r, runErrors = []) {
942
+ return {
943
+ flowId: r.flowId,
944
+ pipelineId: r.pipelineId ?? r.stateJson?.pipelineId ?? null,
945
+ runId: r.runId ?? r.stateJson?.runId ?? null,
946
+ status: r.status,
947
+ lastStep: resolveDisplayStep(r, runErrors),
948
+ revision: r.revision,
949
+ statusReason: r.statusReason ?? null,
950
+ waitKind: r.waitJson?.kind ?? null,
951
+ createdAt: r.createdAt ?? null,
952
+ updatedAt: r.updatedAt ?? null,
953
+ endedAt: r.endedAt ?? null,
954
+ errorsCount: runErrors.length,
955
+ // Derive compact subflow summary from the pre-aggregated child counts.
956
+ subflows: summariseSubflowRollup(r),
957
+ };
958
+ }
959
+
960
+ // Compact subflow summary from the pre-aggregated child counts merged onto
961
+ // each list row (summarizeChildrenByFlowIds) — avoids N+1 subflow queries.
962
+ function summariseSubflowRollup(r) {
963
+ const total = r.subflowTotal ?? 0;
964
+ if (total === 0) return null;
965
+ const failed = r.subflowFailed ?? 0;
966
+ const awaiting = r.subflowPending ?? 0;
967
+ const done = (r.subflowSucceeded ?? 0) + (r.subflowSkipped ?? 0);
968
+ const running = Math.max(0, total - done - failed - awaiting);
969
+ return [{ groupId: "summary", total, done, awaiting, failed, running }];
970
+ }
971
+
972
+ function fullRun(r, runErrors = []) {
973
+ // Strip `errors` — failure_events is now the sole store for error history
974
+ // ("Eradicate soft errors" Phase 1.5); errorEntries below (runErrors,
975
+ // read from failureStore) is the normalized replacement. Only historical rows persisted before that
976
+ // redirect still carry a baked-in errors[] in their stored stateJson.
977
+ const { errors: _errors, ...stateWithoutLegacy } = r.stateJson ?? {};
978
+ return {
979
+ flowId: r.flowId,
980
+ pipelineId: r.stateJson?.pipelineId ?? null,
981
+ runId: r.stateJson?.runId ?? null,
982
+ status: r.status,
983
+ lastStep: resolveDisplayStep(r, runErrors),
984
+ revision: r.revision,
985
+ statusReason: r.statusReason ?? null,
986
+ stateJson: stateWithoutLegacy,
987
+ waitJson: r.waitJson ?? null,
988
+ // Normalized error history sourced from flow_node_executions — sibling
989
+ // to stateJson (not nested inside it) so flow-level and subflow-level
990
+ // shapes stay symmetric.
991
+ errorEntries: runErrors,
992
+ createdAt: r.createdAt ?? null,
993
+ updatedAt: r.updatedAt ?? null,
994
+ endedAt: r.endedAt ?? null,
995
+ };
996
+ }
997
+
998
+ async function serveFile(res, absPath) {
999
+ try {
1000
+ const body = await readFile(absPath);
1001
+ const ext = path.extname(absPath).toLowerCase();
1002
+ const type = MIME[ext] ?? "application/octet-stream";
1003
+ res.writeHead(200, { "Content-Type": type, "Cache-Control": "no-cache" });
1004
+ res.end(body);
1005
+ } catch (err) {
1006
+ if (err.code === "ENOENT") return sendJson(res, 404, { error: "not found" });
1007
+ return sendJson(res, 500, { error: "internal", message: err?.message ?? String(err) });
1008
+ }
1009
+ }
1010
+
1011
+ function sendJson(res, code, body) {
1012
+ const buf = Buffer.from(JSON.stringify(body));
1013
+ res.writeHead(code, { "Content-Type": MIME[".json"], "Cache-Control": "no-cache" });
1014
+ res.end(buf);
1015
+ }