@igorjpimenta/manifold 0.0.0-stage → 2026.11.22-beta.3

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 +1583 -2
  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 +49 -4
  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,37 @@
1
+ {
2
+ "name": "manifold-dashboard",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "description": "React + TypeScript + Tailwind frontend for the manifold plugin's read-only dashboard. Built sources land in dist/ and are served by server.js (no runtime build step required after `npm run build` ships the bundle into the repo).",
7
+ "scripts": {
8
+ "dev": "vite",
9
+ "build": "tsc -b && vite build",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "@radix-ui/react-slot": "^1.1.0",
14
+ "class-variance-authority": "^0.7.0",
15
+ "clsx": "^2.1.1",
16
+ "cytoscape": "^3.30.2",
17
+ "cytoscape-dagre": "^2.5.0",
18
+ "dagre": "^0.8.5",
19
+ "lucide-react": "^0.452.0",
20
+ "react": "^18.3.1",
21
+ "react-dom": "^18.3.1",
22
+ "tailwind-merge": "^2.5.4"
23
+ },
24
+ "devDependencies": {
25
+ "@types/cytoscape": "^3.21.4",
26
+ "@types/dagre": "^0.7.52",
27
+ "@types/node": "^25.8.0",
28
+ "@types/react": "^18.3.11",
29
+ "@types/react-dom": "^18.3.0",
30
+ "@vitejs/plugin-react": "^4.3.2",
31
+ "autoprefixer": "^10.4.20",
32
+ "postcss": "^8.4.47",
33
+ "tailwindcss": "^3.4.13",
34
+ "typescript": "^5.6.2",
35
+ "vite": "^5.4.8"
36
+ }
37
+ }
@@ -0,0 +1,131 @@
1
+ // pipeline-graph.js — serialize a loaded pipeline definition into UI-safe JSON.
2
+ //
3
+ // The in-memory pipeline def holds function values (run/promptBuilder/apply for
4
+ // nodes; conditional edge resolvers). We strip those before shipping over HTTP
5
+ // — the browser only needs topology and labels. For conditional edges, we
6
+ // regex-scan the function's source for quoted node ids so the dashboard can
7
+ // render every possible branch instead of just one.
8
+
9
+ const NODE_ID_RE = /["'`]([A-Za-z_][A-Za-z0-9_]*|__end__|__start__)["'`]/g;
10
+
11
+ export function serializePipeline(pipeline) {
12
+ if (!pipeline) return null;
13
+
14
+ const nodeIds = new Set(Object.keys(pipeline.nodes ?? {}));
15
+ const nodes = [
16
+ { id: "__start__", kind: "start" },
17
+ ...Object.entries(pipeline.nodes ?? {}).map(([id, node]) => ({
18
+ id,
19
+ kind: node.kind,
20
+ ...(node.agent ? { agent: node.agent } : {}),
21
+ ...(node.groupId ? { groupId: node.groupId } : {}),
22
+ ...(node.concurrency ? { concurrency: node.concurrency } : {}),
23
+ ...(node.waitKind ? { waitKind: node.waitKind } : {}),
24
+ ...(node.kind === "subflow" && node.flow ? {
25
+ flow: serializeFlow(node.flow, id, node.groupId ?? id),
26
+ } : {}),
27
+ })),
28
+ { id: "__end__", kind: "end" },
29
+ ];
30
+
31
+ const edges = [];
32
+ for (const [from, edge] of Object.entries(pipeline.edges ?? {})) {
33
+ if (typeof edge === "string") {
34
+ edges.push({ from, to: edge, conditional: false });
35
+ continue;
36
+ }
37
+ if (typeof edge === "function") {
38
+ const hints = pipeline.edgeHints?.[from];
39
+ if (Array.isArray(hints) && hints.length > 0) {
40
+ for (const to of hints) {
41
+ edges.push({ from, to, conditional: true, via: null });
42
+ }
43
+ } else {
44
+ const src = edge.toString();
45
+ const targets = extractTargets(src, nodeIds);
46
+ if (targets.length === 0) {
47
+ edges.push({ from, to: "?", conditional: true, via: shorten(src) });
48
+ } else {
49
+ for (const to of targets) {
50
+ edges.push({ from, to, conditional: true, via: shorten(src) });
51
+ }
52
+ }
53
+ }
54
+ }
55
+ }
56
+
57
+ return {
58
+ id: pipeline.id,
59
+ goal: pipeline.goal ?? null,
60
+ file: pipeline._filepath ?? null,
61
+ dir: pipeline._dir ?? null,
62
+ nodes,
63
+ edges,
64
+ // Optional logical groupings the dashboard renders as compound parents
65
+ // around their member nodes.
66
+ groups: pipeline.groups ?? null,
67
+ // Declared dashboard views — opt-in extra surfaces rendered by
68
+ // the generic <DeclaredView> dispatcher on PipelineDetail. The
69
+ // serializer ships the declarations themselves (not the computed
70
+ // view data); the data comes from /api/stats/pipelines/:id/views.
71
+ // Stored as `null` for pipelines that don't declare any so the
72
+ // type stays stable across pipelines.
73
+ views: Array.isArray(pipeline.views) && pipeline.views.length > 0
74
+ ? pipeline.views
75
+ : null,
76
+ };
77
+ }
78
+
79
+ function extractTargets(src, knownIds) {
80
+ const found = new Set();
81
+ let m;
82
+ NODE_ID_RE.lastIndex = 0;
83
+ while ((m = NODE_ID_RE.exec(src)) !== null) {
84
+ const id = m[1];
85
+ if (id === "__start__" || id === "__end__" || knownIds.has(id)) found.add(id);
86
+ }
87
+ return [...found];
88
+ }
89
+
90
+ function shorten(src) {
91
+ const oneLine = src.replace(/\s+/g, " ").trim();
92
+ return oneLine.length > 200 ? oneLine.slice(0, 197) + "..." : oneLine;
93
+ }
94
+
95
+ /**
96
+ * Serialize a subflow node's inner pipeline ("flow") so the dashboard can
97
+ * render it as an inset graph. Shape mirrors the top-level serialization
98
+ * but keeps the namespace local (no clash with parent node ids).
99
+ */
100
+ function serializeFlow(flow, parentNodeId, groupId) {
101
+ const flowNodeIds = new Set(Object.keys(flow.nodes ?? {}));
102
+ const nodes = [
103
+ { id: "__start__", kind: "start" },
104
+ ...Object.entries(flow.nodes ?? {}).map(([id, node]) => ({
105
+ id,
106
+ kind: node.kind,
107
+ ...(node.agent ? { agent: node.agent } : {}),
108
+ ...(node.skill ? { skill: node.skill } : {}),
109
+ })),
110
+ { id: "__end__", kind: "end" },
111
+ ];
112
+ const edges = [];
113
+ for (const [from, edge] of Object.entries(flow.edges ?? {})) {
114
+ if (typeof edge === "string") {
115
+ edges.push({ from, to: edge, conditional: false });
116
+ continue;
117
+ }
118
+ if (typeof edge === "function") {
119
+ const src = edge.toString();
120
+ const targets = extractTargets(src, flowNodeIds);
121
+ if (targets.length === 0) {
122
+ edges.push({ from, to: "?", conditional: true, via: shorten(src) });
123
+ } else {
124
+ for (const to of targets) {
125
+ edges.push({ from, to, conditional: true, via: shorten(src) });
126
+ }
127
+ }
128
+ }
129
+ }
130
+ return { parentNodeId, groupId, nodes, edges };
131
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {},
5
+ },
6
+ };
@@ -0,0 +1,183 @@
1
+ // In-memory substring search across the dashboard's flow_runs view.
2
+ //
3
+ // Why in-memory and not SQLite FTS5: manifold's dashboard opens
4
+ // registry.sqlite read-only (see sql-store.js) and is not the schema
5
+ // owner. Adding an FTS5 mirror table requires writes + triggers managed
6
+ // by whoever owns the schema, which the dashboard explicitly does not.
7
+ // An in-memory walk avoids the cross-process coordination problem
8
+ // entirely. Upgrade to FTS5 if (a) row count grows past ~10k or
9
+ // (b) query latency on `top-level state stringify` becomes a problem —
10
+ // both checkable on the search endpoint's response.
11
+ //
12
+ // Scope (v1):
13
+ // ✓ Structured fields: flowId, pipelineId, status,
14
+ // lastStep, statusReason, waitJson.hint, waitJson.reason
15
+ // ✓ errorEntries[*].{nodeId,message} — sourced from flow_node_executions
16
+ // (Phase 1.5), not the old state.errors[]. This closes a real gap:
17
+ // flow_node_executions unifies root-level and subflow-level errors in
18
+ // one table, so subflow failures are now searchable for free — the old
19
+ // state.errors[]-only approach never indexed subflow sub-state at all.
20
+ // ✗ Top-level state keys — not searchable: dashboard/server.js's
21
+ // fetchAllRuns() goes through the gateway's /manifold/runs LIST
22
+ // route, which never selects the raw state_json column (only
23
+ // flowId/pipelineId/status/lastStep/statusReason/timestamps +
24
+ // _display-derived fields); adaptRun() synthesizes stateJson as
25
+ // {pipelineId} for every row. Reintroducing per-node output search
26
+ // would mean a dedicated gateway-side route backed by assembleState()
27
+ // (mirroring routes/runs.js's single-run detail path), not a loop
28
+ // over a field this route never populates.
29
+ // ✗ Transcripts — would require walking session JSONL files per
30
+ // query × per run. Deferred to v2 with an offline indexer.
31
+
32
+ const DEFAULT_LIMIT = 50;
33
+ const DEFAULT_CONTEXT_CHARS = 40;
34
+
35
+ export function searchRuns(runs, query, opts = {}) {
36
+ const limit = opts.limit ?? DEFAULT_LIMIT;
37
+ const contextChars = opts.contextChars ?? DEFAULT_CONTEXT_CHARS;
38
+ // Map<flowId, ErrorEntry[]> — caller fetches once via the gateway's
39
+ // GET /manifold/errors (failureStore.queryErrorsByFlowIds, Phase 1.5)
40
+ // so this stays a pure function, DB-free.
41
+ const errorsByFlow = opts.errorsByFlow ?? new Map();
42
+ // Structured status filter applied BEFORE the free-text match —
43
+ // unlike the textual `q=… succeeded` shape, this is exact-equality
44
+ // against `r.status` and won't false-positive on the string "failed"
45
+ // appearing in an error message. The StatStrip sub-count links use
46
+ // this so "click fail = show failed runs" reads strictly.
47
+ const statusFilter = typeof opts.status === "string" ? opts.status.trim().toLowerCase() : "";
48
+ if (statusFilter) runs = runs.filter((r) => (r.status ?? "").toLowerCase() === statusFilter);
49
+ const trimmed = String(query ?? "").trim();
50
+ if (!trimmed) {
51
+ // status-only mode: return every status-filtered run as a hit with
52
+ // no per-field snippets. Hit shape stays compatible (matches: []).
53
+ if (statusFilter) {
54
+ const hits = runs.slice(0, limit).map((r) => ({
55
+ flowId: r.flowId,
56
+ pipelineId: r.stateJson?.pipelineId ?? null,
57
+ status: r.status,
58
+ lastStep: r.lastStep,
59
+ updatedAt: r.updatedAt,
60
+ revision: r.revision,
61
+ matches: [],
62
+ }));
63
+ return {
64
+ query: "",
65
+ status: statusFilter,
66
+ totalHits: runs.length,
67
+ hits,
68
+ truncated: runs.length > limit,
69
+ };
70
+ }
71
+ return { query: "", totalHits: 0, hits: [], truncated: false };
72
+ }
73
+
74
+ // Multi-token: all whitespace-separated tokens must appear (AND). Quoted
75
+ // phrases not supported in v1 — operator can use a single token in URL
76
+ // for now; quoting would mean a real tokenizer.
77
+ const tokens = trimmed.toLowerCase().split(/\s+/).filter(Boolean);
78
+ if (tokens.length === 0) return { query: trimmed, totalHits: 0, hits: [], truncated: false };
79
+
80
+ const hits = [];
81
+ for (const r of runs) {
82
+ const matches = matchesForRun(r, tokens, contextChars, errorsByFlow.get(r.flowId) ?? []);
83
+ if (matches.length === 0) continue;
84
+ hits.push({
85
+ flowId: r.flowId,
86
+ pipelineId: r.stateJson?.pipelineId ?? null,
87
+ status: r.status,
88
+ lastStep: r.lastStep,
89
+ updatedAt: r.updatedAt,
90
+ revision: r.revision,
91
+ matches,
92
+ });
93
+ }
94
+
95
+ // Most-recent first — same as the runs table ordering.
96
+ hits.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
97
+
98
+ return {
99
+ query: trimmed,
100
+ totalHits: hits.length,
101
+ hits: hits.slice(0, limit),
102
+ truncated: hits.length > limit,
103
+ };
104
+ }
105
+
106
+ function matchesForRun(r, tokens, contextChars, runErrors = []) {
107
+ const fields = [];
108
+
109
+ // Structured fields. Order matters for snippet presentation — we want
110
+ // the most identity-bearing ones first.
111
+ pushField(fields, "flowId", r.flowId);
112
+ pushField(fields, "pipelineId", r.pipelineId ?? r.stateJson?.pipelineId);
113
+ pushField(fields, "status", r.status);
114
+ pushField(fields, "lastStep", r.lastStep);
115
+ pushField(fields, "statusReason", r.statusReason);
116
+ pushField(fields, "waitJson.reason", r.waitJson?.reason);
117
+ pushField(fields, "waitJson.hint", r.waitJson?.hint);
118
+
119
+ // errorEntries — iterate so we get a precise field path back. Covers
120
+ // both root-level and subflow-level errors (unified in flow_node_executions).
121
+ runErrors.forEach((err, i) => {
122
+ pushField(fields, `errorEntries[${i}].nodeId`, err?.nodeId);
123
+ pushField(fields, `errorEntries[${i}].message`, err?.message);
124
+ });
125
+
126
+ // AND across fields: a run matches when EVERY token appears in at
127
+ // least one of its fields (the token doesn't have to land in the
128
+ // same field as the others). Earlier behavior required every token
129
+ // in the SAME field's text, which broke combinations like
130
+ // `<pipelineId> failed` — pipelineId text and status text are
131
+ // disjoint, so the conjunction always returned zero.
132
+ //
133
+ // We compute, per token, the set of fields it touches. A run is a
134
+ // hit when every token has at least one such field. The returned
135
+ // matches[] surfaces only fields that contained at least one
136
+ // token, so the snippets remain meaningful.
137
+ const tokenFieldHits = tokens.map((t) => {
138
+ const hitsForToken = [];
139
+ for (const f of fields) {
140
+ const pos = f.text.toLowerCase().indexOf(t);
141
+ if (pos < 0) continue;
142
+ hitsForToken.push({ field: f, token: t, pos });
143
+ }
144
+ return hitsForToken;
145
+ });
146
+ if (tokenFieldHits.some((arr) => arr.length === 0)) return [];
147
+
148
+ // Dedupe field → first hit so we don't emit one match entry per
149
+ // (token, field) pair when several tokens land in the same field.
150
+ const byField = new Map();
151
+ for (const arr of tokenFieldHits) {
152
+ for (const h of arr) {
153
+ const cur = byField.get(h.field.name);
154
+ if (!cur || h.pos < cur.pos) byField.set(h.field.name, h);
155
+ }
156
+ }
157
+ const out = [];
158
+ for (const h of byField.values()) {
159
+ out.push({
160
+ field: h.field.name,
161
+ snippet: snippetAround(h.field.text, h.pos, h.token.length, contextChars),
162
+ matchedAt: h.pos,
163
+ });
164
+ }
165
+ return out;
166
+ }
167
+
168
+ function pushField(fields, name, value) {
169
+ if (value === null || value === undefined) return;
170
+ const text = String(value);
171
+ if (!text) return;
172
+ fields.push({ name, text });
173
+ }
174
+
175
+ function snippetAround(text, pos, matchLen, contextChars) {
176
+ const start = Math.max(0, pos - contextChars);
177
+ const end = Math.min(text.length, pos + matchLen + contextChars);
178
+ const prefix = start > 0 ? "…" : "";
179
+ const suffix = end < text.length ? "…" : "";
180
+ // Collapse newlines/tabs so the snippet stays one line.
181
+ const body = text.slice(start, end).replace(/\s+/g, " ");
182
+ return `${prefix}${body}${suffix}`;
183
+ }