ai-engineering-loop 1.7.0 → 1.9.0

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.
package/studio/app.js CHANGED
@@ -15,6 +15,8 @@ let draft;
15
15
  let source;
16
16
  let loadedRecipeId;
17
17
  let selectedId;
18
+ let selectedIds = new Set();
19
+ let selectedEdgeId;
18
20
  let liveTimer;
19
21
  let validationSequence = 0;
20
22
  let positions = new Map();
@@ -25,6 +27,94 @@ let interaction;
25
27
  let connection;
26
28
  let layoutTimer;
27
29
  let spacePressed = false;
30
+ let pendingConnectionSource;
31
+ let runs = [];
32
+ let goal = { text: '', version: 1, frozen: false };
33
+ let activeRunId;
34
+ let pendingImport;
35
+ let hydratedGoalKey;
36
+ let selectedCheckoutRun;
37
+
38
+ const DISPLAY_NAME_MAX = 80;
39
+ const ROOT_TYPES = new Set(['goal-contract', 'trigger']);
40
+
41
+ function displayName(item) {
42
+ return item?.displayName || item?.name || item?.id || 'Untitled';
43
+ }
44
+
45
+ function edgeId(from, to, index = 0) {
46
+ const suffix = index ? `-${index + 1}` : '';
47
+ const base = `edge-${from}-${to}`.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
48
+ return `${base.slice(0, 64 - suffix.length)}${suffix}`;
49
+ }
50
+
51
+ function uniqueEdgeId(from, to) {
52
+ let index = 0;
53
+ let candidate = edgeId(from, to, index);
54
+ const occupied = new Set((draft?.edges || []).map((edge) => edge.id));
55
+ while (occupied.has(candidate)) candidate = edgeId(from, to, ++index);
56
+ return candidate;
57
+ }
58
+
59
+ function normalizeDraftGraph(recipe) {
60
+ recipe.nodes = (recipe.nodes || []).map((node) => ({
61
+ ...node,
62
+ displayName: displayName(node)
63
+ }));
64
+ if (!Array.isArray(recipe.edges)) {
65
+ recipe.edges = [];
66
+ recipe.nodes.forEach((node) => {
67
+ (node.dependsOn || []).forEach((from, index) => {
68
+ recipe.edges.push({ id: edgeId(from, node.id, index), from, to: node.id });
69
+ });
70
+ });
71
+ }
72
+ const used = new Set();
73
+ recipe.edges = recipe.edges.map((edge, index) => {
74
+ let id = edge.id || edgeId(edge.from, edge.to, index);
75
+ while (used.has(id)) id = `${id}-${index + 1}`;
76
+ used.add(id);
77
+ return { ...edge, id };
78
+ });
79
+ recipe.loopGroups = Array.isArray(recipe.loopGroups) ? recipe.loopGroups : [];
80
+ syncDependencies(recipe);
81
+ return recipe;
82
+ }
83
+
84
+ function syncDependencies(recipe = draft) {
85
+ if (!recipe) return;
86
+ recipe.nodes.forEach((node) => {
87
+ node.dependsOn = recipe.edges
88
+ .filter((edge) => edge.to === node.id)
89
+ .map((edge) => edge.from);
90
+ });
91
+ }
92
+
93
+ function authoringRecipe(recipe = draft) {
94
+ const exported = structuredClone(recipe);
95
+ exported.nodes.forEach((node) => delete node.dependsOn);
96
+ return exported;
97
+ }
98
+
99
+ function validDisplayName(value) {
100
+ const name = String(value || '').trim();
101
+ if (!name) return 'Display Name is required.';
102
+ if (name.length > DISPLAY_NAME_MAX) return `Display Name must be ${DISPLAY_NAME_MAX} characters or fewer.`;
103
+ if (/[\u0000-\u001f\u007f]/.test(name)) return 'Display Name cannot contain control characters.';
104
+ return '';
105
+ }
106
+
107
+ function isInputTarget(target) {
108
+ return target instanceof Element && Boolean(target.closest('input,textarea,select,button,[contenteditable="true"],dialog'));
109
+ }
110
+
111
+ function csv(value) {
112
+ return String(value || '').split(',').map((item) => item.trim()).filter(Boolean);
113
+ }
114
+
115
+ function slug(value) {
116
+ return String(value || 'run').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 64) || 'run';
117
+ }
28
118
 
29
119
  async function api(url, options = {}) {
30
120
  const response = await fetch(url, {
@@ -112,6 +202,72 @@ function edgePath(from, to) {
112
202
  return `M${startX} ${startY} C${startX + bend} ${startY},${endX - bend} ${endY},${endX} ${endY}`;
113
203
  }
114
204
 
205
+ function loopBounds(loopGroup) {
206
+ const points = loopGroup.nodeIds.map((nodeId) => positions.get(nodeId)).filter(Boolean);
207
+ if (!points.length) return null;
208
+ const padding = 44;
209
+ const left = Math.min(...points.map((point) => point.x)) - padding;
210
+ const top = Math.min(...points.map((point) => point.y)) - padding;
211
+ const right = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + padding;
212
+ const bottom = Math.max(...points.map((point) => point.y + 108)) + padding;
213
+ return { left, top, right, bottom, width: right - left, height: bottom - top };
214
+ }
215
+
216
+ function renderLoopGroups() {
217
+ const container = byId('loop-groups');
218
+ container.innerHTML = '';
219
+ for (const loopGroup of draft?.loopGroups || []) {
220
+ const bounds = loopBounds(loopGroup);
221
+ if (!bounds) continue;
222
+ const runtime = catalog.live?.loopGroups?.[loopGroup.id];
223
+ const element = document.createElement('section');
224
+ element.className = `loop-group ${runtime?.status?.toLowerCase() || 'draft'}`;
225
+ element.style.left = `${bounds.left}px`;
226
+ element.style.top = `${bounds.top}px`;
227
+ element.style.width = `${bounds.width}px`;
228
+ element.style.height = `${bounds.height}px`;
229
+ element.innerHTML = `
230
+ <header>
231
+ <span><b>${escapeHtml(loopGroup.displayName)}</b><small>ITERATION ${escapeHtml(runtime?.iteration || 1)} / ${escapeHtml(loopGroup.maxIterations)}</small></span>
232
+ <button type="button" aria-label="Remove ${escapeHtml(loopGroup.displayName)} group">Ungroup</button>
233
+ </header>
234
+ `;
235
+ element.querySelector('button').onclick = (event) => {
236
+ event.stopPropagation();
237
+ draft.loopGroups = draft.loopGroups.filter((candidate) => candidate.id !== loopGroup.id);
238
+ captureHistory();
239
+ renderGraph();
240
+ validateDraft();
241
+ };
242
+ element.querySelector('header').onpointerdown = (event) => {
243
+ if (event.button !== 0 || event.target.closest('button')) return;
244
+ event.preventDefault();
245
+ event.stopPropagation();
246
+ const world = screenToWorld(event.clientX, event.clientY);
247
+ interaction = {
248
+ type: 'group',
249
+ pointerId: event.pointerId,
250
+ groupId: loopGroup.id,
251
+ start: world,
252
+ element: byId('canvas'),
253
+ origins: new Map(loopGroup.nodeIds.map((nodeId) => [nodeId, { ...positions.get(nodeId) }]))
254
+ };
255
+ selectedIds = new Set(loopGroup.nodeIds);
256
+ selectedId = loopGroup.decisionNodeId;
257
+ updateSelection();
258
+ byId('canvas').setPointerCapture(event.pointerId);
259
+ };
260
+ container.append(element);
261
+ }
262
+ }
263
+
264
+ function edgeLoopLabel(edge) {
265
+ const loopGroup = (draft.loopGroups || []).find((candidate) =>
266
+ candidate.decisionNodeId === edge.from && candidate.exitTargetId === edge.to
267
+ );
268
+ return loopGroup ? loopGroup.exitLabel : '';
269
+ }
270
+
115
271
  function stageLabel(node, index) {
116
272
  const stages = {
117
273
  'goal-contract': 'STAGE 01',
@@ -128,36 +284,103 @@ function stageLabel(node, index) {
128
284
 
129
285
  function renderEdges() {
130
286
  const group = byId('edge-paths');
287
+ const controls = byId('edge-controls');
131
288
  group.innerHTML = '';
289
+ controls.innerHTML = '';
132
290
  if (!draft) return;
133
- draft.nodes.forEach((node) => {
134
- for (const dependencyId of node.dependsOn || []) {
135
- const from = positions.get(dependencyId);
136
- const to = positions.get(node.id);
137
- if (!from || !to) continue;
138
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
139
- path.setAttribute('d', edgePath(from, to));
140
- path.setAttribute('class', catalog.live?.nodes?.[dependencyId]?.status === 'RUNNING' ? 'edge active' : 'edge');
141
- path.setAttribute('marker-end', 'url(#arrow)');
142
- group.append(path);
291
+ draft.edges.forEach((edge) => {
292
+ const from = positions.get(edge.from);
293
+ const to = positions.get(edge.to);
294
+ if (!from || !to) return;
295
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
296
+ path.setAttribute('d', edgePath(from, to));
297
+ path.setAttribute('class', `${catalog.live?.nodes?.[edge.from]?.status === 'RUNNING' ? 'edge active' : 'edge'}${selectedEdgeId === edge.id ? ' selected' : ''}`);
298
+ path.setAttribute('marker-end', 'url(#arrow)');
299
+ path.dataset.edgeId = edge.id;
300
+ group.append(path);
301
+
302
+ const midpoint = {
303
+ x: (from.x + NODE_WIDTH + to.x) / 2,
304
+ y: (from.y + to.y) / 2 + NODE_PORT_Y
305
+ };
306
+ const control = document.createElement('button');
307
+ control.className = `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
308
+ control.dataset.edgeId = edge.id;
309
+ control.style.left = `${midpoint.x}px`;
310
+ control.style.top = `${midpoint.y}px`;
311
+ control.title = `${displayName(draft.nodes.find((node) => node.id === edge.from))} → ${displayName(draft.nodes.find((node) => node.id === edge.to))}`;
312
+ control.setAttribute('aria-label', `Delete connection ${control.title}`);
313
+ control.textContent = '×';
314
+ control.onclick = (event) => {
315
+ event.stopPropagation();
316
+ deleteEdge(edge.id);
317
+ };
318
+ let hideTimer;
319
+ path.onpointerenter = () => {
320
+ clearTimeout(hideTimer);
321
+ control.classList.add('visible');
322
+ };
323
+ path.onpointerleave = () => {
324
+ hideTimer = setTimeout(() => control.classList.remove('visible'), 100);
325
+ };
326
+ control.onpointerenter = () => {
327
+ clearTimeout(hideTimer);
328
+ control.classList.add('visible');
329
+ };
330
+ control.onpointerleave = () => control.classList.remove('visible');
331
+ controls.append(control);
332
+ const label = edgeLoopLabel(edge);
333
+ if (label) {
334
+ const badge = document.createElement('span');
335
+ badge.className = 'edge-label';
336
+ badge.style.left = `${midpoint.x}px`;
337
+ badge.style.top = `${midpoint.y - 22}px`;
338
+ badge.textContent = label;
339
+ controls.append(badge);
143
340
  }
144
341
  });
342
+ for (const loopGroup of draft.loopGroups || []) {
343
+ const from = positions.get(loopGroup.decisionNodeId);
344
+ const to = positions.get(loopGroup.repeatTargetId);
345
+ const bounds = loopBounds(loopGroup);
346
+ if (!from || !to || !bounds) continue;
347
+ const returnPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
348
+ returnPath.setAttribute(
349
+ 'd',
350
+ `M${from.x + NODE_WIDTH} ${from.y + NODE_PORT_Y} H${bounds.right + 28} V${bounds.top - 18} H${to.x - 28} V${to.y + NODE_PORT_Y} H${to.x}`
351
+ );
352
+ returnPath.setAttribute('class', 'edge loop-return');
353
+ returnPath.setAttribute('marker-end', 'url(#arrow)');
354
+ group.append(returnPath);
355
+ const label = document.createElement('span');
356
+ label.className = 'edge-label loop-label';
357
+ label.style.left = `${bounds.right + 28}px`;
358
+ label.style.top = `${bounds.top - 18}px`;
359
+ label.textContent = loopGroup.repeatLabel;
360
+ controls.append(label);
361
+ }
145
362
  }
146
363
 
147
364
  function nodeMarkup(node, index) {
148
365
  const runtimeNode = catalog.live?.nodes?.[node.id];
366
+ const outgoing = draft.edges.some((edge) => edge.from === node.id);
367
+ const root = rootCandidates().length === 1 && rootCandidates()[0].id === node.id;
149
368
  return `
150
369
  <button class="port port-in" aria-label="Input for ${escapeHtml(node.id)}" tabindex="-1"></button>
151
370
  <small>${escapeHtml(stageLabel(node, index))} / ${escapeHtml(node.type.toUpperCase())}</small>
152
- <h3>${escapeHtml(node.id)}</h3>
371
+ <button class="node-title" title="Double-click to edit Display Name">${escapeHtml(displayName(node))}</button>
372
+ <span class="technical-id">${escapeHtml(node.id)}</span>
153
373
  <span class="status">● ${escapeHtml(runtimeNode?.status || 'DRAFT')}</span>
154
374
  ${runtimeNode?.activity ? `<p class="node-activity">${escapeHtml(runtimeNode.activity)}</p>` : ''}
155
375
  <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
376
+ ${outgoing ? '' : `<button class="output-add" title="Add connected node" aria-label="Add node connected after ${escapeHtml(displayName(node))}">+</button>`}
377
+ ${root ? `<div class="execute-pod"><input class="task-input" aria-label="Task for this run" placeholder="Describe this run’s task" value="${escapeHtml(catalog.live?.run?.task || '')}"><button class="execute-trigger">${goal.frozen ? 'Execute' : 'Set Goal'}</button><span class="execute-hint">${goal.frozen ? 'Local runtime only' : 'Freeze Goal first'}</span></div>` : ''}
156
378
  `;
157
379
  }
158
380
 
159
381
  function renderGraph() {
160
382
  ensurePositions();
383
+ renderLoopGroups();
161
384
  const container = byId('nodes');
162
385
  container.innerHTML = '';
163
386
  draft.nodes.forEach((node, index) => {
@@ -165,12 +388,15 @@ function renderGraph() {
165
388
  const runtimeNode = catalog.live?.nodes?.[node.id];
166
389
  const element = document.createElement('article');
167
390
  element.dataset.nodeId = node.id;
168
- element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${selectedId === node.id ? 'selected' : ''}`;
391
+ element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${selectedIds.has(node.id) ? 'selected' : ''}`;
169
392
  element.style.left = `${position.x}px`;
170
393
  element.style.top = `${position.y}px`;
171
394
  element.innerHTML = nodeMarkup(node, index);
172
395
  element.addEventListener('pointerdown', beginNodeInteraction);
173
396
  element.querySelector('.port-out').addEventListener('pointerdown', beginConnection);
397
+ element.querySelector('.node-title').addEventListener('dblclick', beginInlineRename);
398
+ element.querySelector('.output-add')?.addEventListener('click', openContextualAdd);
399
+ element.querySelector('.execute-trigger')?.addEventListener('click', executeFromTrigger);
174
400
  container.append(element);
175
401
  });
176
402
  renderEdges();
@@ -198,14 +424,25 @@ function updateRuntimePresentation() {
198
424
 
199
425
  function updateSelection() {
200
426
  document.querySelectorAll('.node').forEach((element) => {
201
- element.classList.toggle('selected', element.dataset.nodeId === selectedId);
427
+ element.classList.toggle('selected', selectedIds.has(element.dataset.nodeId));
202
428
  });
429
+ const actions = byId('selection-actions');
430
+ actions.hidden = selectedIds.size < 2;
431
+ byId('selection-count').textContent = `${selectedIds.size} nodes`;
432
+ const grouped = [...selectedIds].some((nodeId) =>
433
+ (draft?.loopGroups || []).some((group) => group.nodeIds.includes(nodeId))
434
+ );
435
+ byId('create-loop-group').disabled = grouped;
436
+ byId('create-loop-group').title = grouped ? 'Ungroup selected steps before creating another Loop Group' : '';
203
437
  }
204
438
 
205
439
  function renderRecipeDetails() {
206
440
  const existing = recipeSummary();
207
441
  byId('inspector-label').textContent = 'WORKFLOW';
208
442
  byId('inspector-title').textContent = draft.id;
443
+ byId('inspector-title').contentEditable = 'false';
444
+ byId('inspector-title').onkeydown = null;
445
+ byId('inspector-title').onblur = null;
209
446
  byId('details').innerHTML = `
210
447
  <div class="source-line"><span>${escapeHtml(source.toUpperCase())}</span><span>${draft.nodes.length} NODES</span></div>
211
448
  <label for="recipe-id">Name</label><input id="recipe-id" value="${escapeHtml(draft.id)}">
@@ -226,18 +463,38 @@ function renderRecipeDetails() {
226
463
  byId('apply-recipe').onclick = applyRecipeDetails;
227
464
  }
228
465
 
229
- function selectNode(nodeId) {
466
+ function selectNode(nodeId, { additive = false } = {}) {
230
467
  const node = draft.nodes.find((candidate) => candidate.id === nodeId);
231
468
  if (!node) return;
469
+ if (additive) {
470
+ if (selectedIds.has(nodeId)) selectedIds.delete(nodeId);
471
+ else selectedIds.add(nodeId);
472
+ } else {
473
+ selectedIds = new Set([nodeId]);
474
+ }
475
+ selectedEdgeId = null;
232
476
  selectedId = nodeId;
233
477
  updateSelection();
234
478
  const runtimeNode = catalog.live?.nodes?.[nodeId];
235
479
  byId('inspector-label').textContent = 'NODE';
236
- byId('inspector-title').textContent = node.id;
480
+ byId('inspector-title').textContent = displayName(node);
481
+ byId('inspector-title').contentEditable = 'true';
482
+ byId('inspector-title').title = 'Edit Display Name';
483
+ byId('inspector-title').onkeydown = (event) => {
484
+ if (event.key === 'Enter') {
485
+ event.preventDefault();
486
+ event.currentTarget.blur();
487
+ } else if (event.key === 'Escape') {
488
+ event.currentTarget.textContent = displayName(node);
489
+ event.currentTarget.blur();
490
+ }
491
+ };
492
+ byId('inspector-title').onblur = (event) => applyDisplayName(node, event.currentTarget.textContent);
237
493
  byId('inspector-panel').classList.add('open');
238
494
  byId('details').innerHTML = `
239
495
  <div class="source-line"><span>${escapeHtml(node.type.toUpperCase())}</span><span>${escapeHtml(runtimeNode?.status || 'DRAFT')}</span></div>
240
- <label for="node-id">Name</label><input id="node-id" value="${escapeHtml(node.id)}">
496
+ <div id="name-validation" class="validation-message" aria-live="polite"></div>
497
+ <label for="node-id">Technical ID</label><input id="node-id" value="${escapeHtml(node.id)}" disabled>
241
498
  ${node.type === 'delivery' ? deliveryAdapterControls() : ''}
242
499
  <details>
243
500
  <summary>Settings</summary>
@@ -247,6 +504,7 @@ function selectNode(nodeId) {
247
504
  <input id="node-dependencies" value="${escapeHtml((node.dependsOn || []).join(', '))}" placeholder="Connect nodes on the canvas">
248
505
  ${node.type === 'agent' ? `
249
506
  <label for="node-extra">Role</label><input id="node-extra" value="${escapeHtml(node.role || '')}">
507
+ ${node.prompt != null ? customAgentFields(node) : ''}
250
508
  <label for="node-tokens">Token limit</label><input id="node-tokens" type="number" min="1" value="${escapeHtml(node.context?.maxTokens || '')}">
251
509
  ` : node.type === 'approval' ? `
252
510
  <label for="node-extra">Approval message</label><textarea id="node-extra">${escapeHtml(node.message || '')}</textarea>
@@ -270,6 +528,70 @@ function selectNode(nodeId) {
270
528
  bindRuntimeControls(node);
271
529
  }
272
530
 
531
+ function customAgentFields(node) {
532
+ return `
533
+ <label for="custom-node-prompt">Prompt</label><textarea id="custom-node-prompt">${escapeHtml(node.prompt || '')}</textarea>
534
+ <label for="custom-node-capabilities">Capabilities</label><input id="custom-node-capabilities" value="${escapeHtml((node.capabilityRefs || []).join(', '))}">
535
+ <label for="custom-node-mcp">MCP references</label><input id="custom-node-mcp" value="${escapeHtml((node.mcpRefs || []).join(', '))}">
536
+ <label for="custom-node-inputs">Input artifacts</label><input id="custom-node-inputs" value="${escapeHtml((node.inputArtifacts || []).join(', '))}">
537
+ <label for="custom-node-output">Output artifact</label><input id="custom-node-output" value="${escapeHtml(node.outputArtifacts?.[0]?.artifact || '')}">
538
+ <label for="custom-node-schema">Output schema</label><input id="custom-node-schema" value="${escapeHtml(node.outputArtifacts?.[0]?.schema || 'schemas/report.schema.json')}">
539
+ <label for="custom-node-timeout">Timeout (sec)</label><input id="custom-node-timeout" type="number" min="1" value="${escapeHtml(Math.round((node.timeoutMs || 900000) / 1000))}">
540
+ <label for="custom-node-retries">Maximum attempts</label><input id="custom-node-retries" type="number" min="1" value="${escapeHtml(node.retry?.maxAttempts ?? 2)}">
541
+ `;
542
+ }
543
+
544
+ function applyDisplayName(node, value) {
545
+ const error = validDisplayName(value);
546
+ const message = byId('name-validation');
547
+ if (error) {
548
+ if (message) message.textContent = error;
549
+ byId('inspector-title').textContent = displayName(node);
550
+ return false;
551
+ }
552
+ const next = value.trim();
553
+ if (next === displayName(node)) return true;
554
+ node.displayName = next;
555
+ captureHistory();
556
+ renderGraph();
557
+ selectNode(node.id);
558
+ return true;
559
+ }
560
+
561
+ function beginInlineRename(event) {
562
+ event.preventDefault();
563
+ event.stopPropagation();
564
+ const node = draft.nodes.find((candidate) => candidate.id === event.currentTarget.closest('.node').dataset.nodeId);
565
+ const input = document.createElement('input');
566
+ input.className = 'inline-rename';
567
+ input.maxLength = DISPLAY_NAME_MAX;
568
+ input.value = displayName(node);
569
+ event.currentTarget.replaceWith(input);
570
+ input.focus();
571
+ input.select();
572
+ let saved = false;
573
+ const finish = () => {
574
+ if (saved) return;
575
+ saved = true;
576
+ const error = validDisplayName(input.value);
577
+ if (error) notify(error);
578
+ else if (input.value.trim() !== displayName(node)) {
579
+ node.displayName = input.value.trim();
580
+ captureHistory();
581
+ }
582
+ renderGraph();
583
+ selectNode(node.id);
584
+ };
585
+ input.onkeydown = (keyEvent) => {
586
+ if (keyEvent.key === 'Enter') input.blur();
587
+ if (keyEvent.key === 'Escape') {
588
+ input.value = displayName(node);
589
+ input.blur();
590
+ }
591
+ };
592
+ input.onblur = finish;
593
+ }
594
+
273
595
  function deliveryAdapterControls() {
274
596
  const current = catalog.adapters.current;
275
597
  const options = [...catalog.adapters.types];
@@ -322,11 +644,18 @@ function runtimeControls(node, runtimeNode) {
322
644
  if (!catalog.live || !runtimeNode) return '';
323
645
  const approve = node.type === 'approval' && runtimeNode.status === 'READY' ? '<button id="approve-node">APPROVE</button>' : '';
324
646
  const retry = ['FAILED', 'RUNNING'].includes(runtimeNode.status) ? '<button id="retry-node">RETRY</button>' : '';
647
+ const custom = node.type === 'agent' && node.prompt && ['READY', 'RUNNING'].includes(runtimeNode.status) ? `
648
+ <p class="hint">This node is waiting for an external operator. Studio does not execute the agent independently.</p>
649
+ <button id="copy-agent-command">Copy command</button>
650
+ ${runtimeNode.status === 'READY'
651
+ ? '<button id="start-agent-node">Mark running</button>'
652
+ : '<label for="agent-evidence">Run-bound evidence JSON path</label><input id="agent-evidence" placeholder=".ai-engineering-loop/runs/…/agent-report.json"><button id="complete-agent-node">Complete with evidence</button>'}
653
+ ` : '';
325
654
  const activity = runtimeNode.status === 'RUNNING'
326
655
  ? '<label for="runtime-activity">SAFE ACTIVITY UPDATE</label><input id="runtime-activity" maxlength="240"><button id="send-activity">REPORT ACTIVITY</button>'
327
656
  : '';
328
- return approve || retry || activity
329
- ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${activity}<div class="button-row">${approve}${retry}</div></section>`
657
+ return approve || retry || activity || custom
658
+ ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${custom}${activity}<div class="button-row">${approve}${retry}</div></section>`
330
659
  : '';
331
660
  }
332
661
 
@@ -339,6 +668,16 @@ function bindRuntimeControls(node) {
339
668
  runId, nodeId: node.id, message: byId('runtime-activity').value
340
669
  });
341
670
  }
671
+ if (byId('copy-agent-command')) byId('copy-agent-command').onclick = async () => {
672
+ await navigator.clipboard.writeText(`ai-engineering-loop node start ${node.id} --run ${runId}`);
673
+ notify('External operator command copied.');
674
+ };
675
+ if (byId('start-agent-node')) byId('start-agent-node').onclick = () => mutateNode('/api/node/start', { runId, nodeId: node.id });
676
+ if (byId('complete-agent-node')) byId('complete-agent-node').onclick = () => mutateNode('/api/node/complete', {
677
+ runId,
678
+ nodeId: node.id,
679
+ artifact: byId('agent-evidence').value.trim()
680
+ });
342
681
  }
343
682
 
344
683
  async function mutateNode(endpoint, body) {
@@ -365,15 +704,34 @@ function applyRecipeDetails() {
365
704
  function applyNodeDetails() {
366
705
  const node = draft.nodes.find((candidate) => candidate.id === selectedId);
367
706
  if (!node) return;
368
- const previousId = node.id;
369
- node.id = byId('node-id').value.trim();
370
- node.dependsOn = byId('node-dependencies').value.split(',').map((value) => value.trim()).filter(Boolean);
371
- draft.nodes.forEach((candidate) => {
372
- candidate.dependsOn = (candidate.dependsOn || []).map((dependency) => dependency === previousId ? node.id : dependency);
707
+ if (!applyDisplayName(node, byId('inspector-title').textContent)) return;
708
+ const inputs = csv(byId('node-dependencies').value);
709
+ draft.edges = draft.edges.filter((edge) => edge.to !== node.id);
710
+ inputs.forEach((from, index) => {
711
+ if (from !== node.id && draft.nodes.some((candidate) => candidate.id === from)) {
712
+ draft.edges.push({ id: uniqueEdgeId(from, node.id), from, to: node.id });
713
+ }
373
714
  });
715
+ syncDependencies();
374
716
  if (node.type === 'agent') {
375
717
  node.role = byId('node-extra').value.trim();
376
718
  node.context = { ...(node.context || {}), maxTokens: Number(byId('node-tokens').value) };
719
+ if (node.prompt != null) {
720
+ node.prompt = byId('custom-node-prompt').value.trim();
721
+ node.capabilityRefs = csv(byId('custom-node-capabilities').value);
722
+ node.mcpRefs = csv(byId('custom-node-mcp').value);
723
+ node.inputArtifacts = csv(byId('custom-node-inputs').value);
724
+ node.outputArtifacts = [{
725
+ artifact: byId('custom-node-output').value.trim(),
726
+ schema: byId('custom-node-schema').value.trim()
727
+ }];
728
+ node.tokenLimit = Number(byId('node-tokens').value);
729
+ node.timeoutMs = Number(byId('custom-node-timeout').value) * 1000;
730
+ node.retry = {
731
+ maxAttempts: Number(byId('custom-node-retries').value),
732
+ backoffMs: node.retry?.backoffMs || 1000
733
+ };
734
+ }
377
735
  } else if (node.type === 'approval') {
378
736
  node.message = byId('node-extra').value.trim();
379
737
  } else if (node.type === 'condition') {
@@ -385,11 +743,6 @@ function applyNodeDetails() {
385
743
  node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator) ? Number(rawValue) : rawValue;
386
744
  }
387
745
  }
388
- if (previousId !== node.id && positions.has(previousId)) {
389
- positions.set(node.id, positions.get(previousId));
390
- positions.delete(previousId);
391
- }
392
- selectedId = node.id;
393
746
  captureHistory();
394
747
  renderGraph();
395
748
  selectNode(node.id);
@@ -398,14 +751,21 @@ function applyNodeDetails() {
398
751
  }
399
752
 
400
753
  function deleteSelectedNode() {
401
- if (!selectedId) return;
402
- const removedId = selectedId;
403
- draft.nodes = draft.nodes.filter((node) => node.id !== removedId);
404
- draft.nodes.forEach((node) => {
405
- node.dependsOn = (node.dependsOn || []).filter((dependency) => dependency !== removedId);
406
- });
407
- positions.delete(removedId);
754
+ if (!selectedIds.size) return;
755
+ const removed = new Set(selectedIds);
756
+ const containingGroup = (draft.loopGroups || []).find((group) =>
757
+ group.nodeIds.some((nodeId) => removed.has(nodeId))
758
+ );
759
+ if (containingGroup) {
760
+ notify(`Ungroup “${containingGroup.displayName}” before deleting its steps.`);
761
+ return;
762
+ }
763
+ draft.nodes = draft.nodes.filter((node) => !removed.has(node.id));
764
+ draft.edges = draft.edges.filter((edge) => !removed.has(edge.from) && !removed.has(edge.to));
765
+ syncDependencies();
766
+ removed.forEach((id) => positions.delete(id));
408
767
  selectedId = null;
768
+ selectedIds.clear();
409
769
  captureHistory();
410
770
  renderGraph();
411
771
  renderRecipeDetails();
@@ -414,6 +774,17 @@ function deleteSelectedNode() {
414
774
  saveLayoutSoon();
415
775
  }
416
776
 
777
+ function deleteEdge(id) {
778
+ const before = draft.edges.length;
779
+ draft.edges = draft.edges.filter((edge) => edge.id !== id);
780
+ if (draft.edges.length === before) return;
781
+ syncDependencies();
782
+ selectedEdgeId = null;
783
+ captureHistory();
784
+ renderGraph();
785
+ validateDraft();
786
+ }
787
+
417
788
  function uniqueNodeId(type) {
418
789
  let suffix = draft.nodes.length + 1;
419
790
  while (draft.nodes.some((node) => node.id === `${type}-${suffix}`)) suffix += 1;
@@ -421,7 +792,8 @@ function uniqueNodeId(type) {
421
792
  }
422
793
 
423
794
  function createNode(type, id = uniqueNodeId(type)) {
424
- const node = { id, type, dependsOn: [] };
795
+ const label = catalog.nodeTypes.find((candidate) => candidate.type === type)?.label || type.replaceAll('-', ' ');
796
+ const node = { id, type, displayName: label, dependsOn: [] };
425
797
  if (type === 'agent') {
426
798
  Object.assign(node, {
427
799
  role: 'analyst',
@@ -439,6 +811,11 @@ function createNode(type, id = uniqueNodeId(type)) {
439
811
  function addNode(type, position = worldAtCanvasCenter()) {
440
812
  const node = createNode(type);
441
813
  draft.nodes.push(node);
814
+ if (pendingConnectionSource) {
815
+ draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, node.id), from: pendingConnectionSource, to: node.id });
816
+ syncDependencies();
817
+ pendingConnectionSource = null;
818
+ }
442
819
  positions.set(node.id, { x: position.x - NODE_WIDTH / 2, y: position.y - NODE_PORT_Y });
443
820
  captureHistory();
444
821
  renderGraph();
@@ -448,20 +825,44 @@ function addNode(type, position = worldAtCanvasCenter()) {
448
825
  }
449
826
 
450
827
  function duplicateSelectedNode() {
451
- const original = draft.nodes.find((node) => node.id === selectedId);
452
- if (!original) return;
453
- const clone = structuredClone(original);
454
- clone.id = uniqueNodeId(original.type);
455
- if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
456
- draft.nodes.push(clone);
457
- const originalPosition = positions.get(original.id);
458
- positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
828
+ if (!selectedIds.size) return;
829
+ const originals = draft.nodes.filter((node) => selectedIds.has(node.id));
830
+ const mapping = new Map();
831
+ const clones = originals.map((original) => {
832
+ const clone = structuredClone(original);
833
+ clone.id = uniqueNodeId(original.type);
834
+ while (draft.nodes.some((node) => node.id === clone.id) || mapping.has(clone.id)) clone.id = `${clone.id}-copy`;
835
+ clone.displayName = `${displayName(original)} copy`;
836
+ if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
837
+ mapping.set(original.id, clone.id);
838
+ const originalPosition = positions.get(original.id);
839
+ positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
840
+ draft.nodes.push(clone);
841
+ return clone;
842
+ });
843
+ const copiedEdges = draft.edges.filter((edge) => mapping.has(edge.from) && mapping.has(edge.to)).map((edge) => ({
844
+ id: uniqueEdgeId(mapping.get(edge.from), mapping.get(edge.to)),
845
+ from: mapping.get(edge.from),
846
+ to: mapping.get(edge.to)
847
+ }));
848
+ draft.edges.push(...copiedEdges);
849
+ syncDependencies();
850
+ const cloneIds = new Set(clones.map((node) => node.id));
851
+ selectedId = clones.at(-1)?.id;
459
852
  captureHistory();
460
853
  renderGraph();
461
- selectNode(clone.id);
854
+ if (selectedId) selectNode(selectedId);
855
+ selectedIds = cloneIds;
856
+ updateSelection();
462
857
  validateDraft();
463
858
  }
464
859
 
860
+ function openContextualAdd(event) {
861
+ event.stopPropagation();
862
+ pendingConnectionSource = event.currentTarget.closest('.node').dataset.nodeId;
863
+ byId('library-panel').classList.add('open');
864
+ }
865
+
465
866
  function renderPalette() {
466
867
  byId('palette').innerHTML = catalog.nodeTypes.filter((node) => node.executable).map((node) => `
467
868
  <button class="palette-item" draggable="true" data-node-type="${escapeHtml(node.type)}">
@@ -478,15 +879,27 @@ function renderPalette() {
478
879
  }
479
880
 
480
881
  function beginNodeInteraction(event) {
481
- if (event.button !== 0 || event.target.closest('.port')) return;
882
+ if (event.button !== 0 || event.target.closest('.port,.output-add,.execute-pod,.node-title,.inline-rename')) return;
482
883
  event.stopPropagation();
483
884
  const element = event.currentTarget;
484
885
  const nodeId = element.dataset.nodeId;
485
- selectNode(nodeId);
886
+ if (event.shiftKey) {
887
+ selectNode(nodeId, { additive: true });
888
+ return;
889
+ }
890
+ if (!selectedIds.has(nodeId)) selectNode(nodeId);
486
891
  if (spacePressed) return beginPan(event);
487
892
  const world = screenToWorld(event.clientX, event.clientY);
488
893
  const position = positions.get(nodeId);
489
- interaction = { type: 'node', pointerId: event.pointerId, nodeId, element, offsetX: world.x - position.x, offsetY: world.y - position.y };
894
+ interaction = {
895
+ type: 'node',
896
+ pointerId: event.pointerId,
897
+ nodeId,
898
+ element,
899
+ offsetX: world.x - position.x,
900
+ offsetY: world.y - position.y,
901
+ origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }]))
902
+ };
490
903
  element.classList.add('dragging');
491
904
  element.setPointerCapture(event.pointerId);
492
905
  }
@@ -518,10 +931,27 @@ function handlePointerMove(event) {
518
931
  if (interaction.type === 'node') {
519
932
  const world = screenToWorld(event.clientX, event.clientY);
520
933
  const position = { x: world.x - interaction.offsetX, y: world.y - interaction.offsetY };
521
- positions.set(interaction.nodeId, position);
522
- interaction.element.style.left = `${position.x}px`;
523
- interaction.element.style.top = `${position.y}px`;
934
+ const origin = interaction.origins.get(interaction.nodeId);
935
+ const delta = { x: position.x - origin.x, y: position.y - origin.y };
936
+ interaction.origins.forEach((start, id) => {
937
+ const next = { x: start.x + delta.x, y: start.y + delta.y };
938
+ positions.set(id, next);
939
+ const nodeElement = document.querySelector(`.node[data-node-id="${CSS.escape(id)}"]`);
940
+ if (nodeElement) {
941
+ nodeElement.style.left = `${next.x}px`;
942
+ nodeElement.style.top = `${next.y}px`;
943
+ }
944
+ });
524
945
  renderEdges();
946
+ } else if (interaction.type === 'group') {
947
+ const world = screenToWorld(event.clientX, event.clientY);
948
+ const delta = { x: world.x - interaction.start.x, y: world.y - interaction.start.y };
949
+ interaction.origins.forEach((start, id) => {
950
+ positions.set(id, { x: start.x + delta.x, y: start.y + delta.y });
951
+ });
952
+ renderGraph();
953
+ } else if (interaction.type === 'lasso') {
954
+ updateLasso(event);
525
955
  } else {
526
956
  viewport.x = interaction.viewportX + event.clientX - interaction.startX;
527
957
  viewport.y = interaction.viewportY + event.clientY - interaction.startY;
@@ -532,10 +962,10 @@ function handlePointerMove(event) {
532
962
  function finishPointer(event) {
533
963
  if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
534
964
  if (!interaction || interaction.pointerId !== event.pointerId) return;
535
- if (interaction.type === 'node') {
965
+ if (interaction.type === 'node' || interaction.type === 'group') {
536
966
  interaction.element.classList.remove('dragging');
537
967
  captureHistory();
538
- }
968
+ } else if (interaction.type === 'lasso') finishLasso();
539
969
  interaction = null;
540
970
  saveLayoutSoon();
541
971
  }
@@ -565,15 +995,588 @@ function finishConnection(event) {
565
995
  const targetId = targetElement?.dataset.nodeId;
566
996
  if (!targetId || targetId === sourceId) return;
567
997
  const target = draft.nodes.find((node) => node.id === targetId);
568
- if ((target.dependsOn || []).includes(sourceId)) return notify('Nodes are already connected.');
998
+ if (draft.edges.some((edge) => edge.from === sourceId && edge.to === targetId)) return notify('Nodes are already connected.');
569
999
  if (transitivelyDependsOn(sourceId, targetId)) return notify('Connection rejected: it would create a cycle.');
570
- target.dependsOn = [...(target.dependsOn || []), sourceId];
1000
+ draft.edges.push({ id: uniqueEdgeId(sourceId, targetId), from: sourceId, to: targetId });
1001
+ syncDependencies();
571
1002
  captureHistory();
572
1003
  renderGraph();
573
1004
  selectNode(targetId);
574
1005
  validateDraft();
575
1006
  }
576
1007
 
1008
+ function beginLasso(event) {
1009
+ const start = screenToWorld(event.clientX, event.clientY);
1010
+ interaction = { type: 'lasso', pointerId: event.pointerId, start, current: start, additive: event.shiftKey };
1011
+ const marquee = byId('selection-marquee');
1012
+ marquee.style.display = 'block';
1013
+ marquee.style.left = `${start.x}px`;
1014
+ marquee.style.top = `${start.y}px`;
1015
+ marquee.style.width = '0';
1016
+ marquee.style.height = '0';
1017
+ byId('canvas').setPointerCapture(event.pointerId);
1018
+ }
1019
+
1020
+ function updateLasso(event) {
1021
+ interaction.current = screenToWorld(event.clientX, event.clientY);
1022
+ const left = Math.min(interaction.start.x, interaction.current.x);
1023
+ const top = Math.min(interaction.start.y, interaction.current.y);
1024
+ const right = Math.max(interaction.start.x, interaction.current.x);
1025
+ const bottom = Math.max(interaction.start.y, interaction.current.y);
1026
+ const marquee = byId('selection-marquee');
1027
+ Object.assign(marquee.style, {
1028
+ left: `${left}px`, top: `${top}px`, width: `${right - left}px`, height: `${bottom - top}px`
1029
+ });
1030
+ const next = interaction.additive ? new Set(selectedIds) : new Set();
1031
+ positions.forEach((position, id) => {
1032
+ if (position.x < right && position.x + NODE_WIDTH > left && position.y < bottom && position.y + 110 > top) next.add(id);
1033
+ });
1034
+ selectedIds = next;
1035
+ selectedId = [...next].at(-1) || null;
1036
+ updateSelection();
1037
+ }
1038
+
1039
+ function finishLasso() {
1040
+ byId('selection-marquee').style.display = 'none';
1041
+ const finalSelection = new Set(selectedIds);
1042
+ if (selectedId) selectNode(selectedId);
1043
+ selectedIds = finalSelection;
1044
+ updateSelection();
1045
+ }
1046
+
1047
+ function rootCandidates() {
1048
+ if (!draft) return [];
1049
+ const incoming = new Set(draft.edges.map((edge) => edge.to));
1050
+ return draft.nodes.filter((node) => ROOT_TYPES.has(node.type) || !incoming.has(node.id));
1051
+ }
1052
+
1053
+ async function executeFromTrigger(event) {
1054
+ event.stopPropagation();
1055
+ const candidates = rootCandidates();
1056
+ if (candidates.length !== 1) return notify(`Execute requires exactly one trigger/root; found ${candidates.length}.`);
1057
+ const task = event.currentTarget.closest('.execute-pod').querySelector('.task-input').value.trim();
1058
+ if (task) byId('goal-task').value = task;
1059
+ if (!goal.frozen || !activeRunId) {
1060
+ byId('goal-dialog').showModal();
1061
+ return notify('Save and freeze the Goal Contract before execution.');
1062
+ }
1063
+ try {
1064
+ await api(`/api/runs/${encodeURIComponent(activeRunId)}/execute`, {
1065
+ method: 'POST',
1066
+ body: '{}'
1067
+ });
1068
+ notify('Local runtime started. External AI dispatch remains disabled.');
1069
+ await refreshLive();
1070
+ } catch (error) {
1071
+ notify(error.message);
1072
+ }
1073
+ }
1074
+
1075
+ function parseGoalCriteria(value) {
1076
+ return String(value || '').split('\n').map((line) => line.trim()).filter(Boolean).map((line, index) => {
1077
+ const [statement, evidenceRequired, ...failures] = line.split('|').map((part) => part.trim());
1078
+ return {
1079
+ id: `AC-${index + 1}`,
1080
+ statement,
1081
+ evidenceRequired,
1082
+ failureCases: failures.filter(Boolean)
1083
+ };
1084
+ });
1085
+ }
1086
+
1087
+ function goalContractFromForm(runId) {
1088
+ return {
1089
+ schemaVersion: 1,
1090
+ runId,
1091
+ objective: byId('goal-text').value.trim(),
1092
+ acceptanceCriteria: parseGoalCriteria(byId('goal-criteria').value)
1093
+ };
1094
+ }
1095
+
1096
+ function validateGoalForm(contract) {
1097
+ if (!byId('goal-task').value.trim()) return 'Task is required.';
1098
+ if (!contract.objective) return 'Goal objective is required.';
1099
+ if (!contract.acceptanceCriteria.length) return 'Add at least one acceptance failure-table row.';
1100
+ for (const criterion of contract.acceptanceCriteria) {
1101
+ if (!criterion.statement || !criterion.evidenceRequired || !criterion.failureCases.length) {
1102
+ return `${criterion.id} must contain statement | evidence required | failure case.`;
1103
+ }
1104
+ }
1105
+ return '';
1106
+ }
1107
+
1108
+ async function ensureStudioRun() {
1109
+ if (activeRunId && catalog.live?.run && !['DELIVERED', 'REPORTED', 'ESCALATED'].includes(catalog.live.run.state)) {
1110
+ return activeRunId;
1111
+ }
1112
+ const task = byId('goal-task').value.trim();
1113
+ const created = await api('/api/runs', {
1114
+ method: 'POST',
1115
+ body: JSON.stringify({
1116
+ task,
1117
+ constraints: byId('goal-constraints').value.trim(),
1118
+ displayName: byId('goal-run-name').value.trim(),
1119
+ recipeId: loadedRecipeId,
1120
+ mode: draft.compatibleModes.includes('ASSISTED') ? 'ASSISTED' : draft.compatibleModes[0]
1121
+ })
1122
+ });
1123
+ activeRunId = created.run.runId;
1124
+ await refreshLive();
1125
+ return activeRunId;
1126
+ }
1127
+
1128
+ async function saveGoalFromForm() {
1129
+ try {
1130
+ const task = byId('goal-task').value.trim();
1131
+ if (!byId('goal-text').value.trim()) byId('goal-text').value = task;
1132
+ if (!byId('goal-criteria').value.trim()) {
1133
+ byId('goal-criteria').value = [
1134
+ 'Requested outcome works in its real workflow | Tests and Run-bound evidence demonstrate the result | The requested outcome is unavailable or misleading',
1135
+ 'Existing behavior remains reliable | Compatibility checks pass | A supported existing workflow regresses'
1136
+ ].join('\n');
1137
+ }
1138
+ const provisional = goalContractFromForm(activeRunId || 'pending');
1139
+ const error = validateGoalForm(provisional);
1140
+ if (error) {
1141
+ byId('goal-validation').textContent = error;
1142
+ return null;
1143
+ }
1144
+ const runId = await ensureStudioRun();
1145
+ const contract = goalContractFromForm(runId);
1146
+ await api(`/api/runs/${encodeURIComponent(runId)}/goal`, {
1147
+ method: 'PUT',
1148
+ body: JSON.stringify({ goal: contract })
1149
+ });
1150
+ goal = { text: contract.objective, criteria: contract.acceptanceCriteria, version: goal.version, frozen: false };
1151
+ byId('goal-validation').textContent = '';
1152
+ notify('Goal draft saved. It is not frozen yet.');
1153
+ byId('goal-dialog').close();
1154
+ return contract;
1155
+ } catch (error) {
1156
+ byId('goal-validation').textContent = error.message;
1157
+ return null;
1158
+ }
1159
+ }
1160
+
1161
+ function renderGoalState() {
1162
+ const state = byId('goal-state');
1163
+ state.className = `goal-state ${goal.frozen ? 'frozen' : 'draft'}`;
1164
+ state.textContent = goal.frozen
1165
+ ? `Frozen · version ${goal.version} · editing locked`
1166
+ : `Draft · version ${goal.version} · editing allowed`;
1167
+ byId('goal-version').textContent = `V${goal.version}`;
1168
+ byId('goal-text').disabled = goal.frozen;
1169
+ byId('goal-criteria').disabled = goal.frozen;
1170
+ byId('goal-task').disabled = goal.frozen;
1171
+ byId('goal-constraints').disabled = goal.frozen;
1172
+ byId('goal-run-name').disabled = goal.frozen;
1173
+ byId('save-goal').hidden = goal.frozen;
1174
+ byId('review-goal').hidden = goal.frozen;
1175
+ byId('confirm-freeze').hidden = true;
1176
+ byId('unfreeze-goal').hidden = !goal.frozen;
1177
+ }
1178
+
1179
+ async function reviewGoal() {
1180
+ const contract = await saveGoalFromForm();
1181
+ if (!contract) return;
1182
+ byId('goal-dialog').showModal();
1183
+ byId('goal-dialog').querySelector('.advanced-goal').open = true;
1184
+ byId('goal-review').hidden = false;
1185
+ byId('goal-review').innerHTML = `
1186
+ <strong>${escapeHtml(contract.objective)}</strong>
1187
+ <p>${contract.acceptanceCriteria.length} numbered acceptance failure rows are ready.</p>
1188
+ `;
1189
+ byId('confirm-freeze').hidden = false;
1190
+ }
1191
+
1192
+ async function freezeGoalFromForm() {
1193
+ try {
1194
+ const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/freeze`, {
1195
+ method: 'POST',
1196
+ body: JSON.stringify({ actor: 'studio-user' })
1197
+ });
1198
+ catalog.live = catalog.live || {};
1199
+ catalog.live.run = result.run;
1200
+ goal = {
1201
+ text: byId('goal-text').value.trim(),
1202
+ criteria: parseGoalCriteria(byId('goal-criteria').value),
1203
+ version: result.run.goal.version,
1204
+ frozen: true
1205
+ };
1206
+ renderGoalState();
1207
+ renderGraph();
1208
+ notify('Goal frozen with an integrity-bound version.');
1209
+ byId('goal-dialog').close();
1210
+ } catch (error) {
1211
+ byId('goal-validation').textContent = error.message;
1212
+ }
1213
+ }
1214
+
1215
+ async function unfreezeGoalFromForm() {
1216
+ const fields = byId('unfreeze-fields');
1217
+ if (fields.hidden) {
1218
+ fields.hidden = false;
1219
+ byId('unfreeze-reason').focus();
1220
+ return;
1221
+ }
1222
+ try {
1223
+ const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/unfreeze`, {
1224
+ method: 'POST',
1225
+ body: JSON.stringify({ actor: 'studio-user', reason: byId('unfreeze-reason').value })
1226
+ });
1227
+ goal.frozen = false;
1228
+ goal.version = result.run.goal.version;
1229
+ fields.hidden = true;
1230
+ renderGoalState();
1231
+ renderGraph();
1232
+ notify('Goal unfrozen. Previous evidence remains bound to its prior version.');
1233
+ byId('goal-dialog').close();
1234
+ } catch (error) {
1235
+ byId('goal-validation').textContent = error.message;
1236
+ }
1237
+ }
1238
+
1239
+ function syncGoalFromLive() {
1240
+ const liveGoal = catalog.live?.run?.goal;
1241
+ activeRunId = catalog.live?.run?.runId || null;
1242
+ if (!liveGoal) return;
1243
+ goal.version = liveGoal.version || 1;
1244
+ goal.frozen = liveGoal.frozen === true;
1245
+ if (catalog.live.run.task) byId('goal-task').value = catalog.live.run.task;
1246
+ if (catalog.live.run.constraints) byId('goal-constraints').value = catalog.live.run.constraints;
1247
+ if (catalog.live.run.displayName) byId('goal-run-name').value = catalog.live.run.displayName;
1248
+ renderGoalState();
1249
+ }
1250
+
1251
+ async function hydrateGoalFromLive() {
1252
+ const run = catalog.live?.run;
1253
+ const artifactPath = run?.artifacts?.goalContract?.path;
1254
+ const key = `${run?.runId || ''}:${run?.goal?.version || 1}:${artifactPath || ''}`;
1255
+ if (!artifactPath || hydratedGoalKey === key) return;
1256
+ try {
1257
+ const result = await api(`/api/runs/${encodeURIComponent(run.runId)}/artifacts?path=${encodeURIComponent(artifactPath)}`);
1258
+ const contract = JSON.parse(result.artifact.content);
1259
+ byId('goal-text').value = contract.objective || '';
1260
+ byId('goal-criteria').value = (contract.acceptanceCriteria || []).map((criterion) => (
1261
+ `${criterion.statement} | ${criterion.evidenceRequired} | ${(criterion.failureCases || []).join(' | ')}`
1262
+ )).join('\n');
1263
+ goal.text = contract.objective || '';
1264
+ goal.criteria = contract.acceptanceCriteria || [];
1265
+ hydratedGoalKey = key;
1266
+ } catch {
1267
+ // The Goal remains inspectable through Run History if its bounded artifact cannot be hydrated.
1268
+ }
1269
+ }
1270
+
1271
+ async function loadRuns() {
1272
+ const query = byId('run-search').value.trim();
1273
+ try {
1274
+ const params = new URLSearchParams();
1275
+ if (query) params.set('q', query);
1276
+ if (byId('run-status').value) params.set('status', byId('run-status').value);
1277
+ if (byId('run-mode').value) params.set('mode', byId('run-mode').value);
1278
+ if (byId('run-from').value) params.set('from', `${byId('run-from').value}T00:00:00.000Z`);
1279
+ if (byId('run-to').value) params.set('to', `${byId('run-to').value}T23:59:59.999Z`);
1280
+ const result = await api(`/api/runs${params.size ? `?${params}` : ''}`);
1281
+ runs = result.runs;
1282
+ const list = byId('run-list');
1283
+ if (!runs.length) {
1284
+ list.innerHTML = '<div class="empty-state"><h2>No runs found</h2><p>Create a task from the workflow trigger.</p></div>';
1285
+ } else {
1286
+ list.innerHTML = runs.map((run) => `
1287
+ <button class="run-row" data-run-id="${escapeHtml(run.runId)}">
1288
+ <strong>${escapeHtml(run.displayName)}</strong>
1289
+ <span>${escapeHtml(run.status)} · ${escapeHtml(new Date(run.updatedAt).toLocaleString())}</span>
1290
+ <small>${escapeHtml(run.task)}</small>
1291
+ </button>
1292
+ `).join('');
1293
+ list.querySelectorAll('.run-row').forEach((button) => {
1294
+ button.onclick = () => loadRunDetail(button.dataset.runId);
1295
+ });
1296
+ }
1297
+ if (result.corrupt.length) {
1298
+ list.insertAdjacentHTML('beforeend', `<p class="validation-message">${result.corrupt.length} corrupt run record(s) were isolated.</p>`);
1299
+ }
1300
+ } catch (error) {
1301
+ byId('run-list').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1302
+ }
1303
+ }
1304
+
1305
+ async function loadRunDetail(runId) {
1306
+ try {
1307
+ selectedCheckoutRun = runId;
1308
+ const [result, checkoutResult, interactionResult] = await Promise.all([
1309
+ api(`/api/runs/${encodeURIComponent(runId)}`),
1310
+ api(`/api/runs/${encodeURIComponent(runId)}/checkout`),
1311
+ api(`/api/runs/${encodeURIComponent(runId)}/interactions`)
1312
+ ]);
1313
+ const run = result.run;
1314
+ const checkout = checkoutResult.checkout;
1315
+ const maxX = Math.max(...checkout.nodes.map((node) => node.position.x), 0) + NODE_WIDTH + 80;
1316
+ const maxY = Math.max(...checkout.nodes.map((node) => node.position.y), 0) + 180;
1317
+ const paths = checkout.edges.map((edge) => {
1318
+ const from = checkout.nodes.find((node) => node.id === edge.from);
1319
+ const to = checkout.nodes.find((node) => node.id === edge.to);
1320
+ if (!from || !to) return '';
1321
+ const x1 = from.position.x + NODE_WIDTH;
1322
+ const y1 = from.position.y + NODE_PORT_Y;
1323
+ const x2 = to.position.x;
1324
+ const y2 = to.position.y + NODE_PORT_Y;
1325
+ return `<path d="M ${x1} ${y1} C ${x1 + 70} ${y1}, ${x2 - 70} ${y2}, ${x2} ${y2}"></path>`;
1326
+ }).join('');
1327
+ const checkoutGroups = (checkout.loopGroups || []).map((group) => {
1328
+ const members = checkout.nodes.filter((node) => group.nodeIds.includes(node.id));
1329
+ if (!members.length) return '';
1330
+ const left = Math.min(...members.map((node) => node.position.x)) - 28;
1331
+ const top = Math.min(...members.map((node) => node.position.y)) - 36;
1332
+ const right = Math.max(...members.map((node) => node.position.x + NODE_WIDTH)) + 28;
1333
+ const bottom = Math.max(...members.map((node) => node.position.y + 108)) + 28;
1334
+ return `<div class="checkout-loop status-${escapeHtml((group.runtime?.status || 'pending').toLowerCase())}" style="left:${left}px;top:${top}px;width:${right - left}px;height:${bottom - top}px"><b>${escapeHtml(group.displayName)}</b><span>Iteration ${escapeHtml(group.runtime?.iteration || 1)} / ${escapeHtml(group.maxIterations)}</span></div>`;
1335
+ }).join('');
1336
+ byId('run-detail').innerHTML = `
1337
+ <header class="checkout-header">
1338
+ <div><button id="checkout-back" class="quiet">← Run History</button><small>READ-ONLY CHECKOUT · ${escapeHtml(run.status)}</small><h2>${escapeHtml(run.displayName)}</h2><p>${escapeHtml(run.task)}</p></div>
1339
+ <div class="checkout-actions"><button id="copy-agent-handoff">Copy for AI Agent</button><button id="duplicate-run-workflow" class="primary">Duplicate as Workflow</button></div>
1340
+ </header>
1341
+ <div class="checkout-meta"><span>${escapeHtml(run.runId)}</span><span>${run.goalFrozen ? `Goal frozen V${escapeHtml(run.goalVersion)}` : 'Goal draft'}</span><span>Actual node states</span></div>
1342
+ <section class="checkout-canvas" style="--checkout-width:${maxX}px;--checkout-height:${maxY}px">
1343
+ <svg viewBox="0 0 ${maxX} ${maxY}" aria-hidden="true">${paths}</svg>
1344
+ ${checkoutGroups}
1345
+ ${checkout.nodes.map((node) => `<button class="checkout-node status-${escapeHtml(node.status.toLowerCase())}" data-checkout-node="${escapeHtml(node.id)}" style="left:${node.position.x}px;top:${node.position.y}px">
1346
+ <small>${escapeHtml(node.type)}${node.loopIteration ? ` · LOOP ${escapeHtml(node.loopIteration)}` : ''}</small><strong>${escapeHtml(node.displayName)}</strong><span>${escapeHtml(node.status)}</span>
1347
+ </button>`).join('')}
1348
+ </section>
1349
+ <section id="node-io-panel" class="node-io-panel"><div class="empty-state"><h3>Select a node</h3><p>Inspect its real Input, Output, Evidence, and Timeline.</p></div></section>
1350
+ <section class="agent-interactions"><header><div><small>LIVE AGENT INTERACTIONS</small><h3>Questions from the Agent</h3></div><span>Updates automatically</span></header><div id="interaction-list"></div></section>
1351
+ `;
1352
+ renderInteractions(interactionResult.interactions);
1353
+ byId('checkout-back').onclick = () => {
1354
+ selectedCheckoutRun = null;
1355
+ byId('run-detail').innerHTML = '<div class="empty-state"><h2>Select a run</h2><p>Open a read-only checkout to inspect actual node evidence.</p></div>';
1356
+ };
1357
+ byId('copy-agent-handoff').onclick = () => copyAgentHandoff(runId);
1358
+ byId('duplicate-run-workflow').onclick = async () => {
1359
+ try {
1360
+ const duplicate = await api(`/api/runs/${encodeURIComponent(runId)}/duplicate`, {
1361
+ method: 'POST',
1362
+ body: JSON.stringify({ recipeId: `${slug(run.displayName)}-copy` })
1363
+ });
1364
+ draft = normalizeDraftGraph(structuredClone(duplicate.preview.recipe));
1365
+ positions = new Map(checkout.nodes.map((node) => [node.id, node.position]));
1366
+ loadedRecipeId = null;
1367
+ captureHistory({ reset: true });
1368
+ renderGraph();
1369
+ renderRecipeDetails();
1370
+ validateDraft();
1371
+ showWorkspace('workflows');
1372
+ notify('Run duplicated into a new editable workflow. History was not changed.');
1373
+ } catch (error) {
1374
+ notify(error.message);
1375
+ }
1376
+ };
1377
+ byId('run-detail').querySelectorAll('[data-checkout-node]').forEach((button) => {
1378
+ button.onclick = () => loadNodeIo(runId, button.dataset.checkoutNode);
1379
+ });
1380
+ } catch (error) {
1381
+ byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1382
+ }
1383
+ }
1384
+
1385
+ function renderArtifactPreview(artifact) {
1386
+ if (!artifact) return '<p class="muted">No artifact was recorded for this node.</p>';
1387
+ if (artifact.unavailable) return `<p class="validation-message">Artifact unavailable: ${escapeHtml(artifact.code)}</p>`;
1388
+ return `<p class="artifact-path">${escapeHtml(artifact.descriptor.path)}</p><button class="artifact-download" data-artifact-download="${escapeHtml(artifact.descriptor.path)}">Download copy</button><pre>${escapeHtml(artifact.preview.content)}</pre>`;
1389
+ }
1390
+
1391
+ async function loadNodeIo(runId, nodeId) {
1392
+ const panel = byId('node-io-panel');
1393
+ try {
1394
+ const { io } = await api(`/api/runs/${encodeURIComponent(runId)}/nodes/${encodeURIComponent(nodeId)}`);
1395
+ panel.innerHTML = `
1396
+ <header><small>NODE I/O · ${escapeHtml(io.node.status)}</small><h3>${escapeHtml(io.node.displayName)}</h3></header>
1397
+ <div class="io-grid">
1398
+ <section><h4>Input</h4>${io.input.task ? `<p><b>Task</b><br>${escapeHtml(io.input.task)}</p>` : ''}${io.input.constraints ? `<p><b>Constraints</b><br>${escapeHtml(io.input.constraints)}</p>` : ''}${io.input.dependencies.length ? io.input.dependencies.map((dependency) => `<p><b>${escapeHtml(dependency.nodeId)}</b> · ${escapeHtml(dependency.status)}</p>${renderArtifactPreview(dependency.artifact)}`).join('') : '<p class="muted">Root input from this Run.</p>'}</section>
1399
+ <section><h4>Output</h4><p><b>${escapeHtml(io.output.status)}</b>${io.output.reason ? ` · ${escapeHtml(io.output.reason)}` : ''}</p>${renderArtifactPreview(io.output.artifact)}</section>
1400
+ <section><h4>Evidence</h4>${renderArtifactPreview(io.evidence)}</section>
1401
+ <section><h4>Timeline</h4><div class="timeline">${io.timeline.map((event) => `<p><time>${escapeHtml(event.at)}</time><strong>${escapeHtml(event.type)}</strong></p>`).join('') || '<p class="muted">No node events yet.</p>'}</div></section>
1402
+ </div>`;
1403
+ panel.querySelectorAll('[data-artifact-download]').forEach((button) => {
1404
+ button.onclick = async () => {
1405
+ try {
1406
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifactDownload)}`);
1407
+ const blob = new Blob([result.artifact.content], { type: 'text/plain' });
1408
+ const link = document.createElement('a');
1409
+ link.href = URL.createObjectURL(blob);
1410
+ link.download = button.dataset.artifactDownload.split('/').at(-1);
1411
+ link.click();
1412
+ URL.revokeObjectURL(link.href);
1413
+ } catch (error) {
1414
+ notify(error.message);
1415
+ }
1416
+ };
1417
+ });
1418
+ } catch (error) {
1419
+ panel.innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1420
+ }
1421
+ }
1422
+
1423
+ function renderInteractions(result) {
1424
+ const target = byId('interaction-list');
1425
+ if (!target) return;
1426
+ target.innerHTML = result.questions.length ? result.questions.map((question) => `
1427
+ <article class="agent-question ${question.answer ? 'answered' : 'pending'}">
1428
+ <small>Q${escapeHtml(question.number)} · ${escapeHtml(question.actor)}</small>
1429
+ <p>${escapeHtml(question.message)}</p>
1430
+ ${question.answer ? `<div class="agent-answer"><b>Answer</b><p>${escapeHtml(question.answer.message)}</p></div>` : `<form data-answer="${escapeHtml(question.questionId)}"><textarea maxlength="8000" required placeholder="Answer so the Agent can continue…"></textarea><button class="primary">Send answer</button></form>`}
1431
+ </article>
1432
+ `).join('') : '<p class="muted">No questions yet. The Agent can post Q1, Q2, Q3 from the Run-bound CLI.</p>';
1433
+ target.querySelectorAll('[data-answer]').forEach((form) => {
1434
+ form.onsubmit = async (event) => {
1435
+ event.preventDefault();
1436
+ try {
1437
+ await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/questions/${encodeURIComponent(form.dataset.answer)}/answer`, {
1438
+ method: 'POST',
1439
+ body: JSON.stringify({ message: form.querySelector('textarea').value, actor: 'studio-user' })
1440
+ });
1441
+ await refreshCheckoutInteractions();
1442
+ } catch (error) {
1443
+ notify(error.message);
1444
+ }
1445
+ };
1446
+ });
1447
+ }
1448
+
1449
+ async function refreshCheckoutInteractions() {
1450
+ if (!selectedCheckoutRun || !byId('interaction-list')) return;
1451
+ try {
1452
+ const result = await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/interactions`);
1453
+ renderInteractions(result.interactions);
1454
+ } catch {
1455
+ // Corrupt or unavailable Run data is isolated and does not affect another Run.
1456
+ }
1457
+ }
1458
+
1459
+ async function copyAgentHandoff(runId = activeRunId) {
1460
+ try {
1461
+ if (!runId) await ensureStudioRun();
1462
+ const result = await api(`/api/runs/${encodeURIComponent(runId || activeRunId)}/agent-handoff`);
1463
+ await navigator.clipboard.writeText(result.handoff.prompt);
1464
+ byId('goal-dialog').close();
1465
+ notify('Run-bound prompt copied. Paste it into your AI coding Agent.');
1466
+ } catch (error) {
1467
+ byId('goal-validation').textContent = error.message;
1468
+ }
1469
+ }
1470
+
1471
+ function showWorkspace(section) {
1472
+ const showingRuns = section === 'runs';
1473
+ byId('runs-view').hidden = !showingRuns;
1474
+ byId('canvas').hidden = showingRuns;
1475
+ byId('workflow-context').hidden = showingRuns;
1476
+ byId('review').hidden = showingRuns;
1477
+ byId('show-runs').classList.toggle('active', showingRuns);
1478
+ byId('show-runs').setAttribute('aria-current', showingRuns ? 'page' : 'false');
1479
+ byId('show-workflows').classList.toggle('active', !showingRuns);
1480
+ byId('show-workflows').setAttribute('aria-current', showingRuns ? 'false' : 'page');
1481
+ if (showingRuns) loadRuns();
1482
+ }
1483
+
1484
+ async function previewImport() {
1485
+ try {
1486
+ const importedRecipe = JSON.parse(byId('import-source').value);
1487
+ const result = await api('/api/import/preview', {
1488
+ method: 'POST',
1489
+ body: JSON.stringify({ existingRecipe: draft, importedRecipe, operation: 'merge' })
1490
+ });
1491
+ pendingImport = { importedRecipe, mergePlan: result.plan };
1492
+ byId('import-preview').innerHTML = `
1493
+ <strong>${escapeHtml(importedRecipe.id || 'Imported workflow')}</strong>
1494
+ <p>${escapeHtml(importedRecipe.nodes?.length || 0)} nodes · ${escapeHtml(importedRecipe.edges?.length || 0)} explicit Edges</p>
1495
+ <p>${Object.values(result.plan.nodeIdMap).filter((id, index) => id !== Object.keys(result.plan.nodeIdMap)[index]).length} node ID conflict(s) will be renamed.</p>
1496
+ `;
1497
+ byId('import-choices').hidden = false;
1498
+ } catch (error) {
1499
+ pendingImport = null;
1500
+ byId('import-choices').hidden = true;
1501
+ byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1502
+ }
1503
+ }
1504
+
1505
+ async function applyImport(operation) {
1506
+ if (!pendingImport) return;
1507
+ try {
1508
+ const plan = operation === 'merge'
1509
+ ? pendingImport.mergePlan
1510
+ : { operation: 'replace', nodeIdMap: {}, edgeIdMap: {} };
1511
+ const result = await api('/api/import/apply', {
1512
+ method: 'POST',
1513
+ body: JSON.stringify({
1514
+ existingRecipe: draft,
1515
+ importedRecipe: pendingImport.importedRecipe,
1516
+ plan
1517
+ })
1518
+ });
1519
+ draft = normalizeDraftGraph(structuredClone(result.recipe));
1520
+ positions = new Map();
1521
+ ensurePositions();
1522
+ selectedIds.clear();
1523
+ selectedId = null;
1524
+ captureHistory();
1525
+ renderGraph();
1526
+ renderRecipeDetails();
1527
+ validateDraft();
1528
+ byId('import-dialog').close();
1529
+ notify(`${operation === 'merge' ? 'Merged' : 'Replaced'} canvas from validated JSON.`);
1530
+ } catch (error) {
1531
+ byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1532
+ }
1533
+ }
1534
+
1535
+ function exportWorkflowJson() {
1536
+ const blob = new Blob([`${JSON.stringify(authoringRecipe(), null, 2)}\n`], { type: 'application/json' });
1537
+ const link = document.createElement('a');
1538
+ link.href = URL.createObjectURL(blob);
1539
+ link.download = `${draft.id}.workflow.json`;
1540
+ link.click();
1541
+ URL.revokeObjectURL(link.href);
1542
+ }
1543
+
1544
+ function createCustomAgentFromForm(event) {
1545
+ event.preventDefault();
1546
+ const id = uniqueNodeId('agent');
1547
+ const name = byId('custom-name').value.trim();
1548
+ const prompt = byId('custom-prompt').value.trim();
1549
+ const error = validDisplayName(name);
1550
+ if (error || !prompt) return notify(error || 'Custom Agent prompt is required.');
1551
+ const artifact = byId('custom-output').value.trim() || `${id}-report`;
1552
+ const node = {
1553
+ id,
1554
+ type: 'agent',
1555
+ displayName: name,
1556
+ prompt,
1557
+ capabilityRefs: csv(byId('custom-capabilities').value),
1558
+ mcpRefs: csv(byId('custom-mcp').value),
1559
+ inputArtifacts: csv(byId('custom-inputs').value),
1560
+ outputArtifacts: [{ artifact, schema: 'schemas/report.schema.json' }],
1561
+ tokenLimit: Number(byId('custom-tokens').value),
1562
+ timeoutMs: Number(byId('custom-timeout').value) * 1000,
1563
+ retry: { maxAttempts: Number(byId('custom-retries').value), backoffMs: 1000 }
1564
+ };
1565
+ draft.nodes.push(node);
1566
+ if (pendingConnectionSource) {
1567
+ draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, id), from: pendingConnectionSource, to: id });
1568
+ pendingConnectionSource = null;
1569
+ }
1570
+ syncDependencies();
1571
+ const center = worldAtCanvasCenter();
1572
+ positions.set(id, { x: center.x - NODE_WIDTH / 2, y: center.y - NODE_PORT_Y });
1573
+ captureHistory();
1574
+ renderGraph();
1575
+ selectNode(id);
1576
+ validateDraft();
1577
+ byId('custom-dialog').close();
1578
+ }
1579
+
577
1580
  function zoomAt(nextScale, clientX, clientY) {
578
1581
  const scale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));
579
1582
  const rect = byId('canvas').getBoundingClientRect();
@@ -730,7 +1733,10 @@ async function refreshLive() {
730
1733
  try {
731
1734
  const result = await api('/api/live');
732
1735
  catalog.live = result.live;
1736
+ syncGoalFromLive();
1737
+ await hydrateGoalFromLive();
733
1738
  renderLive();
1739
+ await refreshCheckoutInteractions();
734
1740
  } catch {
735
1741
  // A transient refresh failure must not discard the draft.
736
1742
  }
@@ -742,10 +1748,12 @@ async function loadRecipe() {
742
1748
  api(`/api/recipe?id=${encodeURIComponent(id)}`),
743
1749
  api(`/api/layout?id=${encodeURIComponent(id)}`)
744
1750
  ]);
745
- draft = structuredClone(result.recipe);
1751
+ draft = normalizeDraftGraph(structuredClone(result.recipe));
746
1752
  source = result.source;
747
1753
  loadedRecipeId = draft.id;
748
1754
  selectedId = null;
1755
+ selectedIds.clear();
1756
+ selectedEdgeId = null;
749
1757
  byId('inspector-panel').classList.remove('open');
750
1758
  positions = new Map(Object.entries(saved.layout?.positions || {}));
751
1759
  ensurePositions();
@@ -765,6 +1773,7 @@ async function refreshCatalog(selectedRecipe) {
765
1773
  )).join('');
766
1774
  if (selectedRecipe && catalog.recipes.some((recipe) => recipe.id === selectedRecipe)) selector.value = selectedRecipe;
767
1775
  renderPalette();
1776
+ syncGoalFromLive();
768
1777
  renderLive();
769
1778
  }
770
1779
 
@@ -773,10 +1782,12 @@ function bindCanvas() {
773
1782
  canvas.addEventListener('pointerdown', (event) => {
774
1783
  if (event.target === canvas || event.target === byId('scene') || event.target === byId('nodes') || event.target === byId('edges')) {
775
1784
  selectedId = null;
1785
+ if (!event.shiftKey) selectedIds.clear();
776
1786
  updateSelection();
777
1787
  renderRecipeDetails();
778
1788
  byId('inspector-panel').classList.remove('open');
779
- beginPan(event);
1789
+ if (event.button === 1 || spacePressed) beginPan(event);
1790
+ else if (event.button === 0) beginLasso(event);
780
1791
  }
781
1792
  });
782
1793
  canvas.addEventListener('pointermove', handlePointerMove);
@@ -821,7 +1832,15 @@ document.addEventListener('keydown', (event) => {
821
1832
  } else if (modifier && event.key.toLowerCase() === 'y') {
822
1833
  event.preventDefault();
823
1834
  restoreHistory(historyIndex + 1);
824
- } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedId) {
1835
+ } else if (modifier && event.key.toLowerCase() === 'a' && byId('canvas').contains(document.activeElement)) {
1836
+ event.preventDefault();
1837
+ selectedIds = new Set(draft.nodes.map((node) => node.id));
1838
+ selectedId = [...selectedIds].at(-1) || null;
1839
+ updateSelection();
1840
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId) {
1841
+ event.preventDefault();
1842
+ deleteEdge(selectedEdgeId);
1843
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedIds.size) {
825
1844
  event.preventDefault();
826
1845
  deleteSelectedNode();
827
1846
  }
@@ -904,13 +1923,112 @@ function notify(text) {
904
1923
  setTimeout(() => { message.style.display = 'none'; }, 4000);
905
1924
  }
906
1925
 
1926
+ function openLoopDialog() {
1927
+ const members = draft.nodes.filter((node) => selectedIds.has(node.id));
1928
+ if (members.length < 2) return notify('Select at least two steps for a Loop Group.');
1929
+ if ((draft.loopGroups || []).some((group) => group.nodeIds.some((id) => selectedIds.has(id)))) {
1930
+ return notify('A step can only belong to one Loop Group.');
1931
+ }
1932
+ const options = members.map((node) =>
1933
+ `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
1934
+ ).join('');
1935
+ for (const id of ['loop-entry', 'loop-decision', 'loop-repeat-target']) byId(id).innerHTML = options;
1936
+ const incomingEntry = members.find((node) =>
1937
+ draft.edges.some((edge) => edge.to === node.id && !selectedIds.has(edge.from))
1938
+ ) || members[0];
1939
+ const outgoing = draft.edges.find((edge) =>
1940
+ selectedIds.has(edge.from) && !selectedIds.has(edge.to)
1941
+ );
1942
+ if (!outgoing) return notify('Connect the Loop decision step to its Continue step first.');
1943
+ const decision = outgoing
1944
+ ? members.find((node) => node.id === outgoing.from)
1945
+ : members.find((node) => ['decision', 'judge', 'condition'].includes(node.type)) || members.at(-1);
1946
+ const exitIds = new Set(draft.edges
1947
+ .filter((edge) => selectedIds.has(edge.from) && !selectedIds.has(edge.to))
1948
+ .map((edge) => edge.to));
1949
+ const exitCandidates = draft.nodes.filter((node) => exitIds.has(node.id));
1950
+ byId('loop-exit-target').innerHTML = exitCandidates.map((node) =>
1951
+ `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
1952
+ ).join('');
1953
+ byId('loop-entry').value = incomingEntry.id;
1954
+ byId('loop-repeat-target').value = incomingEntry.id;
1955
+ byId('loop-decision').value = decision.id;
1956
+ if (outgoing) byId('loop-exit-target').value = outgoing.to;
1957
+ byId('loop-name').value = '';
1958
+ byId('loop-dialog').showModal();
1959
+ }
1960
+
1961
+ function createLoopGroupFromForm(event) {
1962
+ event.preventDefault();
1963
+ const display = byId('loop-name').value.trim();
1964
+ const repeatOutcome = byId('loop-repeat-outcome').value.trim();
1965
+ const exitOutcome = byId('loop-exit-outcome').value.trim();
1966
+ if (repeatOutcome === exitOutcome) return notify('Repeat and Continue outcomes must be different.');
1967
+ let id = slug(display || 'iteration-loop');
1968
+ const occupied = new Set((draft.loopGroups || []).map((group) => group.id));
1969
+ for (let suffix = 2; occupied.has(id); suffix += 1) id = `${slug(display || 'iteration-loop')}-${suffix}`;
1970
+ const loopGroup = {
1971
+ id,
1972
+ displayName: display,
1973
+ nodeIds: draft.nodes.filter((node) => selectedIds.has(node.id)).map((node) => node.id),
1974
+ entryNodeId: byId('loop-entry').value,
1975
+ decisionNodeId: byId('loop-decision').value,
1976
+ repeatTargetId: byId('loop-repeat-target').value,
1977
+ exitTargetId: byId('loop-exit-target').value,
1978
+ maxIterations: Number(byId('loop-max').value),
1979
+ repeatOutcome,
1980
+ exitOutcome,
1981
+ repeatLabel: byId('loop-repeat-label').value.trim(),
1982
+ exitLabel: byId('loop-exit-label').value.trim()
1983
+ };
1984
+ draft.loopGroups.push(loopGroup);
1985
+ captureHistory();
1986
+ renderGraph();
1987
+ validateDraft();
1988
+ byId('loop-dialog').close();
1989
+ notify(`Loop Group “${display}” created.`);
1990
+ }
1991
+
907
1992
  async function initialize() {
908
1993
  await refreshCatalog('default');
909
1994
  byId('recipe').onchange = loadRecipe;
910
1995
  bindCanvas();
911
1996
  byId('toggle-library').onclick = () => byId('library-panel').classList.toggle('open');
912
- byId('quick-add').onclick = () => byId('library-panel').classList.add('open');
913
1997
  byId('close-library').onclick = () => byId('library-panel').classList.remove('open');
1998
+ byId('show-workflows').onclick = () => showWorkspace('workflows');
1999
+ byId('show-runs').onclick = () => showWorkspace('runs');
2000
+ byId('run-search').oninput = loadRuns;
2001
+ for (const id of ['run-status', 'run-mode', 'run-from', 'run-to']) byId(id).onchange = loadRuns;
2002
+ byId('import-json').onclick = () => byId('import-dialog').showModal();
2003
+ byId('export-json').onclick = exportWorkflowJson;
2004
+ byId('preview-import').onclick = previewImport;
2005
+ byId('import-file').onchange = async (event) => {
2006
+ const [file] = event.currentTarget.files;
2007
+ if (file) byId('import-source').value = await file.text();
2008
+ };
2009
+ byId('merge-import').onclick = () => applyImport('merge');
2010
+ byId('replace-import').onclick = () => applyImport('replace');
2011
+ byId('create-custom').onclick = () => byId('custom-dialog').showModal();
2012
+ byId('custom-form').onsubmit = createCustomAgentFromForm;
2013
+ byId('open-goal').onclick = () => {
2014
+ renderGoalState();
2015
+ byId('goal-dialog').showModal();
2016
+ };
2017
+ byId('save-goal').onclick = saveGoalFromForm;
2018
+ byId('start-agent').onclick = () => copyAgentHandoff();
2019
+ byId('review-goal').onclick = reviewGoal;
2020
+ byId('confirm-freeze').onclick = freezeGoalFromForm;
2021
+ byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
2022
+ byId('duplicate-selection').onclick = duplicateSelectedNode;
2023
+ byId('delete-selection').onclick = deleteSelectedNode;
2024
+ byId('create-loop-group').onclick = openLoopDialog;
2025
+ byId('loop-form').onsubmit = createLoopGroupFromForm;
2026
+ document.querySelectorAll('[data-close]').forEach((button) => {
2027
+ button.onclick = () => byId(button.dataset.close).close();
2028
+ });
2029
+ document.querySelectorAll('.dialog-maximize').forEach((button) => {
2030
+ button.onclick = () => button.closest('dialog').classList.toggle('maximized');
2031
+ });
914
2032
  byId('workflow-settings').onclick = () => {
915
2033
  selectedId = null;
916
2034
  updateSelection();