@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,158 @@
1
+ // GateForm — operator actuation for blocked runs. When a flow is sitting
2
+ // on a human-gate / gate with pending items, this renders an
3
+ // approve / reject / edit form for each pending item and POSTs to
4
+ // `/api/runs/:flowId/approve` (which mirrors the CLI's `manifold
5
+ // approve` semantics). The live WS feed refreshes the parent run state
6
+ // once the executor reacts.
7
+ //
8
+ // Pending entries may be raw strings ("listing-123") or objects with
9
+ // `.id` (`{ id: "listing-123", reason: "..." }`); both shapes render.
10
+
11
+ import { useState } from "react";
12
+ import { Button } from "@/components/ui/button";
13
+ import { api } from "@/api/client";
14
+ import { cn } from "@/lib/utils";
15
+
16
+ type Decision = "approve" | "reject" | "edit";
17
+
18
+ interface GateFormProps {
19
+ flowId: string;
20
+ /** raw pending entries from waitJson.pending */
21
+ pending: unknown[];
22
+ }
23
+
24
+ function entryId(entry: unknown): string | null {
25
+ if (typeof entry === "string") return entry;
26
+ if (entry && typeof entry === "object" && typeof (entry as { id?: unknown }).id === "string") {
27
+ return (entry as { id: string }).id;
28
+ }
29
+ return null;
30
+ }
31
+
32
+ function entryHint(entry: unknown): string | null {
33
+ if (entry && typeof entry === "object") {
34
+ const obj = entry as Record<string, unknown>;
35
+ if (typeof obj.reason === "string") return obj.reason;
36
+ if (typeof obj.hint === "string") return obj.hint;
37
+ }
38
+ return null;
39
+ }
40
+
41
+ // Two signals make a pending entry editable:
42
+ // 1. entry.editable === true — explicit free-text edit is offered
43
+ // 2. typeof entry.text === "string" — there's existing text to edit;
44
+ // used as the textarea's initial value
45
+ // Only one need be true. The gate's `pendingSelector` is the source of
46
+ // truth; if neither is present, the entry is approve/reject only.
47
+ function entryEditable(entry: unknown): { allowed: boolean; initial: string } {
48
+ if (!entry || typeof entry !== "object") return { allowed: false, initial: "" };
49
+ const obj = entry as Record<string, unknown>;
50
+ const hasText = typeof obj.text === "string";
51
+ const hasFlag = obj.editable === true;
52
+ return { allowed: hasText || hasFlag, initial: hasText ? (obj.text as string) : "" };
53
+ }
54
+
55
+ export function GateForm({ flowId, pending }: GateFormProps) {
56
+ const [busy, setBusy] = useState<string | null>(null);
57
+ const [editText, setEditText] = useState<Record<string, string>>({});
58
+ const [editOpen, setEditOpen] = useState<string | null>(null);
59
+ const [error, setError] = useState<string | null>(null);
60
+
61
+ if (!pending || pending.length === 0) return null;
62
+
63
+ async function submit(itemId: string, decision: Decision, text?: string) {
64
+ setBusy(`${itemId}:${decision}`);
65
+ setError(null);
66
+ try {
67
+ await api.approve(flowId, { itemId, decision, text });
68
+ // No state mutation here — the live feed (run.updated) refreshes RunDetail
69
+ // and the form will disappear once the item is no longer pending.
70
+ } catch (e) {
71
+ setError(e instanceof Error ? e.message : String(e));
72
+ } finally {
73
+ setBusy(null);
74
+ }
75
+ }
76
+
77
+ return (
78
+ <div className="mt-3 border-t border-border pt-3">
79
+ <div className="text-fg-dim text-xs uppercase tracking-[0.5px] mb-2">act on pending items</div>
80
+ {error && <div className="text-status-red text-sm mb-2">{error}</div>}
81
+ <div className="grid gap-2">
82
+ {pending.map((entry, idx) => {
83
+ const id = entryId(entry);
84
+ if (!id) {
85
+ return (
86
+ <div key={idx} className="text-fg-dim text-xs italic">
87
+ (skipped: pending entry without `id` — {JSON.stringify(entry).slice(0, 80)})
88
+ </div>
89
+ );
90
+ }
91
+ const hint = entryHint(entry);
92
+ const isEditing = editOpen === id;
93
+ const editable = entryEditable(entry);
94
+ // First time the operator opens the edit panel, seed the textarea
95
+ // with the entry's existing text (if any). After that, keep what
96
+ // they've typed even if they collapse and re-open.
97
+ const currentText = id in editText ? editText[id] : editable.initial;
98
+ return (
99
+ <div key={id} className="border border-border rounded p-2 bg-bg-elev2/30">
100
+ <div className="flex items-center gap-3 flex-wrap min-w-0">
101
+ <span className="font-mono text-sm flex-1 min-w-0 truncate">{id}</span>
102
+ <Button
103
+ variant="chip"
104
+ onClick={() => submit(id, "approve")}
105
+ disabled={busy !== null}
106
+ className={cn("text-status-green border-status-green/40 hover:bg-status-green/10",
107
+ busy === `${id}:approve` && "opacity-60")}
108
+ >
109
+ {busy === `${id}:approve` ? "approving…" : "approve"}
110
+ </Button>
111
+ <Button
112
+ variant="chip"
113
+ onClick={() => submit(id, "reject")}
114
+ disabled={busy !== null}
115
+ className={cn("text-status-red border-status-red/40 hover:bg-status-red/10",
116
+ busy === `${id}:reject` && "opacity-60")}
117
+ >
118
+ {busy === `${id}:reject` ? "rejecting…" : "reject"}
119
+ </Button>
120
+ {editable.allowed && (
121
+ <Button
122
+ variant="chip"
123
+ onClick={() => setEditOpen(isEditing ? null : id)}
124
+ disabled={busy !== null}
125
+ >
126
+ {isEditing ? "cancel edit" : "edit…"}
127
+ </Button>
128
+ )}
129
+ </div>
130
+ {hint && <div className="text-fg-dim text-xs mt-1">{hint}</div>}
131
+ {editable.allowed && isEditing && (
132
+ <div className="mt-2 grid gap-2">
133
+ <textarea
134
+ value={currentText}
135
+ onChange={(e) => setEditText({ ...editText, [id]: e.target.value })}
136
+ placeholder="Edited text (replaces the agent's output for this item)"
137
+ rows={Math.min(12, Math.max(4, currentText.split("\n").length + 1))}
138
+ className="bg-bg-elev border border-border rounded px-2 py-1 text-sm font-mono w-full min-w-0"
139
+ />
140
+ <div>
141
+ <Button
142
+ variant="chip"
143
+ onClick={() => submit(id, "edit", currentText)}
144
+ disabled={busy !== null || !currentText.trim()}
145
+ className="text-accent border-accent/40 hover:bg-accent/10"
146
+ >
147
+ {busy === `${id}:edit` ? "submitting…" : "submit edit"}
148
+ </Button>
149
+ </div>
150
+ </div>
151
+ )}
152
+ </div>
153
+ );
154
+ })}
155
+ </div>
156
+ </div>
157
+ );
158
+ }
@@ -0,0 +1,302 @@
1
+ // Cytoscape wrapper. Renders the pipeline topology with:
2
+ // - explicit groups (pipeline.groups) as compound parents
3
+ // - subflow nodes as compound parents containing their flow.nodes
4
+ // - executed-path overlay (visited/unvisited nodes; taken/untaken edges)
5
+ // - subflow outcome (green/amber/red border + count summary in label)
6
+ //
7
+ // Lifecycle is keyed on (pipeline, run?.flowId, run?.revision, tree) so the
8
+ // same instance survives unrelated re-renders but rebuilds when the data
9
+ // changes — tree arrives asynchronously after run (SUBFLOW_PARENT_STATE_
10
+ // ACCESS.design.md's Phase 3b), so it needs its own dependency slot rather
11
+ // than piggybacking on run?.revision.
12
+
13
+ import { useEffect, useRef } from "react";
14
+ import cytoscape from "cytoscape";
15
+ import dagre from "cytoscape-dagre";
16
+ import type { FlowRunFull, FlowTreeItem, Pipeline, PipelineGroup } from "@/api/types";
17
+ import { buildTracedEdges } from "@/lib/step-history";
18
+ import { classifySubflows, subgraphOutcomeClass } from "@/lib/subflow";
19
+
20
+ // cytoscape-dagre auto-registers when loaded after cytoscape; calling .use is
21
+ // a no-op in 2.x but explicit registration is the documented path.
22
+ cytoscape.use(dagre as unknown as (cy: unknown) => void);
23
+
24
+ interface GraphViewProps {
25
+ pipeline: Pipeline;
26
+ run?: FlowRunFull | null;
27
+ /** Executed-path source (SUBFLOW_PARENT_STATE_ACCESS.design.md's Phase
28
+ * 3b) — GET /manifold/runs/:flowId/tree's items, replacing
29
+ * run.stateJson._stepHistory. null/undefined while loading or on a run
30
+ * with no history yet; tracedNodes/tracedEdges then stay null too. */
31
+ tree?: FlowTreeItem[] | null;
32
+ className?: string;
33
+ onNodeClick?: (nodeId: string) => void;
34
+ selectedNodeId?: string | null;
35
+ }
36
+
37
+ function groupParentClasses(group: PipelineGroup, tracedNodes: Set<string> | null): string {
38
+ const classes = ["group-parent", `group-kind-${group.kind ?? "default"}`];
39
+ if (!tracedNodes) return classes.join(" ");
40
+ const members = group.members ?? [];
41
+ const anyHit = members.some((m) => tracedNodes.has(m));
42
+ classes.push(anyHit ? "group-visited" : "group-untouched");
43
+ return classes.join(" ");
44
+ }
45
+
46
+ function nodeClasses(n: { id: string; kind: string }, run: FlowRunFull | null | undefined, tracedNodes: Set<string> | null, effectiveKind?: string): string {
47
+ const classes: string[] = [];
48
+ if (n.id === "__start__") classes.push("terminal", "start");
49
+ else if (n.id === "__end__") classes.push("terminal", "end");
50
+ else classes.push(`kind-${effectiveKind ?? n.kind}`);
51
+ if (tracedNodes) classes.push(tracedNodes.has(n.id) ? "visited" : "unvisited");
52
+ if (run && run.currentStep === n.id) {
53
+ classes.push("current");
54
+ const map: Record<string, string> = {
55
+ waiting: "blocked", blocked: "blocked",
56
+ running: "running", succeeded: "succeeded", failed: "failed", cancelled: "cancelled",
57
+ };
58
+ const extra = map[run.status];
59
+ if (extra) classes.push(extra);
60
+ }
61
+ return classes.join(" ");
62
+ }
63
+
64
+ // Stylesheet entries use the JS form `{ selector, style: {...} }`. The
65
+ // @types/cytoscape public surface only models the CSS-string form, so we
66
+ // type the entries permissively here.
67
+ type StyleEntry = { selector: string; style: Record<string, unknown> };
68
+ function graphStyle(): StyleEntry[] {
69
+ return [
70
+ { selector: "node", style: {
71
+ "background-color": "#1f262e",
72
+ "border-width": 1.5,
73
+ "border-color": "#2a3038",
74
+ "label": "data(label)",
75
+ "color": "#d8dde6",
76
+ "font-family": "ui-monospace, Menlo, monospace",
77
+ "font-size": 11,
78
+ "text-valign": "center",
79
+ "text-halign": "center",
80
+ "width": "label",
81
+ "height": 28,
82
+ "padding": "10px",
83
+ "shape": "round-rectangle",
84
+ }},
85
+ { selector: "node.terminal", style: { "background-color": "#0e1116", "border-color": "#6e7681", "color": "#8b949e" }},
86
+ { selector: "node.kind-code", style: { "border-color": "#58a6ff" }},
87
+ { selector: "node.kind-agent", style: { "border-color": "#bc8cff" }},
88
+ { selector: "node.kind-loop", style: { "border-color": "#f0883e" }},
89
+ { selector: "node.kind-human-gate", style: { "border-color": "#d29922" }},
90
+ { selector: "node.kind-gate", style: { "border-color": "#3fb950" }},
91
+ { selector: "node.current", style: { "border-width": 3, "background-color": "#1f6feb33" }},
92
+ { selector: "node.running", style: { "border-color": "#3fb950" }},
93
+ { selector: "node.blocked", style: { "border-color": "#d29922" }},
94
+ { selector: "node.succeeded", style: { "border-color": "#79b8ff" }},
95
+ { selector: "node.failed", style: { "border-color": "#f85149" }},
96
+ { selector: "node.cancelled", style: { "border-color": "#6e7681" }},
97
+ { selector: "edge", style: {
98
+ "width": 1.2,
99
+ "line-color": "#2a3038",
100
+ "target-arrow-color": "#2a3038",
101
+ "target-arrow-shape": "triangle",
102
+ "curve-style": "bezier",
103
+ }},
104
+ { selector: "edge.cond", style: { "line-style": "dashed", "line-color": "#6e7681", "target-arrow-color": "#6e7681" }},
105
+ { selector: "node.unvisited", style: { "opacity": 0.32 }},
106
+ { selector: "node.visited", style: { "border-color": "#79b8ff" }},
107
+ { selector: "edge.untaken", style: { "opacity": 0.18 }},
108
+ { selector: "edge.taken", style: { "line-color": "#58a6ff", "target-arrow-color": "#58a6ff", "line-style": "solid", "width": 2 }},
109
+ { selector: "node.group-parent", style: {
110
+ "background-color": "transparent",
111
+ "background-opacity": 0,
112
+ "border-style": "dashed",
113
+ "border-color": "#39424d",
114
+ "border-width": 1.2,
115
+ "label": "data(label)",
116
+ "text-valign": "top",
117
+ "text-halign": "center",
118
+ "text-margin-y": -6,
119
+ "font-size": 10,
120
+ "color": "#8b949e",
121
+ "padding": "16px",
122
+ "shape": "round-rectangle",
123
+ }},
124
+ { selector: "node.group-primary-ok", style: { "border-color": "#3fb950" }},
125
+ { selector: "node.group-engaged", style: { "border-color": "#d29922", "border-style": "solid", "border-width": 1.6 }},
126
+ { selector: "node.group-untouched", style: { "border-color": "#2a3038", "opacity": 0.5 }},
127
+ { selector: "node.group-failed", style: { "border-color": "#f85149", "border-style": "solid", "border-width": 1.6 }},
128
+ { selector: "node.group-running", style: { "border-color": "#58a6ff", "border-style": "solid", "border-width": 1.6 }},
129
+ { selector: "node.selected", style: { "border-color": "#f0883e", "border-width": 3 }},
130
+ ];
131
+ }
132
+
133
+ export function GraphView({ pipeline, run, tree, className, onNodeClick, selectedNodeId }: GraphViewProps) {
134
+ const ref = useRef<HTMLDivElement | null>(null);
135
+ const cyRef = useRef<cytoscape.Core | null>(null);
136
+
137
+ useEffect(() => {
138
+ if (!ref.current) return;
139
+ if (cyRef.current) { try { cyRef.current.destroy(); } catch { /* swallow */ } cyRef.current = null; }
140
+
141
+ const history = Array.isArray(tree) ? tree.map((i) => i.nodeId) : null;
142
+ const tracedNodes = history ? new Set<string>(["__start__", ...history]) : null;
143
+ const tracedEdges = history ? buildTracedEdges(history) : null;
144
+ // `tree` (GET .../tree) carries each top-level node's kind/agent AS OF
145
+ // this specific run's own invocation — point-in-time correct, unlike
146
+ // `pipeline.nodes[].kind` below (the pipeline's CURRENT definition).
147
+ // Only covers nodes this run actually dispatched (subflow_key IS NULL,
148
+ // same scope as `history` above) — an unvisited node has no historical
149
+ // record to fall back to, so it correctly keeps using the live kind.
150
+ const treeKindByNodeId = new Map<string, string>();
151
+ if (Array.isArray(tree)) {
152
+ for (const item of tree) {
153
+ if (item.kind) treeKindByNodeId.set(item.nodeId, item.kind);
154
+ }
155
+ }
156
+
157
+ // Explicit groups → compound parents. Each group is either top-level
158
+ // (its compound has no parent) or subflow-internal (its compound lives
159
+ // inside a subflow node's compound). Loader guarantees a group's
160
+ // members are all in the same scope.
161
+ //
162
+ // `groupOf` maps cytoscape node-id (which for subflow children is
163
+ // `<parentNodeId>.<childId>`) → groupId. We render the group's
164
+ // compound parent with the appropriate `parent:` set, then descendants
165
+ // get `parent: __group:<groupId>` so cytoscape compounds them.
166
+ const groupOf = new Map<string, string>();
167
+ const groupScope = new Map<string, string | null>(); // groupId → null|parentForEachSubgraphId
168
+ const groupParents: cytoscape.NodeDefinition[] = [];
169
+ if (pipeline.groups && typeof pipeline.groups === "object") {
170
+ for (const [groupId, group] of Object.entries(pipeline.groups)) {
171
+ const members = group?.members ?? [];
172
+ let scope: string | null = null;
173
+ for (const m of members) {
174
+ groupOf.set(m, groupId);
175
+ const dot = m.indexOf(".");
176
+ if (dot !== -1 && !scope) scope = m.slice(0, dot);
177
+ }
178
+ groupScope.set(groupId, scope);
179
+ const data: cytoscape.NodeDataDefinition = {
180
+ id: `__group:${groupId}`,
181
+ label: group.label ?? groupId,
182
+ };
183
+ if (scope) data.parent = scope; // nest inside the loop node's compound
184
+ groupParents.push({
185
+ data,
186
+ classes: groupParentClasses(group, tracedNodes),
187
+ });
188
+ }
189
+ }
190
+
191
+ // subflow → compound parents containing namespaced flow
192
+ // children. A child's `parent:` is either the subflow node itself
193
+ // OR a subflow-internal group's compound (which is in turn parented
194
+ // by the subflow node). Cytoscape nests compounds via `parent:`
195
+ // pointers — see groupParents construction above.
196
+ interface CompoundEntry { children: cytoscape.NodeDefinition[]; childEdges: cytoscape.EdgeDefinition[]; concurrency?: number }
197
+ const subgraphCompounds = new Map<string, CompoundEntry>();
198
+ for (const n of pipeline.nodes) {
199
+ if (n.kind !== "subflow" || !n.flow) continue;
200
+ const parentId = n.id;
201
+ const children: cytoscape.NodeDefinition[] = [];
202
+ for (const bn of n.flow.nodes ?? []) {
203
+ const fullId = `${parentId}.${bn.id}`;
204
+ const innerGroup = groupOf.get(fullId);
205
+ children.push({
206
+ data: {
207
+ id: fullId,
208
+ label: bn.id,
209
+ parent: innerGroup ? `__group:${innerGroup}` : parentId,
210
+ },
211
+ classes: nodeClasses({ id: bn.id, kind: bn.kind }, null, null),
212
+ });
213
+ }
214
+ const childEdges: cytoscape.EdgeDefinition[] = (n.flow.edges ?? [])
215
+ .map((e, i) => ({
216
+ data: {
217
+ id: `sge:${parentId}:${i}`,
218
+ source: `${parentId}.${e.from}`,
219
+ target: `${parentId}.${e.to}`,
220
+ },
221
+ classes: e.conditional ? "cond" : "",
222
+ }))
223
+ .filter((e) => !String(e.data.target).endsWith(".?"));
224
+ subgraphCompounds.set(parentId, { children, childEdges, concurrency: n.concurrency });
225
+ }
226
+
227
+ const nodes: cytoscape.NodeDefinition[] = [];
228
+ nodes.push(...groupParents);
229
+ for (const n of pipeline.nodes) {
230
+ const parent = groupOf.get(n.id);
231
+ if (subgraphCompounds.has(n.id)) {
232
+ const cmp = subgraphCompounds.get(n.id)!;
233
+ const subflowCounts = classifySubflows(run?.stateJson?.subflows?.[n.id]);
234
+ const base = `${n.id} (loop${cmp.concurrency ? ` ×${cmp.concurrency}` : ""})`;
235
+ const label = subflowCounts.total > 0
236
+ ? `${base} · ${subflowCounts.succeeded}/${subflowCounts.total} ok${subflowCounts.skipped ? ` · ${subflowCounts.skipped} ⊘` : ""}${subflowCounts.failed ? ` · ${subflowCounts.failed} ✗` : ""}${subflowCounts.awaiting ? ` · ${subflowCounts.awaiting} ⏳` : ""}${subflowCounts.running ? ` · ${subflowCounts.running} →` : ""}`
237
+ : base;
238
+ const cls = ["group-parent", "group-kind-subgraph"];
239
+ if (subflowCounts.total > 0) cls.push(subgraphOutcomeClass(subflowCounts));
240
+ else if (tracedNodes) cls.push(tracedNodes.has(n.id) ? "visited" : "unvisited");
241
+ nodes.push({
242
+ data: { id: n.id, label, ...(parent ? { parent: `__group:${parent}` } : {}) },
243
+ classes: cls.join(" "),
244
+ });
245
+ } else {
246
+ nodes.push({
247
+ data: { id: n.id, label: n.id, ...(parent ? { parent: `__group:${parent}` } : {}) },
248
+ classes: nodeClasses(n as { id: string; kind: string }, run, tracedNodes, treeKindByNodeId.get(n.id)),
249
+ });
250
+ }
251
+ }
252
+ for (const cmp of subgraphCompounds.values()) nodes.push(...cmp.children);
253
+
254
+ const edges: cytoscape.EdgeDefinition[] = pipeline.edges
255
+ .map((e, i) => {
256
+ let source = e.from, target = e.to;
257
+ if (subgraphCompounds.has(source)) source = `${source}.__end__`;
258
+ if (subgraphCompounds.has(target)) target = `${target}.__start__`;
259
+ const classes: string[] = [];
260
+ if (e.conditional) classes.push("cond");
261
+ if (tracedEdges) classes.push(tracedEdges.has(`${e.from}→${e.to}`) ? "taken" : "untaken");
262
+ return {
263
+ data: { id: `e${i}`, source, target, via: e.via ?? "" },
264
+ classes: classes.join(" "),
265
+ };
266
+ })
267
+ .filter((e) => e.data.target && e.data.target !== "?");
268
+ for (const cmp of subgraphCompounds.values()) edges.push(...cmp.childEdges);
269
+
270
+ const cy = cytoscape({
271
+ container: ref.current,
272
+ elements: { nodes, edges },
273
+ style: graphStyle(),
274
+ layout: { name: "dagre", rankDir: "LR", nodeSep: 24, rankSep: 70, edgeSep: 10 } as cytoscape.LayoutOptions,
275
+ wheelSensitivity: 0.2,
276
+ });
277
+ cy.on("tap", "edge.cond", (evt) => {
278
+ const via = evt.target.data("via");
279
+ if (via) alert(via);
280
+ });
281
+ if (onNodeClick) {
282
+ cy.on("tap", "node", (evt) => {
283
+ const id = String(evt.target.id());
284
+ // Skip group compounds, flow children (namespaced as parent.child),
285
+ // and synthetic start/end pseudo-nodes — stats only apply to real
286
+ // top-level pipeline nodes.
287
+ if (id.startsWith("__group:")) return;
288
+ if (id === "__start__" || id === "__end__") return;
289
+ if (id.includes(".")) return;
290
+ onNodeClick(id);
291
+ });
292
+ }
293
+ if (selectedNodeId) {
294
+ const el = cy.getElementById(selectedNodeId);
295
+ if (el && el.length) el.addClass("selected");
296
+ }
297
+ cyRef.current = cy;
298
+ return () => { try { cy.destroy(); } catch { /* swallow */ } };
299
+ }, [pipeline, run?.flowId, run?.revision, tree, onNodeClick, selectedNodeId]);
300
+
301
+ return <div ref={ref} className={`h-[320px] sm:h-[420px] md:h-[480px] bg-bg border border-border rounded ${className ?? ""}`} />;
302
+ }
@@ -0,0 +1,47 @@
1
+ // Aggregated paths summary at the top of each loop group on the
2
+ // run-detail subflows card. Groups subflows by pathSignature and shows each
3
+ // distinct path once with its count. Compact single-line form when every
4
+ // subflow took the same route.
5
+
6
+ import { SubflowPathPills } from "./SubflowPathPills";
7
+ import { pathSignature } from "@/lib/subflow";
8
+ import type { SubflowData } from "@/api/types";
9
+
10
+ export function GroupPathsSummary({
11
+ entries,
12
+ subSteps,
13
+ }: {
14
+ entries: Array<[string, SubflowData]>;
15
+ subSteps: string[];
16
+ }) {
17
+ if (!entries.length) return null;
18
+ const groups = new Map<string, { count: number; sample: SubflowData }>();
19
+ for (const [, b] of entries) {
20
+ const sig = pathSignature(b, subSteps);
21
+ const slot = groups.get(sig);
22
+ if (slot) slot.count++;
23
+ else groups.set(sig, { count: 1, sample: b });
24
+ }
25
+ const sorted = [...groups.values()].sort((a, b) => b.count - a.count);
26
+ if (sorted.length === 1) {
27
+ return (
28
+ <div className="flex items-center gap-2 mb-3 text-[11px] font-mono">
29
+ <span className="text-fg-dim">all {sorted[0].count} took:</span>
30
+ <SubflowPathPills subflow={sorted[0].sample} subSteps={subSteps} />
31
+ </div>
32
+ );
33
+ }
34
+ return (
35
+ <div className="mb-3">
36
+ <div className="text-fg-dim font-mono text-[11px] mb-1.5">{groups.size} distinct paths:</div>
37
+ <div className="grid gap-1">
38
+ {sorted.map((g, i) => (
39
+ <div key={i} className="flex items-center gap-2 py-0.5">
40
+ <span className="min-w-[30px] text-right text-fg-dim text-[11px] font-mono">{g.count}×</span>
41
+ <SubflowPathPills subflow={g.sample} subSteps={subSteps} />
42
+ </div>
43
+ ))}
44
+ </div>
45
+ </div>
46
+ );
47
+ }