@igorjpimenta/manifold 0.0.0-bootstrap.1 → 0.0.0-stage

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/README.md +2 -1583
  2. package/package.json +4 -49
  3. package/.migrations/ops/0000_futuristic_karma.sql +0 -111
  4. package/.migrations/ops/0001_low_maximus.sql +0 -7
  5. package/.migrations/ops/meta/0000_snapshot.json +0 -763
  6. package/.migrations/ops/meta/0001_snapshot.json +0 -173
  7. package/.migrations/ops/meta/_journal.json +0 -20
  8. package/.migrations/runtime/0000_real_boomer.sql +0 -180
  9. package/.migrations/runtime/0001_hot_dakota_north.sql +0 -2
  10. package/.migrations/runtime/0002_breezy_vertigo.sql +0 -8
  11. package/.migrations/runtime/0003_dashing_jack_flag.sql +0 -5
  12. package/.migrations/runtime/0004_panoramic_ego.sql +0 -1
  13. package/.migrations/runtime/0005_tidy_ben_grimm.sql +0 -10
  14. package/.migrations/runtime/0006_wet_nightmare.sql +0 -57
  15. package/.migrations/runtime/0007_ambiguous_chronomancer.sql +0 -8
  16. package/.migrations/runtime/0008_wealthy_thundra.sql +0 -301
  17. package/.migrations/runtime/0009_lying_shocker.sql +0 -96
  18. package/.migrations/runtime/0010_solid_phantom_reporter.sql +0 -160
  19. package/.migrations/runtime/0011_windy_demogoblin.sql +0 -175
  20. package/.migrations/runtime/0012_restore_harness_fks.sql +0 -103
  21. package/.migrations/runtime/meta/0000_snapshot.json +0 -1181
  22. package/.migrations/runtime/meta/0001_snapshot.json +0 -1209
  23. package/.migrations/runtime/meta/0002_snapshot.json +0 -1261
  24. package/.migrations/runtime/meta/0003_snapshot.json +0 -1292
  25. package/.migrations/runtime/meta/0004_snapshot.json +0 -1240
  26. package/.migrations/runtime/meta/0006_snapshot.json +0 -1310
  27. package/.migrations/runtime/meta/0007_snapshot.json +0 -1362
  28. package/.migrations/runtime/meta/0008_snapshot.json +0 -1742
  29. package/.migrations/runtime/meta/0009_snapshot.json +0 -2413
  30. package/.migrations/runtime/meta/0010_snapshot.json +0 -2562
  31. package/.migrations/runtime/meta/0011_snapshot.json +0 -2812
  32. package/.migrations/runtime/meta/0012_snapshot.json +0 -2812
  33. package/.migrations/runtime/meta/_journal.json +0 -97
  34. package/RELEASING.md +0 -89
  35. package/agent/fleet.js +0 -100
  36. package/bin/cli.js +0 -854
  37. package/bin/manifold.js +0 -4
  38. package/boot/flow-revival.js +0 -536
  39. package/budget/index.js +0 -495
  40. package/budget/lib.js +0 -59
  41. package/dashboard/cost.js +0 -528
  42. package/dashboard/dist/assets/index-CUfp63sj.css +0 -1
  43. package/dashboard/dist/assets/index-Qy9JMpma.js +0 -371
  44. package/dashboard/dist/index.html +0 -13
  45. package/dashboard/event-log.js +0 -267
  46. package/dashboard/index.html +0 -12
  47. package/dashboard/package-lock.json +0 -2877
  48. package/dashboard/package.json +0 -37
  49. package/dashboard/pipeline-graph.js +0 -131
  50. package/dashboard/postcss.config.js +0 -6
  51. package/dashboard/search.js +0 -183
  52. package/dashboard/server.js +0 -1015
  53. package/dashboard/src/App.tsx +0 -42
  54. package/dashboard/src/api/client.ts +0 -118
  55. package/dashboard/src/api/types.ts +0 -510
  56. package/dashboard/src/api/ws.tsx +0 -112
  57. package/dashboard/src/components/CancelButton.tsx +0 -63
  58. package/dashboard/src/components/ClickToCopy.tsx +0 -68
  59. package/dashboard/src/components/CopyButton.tsx +0 -61
  60. package/dashboard/src/components/DailyCostTrend.tsx +0 -85
  61. package/dashboard/src/components/DailyTimeTrend.tsx +0 -94
  62. package/dashboard/src/components/Funnel.tsx +0 -149
  63. package/dashboard/src/components/GateForm.tsx +0 -158
  64. package/dashboard/src/components/GraphView.tsx +0 -302
  65. package/dashboard/src/components/GroupPathsSummary.tsx +0 -47
  66. package/dashboard/src/components/Histogram.tsx +0 -292
  67. package/dashboard/src/components/Layout.tsx +0 -28
  68. package/dashboard/src/components/NeedsAttention.tsx +0 -98
  69. package/dashboard/src/components/NodeContextCard.tsx +0 -132
  70. package/dashboard/src/components/PathTrail.tsx +0 -35
  71. package/dashboard/src/components/PipelineCostBreakdown.tsx +0 -277
  72. package/dashboard/src/components/RerunButton.tsx +0 -46
  73. package/dashboard/src/components/RunComparison.tsx +0 -53
  74. package/dashboard/src/components/Sparkline.tsx +0 -94
  75. package/dashboard/src/components/StatStrip.tsx +0 -147
  76. package/dashboard/src/components/StateTree.tsx +0 -84
  77. package/dashboard/src/components/StatusBadge.tsx +0 -18
  78. package/dashboard/src/components/SubflowPathPills.tsx +0 -38
  79. package/dashboard/src/components/SubflowSummary.tsx +0 -24
  80. package/dashboard/src/components/SubflowsCard.tsx +0 -327
  81. package/dashboard/src/components/TodayStrip.tsx +0 -86
  82. package/dashboard/src/components/TranscriptPane.tsx +0 -99
  83. package/dashboard/src/components/TranscriptRow.tsx +0 -69
  84. package/dashboard/src/components/ui/badge.tsx +0 -38
  85. package/dashboard/src/components/ui/button.tsx +0 -28
  86. package/dashboard/src/components/ui/card.tsx +0 -42
  87. package/dashboard/src/components/ui/skeleton.tsx +0 -9
  88. package/dashboard/src/components/ui/table.tsx +0 -62
  89. package/dashboard/src/index.css +0 -26
  90. package/dashboard/src/lib/anomaly.ts +0 -42
  91. package/dashboard/src/lib/format.ts +0 -30
  92. package/dashboard/src/lib/step-history.ts +0 -13
  93. package/dashboard/src/lib/subflow.ts +0 -154
  94. package/dashboard/src/lib/use-click-outside.ts +0 -28
  95. package/dashboard/src/lib/use-ignored-clusters.ts +0 -67
  96. package/dashboard/src/lib/utils.ts +0 -6
  97. package/dashboard/src/main.tsx +0 -10
  98. package/dashboard/src/types/shims.d.ts +0 -4
  99. package/dashboard/src/views/Home.tsx +0 -478
  100. package/dashboard/src/views/PipelineDetail.tsx +0 -1185
  101. package/dashboard/src/views/PipelinesList.tsx +0 -111
  102. package/dashboard/src/views/RunDetail.tsx +0 -248
  103. package/dashboard/src/views/Search.tsx +0 -196
  104. package/dashboard/stats.js +0 -668
  105. package/dashboard/tailwind.config.ts +0 -43
  106. package/dashboard/tree-stats.js +0 -12
  107. package/dashboard/tsconfig.json +0 -25
  108. package/dashboard/views.js +0 -231
  109. package/dashboard/vite.config.ts +0 -34
  110. package/drizzle.config.js +0 -12
  111. package/drizzle.config.ops.js +0 -12
  112. package/elevation.js +0 -116
  113. package/engine/admission-promotion-resume.js +0 -127
  114. package/engine/agent-dispatch.js +0 -64
  115. package/engine/child-resume-trigger.js +0 -315
  116. package/engine/executor-budget.js +0 -87
  117. package/engine/executor-cancel.js +0 -83
  118. package/engine/executor-errors.js +0 -122
  119. package/engine/executor-helpers.js +0 -254
  120. package/engine/executor-nodes.js +0 -292
  121. package/engine/executor-persist.js +0 -212
  122. package/engine/executor-subflow-children.js +0 -275
  123. package/engine/executor.js +0 -1013
  124. package/engine/global-concurrency.js +0 -33
  125. package/engine/loader.js +0 -528
  126. package/engine/needs-resolver.js +0 -229
  127. package/engine/pipelines-watcher.js +0 -133
  128. package/engine/result-replay.js +0 -34
  129. package/engine/revival-messages.js +0 -11
  130. package/engine/spawn-child.js +0 -55
  131. package/engine/wait-for-flow-settlement.js +0 -109
  132. package/events/catalog.js +0 -26
  133. package/events/emit.js +0 -44
  134. package/events/kinds.js +0 -118
  135. package/events/serve-ws.js +0 -74
  136. package/events/stream.js +0 -35
  137. package/events/ws-dialog.js +0 -257
  138. package/events/ws-frame.js +0 -194
  139. package/events/ws-run-events.js +0 -70
  140. package/events.js +0 -32
  141. package/gates/gate-resolver.js +0 -576
  142. package/gates/paused-flows.js +0 -55
  143. package/graphql/columns.js +0 -67
  144. package/graphql/schema.js +0 -333
  145. package/index.js +0 -49
  146. package/mcp/http.js +0 -159
  147. package/mcp/identity.js +0 -94
  148. package/mcp/stdio.js +0 -80
  149. package/mcp/tools.js +0 -245
  150. package/mcp/wire-ops.js +0 -178
  151. package/routes/bearer-auth.js +0 -57
  152. package/routes/discuss-audio.js +0 -87
  153. package/routes/discuss-component.js +0 -39
  154. package/routes/discuss-draft.js +0 -159
  155. package/routes/discuss-helpers.js +0 -20
  156. package/routes/discuss.js +0 -848
  157. package/routes/failures.js +0 -104
  158. package/routes/graphql.js +0 -61
  159. package/routes/health.js +0 -54
  160. package/routes/operator-discuss.js +0 -193
  161. package/routes/operator-resume.js +0 -32
  162. package/routes/operator-retry.js +0 -301
  163. package/routes/operator.js +0 -539
  164. package/routes/pipelines.js +0 -118
  165. package/routes/runs.js +0 -1129
  166. package/scripts/ci/import-check.mjs +0 -50
  167. package/scripts/link-core-self.mjs +0 -31
  168. package/scripts/with-guard.sh +0 -24
  169. package/server/app.js +0 -503
  170. package/server/registry.js +0 -53
  171. package/server/serve.js +0 -163
  172. package/state/admission-queue-store.js +0 -325
  173. package/state/attribution-registries.js +0 -102
  174. package/state/batch-writer.js +0 -162
  175. package/state/db-guard.js +0 -63
  176. package/state/db-health.js +0 -27
  177. package/state/db.js +0 -122
  178. package/state/discuss-store.js +0 -299
  179. package/state/failure-store.js +0 -427
  180. package/state/migrate.js +0 -104
  181. package/state/node-cost.js +0 -67
  182. package/state/node-executions.js +0 -775
  183. package/state/node-health-store.js +0 -124
  184. package/state/ops-merge.js +0 -93
  185. package/state/paths.js +0 -146
  186. package/state/pipeline-dirs.js +0 -99
  187. package/state/pipeline-registry.js +0 -449
  188. package/state/run-store.js +0 -697
  189. package/state/schema.js +0 -438
  190. package/state/schema.ops.js +0 -44
  191. package/state/session-index.js +0 -177
  192. package/state/session-keys.js +0 -39
  193. package/state/state-store.js +0 -311
  194. package/state/subflow-state.js +0 -126
  195. package/state/tool-handoff.js +0 -169
  196. package/telemetry/budget-alert.js +0 -353
  197. package/telemetry/cli.js +0 -331
  198. package/telemetry/grammar.js +0 -119
  199. package/telemetry/http-budget.js +0 -132
  200. package/telemetry/http-cost.js +0 -670
  201. package/telemetry/http-helpers.js +0 -134
  202. package/telemetry/http-tree.js +0 -349
  203. package/telemetry/http.js +0 -44
  204. package/telemetry/index.js +0 -307
  205. package/telemetry/ingest.js +0 -134
  206. package/telemetry/labels.js +0 -115
  207. package/telemetry/pricer.js +0 -77
  208. package/telemetry/resolver.js +0 -314
  209. package/telemetry/store.js +0 -147
  210. package/utils/run-patch.js +0 -43
@@ -1,43 +0,0 @@
1
- import type { Config } from "tailwindcss";
2
-
3
- // Palette mirrors the previous vanilla styles.css so the React + Tailwind
4
- // dashboard matches the established look (dark theme, GitHub-ish accents).
5
- // Status colors keep their names so existing JSX class strings read like
6
- // English: `bg-status-succeeded text-status-succeeded` etc.
7
- export default {
8
- content: ["./index.html", "./src/**/*.{ts,tsx}"],
9
- darkMode: "class",
10
- theme: {
11
- extend: {
12
- colors: {
13
- bg: {
14
- DEFAULT: "#0e1116",
15
- elev: "#161b22",
16
- elev2: "#1f262e",
17
- },
18
- border: {
19
- DEFAULT: "#2a3038",
20
- },
21
- fg: {
22
- DEFAULT: "#d8dde6",
23
- dim: "#8b949e",
24
- },
25
- accent: "#58a6ff",
26
- status: {
27
- green: "#3fb950",
28
- amber: "#d29922",
29
- red: "#f85149",
30
- blue: "#1f6feb",
31
- grey: "#6e7681",
32
- },
33
- },
34
- fontFamily: {
35
- mono: ['ui-monospace', '"SF Mono"', 'Menlo', 'Consolas', 'monospace'],
36
- },
37
- fontSize: {
38
- "2xs": "10px",
39
- },
40
- },
41
- },
42
- plugins: [],
43
- } satisfies Config;
@@ -1,12 +0,0 @@
1
- // Small, dependency-free home for stats derived from the GET
2
- // /manifold/runs/:flowId/tree response shape (routes/runs.js's
3
- // buildTreeNodeRows) — kept out of server.js so it stays importable by unit
4
- // tests without pulling in device.js's `openclaw` package dependency.
5
-
6
- // deriveSystemSummary's stepsExecuted. Sum of executionCount across every
7
- // top-level invocation row, not tree.length — a node re-entered via
8
- // retry/recheck gets more than one execution under the SAME invocation row.
9
- export function stepsExecutedFromTree(tree) {
10
- if (!Array.isArray(tree)) return 0;
11
- return tree.reduce((sum, row) => sum + (row?.executionCount ?? 0), 0);
12
- }
@@ -1,25 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "useDefineForClassFields": true,
5
- "lib": ["ES2023", "DOM", "DOM.Iterable"],
6
- "module": "ESNext",
7
- "skipLibCheck": true,
8
- "moduleResolution": "bundler",
9
- "allowImportingTsExtensions": false,
10
- "resolveJsonModule": true,
11
- "isolatedModules": true,
12
- "moduleDetection": "force",
13
- "noEmit": true,
14
- "jsx": "react-jsx",
15
- "strict": true,
16
- "noUnusedLocals": false,
17
- "noUnusedParameters": false,
18
- "noFallthroughCasesInSwitch": true,
19
- "baseUrl": ".",
20
- "paths": {
21
- "@/*": ["./src/*"]
22
- }
23
- },
24
- "include": ["src", "vite.config.ts", "tailwind.config.ts"]
25
- }
@@ -1,231 +0,0 @@
1
- // Pipeline-declared dashboard views. Each pipeline can opt into
2
- // extra surfaces on its detail page by exporting a `views: [...]`
3
- // array; the dashboard renders them generically — no per-pipeline
4
- // dashboard code.
5
- //
6
- // View shape (pipeline-side):
7
- //
8
- // {
9
- // id: "outcomes", // stable, per-pipeline-unique
10
- // kind: "funnel", // currently the only kind
11
- // label: "outcomes (last 30d)", // card title
12
- // source: {
13
- // kind: "frontmatter-dir",
14
- // path: "/abs/path/to/dir",
15
- // timeField: "sent-at", // optional; default "sent-at"
16
- // },
17
- // stages: [
18
- // { id: "sent", label: "sent" }, // no filter ⇒ matches all records
19
- // { id: "replied", label: "replied", outcomeIn: ["replied","qualified","meeting-scheduled","won"] },
20
- // { id: "won", label: "won", outcomeEq: "won" },
21
- // ],
22
- // }
23
- //
24
- // To add a new view kind: extend `computeView` with the new branch and
25
- // add a record-loader if it pulls from a new source kind. The
26
- // frontend's <DeclaredView> dispatcher mirrors the same `kind` switch.
27
-
28
- import { readdir, readFile, stat } from "node:fs/promises";
29
- import path from "node:path";
30
-
31
- // ─── Top-level dispatcher ────────────────────────────────────────────────────
32
-
33
- export async function computeViews(pipeline, { sinceMs = null } = {}) {
34
- if (!Array.isArray(pipeline?.views) || pipeline.views.length === 0) return [];
35
- // Each view is independent; parallelise the IO. The frontmatter-dir
36
- // loader is already libuv-pool-bound, so this won't fan out further
37
- // than Node can handle.
38
- return Promise.all(pipeline.views.map((v) => computeView(v, { sinceMs })));
39
- }
40
-
41
- async function computeView(view, { sinceMs }) {
42
- // Per-view sinceDays overrides the caller-supplied window.
43
- const effectiveSinceMs = typeof view.sinceDays === "number" && view.sinceDays > 0
44
- ? Date.now() - view.sinceDays * 86_400_000
45
- : sinceMs;
46
- const base = { id: view.id, kind: view.kind, label: view.label, sinceMs: effectiveSinceMs };
47
- try {
48
- if (view.kind === "funnel") return { ...base, ...(await computeFunnelView(view, { sinceMs: effectiveSinceMs })) };
49
- if (view.kind === "metric") return { ...base, ...(await computeMetricView(view, { sinceMs: effectiveSinceMs })) };
50
- if (view.kind === "table") return { ...base, ...(await computeTableView(view, { sinceMs: effectiveSinceMs })) };
51
- return { ...base, error: `unknown view kind: ${view.kind}` };
52
- } catch (err) {
53
- return { ...base, error: err?.message ?? String(err) };
54
- }
55
- }
56
-
57
- // ─── kind: "funnel" ──────────────────────────────────────────────────────────
58
-
59
- async function computeFunnelView(view, { sinceMs }) {
60
- const records = await loadRecords(view.source, { sinceMs });
61
- if (!records) return { total: 0, funnel: [] };
62
- const stageDefs = Array.isArray(view.stages) ? view.stages : [];
63
-
64
- // Compute each stage's count by counting records that match the
65
- // stage's filter. Stages are filters over the full record set —
66
- // they don't have to be nested supersets, but for an honest funnel
67
- // they should be (each later stage ⊆ earlier stage). That's the
68
- // pipeline author's responsibility.
69
- const stages = stageDefs.map((s) => ({
70
- ...s,
71
- count: records.filter((r) => matchStage(r, s)).length,
72
- }));
73
-
74
- const out = stages.map((s, i) => ({
75
- id: s.id,
76
- label: s.label ?? s.id,
77
- count: s.count,
78
- conversionFromPrev: i === 0
79
- ? null
80
- : (stages[i - 1].count > 0 ? s.count / stages[i - 1].count : null),
81
- }));
82
- if (out.length > 1 && stages[0].count > 0) {
83
- out[out.length - 1].conversionFromStart = out[out.length - 1].count / stages[0].count;
84
- }
85
-
86
- // Per-`outcome` distribution — handy for funnels over frontmatter
87
- // sources where the field name is "outcome". When the source uses a
88
- // different field name (future) this is omitted.
89
- const byOutcome = {};
90
- for (const r of records) {
91
- if (typeof r.outcome === "string") {
92
- byOutcome[r.outcome] = (byOutcome[r.outcome] ?? 0) + 1;
93
- }
94
- }
95
-
96
- return {
97
- total: records.length,
98
- funnel: out,
99
- byOutcome: Object.keys(byOutcome).length > 0 ? byOutcome : undefined,
100
- };
101
- }
102
-
103
- function matchStage(record, stage) {
104
- if (Array.isArray(stage.outcomeIn) && stage.outcomeIn.length > 0) {
105
- return stage.outcomeIn.includes(record.outcome);
106
- }
107
- if (typeof stage.outcomeEq === "string") {
108
- return record.outcome === stage.outcomeEq;
109
- }
110
- // No filter declared — stage matches every record (used for "sent",
111
- // i.e. the cohort base of a funnel).
112
- return true;
113
- }
114
-
115
- // ─── kind: "metric" ──────────────────────────────────────────────────────────
116
- //
117
- // compute: "count" — number of records in the window
118
- // compute: "sum:fieldName" — sum of record[fieldName] (parsed as float)
119
- // compute: "avg:fieldName" — average of record[fieldName]
120
-
121
- async function computeMetricView(view, { sinceMs }) {
122
- const records = await loadRecords(view.source, { sinceMs });
123
- if (!records) return { value: null };
124
- const compute = view.compute ?? "count";
125
- if (compute === "count") return { value: records.length, compute };
126
- const [op, field] = compute.split(":");
127
- if (!field) return { value: null, error: `metric compute "${compute}" must be "count" or "op:field"` };
128
- const nums = records.map((r) => parseFloat(r[field])).filter((n) => Number.isFinite(n));
129
- if (nums.length === 0) return { value: null, compute };
130
- if (op === "sum") return { value: nums.reduce((a, b) => a + b, 0), compute };
131
- if (op === "avg") return { value: nums.reduce((a, b) => a + b, 0) / nums.length, compute };
132
- return { value: null, error: `unknown metric op "${op}"` };
133
- }
134
-
135
- // ─── kind: "table" ───────────────────────────────────────────────────────────
136
- //
137
- // columns: string[] — frontmatter fields to include in each row
138
- // limit: number — max rows (default 50), most-recent first
139
- // sortBy: string — frontmatter field to sort by (default: timeField)
140
-
141
- async function computeTableView(view, { sinceMs }) {
142
- const records = await loadRecords(view.source, { sinceMs });
143
- if (!records) return { columns: view.columns ?? [], rows: [], total: 0 };
144
- const columns = Array.isArray(view.columns) && view.columns.length > 0
145
- ? view.columns
146
- : Object.keys(records[0] ?? {}).filter((k) => !k.startsWith("__"));
147
- const sortField = view.sortBy ?? view.source?.timeField ?? "sent-at";
148
- const sorted = [...records].sort((a, b) => {
149
- const at = a[sortField] ?? a.__ts ?? 0;
150
- const bt = b[sortField] ?? b.__ts ?? 0;
151
- return (typeof bt === "number" ? bt : 0) - (typeof at === "number" ? at : 0);
152
- });
153
- const limit = typeof view.limit === "number" && view.limit > 0 ? view.limit : 50;
154
- const rows = sorted.slice(0, limit).map((r) => {
155
- const row = {};
156
- for (const col of columns) row[col] = r[col] ?? null;
157
- return row;
158
- });
159
- return { columns, rows, total: records.length };
160
- }
161
-
162
- // ─── source loaders ──────────────────────────────────────────────────────────
163
-
164
- async function loadRecords(source, { sinceMs }) {
165
- if (!source || typeof source !== "object") return null;
166
- if (source.kind === "frontmatter-dir") return loadFrontmatterDirRecords(source, { sinceMs });
167
- return null;
168
- }
169
-
170
- const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
171
-
172
- // Minimal YAML frontmatter extractor. The sent/*.md files use flat
173
- // `key: value` lines (no nesting, no arrays). A full YAML parser would
174
- // be overkill for five-key headers and would change the build surface.
175
- function parseFrontmatter(text) {
176
- const m = text.match(FRONTMATTER_RE);
177
- if (!m) return null;
178
- const out = {};
179
- for (const line of m[1].split(/\r?\n/)) {
180
- const kv = line.match(/^([^:]+):\s*(.*)$/);
181
- if (!kv) continue;
182
- let v = kv[2].trim();
183
- if (
184
- (v.startsWith('"') && v.endsWith('"')) ||
185
- (v.startsWith("'") && v.endsWith("'"))
186
- ) v = v.slice(1, -1);
187
- out[kv[1].trim()] = v;
188
- }
189
- return out;
190
- }
191
-
192
- function parseDate(raw) {
193
- if (!raw) return null;
194
- const t = Date.parse(raw);
195
- return Number.isFinite(t) ? t : null;
196
- }
197
-
198
- async function loadFrontmatterDirRecords({ path: dir, timeField = "sent-at" }, { sinceMs }) {
199
- if (!dir || typeof dir !== "string") return null;
200
- try {
201
- const s = await stat(dir);
202
- if (!s.isDirectory()) return null;
203
- } catch { return null; }
204
-
205
- let files;
206
- try { files = await readdir(dir); }
207
- catch { return null; }
208
-
209
- const records = [];
210
- await Promise.all(files.map(async (f) => {
211
- if (!f.endsWith(".md")) return;
212
- let raw;
213
- try { raw = await readFile(path.join(dir, f), "utf-8"); }
214
- catch { return; }
215
- const fm = parseFrontmatter(raw);
216
- if (!fm) return;
217
- const ts = parseDate(fm[timeField]);
218
- if (sinceMs != null) {
219
- // Records missing the time field are excluded from windowed
220
- // queries — better to be honest about the cohort than to
221
- // silently inflate it with unknown-date records.
222
- if (ts == null || ts < sinceMs) return;
223
- }
224
- records.push({
225
- id: f.replace(/\.md$/, ""),
226
- ...fm,
227
- __ts: ts,
228
- });
229
- }));
230
- return records;
231
- }
@@ -1,34 +0,0 @@
1
- import { defineConfig } from "vite";
2
- import react from "@vitejs/plugin-react";
3
- import path from "node:path";
4
-
5
- // Built under base `/graph/` so the dashboard can be mounted as a subpath
6
- // behind tailscale serve (e.g. https://<tailnet>/graph/) without asset paths
7
- // colliding with the gateway at `/`. server.js strips the prefix for direct
8
- // loopback requests, and tailscale serve strips it on the proxy side, so the
9
- // same bundle works both ways.
10
- export default defineConfig({
11
- base: "/graph/",
12
- plugins: [react()],
13
- resolve: {
14
- alias: {
15
- "@": path.resolve(__dirname, "./src"),
16
- },
17
- },
18
- build: {
19
- outDir: "dist",
20
- emptyOutDir: true,
21
- rollupOptions: {
22
- output: {
23
- manualChunks: undefined,
24
- },
25
- },
26
- },
27
- server: {
28
- port: 5173,
29
- proxy: {
30
- "/graph/api": { target: "http://127.0.0.1:7430", changeOrigin: false },
31
- "/graph/static": { target: "http://127.0.0.1:7430", changeOrigin: false },
32
- },
33
- },
34
- });
package/drizzle.config.js DELETED
@@ -1,12 +0,0 @@
1
- import { defineConfig } from "drizzle-kit";
2
- import path from "node:path";
3
- import os from "node:os";
4
-
5
- export default defineConfig({
6
- dialect: "sqlite",
7
- schema: "./state/schema.js",
8
- out: "./.migrations/runtime",
9
- dbCredentials: {
10
- url: path.join(os.homedir(), ".openclaw", "runtime.sqlite"),
11
- },
12
- });
@@ -1,12 +0,0 @@
1
- import { defineConfig } from "drizzle-kit";
2
- import path from "node:path";
3
- import os from "node:os";
4
-
5
- export default defineConfig({
6
- dialect: "sqlite",
7
- schema: "./state/schema.ops.js",
8
- out: "./.migrations/ops",
9
- dbCredentials: {
10
- url: path.join(os.homedir(), ".openclaw", "ops.sqlite"),
11
- },
12
- });
package/elevation.js DELETED
@@ -1,116 +0,0 @@
1
- // elevation.js — plugin-side helper for routes that need ambient operator
2
- // scope but are exposed via `auth: "plugin"` (so they accept device tokens
3
- // instead of the env-var token).
4
- //
5
- // The problem this fixes:
6
- // Plugin-auth HTTP routes don't get an operator scope on the request —
7
- // they get "the plugin handles auth" with NO scope propagation. Anything
8
- // inside the handler that scope-checks against operator.* (notably
9
- // subagent.run, which gateway-internally requires operator.write) fails
10
- // with `missing scope: operator.write` even when the device token has
11
- // operator.write declared. This includes async work scheduled via
12
- // setImmediate from inside the handler — the orphaned context has no
13
- // ambient operator scope either.
14
- //
15
- // The mechanism:
16
- // The gateway's `auth: "gateway"` middleware DOES set ambient operator
17
- // scope: when an HTTP request authenticates via the shared-secret
18
- // env-var token (OPENCLAW_GATEWAY_TOKEN), the auth path attaches
19
- // CLI_DEFAULT_OPERATOR_SCOPES (admin/write/read/approvals/pairing/
20
- // talk.secrets) — see http-auth-utils-Chseq2ys.js. Routes registered
21
- // with `auth: "gateway"` inherit that scope ambient through their
22
- // handler execution.
23
- //
24
- // So a plugin-auth route can validate its device token, then loopback
25
- // over localhost to a sibling `auth: "gateway"` route using the env-var
26
- // Bearer to perform the operator-scoped work. The elevation crosses
27
- // the auth boundary cleanly: device-token auth in front, env-var auth
28
- // inside, no token leakage to clients.
29
- //
30
- // Usage pattern:
31
- // In your external (auth: "plugin") route:
32
- // const { ok, status, body } = await invokeElevated("/manifold/_elev/start", payload);
33
- // res.statusCode = status;
34
- // res.end(body);
35
- // In your internal (auth: "gateway") route:
36
- // handler: async (req, res) => {
37
- // // Body already validated by the caller (or re-validate). Scope is
38
- // // ambient operator.*. Do the work that needs it.
39
- // }
40
- //
41
- // When NOT to use this:
42
- // - For purely read-only operations, just keep auth: "plugin" — they
43
- // don't need operator.write.
44
- // - For routes whose auth is acceptable as env-var only (e.g. internal
45
- // gateway-to-gateway), register directly with auth: "gateway" and
46
- // skip the loopback.
47
-
48
- import http from "node:http";
49
-
50
- const GATEWAY_PORT = Number(process.env.OPENCLAW_GATEWAY_PORT) || 18789;
51
- const GATEWAY_HOST = "127.0.0.1";
52
-
53
- /**
54
- * POST to a gateway-auth route on loopback with the env-var Bearer, so the
55
- * target handler runs with CLI_DEFAULT_OPERATOR_SCOPES ambient.
56
- *
57
- * Returns { ok, status, body, error? } — body is the raw response string.
58
- * Caller is responsible for content-type interpretation.
59
- *
60
- * `opts.timeoutMs` defaults to 30s — fine for routes that schedule work
61
- * and return quickly (e.g. /manifold/_elev/start kicks off a flow via
62
- * setImmediate). Routes that block on subagent.run (e.g. /_elev/discuss
63
- * waits up to 5 min for Herculano to compose a reply) MUST pass a
64
- * timeout above the inner wait, or the loopback gives up while the
65
- * inner work is still in flight and surfaces a confusing 500.
66
- */
67
- export async function invokeElevated(path, payload, opts = {}) {
68
- const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : 30_000;
69
- const token = process.env.OPENCLAW_GATEWAY_TOKEN;
70
- if (!token) {
71
- return {
72
- ok: false,
73
- status: 503,
74
- body: JSON.stringify({ ok: false, code: "no_gateway_token", error: "OPENCLAW_GATEWAY_TOKEN unset" }),
75
- error: "no_gateway_token",
76
- };
77
- }
78
- const body = typeof payload === "string" ? payload : JSON.stringify(payload ?? {});
79
- return new Promise((resolve) => {
80
- const req = http.request({
81
- hostname: GATEWAY_HOST,
82
- port: GATEWAY_PORT,
83
- method: "POST",
84
- path,
85
- headers: {
86
- "Content-Type": "application/json",
87
- "Authorization": `Bearer ${token}`,
88
- "Content-Length": Buffer.byteLength(body),
89
- },
90
- }, (res) => {
91
- let raw = "";
92
- res.setEncoding("utf8");
93
- res.on("data", (chunk) => { raw += chunk; });
94
- res.on("end", () => {
95
- resolve({
96
- ok: res.statusCode >= 200 && res.statusCode < 300,
97
- status: res.statusCode ?? 0,
98
- body: raw,
99
- });
100
- });
101
- });
102
- req.on("error", (err) => {
103
- resolve({
104
- ok: false,
105
- status: 0,
106
- body: JSON.stringify({ ok: false, code: "loopback_failed", error: err?.message ?? String(err) }),
107
- error: err?.message ?? String(err),
108
- });
109
- });
110
- req.setTimeout(timeoutMs, () => {
111
- req.destroy(new Error("loopback timeout"));
112
- });
113
- req.write(body);
114
- req.end();
115
- });
116
- }
@@ -1,127 +0,0 @@
1
- // admission-promotion-resume.js — wakes a flow once admission-queue-
2
- // store.js's release()/releaseByFlow()/fillFreeSlots() promotes it out of
3
- // "queued" and into "admitted" — i.e. once a slot in the shared pool
4
- // actually frees up. Handles both admission kinds: kind:"child-dispatch" (a
5
- // queued subflow child) and kind:"flow-start" (a queued root flow, or a
6
- // root flow re-queued on resume from a gate — see engine/child-resume-
7
- // trigger.js's admitAndSetRunning/flipToRunningAndResume).
8
- //
9
- // A queued flow/child has no in-process waiter at all: it's a real
10
- // flow_runs row that may have been queued for hours by a process that has
11
- // since restarted. Promoting it means flipping that row to 'running' and
12
- // re-entering the engine via resume(), like any other blocked/queued-flow
13
- // wake in this codebase — engine/child-resume-trigger.js's
14
- // flipToRunningAndResume already does exactly that.
15
- //
16
- // The promoted flow's run is DETACHED from the releaser's call stack
17
- // (scheduleDetachedResume below): the durable part — the admission
18
- // promotion and the flip to 'running' — is still awaited, but resume()
19
- // itself starts on its own tick. Awaiting it inline would make whoever
20
- // called release() — often a flow that just went blocked or terminal inside
21
- // its own state-store write — wait for the promoted flow's whole run to
22
- // reach its next block point, and that run can release and promote the
23
- // next flow inline in turn, nesting every flow in the queue inside the
24
- // first releaser's call.
25
- //
26
- // Gateway readiness: a flow/child woken here may not have run at all since
27
- // the gateway restarted (a queued admission survives a crash same as any
28
- // other flow_runs row), so it can reach an agent-kind node inside the
29
- // gateway's startup window. Nothing to wait for here: resume() is the
30
- // executor's, and every agent dispatch it makes goes through the executor's
31
- // readiness gate (the harness's run-turn gate).
32
-
33
- import { flipToRunningAndResume } from "./child-resume-trigger.js";
34
-
35
- // On globalThis, not module scope: extensions/manifold/** can load through
36
- // both jiti and native ESM in one process, and a CLI command's
37
- // drainDetachedResumes() must see tasks scheduled by either instance.
38
- const PENDING_KEY = "__manifold_detached_resumes__";
39
- function pendingResumes() {
40
- if (!globalThis[PENDING_KEY]) globalThis[PENDING_KEY] = new Set();
41
- return globalThis[PENDING_KEY];
42
- }
43
-
44
- // Starts resume(flowId) on the next tick, in its own call stack. Never
45
- // throws and never rejects — a failure is logged tagged with `context`,
46
- // since the caller has already returned by the time the run happens.
47
- export function scheduleDetachedResume(resume, flowId, { logger, context } = {}) {
48
- const pending = pendingResumes();
49
- const task = new Promise((ready) => setImmediate(ready))
50
- .then(() => resume(flowId))
51
- .catch((err) => {
52
- logger?.warn?.(`${context ?? "admission-promotion-resume"}: detached resume [${String(flowId).slice(0, 8)}] failed: ${err?.message ?? err}`);
53
- })
54
- .finally(() => pending.delete(task));
55
- pending.add(task);
56
- return task;
57
- }
58
-
59
- // For short-lived processes (CLI commands) that must not exit while a
60
- // detached resume is still pending. Loops because a resumed run can itself
61
- // release a slot and schedule another detached resume.
62
- export async function drainDetachedResumes() {
63
- const pending = pendingResumes();
64
- while (pending.size > 0) {
65
- await Promise.allSettled([...pending]);
66
- }
67
- }
68
-
69
- const RESUMABLE_KINDS = new Set(["child-dispatch", "flow-start"]);
70
-
71
- // Guards against driving a promoted row whose kind this engine doesn't
72
- // admit — such a row has no flow run to flip.
73
- export function isEngineResumableKind(kind) {
74
- return RESUMABLE_KINDS.has(kind);
75
- }
76
-
77
- // Flips the promoted flow to 'running' (awaited) and schedules its run
78
- // (detached — see this file's header), so `resumed: true` means "flipped
79
- // and scheduled", not "ran".
80
- export async function resumePromotedAdmission({ promoted, runStore, resume, logger, api, context }) {
81
- if (!promoted || !isEngineResumableKind(promoted.kind)) {
82
- return { resumed: false, reason: "not_a_resumable_promotion" };
83
- }
84
- if (typeof resume !== "function") return { resumed: false, reason: "no_resume_fn" };
85
- const detachedResume = (flowId) => { scheduleDetachedResume(resume, flowId, { logger, api, context }); };
86
- // No admissionQueueStore passed here, deliberately — this flow was just
87
- // PROMOTED, meaning its admission row is already 'admitted'. Asking
88
- // flipToRunningAndResume to re-admit would claim a second, duplicate
89
- // entry for the same flow+kind.
90
- return flipToRunningAndResume({ parentFlowId: promoted.flowId, runStore, resume: detachedResume, logger, api });
91
- }
92
-
93
- // wakePromotedRelease — the ONE place every admissionQueueStore.release()/
94
- // releaseByFlow() call site should go through, instead of each
95
- // independently re-deriving the same "if (result.promoted) { await
96
- // resumePromotedAdmission(...).catch(err => logger.warn(...)) }" glue.
97
- //
98
- // `releaseResult` is whatever release()/releaseByFlow() resolved to, or an
99
- // array of several (state-store.js's triggerAdmissionRelease releases both
100
- // flow-start and child-dispatch for the SAME departing flow in one
101
- // Promise.all — at most one of the two can ever carry a real promotion, so
102
- // the first non-null wins). An unsuccessful outcome — resumePromotedAdmission
103
- // resolving {resumed:false}, or throwing outright — logs a warning tagged
104
- // with the caller-supplied `context`, so no call site has to remember to
105
- // check `result.resumed` itself.
106
- //
107
- // Returns resumePromotedAdmission's own result shape ({resumed, reason,
108
- // ...}) so a caller that wants to act on the outcome (e.g. bin/cli.js's
109
- // release-leaked-admission, which prints it for the operator) still can;
110
- // callers that are purely fire-and-forget can ignore the return value.
111
- export async function wakePromotedRelease(releaseResult, { runStore, resume, logger, api, context }) {
112
- const results = Array.isArray(releaseResult) ? releaseResult : [releaseResult];
113
- const promoted = results.reduce((found, r) => found ?? r?.promoted ?? null, null);
114
- if (!promoted || !isEngineResumableKind(promoted.kind)) {
115
- return { resumed: false, reason: "nothing_to_wake" };
116
- }
117
- try {
118
- const result = await resumePromotedAdmission({ promoted, runStore, resume, logger, api, context });
119
- if (!result.resumed) {
120
- logger?.warn?.(`${context}: promoted [${promoted.id.slice(0, 8)}] did not resume: ${result.reason ?? "unknown"}`);
121
- }
122
- return result;
123
- } catch (err) {
124
- logger?.warn?.(`${context}: resume after promotion [${promoted.id.slice(0, 8)}] failed: ${err?.message ?? err}`);
125
- return { resumed: false, reason: "threw", error: err?.message ?? String(err) };
126
- }
127
- }