@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,57 @@
1
+ // routes/bearer-auth.js — winch-style bearer guard for manifold HTTP routes.
2
+ //
3
+ // One shared secret, no pairing, no device tokens: `Authorization: Bearer
4
+ // <MANIFOLD_BEARER>` — the same env the MCP HTTP server requires before it
5
+ // starts. Timing-safe compare; TLS terminates in front (reverse proxy or
6
+ // ingress). An unset/empty secret fails every check (fail-closed); the
7
+ // first rejection logs once so a missing env is loud instead of mysterious.
8
+ //
9
+ // The harness declares itself per call with X-Manifold-Harness where
10
+ // identity matters (MCP sessions); these operator routes authenticate the
11
+ // caller, not the harness.
12
+ import { timingSafeEqual } from "node:crypto";
13
+
14
+ let warnedNoSecret = false;
15
+
16
+ function tokensEqual(a, b) {
17
+ const ab = Buffer.from(a, "utf8");
18
+ const bb = Buffer.from(b, "utf8");
19
+ if (ab.length !== bb.length) {
20
+ timingSafeEqual(ab, ab); // burn the cycles to keep timing flat
21
+ return false;
22
+ }
23
+ return timingSafeEqual(ab, bb);
24
+ }
25
+
26
+ /**
27
+ * Returns {ok: true} or {ok: false, reason}. Reasons: "no-bearer"
28
+ * (missing/non-Bearer scheme), "empty-token", "no-secret" (MANIFOLD_BEARER
29
+ * unset — fail-closed), "no-match".
30
+ */
31
+ export function authorizeBearerRequest(req, { logger = null, secret: secretOverride = null } = {}) {
32
+ const raw = req?.headers?.authorization ?? "";
33
+ if (typeof raw !== "string" || !raw.toLowerCase().startsWith("bearer ")) {
34
+ return { ok: false, reason: "no-bearer" };
35
+ }
36
+ const token = raw.slice(7).trim();
37
+ if (!token) return { ok: false, reason: "empty-token" };
38
+ // A caller may pin its own secret (the telemetry ingest token the core
39
+ // mints for its adapter) without touching the operator-wide bearer.
40
+ const secret = secretOverride ?? process.env.MANIFOLD_BEARER ?? "";
41
+ if (!secret) {
42
+ if (!warnedNoSecret) {
43
+ warnedNoSecret = true;
44
+ try { logger?.warn?.("manifold: MANIFOLD_BEARER is unset — every bearer check fails closed"); } catch {}
45
+ }
46
+ return { ok: false, reason: "no-secret" };
47
+ }
48
+ if (!tokensEqual(token, secret)) return { ok: false, reason: "no-match" };
49
+ return { ok: true };
50
+ }
51
+
52
+ /** Standard 401 for a bearer-rejected request. */
53
+ export function sendUnauthorized(res, reason) {
54
+ res.statusCode = 401;
55
+ res.setHeader("Content-Type", "application/json");
56
+ res.end(JSON.stringify({ error: "unauthorized", reason: reason ?? "unauthorized" }));
57
+ }
@@ -0,0 +1,87 @@
1
+ // Audio constants and filesystem helpers for discuss audio upload/serve/history.
2
+ import path from "node:path";
3
+ import { resolveStorePaths, harnessMediaAudioDir } from "../state/paths.js";
4
+ import { assertDeclaration } from "../mcp/identity.js";
5
+
6
+ export const AUDIO_MIME_EXT = {
7
+ "audio/m4a": "m4a",
8
+ "audio/mp4": "m4a",
9
+ "audio/aac": "m4a",
10
+ "audio/x-m4a": "m4a",
11
+ "audio/mpeg": "mp3",
12
+ "audio/mp3": "mp3",
13
+ "audio/wav": "wav",
14
+ "audio/x-wav": "wav",
15
+ "audio/webm": "webm",
16
+ "audio/ogg": "ogg",
17
+ };
18
+
19
+ export const EXT_TO_MIME = {
20
+ m4a: "audio/m4a",
21
+ mp3: "audio/mpeg",
22
+ wav: "audio/wav",
23
+ webm: "audio/webm",
24
+ ogg: "audio/ogg",
25
+ };
26
+
27
+ // Harness namespace for stored audio, declared per connection like every
28
+ // other harness identity (mcp/identity.js): the X-Manifold-Harness header
29
+ // on the request that delivered the audio. Never env, never defaulted —
30
+ // an undeclared harness refuses before any filesystem touch.
31
+ export function resolveAudioHarness(req) {
32
+ const header = req?.headers?.["x-manifold-harness"];
33
+ const { harness } = assertDeclaration({ harness: Array.isArray(header) ? header[0] : header });
34
+ return harness;
35
+ }
36
+
37
+ // Media root for the given harness: <store-home>/media/audio/<harness>.
38
+ // Resolved per call so a MANIFOLD_DATA_DIR change between import and first
39
+ // use still relocates the store. The harness is required — callers pass
40
+ // the connection-declared value (resolveAudioHarness), never a default.
41
+ export function harnessAudioDir(harness) {
42
+ return harnessMediaAudioDir(resolveStorePaths().dataDir, harness);
43
+ }
44
+
45
+ export function audioRootForFlow(flowId, harness) {
46
+ return path.join(harnessAudioDir(harness), flowId);
47
+ }
48
+
49
+ // Single search root: this harness's media dir. No cross-harness reads.
50
+ export function audioRootsForFlow(flowId, harness) {
51
+ return [audioRootForFlow(flowId, harness)];
52
+ }
53
+
54
+ export function audioDirForFlow(flowId, itemId, harness) {
55
+ const safeItem = String(itemId).replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 120) || "_";
56
+ return path.join(audioRootForFlow(flowId, harness), safeItem);
57
+ }
58
+
59
+ // Read all .meta.json sidecars under <store-home>/media/audio/<harness>/<flowId>/
60
+ // across every item sub-directory. Returns a flat array of parsed meta objects,
61
+ // [] when the root is absent.
62
+ export async function loadAudioMetasForFlow(flowId, harness) {
63
+ return (await readMetasUnder(audioRootForFlow(flowId, harness))) ?? [];
64
+ }
65
+
66
+ // Null when the root is absent; an array otherwise.
67
+ async function readMetasUnder(root) {
68
+ const { readdir, readFile } = await import("node:fs/promises");
69
+ let itemDirs;
70
+ try { itemDirs = await readdir(root); }
71
+ catch { return null; }
72
+ const metas = [];
73
+ for (const itemDir of itemDirs) {
74
+ let files;
75
+ try { files = await readdir(path.join(root, itemDir)); }
76
+ catch { continue; }
77
+ for (const f of files) {
78
+ if (!f.endsWith(".meta.json")) continue;
79
+ try {
80
+ const text = await readFile(path.join(root, itemDir, f), "utf8");
81
+ const parsed = JSON.parse(text);
82
+ if (parsed && typeof parsed === "object") metas.push(parsed);
83
+ } catch { /* skip corrupt sidecar */ }
84
+ }
85
+ }
86
+ return metas;
87
+ }
@@ -0,0 +1,39 @@
1
+ // routes/discuss-component.js — component fan-out for gate discuss.
2
+ //
3
+ // componentEmitter persists the component, then emits the canonical
4
+ // discuss.component.proposed plus the derived discuss.pending.updated
5
+ // through the shared emitter. The pending derivation (draft→text,
6
+ // meta→fields) lives here, beside the emit — not duplicated in each
7
+ // producer — because it is what cold-reconnect replays.
8
+ export function createComponentEmitter({ discussStore, emit }) {
9
+ return function componentEmitter({ flowId, itemId, component }) {
10
+ return Promise.resolve().then(async () => {
11
+ try { await discussStore.setComponent(flowId, itemId, component); } catch {}
12
+ if (!emit) return;
13
+ try {
14
+ await emit("discuss.component.proposed", { flowId, itemId, component });
15
+ } catch {}
16
+ if (component.kind === "proposed_draft") {
17
+ try {
18
+ await emit("discuss.pending.updated", {
19
+ flowId,
20
+ itemId,
21
+ text: component.text ?? null,
22
+ fields: null,
23
+ updatedAt: component.updatedAt ?? Date.now(),
24
+ });
25
+ } catch {}
26
+ } else if (component.kind === "proposed_meta") {
27
+ try {
28
+ await emit("discuss.pending.updated", {
29
+ flowId,
30
+ itemId,
31
+ text: null,
32
+ fields: component.fields ?? null,
33
+ updatedAt: component.updatedAt ?? Date.now(),
34
+ });
35
+ } catch {}
36
+ }
37
+ });
38
+ };
39
+ }
@@ -0,0 +1,159 @@
1
+ // Draft persistence helpers for discuss handlers.
2
+ // These functions mutate flow waitJson (via store.setWaiting).
3
+ import { looksLikeMetaNarration } from "./discuss-helpers.js";
4
+
5
+ export async function persistRevisedDraft({ flowId, itemId, newDraft, source, store, logger }) {
6
+ if (source !== "app" && looksLikeMetaNarration(newDraft)) {
7
+ return { applied: false, code: "rejected_meta_narration" };
8
+ }
9
+ {
10
+ const flow = await store.get(flowId);
11
+ if (!flow) return { applied: false, code: "flow_not_found" };
12
+ }
13
+ for (let attempt = 0; attempt < 5; attempt++) {
14
+ const flow = await store.get(flowId);
15
+ if (!flow) return { applied: false, code: "flow_not_found" };
16
+ if (flow.waitJson?.kind !== "human-gate" && flow.waitJson?.kind !== "gate") return { applied: false, code: "not_a_gate" };
17
+ const items = Array.isArray(flow.waitJson?.items) ? flow.waitJson.items : [];
18
+ const targetItemId = itemId ?? items[0]?.itemId;
19
+ const idx = items.findIndex((it) => it?.itemId === targetItemId);
20
+ if (idx < 0) return { applied: false, code: "item_not_found" };
21
+ const nextItems = items.map((it, i) => {
22
+ if (i !== idx) return it;
23
+ return {
24
+ ...it,
25
+ requestPayload: {
26
+ ...(it.requestPayload ?? {}),
27
+ editableText: newDraft,
28
+ },
29
+ };
30
+ });
31
+ const result = await store.setWaiting({
32
+ flowId,
33
+ expectedRevision: flow.revision,
34
+ lastStep: flow.lastStep,
35
+ stateJson: flow.stateJson,
36
+ waitJson: { ...flow.waitJson, items: nextItems },
37
+ statusReason: flow.statusReason,
38
+ });
39
+ if (result.applied) return { applied: true };
40
+ if (result.code !== "revision_conflict") return { applied: false, code: result.code };
41
+ await new Promise((r) => setTimeout(r, 25 + attempt * 25));
42
+ }
43
+ return { applied: false, code: "retry_exhausted" };
44
+ }
45
+
46
+ // Field `type`s that a gate-layout.js declares for genuinely numeric data
47
+ // (currency amounts, day counts). A value destined for one of these MUST
48
+ // arrive as a real JS number — a numeric string (e.g. from a lenient
49
+ // client) is rejected outright rather than silently coerced, so a malformed
50
+ // edit fails loudly instead of writing a value nothing validated.
51
+ const NUMERIC_FIELD_TYPES = new Set(["money", "number"]);
52
+
53
+ function collectLayoutFieldTypes(layout) {
54
+ const types = {};
55
+ if (!Array.isArray(layout)) return types;
56
+ for (const entry of layout) {
57
+ if (!entry) continue;
58
+ if (entry.kind === "field" && typeof entry.id === "string" && typeof entry.type === "string") {
59
+ types[entry.id] = entry.type;
60
+ } else if (entry.kind === "field-group" && Array.isArray(entry.fields)) {
61
+ for (const f of entry.fields) {
62
+ if (f && typeof f.id === "string" && typeof f.type === "string") types[f.id] = f.type;
63
+ }
64
+ }
65
+ }
66
+ return types;
67
+ }
68
+
69
+ export async function persistRevisedMeta({ flowId, itemId, fields, store, logger }) {
70
+ if (!fields || typeof fields !== "object" || Object.keys(fields).length === 0) {
71
+ return { applied: false, code: "empty_fields" };
72
+ }
73
+ {
74
+ const flow = await store.get(flowId);
75
+ if (!flow) return { applied: false, code: "flow_not_found" };
76
+ }
77
+ for (let attempt = 0; attempt < 5; attempt++) {
78
+ const flow = await store.get(flowId);
79
+ if (!flow) return { applied: false, code: "flow_not_found" };
80
+ if (flow.waitJson?.kind !== "human-gate" && flow.waitJson?.kind !== "gate") return { applied: false, code: "not_a_gate" };
81
+ const items = Array.isArray(flow.waitJson?.items) ? flow.waitJson.items : [];
82
+ const targetItemId = itemId ?? items[0]?.itemId;
83
+ const idx = items.findIndex((it) => it?.itemId === targetItemId);
84
+ if (idx < 0) return { applied: false, code: "item_not_found" };
85
+ // Reject the whole call if any field the pipeline declares numeric
86
+ // (type: "money"/"number" in its own gate-layout.js) is being set to
87
+ // something other than a real number — e.g. a numeric-looking string.
88
+ // Fields the layout doesn't know about (legacy callers, unknown ids)
89
+ // fall through unchecked since there's no declared type to enforce.
90
+ const fieldTypes = collectLayoutFieldTypes(items[idx]?.requestPayload?.layout);
91
+ for (const [key, v] of Object.entries(fields)) {
92
+ const declaredType = fieldTypes[key];
93
+ if (declaredType && NUMERIC_FIELD_TYPES.has(declaredType) && typeof v !== "number") {
94
+ return { applied: false, code: "invalid_field_type", field: key, expectedType: "number" };
95
+ }
96
+ }
97
+ const nextItems = items.map((it, i) => {
98
+ if (i !== idx) return it;
99
+ const rp = it.requestPayload ?? {};
100
+ // Legacy shape — no current gate-layout.js produces a top-level
101
+ // requestPayload.editableFields (executor-helpers.js enforces every
102
+ // gate declares `layout` explicitly), but patch it too in case
103
+ // anything still reads it.
104
+ const isPatchable = (v) => typeof v === "string" || typeof v === "number";
105
+ const nextFieldsArr = Array.isArray(rp.editableFields)
106
+ ? rp.editableFields.map((f) => {
107
+ if (!f || typeof f.id !== "string") return f;
108
+ const v = fields[f.id];
109
+ if (!isPatchable(v)) return f;
110
+ return { ...f, value: String(v) };
111
+ })
112
+ : rp.editableFields;
113
+ // Real shape — gate-projector.js's projectGateItem() serves
114
+ // rp.layout verbatim to clients, so a budget/timeframe/language edit
115
+ // has to land here or the chip never reflects it, regardless of
116
+ // editableMeta/editableFields getting updated correctly.
117
+ const nextLayout = Array.isArray(rp.layout)
118
+ ? rp.layout.map((entry) => {
119
+ if (!entry) return entry;
120
+ if (entry.kind === "field" && typeof entry.id === "string" && isPatchable(fields[entry.id])) {
121
+ return { ...entry, value: String(fields[entry.id]) };
122
+ }
123
+ if (entry.kind === "field-group" && Array.isArray(entry.fields)) {
124
+ return {
125
+ ...entry,
126
+ fields: entry.fields.map((f) =>
127
+ f && typeof f.id === "string" && isPatchable(fields[f.id])
128
+ ? { ...f, value: String(fields[f.id]) }
129
+ : f
130
+ ),
131
+ };
132
+ }
133
+ return entry;
134
+ })
135
+ : rp.layout;
136
+ return {
137
+ ...it,
138
+ requestPayload: {
139
+ ...rp,
140
+ editableMeta: { ...(rp.editableMeta ?? {}), ...fields },
141
+ editableFields: nextFieldsArr,
142
+ layout: nextLayout,
143
+ },
144
+ };
145
+ });
146
+ const result = await store.setWaiting({
147
+ flowId,
148
+ expectedRevision: flow.revision,
149
+ lastStep: flow.lastStep,
150
+ stateJson: flow.stateJson,
151
+ waitJson: { ...flow.waitJson, items: nextItems },
152
+ statusReason: flow.statusReason,
153
+ });
154
+ if (result.applied) return { applied: true };
155
+ if (result.code !== "revision_conflict") return { applied: false, code: result.code };
156
+ await new Promise((r) => setTimeout(r, 25 + attempt * 25));
157
+ }
158
+ return { applied: false, code: "retry_exhausted" };
159
+ }
@@ -0,0 +1,20 @@
1
+ // Pure helpers for discuss handlers — no I/O, no closure deps, fully unit-testable.
2
+
3
+ export const DRAFT_META_PREFIXES = [
4
+ /^draft\b.{0,80}(written|saved|done|updated|complete)/i,
5
+ /^here'?s\s+/i,
6
+ /^below\s+is/i,
7
+ /^above\s+is/i,
8
+ /^the\s+(new|revised|updated)\s+(version|draft|reply|text)/i,
9
+ /^i\s+(have\s+)?revised/i,
10
+ /^revised\s+(version|draft)/i,
11
+ /^changes?:/i,
12
+ /^(before|after)\s*(\(|:)/i,
13
+ ];
14
+
15
+ export function looksLikeMetaNarration(text) {
16
+ const trimmed = text.trim();
17
+ if (trimmed.length < 40) return true;
18
+ const firstLine = trimmed.split("\n", 1)[0].trim();
19
+ return DRAFT_META_PREFIXES.some((re) => re.test(firstLine));
20
+ }