Spaces:
Running

File size: 10,809 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Pure helpers for the workflow editor: the plain-language describer (a port of
// core/workflows/dsl.py `describe`), definition -> canvas graph, JSON sync and step edits.
// Every edit returns a NEW definition object; the three views render the same one.

import type { Condition, ConditionOp, Issue, Step, Trigger, WorkflowDefinition } from "./types";

// ---------------------------------------------------------------- describer

/** Python's str() for scalars, so the client text matches the server's exactly. */
function pyStr(v: unknown): string {
  if (v === null || v === undefined) return "None";
  if (v === true) return "True";
  if (v === false) return "False";
  return String(v);
}

export function refText(v: unknown): string {
  if (typeof v === "string" && v.startsWith("$.")) return `«${v.slice(2)}»`;
  if (Array.isArray(v)) return `[${v.map(refText).join(", ")}]`;
  if (v && typeof v === "object") {
    return `{${Object.entries(v as Record<string, unknown>)

      .map(([k, x]) => `${k}: ${refText(x)}`)

      .join(", ")}}`;
  }
  return pyStr(v);
}

export const OP_TEXT: Record<ConditionOp, string> = {
  eq: "is",
  ne: "is not",
  gt: ">",
  gte: ">=",
  lt: "<",
  lte: "<=",
  in: "is one of",
  not_in: "is not one of",
  contains: "contains",
  exists: "exists",
  not_exists: "is missing",
  truthy: "is set",
  falsy: "is not set",
};

const UNARY = new Set<ConditionOp>(["exists", "not_exists", "truthy", "falsy"]);

export function describeCondition(c: Condition): string {
  const op = OP_TEXT[c.op] ?? c.op;
  if (UNARY.has(c.op)) return `${refText(c.left)} ${op}`;
  return `${refText(c.left)} ${op} ${refText(c.right ?? null)}`;
}

export function describeTrigger(t: Trigger): string {
  if (t.type === "schedule") return `On schedule '${t.cron}' (${t.tz ?? "Asia/Karachi"})`;
  if (t.type === "event") {
    const extra = t.when?.length ? " when " + t.when.map(describeCondition).join(" and ") : "";
    return `When event '${t.event_type}' arrives${extra}`;
  }
  return "When started by hand";
}

export type StepKind = "tool" | "wait" | "approval";

export function stepKind(s: Step): StepKind {
  if (s.wait) return "wait";
  if (s.approval) return "approval";
  return "tool";
}

export function describeStep(s: Step, i: number): string {
  const kind = stepKind(s);
  let text: string;
  if (kind === "wait") {
    text = `wait ${pyStr(s.wait?.seconds)} seconds`;
  } else if (kind === "approval") {
    text = `ask the owner to sign off: ${s.approval?.summary ?? ""}`;
  } else {
    const args = Object.entries(s.args ?? {})
      .map(([k, v]) => `${k}=${refText(v)}`)
      .join(", ");
    text = `call ${pyStr(s.tool)}(${args})`;
    if (s.for_each) text = `for each item in ${refText(s.for_each)}, ${text}`;
    if (s.requires_approval) text += " after a human approves";
  }
  if (s.when?.length) text += " only if " + s.when.map(describeCondition).join(" and ");
  return `${i}. [${s.id}] ${text}`;
}

/** Deterministic plain-language rendering, identical to the server's ``describe``. */
export function describe(defn: WorkflowDefinition): string[] {
  return [
    describeTrigger(defn.trigger) + ":",
    ...(defn.steps ?? []).map((s, i) => describeStep(s, i + 1)),
  ];
}

// ---------------------------------------------------------------- canvas graph

export interface TriggerNodeData extends Record<string, unknown> {
  label: string;
  trigger: Trigger;
}

export interface StepNodeData extends Record<string, unknown> {
  index: number;
  step: Step;
  kind: StepKind;
  conditions: string[];
}

export interface FlowNode {
  id: string;
  type: "trigger" | "step";
  position: { x: number; y: number };
  data: TriggerNodeData | StepNodeData;
  selected?: boolean;
}

export interface FlowEdge {
  id: string;
  source: string;
  target: string;
}

export const TRIGGER_NODE_ID = "__trigger";
export const NODE_GAP_Y = 150;

/** Trigger node, then one node per step in a vertical column; edges in order. */
export function toFlow(

  defn: WorkflowDefinition,

  selected: number | null = null,

): { nodes: FlowNode[]; edges: FlowEdge[] } {
  const nodes: FlowNode[] = [
    {
      id: TRIGGER_NODE_ID,
      type: "trigger",
      position: { x: 0, y: 0 },
      data: { label: describeTrigger(defn.trigger), trigger: defn.trigger },
    },
  ];
  const edges: FlowEdge[] = [];
  let prev = TRIGGER_NODE_ID;
  (defn.steps ?? []).forEach((step, index) => {
    const id = `step:${index}:${step.id}`;
    nodes.push({
      id,
      type: "step",
      position: { x: 0, y: (index + 1) * NODE_GAP_Y },
      data: {
        index,
        step,
        kind: stepKind(step),
        conditions: (step.when ?? []).map(describeCondition),
      },
      selected: selected === index,
    });
    edges.push({ id: `e:${prev}->${id}`, source: prev, target: id });
    prev = id;
  });
  return { nodes, edges };
}

// ---------------------------------------------------------------- JSON sync

/** JSON with sorted object keys: two definitions are the same iff these strings match. */
export function canonical(v: unknown): string {
  return JSON.stringify(sortKeys(v));
}

function sortKeys(v: unknown): unknown {
  if (Array.isArray(v)) return v.map(sortKeys);
  if (v && typeof v === "object") {
    return Object.fromEntries(
      Object.keys(v as Record<string, unknown>)
        .sort()
        .filter((k) => (v as Record<string, unknown>)[k] !== undefined)
        .map((k) => [k, sortKeys((v as Record<string, unknown>)[k])]),
    );
  }
  return v;
}

export function sameDefinition(a: unknown, b: unknown): boolean {
  return canonical(a) === canonical(b);
}

export function formatDefinition(defn: WorkflowDefinition): string {
  return JSON.stringify(defn, null, 2);
}

export type ParseResult =
  | { ok: true; value: WorkflowDefinition }
  | { ok: false; error: string };

/** Parse editor text into a definition-shaped object (shape only; the server checks it). */
export function parseDefinition(text: string): ParseResult {
  let v: unknown;
  try {
    v = JSON.parse(text);
  } catch (e) {
    return { ok: false, error: e instanceof Error ? e.message : String(e) };
  }
  if (!v || typeof v !== "object" || Array.isArray(v)) {
    return { ok: false, error: "The definition must be a JSON object." };
  }
  const o = v as Record<string, unknown>;
  if (!o.trigger || typeof o.trigger !== "object") {
    return { ok: false, error: "Missing \"trigger\" object." };
  }
  if (!Array.isArray(o.steps)) return { ok: false, error: "\"steps\" must be a list." };
  if (o.steps.some((s) => !s || typeof s !== "object" || Array.isArray(s))) {
    return { ok: false, error: "Every step must be an object." };
  }
  return { ok: true, value: v as WorkflowDefinition };
}

// ---------------------------------------------------------------- step edits

function withSteps(defn: WorkflowDefinition, steps: Step[]): WorkflowDefinition {
  return { ...defn, steps };
}

export function moveStep(defn: WorkflowDefinition, index: number, delta: number): WorkflowDefinition {
  const to = index + delta;
  if (index < 0 || index >= defn.steps.length || to < 0 || to >= defn.steps.length) return defn;
  const steps = [...defn.steps];
  const [s] = steps.splice(index, 1);
  steps.splice(to, 0, s);
  return withSteps(defn, steps);
}

export function deleteStep(defn: WorkflowDefinition, index: number): WorkflowDefinition {
  if (index < 0 || index >= defn.steps.length) return defn;
  return withSteps(
    defn,
    defn.steps.filter((_, i) => i !== index),
  );
}

export function newStepId(defn: WorkflowDefinition, base = "step"): string {
  const taken = new Set(defn.steps.map((s) => s.id));
  for (let n = defn.steps.length + 1; ; n++) {
    const id = `${base}_${n}`;
    if (!taken.has(id)) return id;
  }
}

export function blankStep(defn: WorkflowDefinition, kind: StepKind, tool = ""): Step {
  const id = newStepId(defn);
  if (kind === "wait") return { id, wait: { seconds: 60 } };
  if (kind === "approval") return { id, approval: { summary: "Check before continuing" } };
  return { id, tool, args: {} };
}

/** Insert ``step`` after ``after`` (or at the end). */
export function addStep(defn: WorkflowDefinition, step: Step, after: number | null = null): WorkflowDefinition {
  const steps = [...defn.steps];
  const at = after === null ? steps.length : Math.min(after + 1, steps.length);
  steps.splice(at, 0, step);
  return withSteps(defn, steps);
}

/** Replace step ``index``; keys set to ``undefined`` in ``patch`` are removed. */
export function updateStep(

  defn: WorkflowDefinition,

  index: number,

  patch: Partial<Step>,

): WorkflowDefinition {
  if (index < 0 || index >= defn.steps.length) return defn;
  const merged: Record<string, unknown> = { ...defn.steps[index], ...patch };
  for (const k of Object.keys(merged)) if (merged[k] === undefined) delete merged[k];
  return withSteps(
    defn,
    defn.steps.map((s, i) => (i === index ? (merged as unknown as Step) : s)),
  );
}

// ---------------------------------------------------------------- errors

export interface IssueReport {
  message: string;
  errors: Issue[];
  warnings: Issue[];
}

/** The structured 422 ``detail`` of create/version calls, if the body has one. */
export function issuesFromBody(body: unknown): IssueReport | null {
  if (!body || typeof body !== "object" || !("detail" in body)) return null;
  const d = (body as { detail: unknown }).detail;
  if (!d || typeof d !== "object" || Array.isArray(d)) return null;
  const o = d as Record<string, unknown>;
  if (!Array.isArray(o.errors)) return null;
  return {
    message: typeof o.message === "string" ? o.message : "",
    errors: o.errors as Issue[],
    warnings: Array.isArray(o.warnings) ? (o.warnings as Issue[]) : [],
  };
}

/** Which lifecycle actions the selected version allows. */
export function versionActions(

  v: { status: string; dry_run_current: boolean },

  activeVersion: number | null,

) {
  return {
    approve: v.status === "dry_run_ok" && v.dry_run_current,
    activate: ["approved", "superseded", "rolled_back"].includes(v.status),
    rollback: activeVersion !== null,
  };
}

/** Classify a dry-run line by its marker: + would execute, ? needs approval, x denied. */
export function lineTone(line: string): "execute" | "approval" | "denied" | "plain" {
  const c = line.trimStart().charAt(0);
  if (c === "+") return "execute";
  if (c === "?") return "approval";
  if (c === "x") return "denied";
  return "plain";
}