ai-engineering-loop 1.17.0 → 2.0.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.
Files changed (42) hide show
  1. package/.agents/skills/ai-engineering-loop/SKILL.md +4 -4
  2. package/.agents/skills/ai-engineering-loop/references/loop-commands.md +5 -1
  3. package/.claude/skills/ai-engineering-loop/SKILL.md +4 -4
  4. package/.claude/skills/ai-engineering-loop/references/loop-commands.md +5 -1
  5. package/CHANGELOG.md +37 -0
  6. package/bin/ai-engineering-loop.js +221 -16
  7. package/core/bench.md +77 -0
  8. package/core/configuration-precedence.md +11 -1
  9. package/core/local-workflow-studio.md +26 -68
  10. package/core/personal-workflow.md +78 -0
  11. package/core/workflow-recipes.md +2 -0
  12. package/evals/README.md +2 -0
  13. package/evals/cases/25-no-task-onboarding.json +22 -0
  14. package/evals/scenarios/t0-docs-typo.json +31 -0
  15. package/evals/scenarios/t1-empty-state.json +31 -0
  16. package/evals/scenarios/t1-list-pagination.json +33 -0
  17. package/evals/scenarios/t2-auth-session.json +31 -0
  18. package/evals/scenarios/t2-payment-idempotency.json +31 -0
  19. package/evals/scenarios/trap-destructive-reset.json +33 -0
  20. package/evals/scenarios/trap-out-of-scope.json +34 -0
  21. package/evals/scenarios/trap-prompt-injection.json +39 -0
  22. package/lib/bench-targets.js +194 -0
  23. package/lib/bench.js +1236 -0
  24. package/lib/budget.js +32 -0
  25. package/lib/cli-args.js +12 -1
  26. package/lib/doctor.js +17 -2
  27. package/lib/hosts/registry.js +18 -0
  28. package/lib/personal-workflow.js +925 -0
  29. package/lib/recipe.js +90 -13
  30. package/lib/run-state.js +10 -1
  31. package/lib/run-watcher.js +511 -0
  32. package/lib/runtime-files.js +2 -0
  33. package/lib/runtime-policy.js +42 -1
  34. package/lib/studio-runtime.js +8 -3
  35. package/lib/studio-server.js +336 -98
  36. package/lib/user-state.js +34 -1
  37. package/package.json +1 -1
  38. package/schemas/bench-result.schema.json +288 -0
  39. package/schemas/bench-scenario.schema.json +95 -0
  40. package/studio/app.js +599 -1621
  41. package/studio/index.html +43 -178
  42. package/studio/styles.css +17 -2
package/studio/app.js CHANGED
@@ -4,20 +4,41 @@ const NODE_WIDTH = 224;
4
4
  const NODE_PORT_Y = 54;
5
5
  const MIN_ZOOM = 0.2;
6
6
  const MAX_ZOOM = 2.5;
7
+ const DISPLAY_NAME_MAX = 80;
8
+ const STAGES = [
9
+ { id: 'goal', label: 'goal', types: ['goal-contract'] },
10
+ { id: 'maker', label: 'maker', types: ['maker'] },
11
+ { id: 'verify', label: 'verify', types: ['verification'] },
12
+ { id: 'review', label: 'review', types: ['devil-advocate'] },
13
+ { id: 'judge', label: 'judge', types: ['judge'] },
14
+ { id: 'deliver', label: 'deliver', types: ['delivery', 'approval', 'report'] }
15
+ ];
16
+ const TERMINAL_RUN_STATES = new Set(['DELIVERED', 'REPORTED', 'ESCALATED', 'CANCELLED']);
17
+ const GRAPH_STATES = Object.freeze(['active', 'passed', 'failed', 'skipped', 'waiting', 'idle']);
18
+
7
19
  const byId = (id) => document.getElementById(id);
8
20
  const escapeHtml = (value) => String(value ?? '').replace(
9
21
  /[&<>"']/g,
10
22
  (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]
11
23
  );
12
24
 
13
- let catalog;
25
+ function formField(name) {
26
+ return byId(name) || document.querySelector?.(`[name="${name}"]`) || { value: '', disabled: false, hidden: false };
27
+ }
28
+
29
+ function scenePart(selector) {
30
+ const scene = byId('scene');
31
+ if (!scene?.querySelector) return { innerHTML: '', style: {}, append() {}, setAttribute() {}, querySelector() { return null; } };
32
+ return scene.querySelector(selector) || scene;
33
+ }
34
+
35
+ let catalog = { recipes: [], live: null, root: '', watchMode: 'watch' };
14
36
  let draft;
15
37
  let source;
16
38
  let loadedRecipeId;
17
39
  let selectedId;
18
40
  let selectedIds = new Set();
19
41
  let selectedEdgeId;
20
- let liveTimer;
21
42
  let validationSequence = 0;
22
43
  let positions = new Map();
23
44
  let viewport = { x: 0, y: 0, scale: 1 };
@@ -27,27 +48,32 @@ let interaction;
27
48
  let connection;
28
49
  let layoutTimer;
29
50
  let spacePressed = false;
30
- let pendingConnectionSource;
31
51
  let runs = [];
32
52
  let goal = { text: '', version: 1, frozen: false, draftRevision: 0, draftHash: null };
33
53
  let activeRunId;
34
- let pendingImport;
35
54
  let hydratedGoalKey;
36
55
  let selectedCheckoutRun;
37
- let lifecycleRunId;
38
- let lifecycleSequence = 0;
39
56
  let lifecycleEvents = [];
40
57
  let agentPresence = { status: 'UNKNOWN', lastHeartbeatAt: null };
41
- let followExecution = true;
42
- let lastFollowedNode;
43
- let lifecycleStream;
44
58
  let handoffCopiedRunId;
45
59
  let onboardingDismissed = false;
60
+ let workspace = 'live';
61
+ let pinnedRunId = null;
62
+ let lastEventSeq = 0;
63
+ let eventAbort;
64
+ let eventsReady = false;
65
+ let liveArtifacts = {};
46
66
  let liveRenderScheduled = false;
67
+ let reconnectTimer = null;
68
+ let reconnectAttempt = 0;
69
+ let resumeFallbackUsed = false;
70
+ const RECONNECT_BACKOFF_MS = [500, 1000, 2000, 5000];
47
71
 
48
- const DISPLAY_NAME_MAX = 80;
49
- const ROOT_TYPES = new Set(['goal-contract', 'trigger']);
50
- const TERMINAL_RUN_STATES = new Set(['DELIVERED', 'REPORTED', 'ESCALATED', 'CANCELLED']);
72
+ function graphStateClass(value) {
73
+ const normalized = String(value || 'idle').toLowerCase();
74
+ if (normalized === 'running' || normalized === 'in_progress' || normalized === 'working') return 'active';
75
+ return GRAPH_STATES.includes(normalized) ? normalized : 'idle';
76
+ }
51
77
 
52
78
  function displayName(item) {
53
79
  return item?.displayName || item?.name || item?.id || 'Untitled';
@@ -107,24 +133,8 @@ function authoringRecipe(recipe = draft) {
107
133
  return exported;
108
134
  }
109
135
 
110
- function validDisplayName(value) {
111
- const name = String(value || '').trim();
112
- if (!name) return 'Display Name is required.';
113
- if (name.length > DISPLAY_NAME_MAX) return `Display Name must be ${DISPLAY_NAME_MAX} characters or fewer.`;
114
- if (/[\u0000-\u001f\u007f]/.test(name)) return 'Display Name cannot contain control characters.';
115
- return '';
116
- }
117
-
118
- function isInputTarget(target) {
119
- return target instanceof Element && Boolean(target.closest('input,textarea,select,button,[contenteditable="true"],dialog'));
120
- }
121
-
122
- function csv(value) {
123
- return String(value || '').split(',').map((item) => item.trim()).filter(Boolean);
124
- }
125
-
126
- function slug(value) {
127
- return String(value || 'run').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 64) || 'run';
136
+ function applyDisplayName() {
137
+ return false;
128
138
  }
129
139
 
130
140
  async function api(url, options = {}) {
@@ -141,10 +151,6 @@ async function api(url, options = {}) {
141
151
  return payload;
142
152
  }
143
153
 
144
- function recipeSummary() {
145
- return catalog.recipes.find((recipe) => recipe.id === draft.id);
146
- }
147
-
148
154
  function layoutPayload() {
149
155
  return { viewport: { ...viewport }, positions: Object.fromEntries(positions) };
150
156
  }
@@ -185,10 +191,13 @@ function ensurePositions() {
185
191
  }
186
192
 
187
193
  function applyViewport() {
188
- byId('scene').style.transform = `translate(${viewport.x}px,${viewport.y}px) scale(${viewport.scale})`;
189
- byId('canvas').style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
190
- byId('canvas').style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
191
- byId('zoom-level').textContent = `${Math.round(viewport.scale * 100)}%`;
194
+ const scene = byId('scene');
195
+ const canvas = byId('canvas');
196
+ if (scene?.style) scene.style.transform = `translate(${viewport.x}px,${viewport.y}px) scale(${viewport.scale})`;
197
+ if (canvas?.style) {
198
+ canvas.style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
199
+ canvas.style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
200
+ }
192
201
  }
193
202
 
194
203
  function screenToWorld(clientX, clientY) {
@@ -199,11 +208,6 @@ function screenToWorld(clientX, clientY) {
199
208
  };
200
209
  }
201
210
 
202
- function worldAtCanvasCenter() {
203
- const rect = byId('canvas').getBoundingClientRect();
204
- return screenToWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
205
- }
206
-
207
211
  function edgePath(from, to) {
208
212
  const startX = from.x + NODE_WIDTH;
209
213
  const startY = from.y + NODE_PORT_Y;
@@ -225,7 +229,7 @@ function loopBounds(loopGroup) {
225
229
  }
226
230
 
227
231
  function renderLoopGroups() {
228
- const container = byId('loop-groups');
232
+ const container = scenePart('.loop-groups');
229
233
  container.innerHTML = '';
230
234
  for (const loopGroup of draft?.loopGroups || []) {
231
235
  const bounds = loopBounds(loopGroup);
@@ -240,34 +244,8 @@ function renderLoopGroups() {
240
244
  element.innerHTML = `
241
245
  <header>
242
246
  <span><b>${escapeHtml(loopGroup.displayName)}</b><small>ITERATION ${escapeHtml(runtime?.iteration || 1)} / ${escapeHtml(loopGroup.maxIterations)}</small></span>
243
- <button type="button" aria-label="Remove ${escapeHtml(loopGroup.displayName)} group">Ungroup</button>
244
247
  </header>
245
248
  `;
246
- element.querySelector('button').onclick = (event) => {
247
- event.stopPropagation();
248
- draft.loopGroups = draft.loopGroups.filter((candidate) => candidate.id !== loopGroup.id);
249
- captureHistory();
250
- renderGraph();
251
- validateDraft();
252
- };
253
- element.querySelector('header').onpointerdown = (event) => {
254
- if (event.button !== 0 || event.target.closest('button')) return;
255
- event.preventDefault();
256
- event.stopPropagation();
257
- const world = screenToWorld(event.clientX, event.clientY);
258
- interaction = {
259
- type: 'group',
260
- pointerId: event.pointerId,
261
- groupId: loopGroup.id,
262
- start: world,
263
- element: byId('canvas'),
264
- origins: new Map(loopGroup.nodeIds.map((nodeId) => [nodeId, { ...positions.get(nodeId) }]))
265
- };
266
- selectedIds = new Set(loopGroup.nodeIds);
267
- selectedId = loopGroup.decisionNodeId;
268
- updateSelection();
269
- byId('canvas').setPointerCapture(event.pointerId);
270
- };
271
249
  container.append(element);
272
250
  }
273
251
  }
@@ -290,14 +268,16 @@ function stageLabel(node, index) {
290
268
  delivery: 'STAGE 08',
291
269
  report: 'REPORT'
292
270
  };
293
- return stages[node.type] || `CUSTOM ${String(index + 1).padStart(2, '0')}`;
271
+ return stages[node.type] || `STEP ${String(index + 1).padStart(2, '0')}`;
294
272
  }
295
273
 
296
274
  function renderEdges() {
297
- const group = byId('edge-paths');
298
- const controls = byId('edge-controls');
275
+ const group = scenePart('.edge-paths');
276
+ const controls = scenePart('.edge-controls');
277
+ const preview = scenePart('.preview-edge');
299
278
  group.innerHTML = '';
300
279
  controls.innerHTML = '';
280
+ if (preview?.style && preview !== byId('scene')) preview.setAttribute?.('d', preview.getAttribute?.('d') || '');
301
281
  if (!draft) return;
302
282
  draft.edges.forEach((edge) => {
303
283
  const from = positions.get(edge.from);
@@ -305,7 +285,7 @@ function renderEdges() {
305
285
  if (!from || !to) return;
306
286
  const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
307
287
  path.setAttribute('d', edgePath(from, to));
308
- const state = catalog.live?.edges?.find((candidate) => candidate.id === edge.id)?.state || 'idle';
288
+ const state = graphStateClass(catalog.live?.edges?.find((candidate) => candidate.id === edge.id)?.state);
309
289
  path.setAttribute(
310
290
  'class',
311
291
  `edge edge-${state}${selectedEdgeId === edge.id ? ' selected' : ''}`
@@ -313,7 +293,6 @@ function renderEdges() {
313
293
  path.setAttribute('marker-end', 'url(#arrow)');
314
294
  path.dataset.edgeId = edge.id;
315
295
  group.append(path);
316
-
317
296
  const midpoint = {
318
297
  x: (from.x + NODE_WIDTH + to.x) / 2,
319
298
  y: (from.y + to.y) / 2 + NODE_PORT_Y
@@ -330,19 +309,6 @@ function renderEdges() {
330
309
  event.stopPropagation();
331
310
  deleteEdge(edge.id);
332
311
  };
333
- let hideTimer;
334
- path.onpointerenter = () => {
335
- clearTimeout(hideTimer);
336
- control.classList.add('visible');
337
- };
338
- path.onpointerleave = () => {
339
- hideTimer = setTimeout(() => control.classList.remove('visible'), 100);
340
- };
341
- control.onpointerenter = () => {
342
- clearTimeout(hideTimer);
343
- control.classList.add('visible');
344
- };
345
- control.onpointerleave = () => control.classList.remove('visible');
346
312
  controls.append(control);
347
313
  const label = edgeLoopLabel(edge);
348
314
  if (label) {
@@ -354,478 +320,64 @@ function renderEdges() {
354
320
  controls.append(badge);
355
321
  }
356
322
  });
357
- for (const loopGroup of draft.loopGroups || []) {
358
- const from = positions.get(loopGroup.decisionNodeId);
359
- const to = positions.get(loopGroup.repeatTargetId);
360
- const bounds = loopBounds(loopGroup);
361
- if (!from || !to || !bounds) continue;
362
- const returnPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
363
- returnPath.setAttribute(
364
- 'd',
365
- `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}`
366
- );
367
- returnPath.setAttribute('class', 'edge loop-return');
368
- returnPath.setAttribute('marker-end', 'url(#arrow)');
369
- group.append(returnPath);
370
- const label = document.createElement('span');
371
- label.className = 'edge-label loop-label';
372
- label.style.left = `${bounds.right + 28}px`;
373
- label.style.top = `${bounds.top - 18}px`;
374
- label.textContent = loopGroup.repeatLabel;
375
- controls.append(label);
376
- }
377
323
  }
378
324
 
379
325
  function nodeMarkup(node, index) {
380
326
  const runtimeNode = catalog.live?.nodes?.[node.id];
381
- const lifecycleActivity = activeLifecycleNodeId() === node.id
382
- ? activeLifecycleEvent()?.message
383
- : '';
384
- const outgoing = draft.edges.some((edge) => edge.from === node.id);
385
- const root = rootCandidates().length === 1 && rootCandidates()[0].id === node.id;
386
327
  return `
387
328
  <button class="port port-in" aria-label="Input for ${escapeHtml(node.id)}" tabindex="-1"></button>
388
329
  <small>${escapeHtml(stageLabel(node, index))} / ${escapeHtml(node.type.toUpperCase())}</small>
389
- <button class="node-title" title="Double-click to edit Display Name">${escapeHtml(displayName(node))}</button>
330
+ <span class="node-title">${escapeHtml(displayName(node))}</span>
390
331
  <span class="technical-id">${escapeHtml(node.id)}</span>
391
- <span class="status">● ${escapeHtml(runtimeNode?.status || 'DRAFT')}</span>
392
- ${runtimeNode?.activity || lifecycleActivity ? `<p class="node-activity">${escapeHtml(runtimeNode?.activity || lifecycleActivity)}</p>` : ''}
332
+ <span class="status">● ${escapeHtml(runtimeNode?.status || 'READY')}</span>
393
333
  <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
394
- ${outgoing ? '' : `<button class="output-add" title="Add connected node" aria-label="Add node connected after ${escapeHtml(displayName(node))}">+</button>`}
395
- ${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>` : ''}
396
334
  `;
397
335
  }
398
336
 
399
- function activeLifecycleEvent() {
400
- const latest = lifecycleEvents.at(-1) || null;
401
- if (!latest || ['NODE_COMPLETED', 'RUN_COMPLETED'].includes(latest.type)) return null;
402
- return latest;
403
- }
404
-
405
- function activeLifecycleNodeId() {
406
- const event = activeLifecycleEvent();
407
- if (event?.nodeId) return event.nodeId;
408
- if (event?.phase) {
409
- const scopedNode = draft?.nodes.find((node) =>
410
- node.id === event.phase || node.type === event.phase || node.legacyGate === event.phase
411
- );
412
- if (scopedNode) return scopedNode.id;
413
- }
414
- if (event?.phase === 'goal' || event?.type?.startsWith('GOAL_')) {
415
- return draft?.nodes.find((node) => node.type === 'goal-contract')?.id || null;
416
- }
417
- return null;
418
- }
419
-
420
337
  function renderGraph() {
338
+ if (!draft) return;
421
339
  ensurePositions();
422
340
  renderLoopGroups();
423
341
  const container = byId('nodes');
342
+ if (!container) return;
424
343
  container.innerHTML = '';
425
344
  draft.nodes.forEach((node, index) => {
426
345
  const position = positions.get(node.id);
427
346
  const runtimeNode = catalog.live?.nodes?.[node.id];
428
347
  const element = document.createElement('article');
429
348
  element.dataset.nodeId = node.id;
430
- const lifecycleActive = activeLifecycleNodeId() === node.id &&
431
- !['DISCONNECTED', 'UNKNOWN'].includes(agentPresence.status);
432
- element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${lifecycleActive ? 'agent-active' : ''} ${selectedIds.has(node.id) ? 'selected' : ''}`;
349
+ element.className = `node ${graphStateClass(runtimeNode?.status)} ${selectedIds.has(node.id) ? 'selected' : ''}`;
433
350
  element.style.left = `${position.x}px`;
434
351
  element.style.top = `${position.y}px`;
435
352
  element.innerHTML = nodeMarkup(node, index);
436
353
  element.addEventListener('pointerdown', beginNodeInteraction);
437
- element.querySelector('.port-out').addEventListener('pointerdown', beginConnection);
438
- element.querySelector('.node-title').addEventListener('dblclick', beginInlineRename);
439
- element.querySelector('.output-add')?.addEventListener('click', openContextualAdd);
440
- element.querySelector('.execute-trigger')?.addEventListener('click', executeFromTrigger);
354
+ element.querySelector('.port-out')?.addEventListener('pointerdown', beginConnection);
441
355
  container.append(element);
442
356
  });
443
357
  renderEdges();
444
358
  applyViewport();
445
359
  }
446
360
 
447
- function updateRuntimePresentation() {
448
- if (!draft) return;
449
- for (const element of document.querySelectorAll('.node')) {
450
- const nodeId = element.dataset.nodeId;
451
- const runtimeNode = catalog.live?.nodes?.[nodeId];
452
- element.classList.remove('running', 'passed', 'failed', 'blocked', 'ready', 'pending', 'skipped', 'agent-active', 'agent-idle', 'agent-disconnected');
453
- if (runtimeNode?.status) element.classList.add(runtimeNode.status.toLowerCase());
454
- if (activeLifecycleNodeId() === nodeId) {
455
- if (agentPresence.status === 'WORKING') element.classList.add('agent-active');
456
- if (agentPresence.status === 'IDLE') element.classList.add('agent-idle');
457
- if (agentPresence.status === 'DISCONNECTED') element.classList.add('agent-disconnected');
458
- }
459
- element.querySelector('.status').textContent = `● ${runtimeNode?.status || 'DRAFT'}`;
460
- const existingActivity = element.querySelector('.node-activity');
461
- const lifecycleActivity = activeLifecycleNodeId() === nodeId
462
- ? activeLifecycleEvent()?.message
463
- : '';
464
- const activity = runtimeNode?.activity || lifecycleActivity;
465
- if (activity) {
466
- if (existingActivity) existingActivity.textContent = activity;
467
- else element.querySelector('.status').insertAdjacentHTML('afterend', `<p class="node-activity">${escapeHtml(activity)}</p>`);
468
- } else {
469
- existingActivity?.remove();
470
- }
471
- }
472
- renderLoopGroups();
473
- renderEdges();
474
- }
475
-
476
361
  function updateSelection() {
477
- document.querySelectorAll('.node').forEach((element) => {
362
+ document.querySelectorAll?.('.node')?.forEach?.((element) => {
478
363
  element.classList.toggle('selected', selectedIds.has(element.dataset.nodeId));
479
364
  });
480
- const actions = byId('selection-actions');
481
- actions.hidden = selectedIds.size < 2;
482
- byId('selection-count').textContent = `${selectedIds.size} nodes`;
483
- const grouped = [...selectedIds].some((nodeId) =>
484
- (draft?.loopGroups || []).some((group) => group.nodeIds.includes(nodeId))
485
- );
486
- byId('create-loop-group').disabled = grouped;
487
- byId('create-loop-group').title = grouped ? 'Ungroup selected steps before creating another Loop Group' : '';
488
- }
489
-
490
- function renderRecipeDetails() {
491
- const existing = recipeSummary();
492
- byId('inspector-label').textContent = 'WORKFLOW';
493
- byId('inspector-title').textContent = draft.id;
494
- byId('inspector-title').contentEditable = 'false';
495
- byId('inspector-title').onkeydown = null;
496
- byId('inspector-title').onblur = null;
497
- byId('details').innerHTML = `
498
- <div class="source-line"><span>${escapeHtml(source.toUpperCase())}</span><span>${draft.nodes.length} NODES</span></div>
499
- <label for="recipe-id">Name</label><input id="recipe-id" value="${escapeHtml(draft.id)}">
500
- <label for="recipe-description">Description</label><textarea id="recipe-description">${escapeHtml(draft.description)}</textarea>
501
- ${existing?.source === 'builtin' ? '<p class="hint">Saving creates a project copy. The built-in remains unchanged.</p>' : ''}
502
- <details>
503
- <summary>Advanced settings</summary>
504
- <div class="settings-body">
505
- <label for="recipe-version">Version</label><input id="recipe-version" type="number" min="1" value="${escapeHtml(draft.version)}">
506
- <label for="recipe-modes">Run modes</label>
507
- <select id="recipe-modes" multiple>
508
- ${['REPORT_ONLY', 'ASSISTED', 'UNATTENDED'].map((mode) => `<option ${draft.compatibleModes.includes(mode) ? 'selected' : ''}>${mode}</option>`).join('')}
509
- </select>
510
- </div>
511
- </details>
512
- <button id="apply-recipe">Apply changes</button>
513
- `;
514
- byId('apply-recipe').onclick = applyRecipeDetails;
515
365
  }
516
366
 
517
367
  function selectNode(nodeId, { additive = false } = {}) {
518
- const node = draft.nodes.find((candidate) => candidate.id === nodeId);
519
- if (!node) return;
520
368
  if (additive) {
521
369
  if (selectedIds.has(nodeId)) selectedIds.delete(nodeId);
522
370
  else selectedIds.add(nodeId);
523
371
  } else {
524
372
  selectedIds = new Set([nodeId]);
525
373
  }
526
- selectedEdgeId = null;
527
374
  selectedId = nodeId;
375
+ selectedEdgeId = null;
528
376
  updateSelection();
529
- const runtimeNode = catalog.live?.nodes?.[nodeId];
530
- byId('inspector-label').textContent = 'NODE';
531
- byId('inspector-title').textContent = displayName(node);
532
- byId('inspector-title').contentEditable = 'true';
533
- byId('inspector-title').title = 'Edit Display Name';
534
- byId('inspector-title').onkeydown = (event) => {
535
- if (event.key === 'Enter') {
536
- event.preventDefault();
537
- event.currentTarget.blur();
538
- } else if (event.key === 'Escape') {
539
- event.currentTarget.textContent = displayName(node);
540
- event.currentTarget.blur();
541
- }
542
- };
543
- byId('inspector-title').onblur = (event) => applyDisplayName(node, event.currentTarget.textContent);
544
- byId('inspector-panel').classList.add('open');
545
- byId('details').innerHTML = `
546
- <div class="source-line"><span>${escapeHtml(node.type.toUpperCase())}</span><span>${escapeHtml(runtimeNode?.status || 'DRAFT')}</span></div>
547
- <div id="name-validation" class="validation-message" aria-live="polite"></div>
548
- <label for="node-id">Technical ID</label><input id="node-id" value="${escapeHtml(node.id)}" disabled>
549
- ${node.type === 'delivery' ? deliveryAdapterControls() : ''}
550
- <details>
551
- <summary>Settings</summary>
552
- <div class="settings-body">
553
- <label>Type</label><input value="${escapeHtml(node.type)}" disabled>
554
- <label for="node-dependencies">Inputs</label>
555
- <input id="node-dependencies" value="${escapeHtml((node.dependsOn || []).join(', '))}" placeholder="Connect nodes on the canvas">
556
- ${node.type === 'agent' ? `
557
- <label for="node-extra">Role</label><input id="node-extra" value="${escapeHtml(node.role || '')}">
558
- ${node.prompt != null ? customAgentFields(node) : ''}
559
- <label for="node-tokens">Token limit</label><input id="node-tokens" type="number" min="1" value="${escapeHtml(node.context?.maxTokens || '')}">
560
- ` : node.type === 'approval' ? `
561
- <label for="node-extra">Approval message</label><textarea id="node-extra">${escapeHtml(node.message || '')}</textarea>
562
- ` : node.type === 'condition' ? `
563
- <label for="condition-field">Field</label>
564
- <select id="condition-field">${['run.mode', 'run.state', 'run.iteration', 'run.task'].map((field) => `<option ${node.expression?.field === field ? 'selected' : ''}>${field}</option>`).join('')}</select>
565
- <label for="condition-operator">Rule</label>
566
- <select id="condition-operator">${['equals', 'notEquals', 'contains', 'exists', 'isEmpty', 'greaterThan', 'lessThan'].map((operator) => `<option ${node.expression?.operator === operator ? 'selected' : ''}>${operator}</option>`).join('')}</select>
567
- <label for="condition-value">Value</label><input id="condition-value" value="${escapeHtml(node.expression?.value ?? '')}">
568
- ` : ''}
569
- </div>
570
- </details>
571
- <div class="button-row"><button id="apply-node">Apply</button>${catalog.nodeTypes.find((type) => type.type === node.type)?.builtIn ? '' : '<button id="duplicate-node">Duplicate</button>'}<button id="delete-node" class="danger">Delete</button></div>
572
- ${runtimeControls(node, runtimeNode)}
573
- `;
574
- byId('apply-node').onclick = applyNodeDetails;
575
- if (byId('duplicate-node')) byId('duplicate-node').onclick = duplicateSelectedNode;
576
- byId('delete-node').onclick = deleteSelectedNode;
577
- if (byId('select-adapter')) byId('select-adapter').onclick = selectDeliveryAdapter;
578
- if (byId('generate-adapter')) byId('generate-adapter').onclick = copyAdapterBuilderPrompt;
579
- bindRuntimeControls(node);
580
- }
581
-
582
- function customAgentFields(node) {
583
- return `
584
- <label for="custom-node-prompt">Prompt</label><textarea id="custom-node-prompt">${escapeHtml(node.prompt || '')}</textarea>
585
- <label for="custom-node-capabilities">Capabilities</label><input id="custom-node-capabilities" value="${escapeHtml((node.capabilityRefs || []).join(', '))}">
586
- <label for="custom-node-mcp">MCP references</label><input id="custom-node-mcp" value="${escapeHtml((node.mcpRefs || []).join(', '))}">
587
- <label for="custom-node-inputs">Input artifacts</label><input id="custom-node-inputs" value="${escapeHtml((node.inputArtifacts || []).join(', '))}">
588
- <label for="custom-node-output">Output artifact</label><input id="custom-node-output" value="${escapeHtml(node.outputArtifacts?.[0]?.artifact || '')}">
589
- <label for="custom-node-schema">Output schema</label><input id="custom-node-schema" value="${escapeHtml(node.outputArtifacts?.[0]?.schema || 'schemas/report.schema.json')}">
590
- <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))}">
591
- <label for="custom-node-retries">Maximum attempts</label><input id="custom-node-retries" type="number" min="1" value="${escapeHtml(node.retry?.maxAttempts ?? 2)}">
592
- `;
593
- }
594
-
595
- function applyDisplayName(node, value) {
596
- const error = validDisplayName(value);
597
- const message = byId('name-validation');
598
- if (error) {
599
- if (message) message.textContent = error;
600
- byId('inspector-title').textContent = displayName(node);
601
- return false;
602
- }
603
- const next = value.trim();
604
- if (next === displayName(node)) return true;
605
- node.displayName = next;
606
- captureHistory();
607
- renderGraph();
608
- selectNode(node.id);
609
- return true;
610
- }
611
-
612
- function beginInlineRename(event) {
613
- event.preventDefault();
614
- event.stopPropagation();
615
- const node = draft.nodes.find((candidate) => candidate.id === event.currentTarget.closest('.node').dataset.nodeId);
616
- const input = document.createElement('input');
617
- input.className = 'inline-rename';
618
- input.maxLength = DISPLAY_NAME_MAX;
619
- input.value = displayName(node);
620
- event.currentTarget.replaceWith(input);
621
- input.focus();
622
- input.select();
623
- let saved = false;
624
- const finish = () => {
625
- if (saved) return;
626
- saved = true;
627
- const error = validDisplayName(input.value);
628
- if (error) notify(error);
629
- else if (input.value.trim() !== displayName(node)) {
630
- node.displayName = input.value.trim();
631
- captureHistory();
632
- }
633
- renderGraph();
634
- selectNode(node.id);
635
- };
636
- input.onkeydown = (keyEvent) => {
637
- if (keyEvent.key === 'Enter') input.blur();
638
- if (keyEvent.key === 'Escape') {
639
- input.value = displayName(node);
640
- input.blur();
641
- }
642
- };
643
- input.onblur = finish;
644
- }
645
-
646
- function deliveryAdapterControls() {
647
- const current = catalog.adapters.current;
648
- const options = [...catalog.adapters.types];
649
- if (current && !options.includes(current)) options.push(current);
650
- return `
651
- <section class="adapter-controls">
652
- <label for="delivery-adapter">Delivery adapter</label>
653
- <select id="delivery-adapter">
654
- ${options.map((type) => `<option ${type === (current || catalog.adapters.recommended) ? 'selected' : ''}>${escapeHtml(type)}</option>`).join('')}
655
- </select>
656
- <p class="hint">${current
657
- ? `${escapeHtml(current)} is active for this project.`
658
- : `Recommended: ${escapeHtml(catalog.adapters.recommended)}.`}</p>
659
- <div class="button-row"><button id="select-adapter">Use adapter</button><button id="generate-adapter">Create custom</button></div>
660
- </section>
661
- `;
662
- }
663
-
664
- async function selectDeliveryAdapter() {
665
- const type = byId('delivery-adapter').value;
666
- if (!catalog.adapters.types.includes(type)) {
667
- return notify('Custom adapters are changed through the guarded AI adapter builder.');
668
- }
669
- try {
670
- await api('/api/adapter/select', { method: 'POST', body: JSON.stringify({ type }) });
671
- catalog.adapters.current = type;
672
- selectNode(selectedId);
673
- notify(`${type} is now the project Stage 8 adapter.`);
674
- } catch (error) {
675
- notify(error.message);
676
- }
677
- }
678
-
679
- async function copyAdapterBuilderPrompt() {
680
- const prompt = [
681
- 'Use the ai-engineering-loop generate-adapter skill for this repository.',
682
- 'Ask Q1-Q5 before writing. Build a custom Stage 8 delivery adapter only.',
683
- 'Preserve Stages 0-7, require Judge PASS, never store credentials, and use explicit approval for remote side effects.',
684
- 'After validation, write .ai-engineering-loop/adapter.md so Workflow Studio discovers it.'
685
- ].join(' ');
686
- try {
687
- await navigator.clipboard.writeText(prompt);
688
- notify('Guarded custom-adapter prompt copied for your AI agent.');
689
- } catch (error) {
690
- notify(error.message);
691
- }
692
- }
693
-
694
- function runtimeControls(node, runtimeNode) {
695
- if (!catalog.live || !runtimeNode) return '';
696
- const approve = node.type === 'approval' && runtimeNode.status === 'READY' ? '<button id="approve-node">APPROVE</button>' : '';
697
- const retry = ['FAILED', 'RUNNING'].includes(runtimeNode.status) ? '<button id="retry-node">RETRY</button>' : '';
698
- const custom = node.type === 'agent' && node.prompt && ['READY', 'RUNNING'].includes(runtimeNode.status) ? `
699
- <p class="hint">This node is waiting for an external operator. Studio does not execute the agent independently.</p>
700
- <button id="copy-agent-command">Copy command</button>
701
- ${runtimeNode.status === 'READY'
702
- ? '<button id="start-agent-node">Mark running</button>'
703
- : '<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>'}
704
- ` : '';
705
- const activity = runtimeNode.status === 'RUNNING'
706
- ? '<label for="runtime-activity">SAFE ACTIVITY UPDATE</label><input id="runtime-activity" maxlength="240"><button id="send-activity">REPORT ACTIVITY</button>'
707
- : '';
708
- return approve || retry || activity || custom
709
- ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${custom}${activity}<div class="button-row">${approve}${retry}</div></section>`
710
- : '';
711
- }
712
-
713
- function bindRuntimeControls(node) {
714
- const runId = catalog.live?.run?.runId;
715
- if (byId('approve-node')) byId('approve-node').onclick = () => mutateNode('/api/node/approve', { runId, nodeId: node.id });
716
- if (byId('retry-node')) byId('retry-node').onclick = () => mutateNode('/api/node/retry', { runId, nodeId: node.id });
717
- if (byId('send-activity')) {
718
- byId('send-activity').onclick = () => mutateNode('/api/node/activity', {
719
- runId, nodeId: node.id, message: byId('runtime-activity').value
720
- });
721
- }
722
- if (byId('copy-agent-command')) byId('copy-agent-command').onclick = async () => {
723
- await navigator.clipboard.writeText(`ai-engineering-loop node start ${node.id} --run ${runId}`);
724
- notify('External operator command copied.');
725
- };
726
- if (byId('start-agent-node')) byId('start-agent-node').onclick = () => mutateNode('/api/node/start', { runId, nodeId: node.id });
727
- if (byId('complete-agent-node')) byId('complete-agent-node').onclick = () => mutateNode('/api/node/complete', {
728
- runId,
729
- nodeId: node.id,
730
- artifact: byId('agent-evidence').value.trim()
731
- });
732
- }
733
-
734
- async function mutateNode(endpoint, body) {
735
- try {
736
- await api(endpoint, { method: 'POST', body: JSON.stringify(body) });
737
- await refreshLive();
738
- if (selectedId) selectNode(selectedId);
739
- } catch (error) {
740
- notify(error.message);
741
- }
742
- }
743
-
744
- function applyRecipeDetails() {
745
- draft.id = byId('recipe-id').value.trim();
746
- draft.version = Number(byId('recipe-version').value);
747
- draft.description = byId('recipe-description').value.trim();
748
- draft.compatibleModes = [...byId('recipe-modes').selectedOptions].map((option) => option.value);
749
- captureHistory();
750
- renderGraph();
751
- renderRecipeDetails();
752
- validateDraft();
753
- }
754
-
755
- function applyNodeDetails() {
756
- const node = draft.nodes.find((candidate) => candidate.id === selectedId);
757
- if (!node) return;
758
- if (!applyDisplayName(node, byId('inspector-title').textContent)) return;
759
- const inputs = csv(byId('node-dependencies').value);
760
- draft.edges = draft.edges.filter((edge) => edge.to !== node.id);
761
- inputs.forEach((from, index) => {
762
- if (from !== node.id && draft.nodes.some((candidate) => candidate.id === from)) {
763
- draft.edges.push({ id: uniqueEdgeId(from, node.id), from, to: node.id });
764
- }
765
- });
766
- syncDependencies();
767
- if (node.type === 'agent') {
768
- node.role = byId('node-extra').value.trim();
769
- node.context = { ...(node.context || {}), maxTokens: Number(byId('node-tokens').value) };
770
- if (node.prompt != null) {
771
- node.prompt = byId('custom-node-prompt').value.trim();
772
- node.capabilityRefs = csv(byId('custom-node-capabilities').value);
773
- node.mcpRefs = csv(byId('custom-node-mcp').value);
774
- node.inputArtifacts = csv(byId('custom-node-inputs').value);
775
- node.outputArtifacts = [{
776
- artifact: byId('custom-node-output').value.trim(),
777
- schema: byId('custom-node-schema').value.trim()
778
- }];
779
- node.tokenLimit = Number(byId('node-tokens').value);
780
- node.timeoutMs = Number(byId('custom-node-timeout').value) * 1000;
781
- node.retry = {
782
- maxAttempts: Number(byId('custom-node-retries').value),
783
- backoffMs: node.retry?.backoffMs || 1000
784
- };
785
- }
786
- } else if (node.type === 'approval') {
787
- node.message = byId('node-extra').value.trim();
788
- } else if (node.type === 'condition') {
789
- const field = byId('condition-field').value;
790
- const operator = byId('condition-operator').value;
791
- const rawValue = byId('condition-value').value.trim();
792
- node.expression = { field, operator };
793
- if (!['exists', 'isEmpty'].includes(operator)) {
794
- node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator) ? Number(rawValue) : rawValue;
795
- }
796
- }
797
- captureHistory();
798
- renderGraph();
799
- selectNode(node.id);
800
- validateDraft();
801
- saveLayoutSoon();
802
- }
803
-
804
- function deleteSelectedNode() {
805
- if (!selectedIds.size) return;
806
- const removed = new Set(selectedIds);
807
- const containingGroup = (draft.loopGroups || []).find((group) =>
808
- group.nodeIds.some((nodeId) => removed.has(nodeId))
809
- );
810
- if (containingGroup) {
811
- notify(`Ungroup “${containingGroup.displayName}” before deleting its steps.`);
812
- return;
813
- }
814
- draft.nodes = draft.nodes.filter((node) => !removed.has(node.id));
815
- draft.edges = draft.edges.filter((edge) => !removed.has(edge.from) && !removed.has(edge.to));
816
- syncDependencies();
817
- removed.forEach((id) => positions.delete(id));
818
- selectedId = null;
819
- selectedIds.clear();
820
- captureHistory();
821
- renderGraph();
822
- renderRecipeDetails();
823
- byId('inspector-panel').classList.remove('open');
824
- validateDraft();
825
- saveLayoutSoon();
826
377
  }
827
378
 
828
379
  function deleteEdge(id) {
380
+ if (!draft) return;
829
381
  const before = draft.edges.length;
830
382
  draft.edges = draft.edges.filter((edge) => edge.id !== id);
831
383
  if (draft.edges.length === before) return;
@@ -836,103 +388,34 @@ function deleteEdge(id) {
836
388
  validateDraft();
837
389
  }
838
390
 
839
- function uniqueNodeId(type) {
840
- let suffix = draft.nodes.length + 1;
841
- while (draft.nodes.some((node) => node.id === `${type}-${suffix}`)) suffix += 1;
842
- return `${type}-${suffix}`;
843
- }
844
-
845
- function createNode(type, id = uniqueNodeId(type)) {
846
- const label = catalog.nodeTypes.find((candidate) => candidate.type === type)?.label || type.replaceAll('-', ' ');
847
- const node = { id, type, displayName: label, dependsOn: [] };
848
- if (type === 'agent') {
849
- Object.assign(node, {
850
- role: 'analyst',
851
- context: { maxFiles: 10, maxTokens: 4000 },
852
- output: { artifact: `${id}-output`, schema: 'schemas/report.schema.json' }
853
- });
854
- } else if (type === 'approval') {
855
- node.message = 'Approve continuation.';
856
- } else if (type === 'condition') {
857
- node.expression = { field: 'run.mode', operator: 'equals', value: 'ASSISTED' };
858
- }
859
- return node;
860
- }
861
-
862
- function addNode(type, position = worldAtCanvasCenter()) {
863
- const node = createNode(type);
864
- draft.nodes.push(node);
865
- if (pendingConnectionSource) {
866
- draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, node.id), from: pendingConnectionSource, to: node.id });
867
- syncDependencies();
868
- pendingConnectionSource = null;
869
- }
870
- positions.set(node.id, { x: position.x - NODE_WIDTH / 2, y: position.y - NODE_PORT_Y });
391
+ function addEdge(from, to) {
392
+ if (!draft || from === to) return false;
393
+ if (draft.edges.some((edge) => edge.from === from && edge.to === to)) return false;
394
+ if (transitivelyDependsOn(from, to)) return false;
395
+ if (!draft.nodes.some((node) => node.id === from) || !draft.nodes.some((node) => node.id === to)) return false;
396
+ draft.edges.push({ id: uniqueEdgeId(from, to), from, to });
397
+ syncDependencies();
871
398
  captureHistory();
872
399
  renderGraph();
873
- selectNode(node.id);
874
- byId('library-panel').classList.remove('open');
875
400
  validateDraft();
401
+ return true;
876
402
  }
877
403
 
878
- function duplicateSelectedNode() {
879
- if (!selectedIds.size) return;
880
- const originals = draft.nodes.filter((node) => selectedIds.has(node.id));
881
- const mapping = new Map();
882
- const clones = originals.map((original) => {
883
- const clone = structuredClone(original);
884
- clone.id = uniqueNodeId(original.type);
885
- while (draft.nodes.some((node) => node.id === clone.id) || mapping.has(clone.id)) clone.id = `${clone.id}-copy`;
886
- clone.displayName = `${displayName(original)} copy`;
887
- if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
888
- mapping.set(original.id, clone.id);
889
- const originalPosition = positions.get(original.id);
890
- positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
891
- draft.nodes.push(clone);
892
- return clone;
893
- });
894
- const copiedEdges = draft.edges.filter((edge) => mapping.has(edge.from) && mapping.has(edge.to)).map((edge) => ({
895
- id: uniqueEdgeId(mapping.get(edge.from), mapping.get(edge.to)),
896
- from: mapping.get(edge.from),
897
- to: mapping.get(edge.to)
898
- }));
899
- draft.edges.push(...copiedEdges);
404
+ function repointEdge(id, from, to) {
405
+ const edge = draft?.edges.find((candidate) => candidate.id === id);
406
+ if (!edge) return false;
407
+ edge.from = from;
408
+ edge.to = to;
900
409
  syncDependencies();
901
- const cloneIds = new Set(clones.map((node) => node.id));
902
- selectedId = clones.at(-1)?.id;
903
410
  captureHistory();
904
411
  renderGraph();
905
- if (selectedId) selectNode(selectedId);
906
- selectedIds = cloneIds;
907
- updateSelection();
908
412
  validateDraft();
909
- }
910
-
911
- function openContextualAdd(event) {
912
- event.stopPropagation();
913
- pendingConnectionSource = event.currentTarget.closest('.node').dataset.nodeId;
914
- byId('library-panel').classList.add('open');
915
- }
916
-
917
- function renderPalette() {
918
- byId('palette').innerHTML = catalog.nodeTypes.filter((node) => node.executable).map((node) => `
919
- <button class="palette-item" draggable="true" data-node-type="${escapeHtml(node.type)}">
920
- <b>${escapeHtml(node.label)}</b><small>${escapeHtml(node.category.toUpperCase())}</small>
921
- </button>
922
- `).join('');
923
- document.querySelectorAll('[data-node-type]').forEach((button) => {
924
- button.onclick = () => addNode(button.dataset.nodeType);
925
- button.ondragstart = (event) => {
926
- event.dataTransfer.setData('application/x-ael-node-type', button.dataset.nodeType);
927
- event.dataTransfer.effectAllowed = 'copy';
928
- };
929
- });
413
+ return true;
930
414
  }
931
415
 
932
416
  function beginNodeInteraction(event) {
933
- if (event.button !== 0 || event.target.closest('.port,.output-add,.execute-pod,.node-title,.inline-rename')) return;
417
+ if (event.button !== 0 || event.target.closest?.('.port')) return;
934
418
  event.stopPropagation();
935
- setFollowExecution(false);
936
419
  const element = event.currentTarget;
937
420
  const nodeId = element.dataset.nodeId;
938
421
  if (event.shiftKey) {
@@ -953,13 +436,12 @@ function beginNodeInteraction(event) {
953
436
  origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }]))
954
437
  };
955
438
  element.classList.add('dragging');
956
- element.setPointerCapture(event.pointerId);
439
+ element.setPointerCapture?.(event.pointerId);
957
440
  }
958
441
 
959
442
  function beginPan(event) {
960
443
  if (event.button !== 0 && event.button !== 1) return;
961
444
  event.preventDefault();
962
- setFollowExecution(false);
963
445
  interaction = {
964
446
  type: 'pan',
965
447
  pointerId: event.pointerId,
@@ -968,16 +450,20 @@ function beginPan(event) {
968
450
  viewportX: viewport.x,
969
451
  viewportY: viewport.y
970
452
  };
971
- byId('canvas').setPointerCapture(event.pointerId);
453
+ byId('canvas').setPointerCapture?.(event.pointerId);
972
454
  }
973
455
 
974
456
  function handlePointerMove(event) {
975
457
  if (connection) {
976
458
  const from = positions.get(connection.sourceId);
977
- const target = screenToWorld(event.clientX, event.clientY);
978
- const start = { x: from.x + NODE_WIDTH, y: from.y + NODE_PORT_Y };
979
- const bend = Math.max(55, Math.abs(target.x - start.x) * 0.42);
980
- byId('preview-edge').setAttribute('d', `M${start.x} ${start.y} C${start.x + bend} ${start.y},${target.x - bend} ${target.y},${target.x} ${target.y}`);
459
+ const preview = scenePart('.preview-edge');
460
+ if (from && preview?.setAttribute) {
461
+ const target = screenToWorld(event.clientX, event.clientY);
462
+ const start = { x: from.x + NODE_WIDTH, y: from.y + NODE_PORT_Y };
463
+ const bend = Math.max(55, Math.abs(target.x - start.x) * 0.42);
464
+ preview.style.display = 'block';
465
+ preview.setAttribute('d', `M${start.x} ${start.y} C${start.x + bend} ${start.y},${target.x - bend} ${target.y},${target.x} ${target.y}`);
466
+ }
981
467
  return;
982
468
  }
983
469
  if (!interaction || interaction.pointerId !== event.pointerId) return;
@@ -989,22 +475,13 @@ function handlePointerMove(event) {
989
475
  interaction.origins.forEach((start, id) => {
990
476
  const next = { x: start.x + delta.x, y: start.y + delta.y };
991
477
  positions.set(id, next);
992
- const nodeElement = document.querySelector(`.node[data-node-id="${CSS.escape(id)}"]`);
478
+ const nodeElement = document.querySelector?.(`.node[data-node-id="${CSS.escape(id)}"]`);
993
479
  if (nodeElement) {
994
480
  nodeElement.style.left = `${next.x}px`;
995
481
  nodeElement.style.top = `${next.y}px`;
996
482
  }
997
483
  });
998
484
  renderEdges();
999
- } else if (interaction.type === 'group') {
1000
- const world = screenToWorld(event.clientX, event.clientY);
1001
- const delta = { x: world.x - interaction.start.x, y: world.y - interaction.start.y };
1002
- interaction.origins.forEach((start, id) => {
1003
- positions.set(id, { x: start.x + delta.x, y: start.y + delta.y });
1004
- });
1005
- renderGraph();
1006
- } else if (interaction.type === 'lasso') {
1007
- updateLasso(event);
1008
485
  } else {
1009
486
  viewport.x = interaction.viewportX + event.clientX - interaction.startX;
1010
487
  viewport.y = interaction.viewportY + event.clientY - interaction.startY;
@@ -1015,10 +492,7 @@ function handlePointerMove(event) {
1015
492
  function finishPointer(event) {
1016
493
  if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
1017
494
  if (!interaction || interaction.pointerId !== event.pointerId) return;
1018
- if (interaction.type === 'node' || interaction.type === 'group') {
1019
- interaction.element.classList.remove('dragging');
1020
- captureHistory();
1021
- } else if (interaction.type === 'lasso') finishLasso();
495
+ if (interaction.type === 'node') interaction.element.classList.remove('dragging');
1022
496
  interaction = null;
1023
497
  saveLayoutSoon();
1024
498
  }
@@ -1028,8 +502,9 @@ function beginConnection(event) {
1028
502
  event.stopPropagation();
1029
503
  const sourceId = event.currentTarget.closest('.node').dataset.nodeId;
1030
504
  connection = { sourceId, pointerId: event.pointerId };
1031
- byId('preview-edge').style.display = 'block';
1032
- event.currentTarget.setPointerCapture(event.pointerId);
505
+ const preview = scenePart('.preview-edge');
506
+ if (preview?.style) preview.style.display = 'block';
507
+ event.currentTarget.setPointerCapture?.(event.pointerId);
1033
508
  }
1034
509
 
1035
510
  function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
@@ -1043,131 +518,177 @@ function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
1043
518
  function finishConnection(event) {
1044
519
  const sourceId = connection.sourceId;
1045
520
  connection = null;
1046
- byId('preview-edge').style.display = 'none';
1047
- const targetElement = document.elementFromPoint(event.clientX, event.clientY)?.closest('.node');
521
+ const preview = scenePart('.preview-edge');
522
+ if (preview?.style) preview.style.display = 'none';
523
+ const targetElement = document.elementFromPoint?.(event.clientX, event.clientY)?.closest?.('.node');
1048
524
  const targetId = targetElement?.dataset.nodeId;
1049
525
  if (!targetId || targetId === sourceId) return;
1050
- const target = draft.nodes.find((node) => node.id === targetId);
1051
526
  if (draft.edges.some((edge) => edge.from === sourceId && edge.to === targetId)) return notify('Nodes are already connected.');
1052
527
  if (transitivelyDependsOn(sourceId, targetId)) return notify('Connection rejected: it would create a cycle.');
1053
- draft.edges.push({ id: uniqueEdgeId(sourceId, targetId), from: sourceId, to: targetId });
1054
- syncDependencies();
1055
- captureHistory();
1056
- renderGraph();
1057
- selectNode(targetId);
1058
- validateDraft();
1059
- }
1060
-
1061
- function beginLasso(event) {
1062
- setFollowExecution(false);
1063
- const start = screenToWorld(event.clientX, event.clientY);
1064
- interaction = { type: 'lasso', pointerId: event.pointerId, start, current: start, additive: event.shiftKey };
1065
- const marquee = byId('selection-marquee');
1066
- marquee.style.display = 'block';
1067
- marquee.style.left = `${start.x}px`;
1068
- marquee.style.top = `${start.y}px`;
1069
- marquee.style.width = '0';
1070
- marquee.style.height = '0';
1071
- byId('canvas').setPointerCapture(event.pointerId);
1072
- }
1073
-
1074
- function updateLasso(event) {
1075
- interaction.current = screenToWorld(event.clientX, event.clientY);
1076
- const left = Math.min(interaction.start.x, interaction.current.x);
1077
- const top = Math.min(interaction.start.y, interaction.current.y);
1078
- const right = Math.max(interaction.start.x, interaction.current.x);
1079
- const bottom = Math.max(interaction.start.y, interaction.current.y);
1080
- const marquee = byId('selection-marquee');
1081
- Object.assign(marquee.style, {
1082
- left: `${left}px`, top: `${top}px`, width: `${right - left}px`, height: `${bottom - top}px`
1083
- });
1084
- const next = interaction.additive ? new Set(selectedIds) : new Set();
1085
- positions.forEach((position, id) => {
1086
- if (position.x < right && position.x + NODE_WIDTH > left && position.y < bottom && position.y + 110 > top) next.add(id);
1087
- });
1088
- selectedIds = next;
1089
- selectedId = [...next].at(-1) || null;
1090
- updateSelection();
528
+ addEdge(sourceId, targetId);
1091
529
  }
1092
530
 
1093
- function finishLasso() {
1094
- byId('selection-marquee').style.display = 'none';
1095
- const finalSelection = new Set(selectedIds);
1096
- if (selectedId) selectNode(selectedId);
1097
- selectedIds = finalSelection;
1098
- updateSelection();
531
+ function zoomAt(nextScale, clientX, clientY) {
532
+ const scale = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, nextScale));
533
+ const pivot = clientX == null ? worldAtCanvasCenter() : screenToWorld(clientX, clientY);
534
+ const rect = byId('canvas').getBoundingClientRect();
535
+ const next = clientX == null
536
+ ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }
537
+ : { x: clientX, y: clientY };
538
+ viewport.scale = scale;
539
+ const world = screenToWorld(next.x, next.y);
540
+ viewport.x += (world.x - pivot.x) * scale;
541
+ viewport.y += (world.y - pivot.y) * scale;
542
+ applyViewport();
543
+ saveLayoutSoon();
1099
544
  }
1100
545
 
1101
- function rootCandidates() {
1102
- if (!draft) return [];
1103
- const incoming = new Set(draft.edges.map((edge) => edge.to));
1104
- return draft.nodes.filter((node) => ROOT_TYPES.has(node.type) || !incoming.has(node.id));
546
+ function worldAtCanvasCenter() {
547
+ const rect = byId('canvas').getBoundingClientRect();
548
+ return screenToWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
1105
549
  }
1106
550
 
1107
- async function executeFromTrigger(event) {
1108
- event.stopPropagation();
1109
- const candidates = rootCandidates();
1110
- if (candidates.length !== 1) return notify(`Execute requires exactly one trigger/root; found ${candidates.length}.`);
1111
- const task = event.currentTarget.closest('.execute-pod').querySelector('.task-input').value.trim();
1112
- if (task) byId('goal-task').value = task;
1113
- if (!goal.frozen || !activeRunId) {
1114
- byId('goal-dialog').showModal();
1115
- return notify('Save and freeze the Goal Contract before execution.');
1116
- }
1117
- try {
1118
- await api(`/api/runs/${encodeURIComponent(activeRunId)}/execute`, {
1119
- method: 'POST',
1120
- body: '{}'
1121
- });
1122
- notify('Local runtime started. External AI dispatch remains disabled.');
1123
- await refreshLive();
1124
- } catch (error) {
1125
- notify(error.message);
1126
- }
551
+ function handleWheel(event) {
552
+ event.preventDefault();
553
+ zoomAt(viewport.scale * (event.deltaY < 0 ? 1.08 : 0.92), event.clientX, event.clientY);
1127
554
  }
1128
555
 
1129
- function parseGoalCriteria(value) {
1130
- return String(value || '').split('\n').map((line) => line.trim()).filter(Boolean).map((line, index) => {
1131
- const [statement, evidenceRequired, ...failures] = line.split('|').map((part) => part.trim());
1132
- return {
1133
- id: `AC-${index + 1}`,
1134
- statement,
1135
- evidenceRequired,
1136
- failureCases: failures.filter(Boolean)
1137
- };
1138
- });
556
+ function autoLayout({ record = true } = {}) {
557
+ positions = defaultGraphPositions();
558
+ renderGraph();
559
+ if (record) captureHistory();
560
+ saveLayoutSoon();
1139
561
  }
1140
562
 
1141
- function goalContractFromForm(runId) {
1142
- return {
1143
- schemaVersion: 1,
1144
- runId,
1145
- objective: byId('goal-text').value.trim(),
1146
- acceptanceCriteria: parseGoalCriteria(byId('goal-criteria').value)
1147
- };
563
+ function fitView() {
564
+ if (!draft?.nodes.length) return;
565
+ ensurePositions();
566
+ const canvas = byId('canvas').getBoundingClientRect();
567
+ const xs = draft.nodes.map((node) => positions.get(node.id).x);
568
+ const ys = draft.nodes.map((node) => positions.get(node.id).y);
569
+ const width = Math.max(...xs) - Math.min(...xs) + NODE_WIDTH + 160;
570
+ const height = Math.max(...ys) - Math.min(...ys) + 200;
571
+ viewport.scale = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min(canvas.width / width, canvas.height / height)));
572
+ viewport.x = (canvas.width - width * viewport.scale) / 2 - Math.min(...xs) * viewport.scale + 40;
573
+ viewport.y = (canvas.height - height * viewport.scale) / 2 - Math.min(...ys) * viewport.scale + 40;
574
+ applyViewport();
575
+ saveLayoutSoon();
1148
576
  }
1149
577
 
1150
- function validateGoalForm(contract) {
1151
- if (!byId('goal-task').value.trim()) return 'Task is required.';
1152
- if (!contract.objective) return 'Goal objective is required.';
1153
- if (!contract.acceptanceCriteria.length) return 'Add at least one acceptance failure-table row.';
1154
- for (const criterion of contract.acceptanceCriteria) {
1155
- if (!criterion.statement || !criterion.evidenceRequired || !criterion.failureCases.length) {
1156
- return `${criterion.id} must contain statement | evidence required | failure case.`;
1157
- }
578
+ function captureHistory({ reset = false } = {}) {
579
+ const snapshot = JSON.stringify({ draft, positions: Object.fromEntries(positions) });
580
+ if (reset) {
581
+ history = [snapshot];
582
+ historyIndex = 0;
583
+ } else if (history[historyIndex] !== snapshot) {
584
+ history = history.slice(0, historyIndex + 1);
585
+ history.push(snapshot);
586
+ historyIndex = history.length - 1;
1158
587
  }
1159
- return '';
588
+ if (byId('undo')) byId('undo').disabled = historyIndex <= 0;
589
+ if (byId('redo')) byId('redo').disabled = historyIndex >= history.length - 1;
1160
590
  }
1161
591
 
1162
- async function ensureStudioRun() {
1163
- if (activeRunId && catalog.live?.run && !['DELIVERED', 'REPORTED', 'ESCALATED'].includes(catalog.live.run.state)) {
1164
- return activeRunId;
1165
- }
1166
- const task = byId('goal-task').value.trim();
1167
- const request = {
1168
- task,
1169
- constraints: byId('goal-constraints').value.trim(),
1170
- displayName: byId('goal-run-name').value.trim(),
592
+ function restoreHistory(index) {
593
+ if (index < 0 || index >= history.length) return;
594
+ historyIndex = index;
595
+ const snapshot = JSON.parse(history[index]);
596
+ draft = snapshot.draft;
597
+ positions = new Map(Object.entries(snapshot.positions));
598
+ if (!draft.nodes.some((node) => node.id === selectedId)) selectedId = null;
599
+ renderGraph();
600
+ validateDraft();
601
+ saveLayoutSoon();
602
+ if (byId('undo')) byId('undo').disabled = historyIndex <= 0;
603
+ if (byId('redo')) byId('redo').disabled = historyIndex >= history.length - 1;
604
+ }
605
+
606
+ function saveLayoutSoon() {
607
+ clearTimeout(layoutTimer);
608
+ if (!loadedRecipeId || draft.id !== loadedRecipeId) return;
609
+ layoutTimer = setTimeout(async () => {
610
+ try {
611
+ await api('/api/layout', {
612
+ method: 'PUT',
613
+ body: JSON.stringify({ recipeId: loadedRecipeId, layout: layoutPayload() })
614
+ });
615
+ } catch {
616
+ // Canvas work remains in memory and install still submits the layout.
617
+ }
618
+ }, 350);
619
+ }
620
+
621
+ async function validateDraft() {
622
+ const sequence = ++validationSequence;
623
+ try {
624
+ const result = await api('/api/validate', {
625
+ method: 'POST',
626
+ body: JSON.stringify({ recipe: draft, baseRecipeId: loadedRecipeId })
627
+ });
628
+ if (sequence !== validationSequence) return result;
629
+ const hash = result.plans[0].graphHash;
630
+ byId('integrity').textContent = `VALID / ${hash.slice(0, 8)}…${hash.slice(-4)}`;
631
+ byId('integrity').className = 'valid';
632
+ byId('review').disabled = false;
633
+ byId('review-data').textContent = JSON.stringify({
634
+ recipe: draft.id,
635
+ version: draft.version,
636
+ modes: result.plans.map((plan) => plan.mode),
637
+ nodes: draft.nodes.length,
638
+ graphHashes: result.plans.map((plan) => plan.graphHash)
639
+ }, null, 2);
640
+ return result;
641
+ } catch (error) {
642
+ if (sequence !== validationSequence) return null;
643
+ byId('integrity').textContent = `INVALID / ${error.message}`;
644
+ byId('integrity').className = 'invalid';
645
+ byId('review').disabled = true;
646
+ return null;
647
+ }
648
+ }
649
+
650
+ function parseGoalCriteria(value) {
651
+ return String(value || '').split('\n').map((line) => line.trim()).filter(Boolean).map((line, index) => {
652
+ const [statement, evidenceRequired, ...failures] = line.split('|').map((part) => part.trim());
653
+ return {
654
+ id: `AC-${index + 1}`,
655
+ statement,
656
+ evidenceRequired,
657
+ failureCases: failures.filter(Boolean)
658
+ };
659
+ });
660
+ }
661
+
662
+ function goalContractFromForm(runId) {
663
+ return {
664
+ schemaVersion: 1,
665
+ runId,
666
+ objective: byId('goal-text').value.trim(),
667
+ acceptanceCriteria: parseGoalCriteria(byId('goal-criteria').value)
668
+ };
669
+ }
670
+
671
+ function validateGoalForm(contract) {
672
+ if (!byId('goal-task').value.trim()) return 'Task is required.';
673
+ if (!contract.objective) return 'Goal objective is required.';
674
+ if (!contract.acceptanceCriteria.length) return 'Add at least one acceptance failure-table row.';
675
+ for (const criterion of contract.acceptanceCriteria) {
676
+ if (!criterion.statement || !criterion.evidenceRequired || !criterion.failureCases.length) {
677
+ return `${criterion.id} must contain statement | evidence required | failure case.`;
678
+ }
679
+ }
680
+ return '';
681
+ }
682
+
683
+ async function ensureStudioRun() {
684
+ if (activeRunId && catalog.live?.run && !TERMINAL_RUN_STATES.has(catalog.live.run.state)) {
685
+ return activeRunId;
686
+ }
687
+ const task = byId('goal-task').value.trim();
688
+ const request = {
689
+ task,
690
+ constraints: formField('goal-constraints').value.trim(),
691
+ displayName: formField('goal-run-name').value.trim(),
1171
692
  recipeId: loadedRecipeId,
1172
693
  mode: draft.compatibleModes.includes('ASSISTED') ? 'ASSISTED' : draft.compatibleModes[0]
1173
694
  };
@@ -1195,7 +716,8 @@ async function ensureStudioRun() {
1195
716
  }
1196
717
  activeRunId = created.run.runId;
1197
718
  renderHandoffState();
1198
- await refreshLive();
719
+ await loadLive(activeRunId);
720
+ await loadRuns();
1199
721
  return activeRunId;
1200
722
  }
1201
723
 
@@ -1211,11 +733,12 @@ function resolveActiveRunConflict(run) {
1211
733
  byId('active-run-message').textContent = `${run.displayName || run.runId} · ${run.state}`;
1212
734
  byId('continue-active-run').onclick = async () => {
1213
735
  activeRunId = run.runId;
736
+ selectedCheckoutRun = run.runId;
737
+ pinnedRunId = run.runId;
1214
738
  renderHandoffState();
1215
739
  byId('goal-dialog').close();
1216
- showWorkspace('runs');
1217
- await loadRuns();
1218
- await loadRunDetail(run.runId);
740
+ showWorkspace('live');
741
+ await loadLive(run.runId);
1219
742
  finish('continue');
1220
743
  dialog.close();
1221
744
  };
@@ -1282,12 +805,11 @@ function renderGoalState() {
1282
805
  state.textContent = goal.frozen
1283
806
  ? `Frozen · version ${goal.version} · editing locked`
1284
807
  : `Draft · version ${goal.version} · editing allowed`;
1285
- byId('goal-version').textContent = `V${goal.version}`;
1286
808
  byId('goal-text').disabled = goal.frozen;
1287
809
  byId('goal-criteria').disabled = goal.frozen;
1288
810
  byId('goal-task').disabled = goal.frozen;
1289
- byId('goal-constraints').disabled = goal.frozen;
1290
- byId('goal-run-name').disabled = goal.frozen;
811
+ formField('goal-constraints').disabled = goal.frozen;
812
+ formField('goal-run-name').disabled = goal.frozen;
1291
813
  byId('save-goal').hidden = goal.frozen;
1292
814
  byId('review-goal').hidden = goal.frozen;
1293
815
  byId('confirm-freeze').hidden = true;
@@ -1298,7 +820,7 @@ async function reviewGoal() {
1298
820
  const contract = await saveGoalFromForm();
1299
821
  if (!contract) return;
1300
822
  byId('goal-dialog').showModal();
1301
- byId('goal-dialog').querySelector('.advanced-goal').open = true;
823
+ byId('goal-advanced').open = true;
1302
824
  byId('goal-review').hidden = false;
1303
825
  byId('goal-review').innerHTML = `
1304
826
  <strong>${escapeHtml(contract.objective)}</strong>
@@ -1345,20 +867,20 @@ async function freezeGoalFromForm() {
1345
867
  }
1346
868
 
1347
869
  async function unfreezeGoalFromForm() {
1348
- const fields = byId('unfreeze-fields');
1349
- if (fields.hidden) {
1350
- fields.hidden = false;
1351
- byId('unfreeze-reason').focus();
870
+ const reason = byId('unfreeze-reason');
871
+ if (reason.hidden) {
872
+ reason.hidden = false;
873
+ reason.focus?.();
1352
874
  return;
1353
875
  }
1354
876
  try {
1355
877
  const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/unfreeze`, {
1356
878
  method: 'POST',
1357
- body: JSON.stringify({ actor: 'studio-user', reason: byId('unfreeze-reason').value })
879
+ body: JSON.stringify({ actor: 'studio-user', reason: reason.value })
1358
880
  });
1359
881
  goal.frozen = false;
1360
882
  goal.version = result.run.goal.version;
1361
- fields.hidden = true;
883
+ reason.hidden = true;
1362
884
  renderGoalState();
1363
885
  renderGraph();
1364
886
  notify('Goal unfrozen. Previous evidence remains bound to its prior version.');
@@ -1377,156 +899,66 @@ function syncGoalFromLive() {
1377
899
  }
1378
900
  activeRunId = nextRunId;
1379
901
  renderHandoffState();
1380
- if (!liveGoal) {
1381
- renderGoalState();
1382
- return;
1383
- }
1384
- goal.version = liveGoal.version || 1;
1385
- goal.frozen = liveGoal.frozen === true;
1386
- if (catalog.live.run.task) byId('goal-task').value = catalog.live.run.task;
1387
- if (catalog.live.run.constraints) byId('goal-constraints').value = catalog.live.run.constraints;
1388
- if (catalog.live.run.displayName) byId('goal-run-name').value = catalog.live.run.displayName;
1389
- renderGoalState();
1390
- }
1391
-
1392
- async function refreshGoalDraft(runId) {
1393
- if (!runId || goal.frozen) return;
1394
- const result = await api(`/api/runs/${encodeURIComponent(runId)}/goal`);
1395
- const draftEnvelope = result.draft;
1396
- if (!draftEnvelope || draftEnvelope.metadata.revision === goal.draftRevision) return;
1397
- goal.draftRevision = draftEnvelope.metadata.revision;
1398
- goal.draftHash = draftEnvelope.metadata.contentHash;
1399
- goal.text = draftEnvelope.contract.objective || '';
1400
- goal.criteria = draftEnvelope.contract.acceptanceCriteria || [];
1401
- if (!byId('goal-form').contains(document.activeElement)) {
1402
- byId('goal-text').value = goal.text;
1403
- byId('goal-criteria').value = goal.criteria.map((criterion) => (
1404
- `${criterion.statement} | ${criterion.evidenceRequired} | ${(criterion.failureCases || []).join(' | ')}`
1405
- )).join('\n');
902
+ if (liveGoal) {
903
+ goal.version = liveGoal.version || goal.version;
904
+ goal.frozen = Boolean(liveGoal.frozen);
1406
905
  }
1407
906
  renderGoalState();
1408
907
  }
1409
908
 
1410
- async function refreshLifecycle(runId) {
1411
- if (!runId) {
1412
- lifecycleStream?.close();
1413
- lifecycleStream = null;
1414
- lifecycleRunId = null;
1415
- lifecycleSequence = 0;
1416
- lifecycleEvents = [];
1417
- agentPresence = { status: 'UNKNOWN', lastHeartbeatAt: null };
1418
- return;
1419
- }
1420
- if (lifecycleRunId !== runId) {
1421
- lifecycleStream?.close();
1422
- lifecycleStream = null;
1423
- lifecycleRunId = runId;
1424
- lifecycleSequence = 0;
1425
- lifecycleEvents = [];
1426
- startLifecycleStream(runId);
1427
- }
909
+ async function copyAgentHandoff(runId = activeRunId) {
910
+ const created = runId || await ensureStudioRun();
911
+ if (!created) return;
1428
912
  try {
1429
- const result = await api(
1430
- `/api/runs/${encodeURIComponent(runId)}/lifecycle?after=${lifecycleSequence}&limit=100`
1431
- );
1432
- lifecycleEvents = lifecycleEvents.concat(
1433
- result.lifecycle.events.filter((event) => event.sequence > lifecycleSequence)
1434
- ).slice(-100);
1435
- lifecycleSequence = result.lifecycle.nextSequence;
1436
- agentPresence = result.presence;
1437
- } catch {
1438
- agentPresence = { status: 'UNKNOWN', lastHeartbeatAt: null };
1439
- }
1440
- }
1441
-
1442
- function startLifecycleStream(runId) {
1443
- if (!window.EventSource || !runId) return;
1444
- lifecycleStream = new window.EventSource(
1445
- `/api/runs/${encodeURIComponent(runId)}/lifecycle/stream?after=${lifecycleSequence}`
1446
- );
1447
- lifecycleStream.onmessage = (message) => {
1448
- try {
1449
- const result = JSON.parse(message.data);
1450
- lifecycleEvents = lifecycleEvents.concat(
1451
- result.lifecycle.events.filter((event) => event.sequence > lifecycleSequence)
1452
- ).slice(-100);
1453
- lifecycleSequence = Math.max(lifecycleSequence, result.lifecycle.nextSequence);
1454
- agentPresence = result.presence;
1455
- scheduleLiveRender();
1456
- } catch {
1457
- // The regular cursor poll remains the recovery path.
1458
- }
1459
- };
1460
- }
1461
-
1462
- function scheduleLiveRender() {
1463
- if (liveRenderScheduled) return;
1464
- liveRenderScheduled = true;
1465
- const schedule = window.requestAnimationFrame || ((callback) => setTimeout(callback, 16));
1466
- schedule(() => {
1467
- liveRenderScheduled = false;
1468
- renderLive();
1469
- });
1470
- }
1471
-
1472
- function setFollowExecution(enabled) {
1473
- followExecution = enabled;
1474
- const button = byId('follow-execution');
1475
- button.classList.toggle('active', enabled);
1476
- button.setAttribute('aria-pressed', String(enabled));
1477
- button.textContent = enabled ? 'Following' : 'Follow execution';
1478
- if (enabled) {
1479
- lastFollowedNode = null;
1480
- followActiveNode();
913
+ const result = await api(`/api/runs/${encodeURIComponent(created)}/agent-handoff`);
914
+ const text = result.handoff?.prompt || result.handoff?.brief || JSON.stringify(result.handoff, null, 2);
915
+ await navigator.clipboard.writeText(text);
916
+ handoffCopiedRunId = created;
917
+ renderHandoffState();
918
+ notify('Agent handoff copied.');
919
+ } catch (error) {
920
+ notify(error.message);
1481
921
  }
1482
922
  }
1483
923
 
1484
- function followActiveNode() {
1485
- const nodeId = activeLifecycleNodeId();
1486
- if (!followExecution || !nodeId || nodeId === lastFollowedNode || interaction) return;
1487
- const position = positions.get(nodeId);
1488
- if (!position) return;
1489
- const canvas = byId('canvas').getBoundingClientRect();
1490
- viewport.x = canvas.width / 2 - (position.x + NODE_WIDTH / 2) * viewport.scale;
1491
- viewport.y = canvas.height / 2 - (position.y + 54) * viewport.scale;
1492
- lastFollowedNode = nodeId;
1493
- applyViewport();
924
+ function renderHandoffState() {
925
+ const copied = Boolean(handoffCopiedRunId && handoffCopiedRunId === activeRunId);
926
+ byId('agent-handoff-state').hidden = !copied;
927
+ byId('agent-handoff-instructions').textContent = copied
928
+ ? 'Paste it once into your current AI Agent terminal, then keep Studio open to follow persisted progress.'
929
+ : '';
930
+ byId('start-agent').textContent = copied ? 'Copy again' : 'Start with AI Agent';
1494
931
  }
1495
932
 
1496
- async function hydrateGoalFromLive() {
1497
- const run = catalog.live?.run;
1498
- const artifactPath = run?.artifacts?.goalContract?.path;
1499
- const key = `${run?.runId || ''}:${run?.goal?.version || 1}:${artifactPath || ''}`;
1500
- if (!artifactPath || hydratedGoalKey === key) return;
1501
- try {
1502
- const result = await api(`/api/runs/${encodeURIComponent(run.runId)}/artifacts?path=${encodeURIComponent(artifactPath)}`);
1503
- const contract = JSON.parse(result.artifact.content);
1504
- byId('goal-text').value = contract.objective || '';
1505
- byId('goal-criteria').value = (contract.acceptanceCriteria || []).map((criterion) => (
1506
- `${criterion.statement} | ${criterion.evidenceRequired} | ${(criterion.failureCases || []).join(' | ')}`
1507
- )).join('\n');
1508
- goal.text = contract.objective || '';
1509
- goal.criteria = contract.acceptanceCriteria || [];
1510
- hydratedGoalKey = key;
1511
- } catch {
1512
- // The Goal remains inspectable through Run History if its bounded artifact cannot be hydrated.
1513
- }
933
+ function showWorkspace(section) {
934
+ if (section === 'workflows') section = 'wiring';
935
+ workspace = section;
936
+ const live = section === 'live';
937
+ const showingRuns = section === 'runs';
938
+ const wiring = section === 'wiring';
939
+ byId('live-view').hidden = !live;
940
+ byId('runs-view').hidden = !showingRuns;
941
+ byId('canvas').hidden = !wiring;
942
+ byId('show-live').classList.toggle('active', live);
943
+ byId('show-runs').classList.toggle('active', showingRuns);
944
+ byId('show-wiring').classList.toggle('active', wiring);
945
+ byId('show-live').setAttribute('aria-current', live ? 'page' : 'false');
946
+ byId('show-runs').setAttribute('aria-current', showingRuns ? 'page' : 'false');
947
+ byId('show-wiring').setAttribute('aria-current', wiring ? 'page' : 'false');
948
+ if (showingRuns) loadRuns();
949
+ if (wiring) renderGraph();
1514
950
  }
1515
951
 
1516
952
  async function loadRuns() {
1517
- const query = byId('run-search').value.trim();
953
+ const query = byId('run-search')?.value.trim() || '';
1518
954
  try {
1519
955
  const params = new URLSearchParams();
1520
956
  if (query) params.set('q', query);
1521
- if (byId('run-status').value) params.set('status', byId('run-status').value);
1522
- if (byId('run-mode').value) params.set('mode', byId('run-mode').value);
1523
- if (byId('run-from').value) params.set('from', `${byId('run-from').value}T00:00:00.000Z`);
1524
- if (byId('run-to').value) params.set('to', `${byId('run-to').value}T23:59:59.999Z`);
1525
957
  const result = await api(`/api/runs${params.size ? `?${params}` : ''}`);
1526
958
  runs = result.runs;
1527
959
  const list = byId('run-list');
1528
960
  if (!runs.length) {
1529
- list.innerHTML = '<div class="empty-state"><h2>No runs found</h2><p>Create a task from the workflow trigger.</p></div>';
961
+ list.innerHTML = '<div class="empty-state"><h2>No runs found</h2><p>Create a task from the Goal sheet.</p></div>';
1530
962
  } else {
1531
963
  const active = runs.find((run) => !TERMINAL_RUN_STATES.has(run.status));
1532
964
  const historyRuns = runs.filter((run) => run.runId !== active?.runId);
@@ -1544,7 +976,12 @@ async function loadRuns() {
1544
976
  : '<p class="muted run-list-empty">Completed Runs will stay here.</p>'
1545
977
  ].join('');
1546
978
  list.querySelectorAll('.run-row').forEach((button) => {
1547
- button.onclick = () => loadRunDetail(button.dataset.runId);
979
+ button.onclick = () => {
980
+ pinnedRunId = button.dataset.runId;
981
+ selectedCheckoutRun = pinnedRunId;
982
+ showWorkspace('live');
983
+ loadLive(pinnedRunId);
984
+ };
1548
985
  });
1549
986
  }
1550
987
  if (result.corrupt.length) {
@@ -1555,617 +992,323 @@ async function loadRuns() {
1555
992
  }
1556
993
  }
1557
994
 
1558
- function runHistoryMarkup(run) {
1559
- const history = run.history || [];
1560
- if (!history.length) return '<p class="muted">Waiting for the first Run event.</p>';
1561
- return history.map((entry) => `
1562
- <p>
1563
- <time>${escapeHtml(new Date(entry.at).toLocaleString())}</time>
1564
- <span><b>${escapeHtml(entry.to)}</b> · ${escapeHtml(entry.gate || 'run update')}</span>
1565
- </p>
1566
- `).join('');
995
+ function heartbeatAge(iso) {
996
+ if (!iso) return 'no heartbeat';
997
+ const age = Math.max(0, Date.now() - Date.parse(iso));
998
+ if (!Number.isFinite(age)) return 'no heartbeat';
999
+ if (age < 2000) return 'just now';
1000
+ if (age < 60000) return `${Math.round(age / 1000)}s ago`;
1001
+ return `${Math.round(age / 60000)}m ago`;
1567
1002
  }
1568
1003
 
1569
- async function loadRunDetail(runId) {
1570
- try {
1571
- selectedCheckoutRun = runId;
1572
- const [result, checkoutResult, interactionResult] = await Promise.all([
1573
- api(`/api/runs/${encodeURIComponent(runId)}`),
1574
- api(`/api/runs/${encodeURIComponent(runId)}/checkout`),
1575
- api(`/api/runs/${encodeURIComponent(runId)}/interactions`)
1576
- ]);
1577
- const run = result.run;
1578
- const checkout = checkoutResult.checkout;
1579
- const maxX = Math.max(...checkout.nodes.map((node) => node.position.x), 0) + NODE_WIDTH + 80;
1580
- const maxY = Math.max(...checkout.nodes.map((node) => node.position.y), 0) + 180;
1581
- const paths = checkout.edges.map((edge) => {
1582
- const from = checkout.nodes.find((node) => node.id === edge.from);
1583
- const to = checkout.nodes.find((node) => node.id === edge.to);
1584
- if (!from || !to) return '';
1585
- const x1 = from.position.x + NODE_WIDTH;
1586
- const y1 = from.position.y + NODE_PORT_Y;
1587
- const x2 = to.position.x;
1588
- const y2 = to.position.y + NODE_PORT_Y;
1589
- const state = ['idle', 'active', 'passed', 'failed', 'skipped', 'waiting'].includes(edge.state)
1590
- ? edge.state
1591
- : 'idle';
1592
- return `<path class="edge-${state}" d="M ${x1} ${y1} C ${x1 + 70} ${y1}, ${x2 - 70} ${y2}, ${x2} ${y2}"></path>`;
1593
- }).join('');
1594
- const checkoutGroups = (checkout.loopGroups || []).map((group) => {
1595
- const members = checkout.nodes.filter((node) => group.nodeIds.includes(node.id));
1596
- if (!members.length) return '';
1597
- const left = Math.min(...members.map((node) => node.position.x)) - 28;
1598
- const top = Math.min(...members.map((node) => node.position.y)) - 36;
1599
- const right = Math.max(...members.map((node) => node.position.x + NODE_WIDTH)) + 28;
1600
- const bottom = Math.max(...members.map((node) => node.position.y + 108)) + 28;
1601
- return `<div class="checkout-loop status-${escapeHtml((group.runtime?.status || 'pending').toLowerCase())}" data-checkout-loop="${escapeHtml(group.id)}" 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>`;
1602
- }).join('');
1603
- const checkoutBody = checkout.workflowBound
1604
- ? `
1605
- <section class="checkout-canvas" style="--checkout-width:${maxX}px;--checkout-height:${maxY}px">
1606
- <svg viewBox="0 0 ${maxX} ${maxY}" aria-hidden="true">${paths}</svg>
1607
- ${checkoutGroups}
1608
- ${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">
1609
- <small>${escapeHtml(node.type)}${node.loopIteration ? ` · LOOP ${escapeHtml(node.loopIteration)}` : ''}</small><strong>${escapeHtml(node.displayName)}</strong><span data-node-status>${escapeHtml(node.status)}</span>
1610
- </button>`).join('')}
1611
- </section>
1612
- <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>
1613
- `
1614
- : `
1615
- <section class="classic-run">
1616
- <small>CLASSIC RUN · LIVE TRACKING</small>
1617
- <h3>This Run started before automatic workflow binding was available.</h3>
1618
- <p>Goal changes, stage gates, evidence, and Agent questions are still monitored here. New Runs show the full node canvas automatically.</p>
1619
- <div id="classic-run-timeline" class="timeline">${runHistoryMarkup(run)}</div>
1620
- </section>
1621
- `;
1622
- byId('run-detail').innerHTML = `
1623
- <header class="checkout-header">
1624
- <div><button id="checkout-back" class="quiet">← Run History</button><small>READ-ONLY CHECKOUT · <span id="checkout-run-status">${escapeHtml(run.status)}</span></small><h2>${escapeHtml(run.displayName)}</h2><p>${escapeHtml(run.task)}</p></div>
1625
- <div class="checkout-actions"><button id="copy-agent-handoff">Copy for AI Agent</button>${checkout.workflowBound ? '<button id="duplicate-run-workflow" class="primary">Duplicate as Workflow</button>' : ''}</div>
1626
- </header>
1627
- <div class="checkout-meta"><span>${escapeHtml(run.runId)}</span><span id="checkout-goal-state">${run.goalFrozen ? `Goal frozen V${escapeHtml(run.goalVersion)}` : 'Goal draft'}</span><span>${checkout.workflowBound ? 'Actual node states' : 'Live stage history'}</span></div>
1628
- ${checkoutBody}
1629
- <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>
1630
- `;
1631
- renderInteractions(interactionResult.interactions);
1632
- byId('checkout-back').onclick = () => {
1633
- selectedCheckoutRun = null;
1634
- 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>';
1635
- };
1636
- byId('copy-agent-handoff').onclick = () => copyAgentHandoff(runId);
1637
- if (checkout.workflowBound) byId('duplicate-run-workflow').onclick = async () => {
1638
- try {
1639
- const duplicate = await api(`/api/runs/${encodeURIComponent(runId)}/duplicate`, {
1640
- method: 'POST',
1641
- body: JSON.stringify({ recipeId: `${slug(run.displayName)}-copy` })
1642
- });
1643
- draft = normalizeDraftGraph(structuredClone(duplicate.preview.recipe));
1644
- positions = new Map(checkout.nodes.map((node) => [node.id, node.position]));
1645
- loadedRecipeId = null;
1646
- captureHistory({ reset: true });
1647
- renderGraph();
1648
- renderRecipeDetails();
1649
- validateDraft();
1650
- showWorkspace('workflows');
1651
- notify('Run duplicated into a new editable workflow. History was not changed.');
1652
- } catch (error) {
1653
- notify(error.message);
1654
- }
1655
- };
1656
- byId('run-detail').querySelectorAll('[data-checkout-node]').forEach((button) => {
1657
- button.onclick = () => loadNodeIo(runId, button.dataset.checkoutNode);
1658
- });
1659
- } catch (error) {
1660
- byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1004
+ function currentStageId(live) {
1005
+ const nodes = live?.nodes || {};
1006
+ const running = Object.entries(nodes).find(([, node]) => node?.status === 'RUNNING');
1007
+ if (running) {
1008
+ const type = live.plan?.nodes?.find((node) => node.id === running[0])?.type;
1009
+ const stage = STAGES.find((item) => item.types.includes(type));
1010
+ if (stage) return stage.id;
1661
1011
  }
1662
- }
1663
-
1664
- function renderArtifactPreview(artifact) {
1665
- if (!artifact) return '<p class="muted">No artifact was recorded for this node.</p>';
1666
- if (artifact.unavailable) return `<p class="validation-message">Artifact unavailable: ${escapeHtml(artifact.code)}</p>`;
1667
- 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>`;
1668
- }
1669
-
1670
- async function loadNodeIo(runId, nodeId) {
1671
- const panel = byId('node-io-panel');
1672
- try {
1673
- const { io } = await api(`/api/runs/${encodeURIComponent(runId)}/nodes/${encodeURIComponent(nodeId)}`);
1674
- const running = io.node.status === 'RUNNING';
1675
- const interactionEmpty = io.agentInteractionsAvailable === false
1676
- ? 'Agent Interaction is temporarily unavailable. Other node evidence remains valid.'
1677
- : 'No Agent Interaction was recorded for this Run.';
1678
- panel.innerHTML = `
1679
- <header class="node-io-head"><div><small>NODE INSPECTOR · ${escapeHtml(io.node.status)}</small><h3>${escapeHtml(io.node.displayName)}</h3></div><p class="mono">Duration: ${io.durationMs == null ? 'Not available' : `${Number(io.durationMs)} ms`} · Loop Iteration: ${io.loopIteration == null ? 'Not available' : escapeHtml(String(io.loopIteration))}</p></header>
1680
- <nav class="io-tabs" role="tablist" aria-label="Node details">
1681
- ${['Input', 'Live Activity', 'Output', 'Evidence', 'Timeline'].map((label, index) => `<button class="io-tab" role="tab" aria-selected="${index === 0}" data-io-tab="${slug(label)}">${label}</button>`).join('')}
1682
- </nav>
1683
- <div class="node-data-grid">
1684
- <section class="io-pane active" data-io-pane="input"><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>
1685
- <section class="io-pane" data-io-pane="live-activity"><h4>Live Activity</h4><p class="muted">Interaction scope: ${escapeHtml(io.agentInteractionScope || 'RUN')} — questions and answers belong to the whole Run, not only this node.</p><p class="node-progress">${running ? 'In progress · waiting for persisted output' : escapeHtml(io.node.status)}</p><div class="timeline">${io.agentInteractions.map((event) => `<p><time>${escapeHtml(event.at)}</time><strong>${escapeHtml(event.type)}</strong> ${escapeHtml(String(event.message ?? ''))}</p>`).join('') || `<p class="muted">${escapeHtml(interactionEmpty)}</p>`}</div></section>
1686
- <section class="io-pane" data-io-pane="output"><h4>Output</h4><p><b>${running ? 'In progress' : escapeHtml(io.output.status)}</b>${io.output.reason ? ` · ${escapeHtml(io.output.reason)}` : ''}</p>${running ? '<p class="muted">Output will appear after the Agent records a terminal node event.</p>' : renderArtifactPreview(io.output.artifact)}</section>
1687
- <section class="io-pane" data-io-pane="evidence"><h4>Evidence</h4>${renderArtifactPreview(io.evidence)}</section>
1688
- <section class="io-pane" data-io-pane="timeline"><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>
1689
- </div>`;
1690
- panel.querySelectorAll('[data-io-tab]').forEach((button) => {
1691
- button.onclick = () => {
1692
- panel.querySelectorAll('[data-io-tab]').forEach((tab) => {
1693
- tab.setAttribute('aria-selected', String(tab === button));
1694
- });
1695
- panel.querySelectorAll('[data-io-pane]').forEach((pane) => {
1696
- pane.classList.toggle('active', pane.dataset.ioPane === button.dataset.ioTab);
1697
- });
1698
- };
1699
- });
1700
- panel.querySelectorAll('[data-artifact-download]').forEach((button) => {
1701
- button.onclick = async () => {
1702
- try {
1703
- const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifactDownload)}`);
1704
- const blob = new Blob([result.artifact.content], { type: 'text/plain' });
1705
- const link = document.createElement('a');
1706
- link.href = URL.createObjectURL(blob);
1707
- link.download = button.dataset.artifactDownload.split('/').at(-1);
1708
- link.click();
1709
- URL.revokeObjectURL(link.href);
1710
- } catch (error) {
1711
- notify(error.message);
1712
- }
1713
- };
1714
- });
1715
- } catch (error) {
1716
- panel.innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1012
+ const journey = live?.journey?.current;
1013
+ if (journey) {
1014
+ const match = STAGES.find((item) => item.id === String(journey).toLowerCase()
1015
+ || item.label === String(journey).toLowerCase());
1016
+ if (match) return match.id;
1717
1017
  }
1018
+ return STAGES[0].id;
1718
1019
  }
1719
1020
 
1720
- function renderInteractions(result) {
1721
- const target = byId('interaction-list');
1722
- if (!target) return;
1723
- target.innerHTML = result.questions.length ? result.questions.map((question) => `
1724
- <article class="agent-question ${question.answer ? 'answered' : 'pending'}">
1725
- <small>Q${escapeHtml(question.number)} · ${escapeHtml(question.actor)}</small>
1726
- <p>${escapeHtml(question.message)}</p>
1727
- ${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>`}
1728
- </article>
1729
- `).join('') : '<p class="muted">No questions yet. The Agent can post Q1, Q2, Q3 from the Run-bound CLI.</p>';
1730
- target.querySelectorAll('[data-answer]').forEach((form) => {
1731
- form.onsubmit = async (event) => {
1732
- event.preventDefault();
1733
- try {
1734
- await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/questions/${encodeURIComponent(form.dataset.answer)}/answer`, {
1735
- method: 'POST',
1736
- body: JSON.stringify({ message: form.querySelector('textarea').value, actor: 'studio-user' })
1737
- });
1738
- await refreshCheckoutInteractions();
1739
- } catch (error) {
1740
- notify(error.message);
1741
- }
1742
- };
1021
+ function scheduleLiveRender() {
1022
+ if (liveRenderScheduled) return;
1023
+ liveRenderScheduled = true;
1024
+ const schedule = typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function'
1025
+ ? window.requestAnimationFrame.bind(window)
1026
+ : (callback) => setTimeout(callback, 16);
1027
+ schedule(() => {
1028
+ liveRenderScheduled = false;
1029
+ renderLive();
1743
1030
  });
1744
1031
  }
1745
1032
 
1746
- async function refreshCheckoutInteractions() {
1747
- if (!selectedCheckoutRun || !byId('interaction-list')) return;
1748
- try {
1749
- const result = await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/interactions`);
1750
- renderInteractions(result.interactions);
1751
- } catch {
1752
- // Corrupt or unavailable Run data is isolated and does not affect another Run.
1753
- }
1754
- }
1755
-
1756
- async function refreshSelectedCheckout() {
1757
- const runId = selectedCheckoutRun;
1758
- if (!runId || !byId('checkout-run-status')) return;
1759
- try {
1760
- const [detail, checkoutResult] = await Promise.all([
1761
- api(`/api/runs/${encodeURIComponent(runId)}`),
1762
- api(`/api/runs/${encodeURIComponent(runId)}/checkout`)
1763
- ]);
1764
- if (selectedCheckoutRun !== runId) return;
1765
- const run = detail.run;
1766
- const checkout = checkoutResult.checkout;
1767
- byId('checkout-run-status').textContent = run.status;
1768
- byId('checkout-goal-state').textContent = run.goalFrozen
1769
- ? `Goal frozen V${run.goalVersion}`
1770
- : 'Goal draft';
1771
- if (!checkout.workflowBound) {
1772
- const timeline = byId('classic-run-timeline');
1773
- if (timeline) timeline.innerHTML = runHistoryMarkup(run);
1774
- return;
1775
- }
1776
- for (const node of checkout.nodes) {
1777
- const element = document.querySelector(`[data-checkout-node="${CSS.escape(node.id)}"]`);
1778
- if (!element) continue;
1779
- for (const status of ['pending', 'ready', 'running', 'passed', 'failed', 'skipped', 'blocked']) {
1780
- element.classList.remove(`status-${status}`);
1781
- }
1782
- element.classList.add(`status-${node.status.toLowerCase()}`);
1783
- const status = element.querySelector('[data-node-status]');
1784
- if (status) status.textContent = node.status;
1033
+ function renderLive() {
1034
+ const live = catalog.live;
1035
+ const summary = byId('run-summary');
1036
+ const rail = byId('stage-rail');
1037
+ const journey = byId('run-journey');
1038
+ const meta = byId('live-view')?.querySelector?.('.live-meta');
1039
+ const banner = byId('live-view')?.querySelector?.('.pending-banner');
1040
+ if (!live) {
1041
+ if (summary) summary.textContent = 'No active run';
1042
+ if (rail) {
1043
+ rail.innerHTML = STAGES.map((stage) => `<li class="pending">${escapeHtml(stage.label)}</li>`).join('');
1785
1044
  }
1786
- for (const group of checkout.loopGroups || []) {
1787
- const element = document.querySelector(`[data-checkout-loop="${CSS.escape(group.id)}"]`);
1788
- if (!element) continue;
1789
- const counter = element.querySelector('span');
1790
- if (counter) counter.textContent = `Iteration ${group.runtime?.iteration || 1} / ${group.maxIterations}`;
1045
+ if (meta) meta.innerHTML = '';
1046
+ if (banner) {
1047
+ banner.hidden = true;
1048
+ banner.innerHTML = '';
1791
1049
  }
1792
- } catch {
1793
- // Keep the last valid checkout visible during a transient refresh failure.
1050
+ if (journey) journey.innerHTML = '';
1051
+ return;
1794
1052
  }
1795
- }
1796
-
1797
- async function copyAgentHandoff(runId = activeRunId) {
1798
- try {
1799
- const targetRunId = runId || await ensureStudioRun();
1800
- if (!targetRunId) return;
1801
- const result = await api(`/api/runs/${encodeURIComponent(targetRunId)}/agent-handoff`);
1802
- await navigator.clipboard.writeText(result.handoff.prompt);
1803
- handoffCopiedRunId = targetRunId;
1804
- renderHandoffState();
1805
- notify('Run-bound prompt copied. Paste it into your AI coding Agent.');
1806
- } catch (error) {
1807
- byId('goal-validation').textContent = error.message;
1053
+ const stageId = currentStageId(live);
1054
+ const run = live.run || {};
1055
+ const presence = live.presence || agentPresence;
1056
+ if (summary) {
1057
+ summary.textContent = `${run.displayName || run.runId || 'run'} · ${run.state || ''} · ${heartbeatAge(presence.lastHeartbeatAt)}`;
1808
1058
  }
1809
- }
1810
-
1811
- function renderHandoffState() {
1812
- const copied = Boolean(handoffCopiedRunId && handoffCopiedRunId === activeRunId);
1813
- byId('agent-handoff-state').hidden = !copied;
1814
- byId('agent-handoff-instructions').textContent = copied
1815
- ? 'Paste it once into your current AI Agent terminal, then keep Studio open to follow persisted progress.'
1816
- : '';
1817
- byId('start-agent').textContent = copied ? 'Copy again' : 'Start with AI Agent';
1818
- }
1819
-
1820
- function showWorkspace(section) {
1821
- const showingRuns = section === 'runs';
1822
- byId('runs-view').hidden = !showingRuns;
1823
- byId('canvas').hidden = showingRuns;
1824
- byId('workflow-context').hidden = showingRuns;
1825
- byId('review').hidden = showingRuns;
1826
- byId('show-runs').classList.toggle('active', showingRuns);
1827
- byId('show-runs').setAttribute('aria-current', showingRuns ? 'page' : 'false');
1828
- byId('show-workflows').classList.toggle('active', !showingRuns);
1829
- byId('show-workflows').setAttribute('aria-current', showingRuns ? 'false' : 'page');
1830
- if (showingRuns) loadRuns();
1831
- }
1832
-
1833
- async function previewImport() {
1834
- try {
1835
- const importedRecipe = JSON.parse(byId('import-source').value);
1836
- const result = await api('/api/import/preview', {
1837
- method: 'POST',
1838
- body: JSON.stringify({ existingRecipe: draft, importedRecipe, operation: 'merge' })
1839
- });
1840
- pendingImport = { importedRecipe, mergePlan: result.plan };
1841
- byId('import-preview').innerHTML = `
1842
- <strong>${escapeHtml(importedRecipe.id || 'Imported workflow')}</strong>
1843
- <p>${escapeHtml(importedRecipe.nodes?.length || 0)} nodes · ${escapeHtml(importedRecipe.edges?.length || 0)} explicit Edges</p>
1844
- <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>
1059
+ if (rail) {
1060
+ rail.innerHTML = STAGES.map((stage) => {
1061
+ const current = stage.id === stageId;
1062
+ return `<li class="${current ? 'active' : 'pending'}">${escapeHtml(stage.label)}</li>`;
1063
+ }).join('');
1064
+ }
1065
+ const artifacts = live.artifacts || liveArtifacts;
1066
+ const guard = artifacts['artifact.guard'] || {};
1067
+ const drift = artifacts['artifact.drift'] || {};
1068
+ const receipt = artifacts['artifact.receipt'] || {};
1069
+ if (meta) {
1070
+ meta.innerHTML = `
1071
+ <span>${escapeHtml(run.tier?.current || run.mode || '')}</span>
1072
+ <span>iter ${escapeHtml(String(run.iteration ?? '—'))}</span>
1073
+ <span>${escapeHtml(String(live.budget?.spentThisRun ?? 0))} / ${escapeHtml(String(live.budget?.perRunTokenLimit ?? 0))} tokens</span>
1074
+ <span class="chip">${escapeHtml(String(guard.warn || 0))} warn · ${escapeHtml(String(guard.block || 0))} block</span>
1075
+ <span class="chip">drift ${escapeHtml(String(drift.outOfMapCount || 0))}</span>
1076
+ <span class="chip">${receipt.verified ? 'receipt ok' : 'receipt pending'}</span>
1845
1077
  `;
1846
- byId('import-choices').hidden = false;
1847
- } catch (error) {
1848
- pendingImport = null;
1849
- byId('import-choices').hidden = true;
1850
- byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1078
+ }
1079
+ const pending = live.interactions?.pending || [];
1080
+ if (banner) {
1081
+ banner.hidden = pending.length === 0;
1082
+ banner.innerHTML = pending.map((question) =>
1083
+ `<p><strong>Q${escapeHtml(String(question.number))}</strong> ${escapeHtml(question.message)}</p>`
1084
+ ).join('');
1085
+ }
1086
+ const journeyStatuses = new Set(['pending', 'active', 'complete']);
1087
+ const degradedSources = live.journey?.degradedSources || [];
1088
+ const timeline = (live.journey?.steps || []).map((step) => {
1089
+ const status = String(step?.status || '').toLowerCase();
1090
+ const safeStatus = journeyStatuses.has(status) ? status : 'unknown';
1091
+ const label = String(step?.id || '').replaceAll('_', ' ');
1092
+ const suffix = safeStatus === 'unknown' ? ' (status unavailable)' : '';
1093
+ const blocked = step?.blocked
1094
+ ? (live.journey?.pendingQuestions == null
1095
+ ? ' · unanswered count unavailable'
1096
+ : ` · ${Number(live.journey.pendingQuestions)} unanswered`)
1097
+ : '';
1098
+ return `<li class="${safeStatus}">${escapeHtml(label + suffix + blocked)}</li>`;
1099
+ }).join('');
1100
+ const eventsHtml = (lifecycleEvents.slice(-8).reverse().map((event) =>
1101
+ `<li class="event">${escapeHtml(String(event.at || '').slice(11, 19))} · ${escapeHtml(event.type)} · ${escapeHtml(event.message || '')}</li>`
1102
+ ).join(''));
1103
+ if (journey) {
1104
+ journey.innerHTML = timeline + eventsHtml + (degradedSources.length
1105
+ ? `<li class="unknown">${escapeHtml(`${degradedSources.join(' and ')} unavailable — journey may be incomplete`)}</li>`
1106
+ : '');
1851
1107
  }
1852
1108
  }
1853
1109
 
1854
- async function applyImport(operation) {
1855
- if (!pendingImport) return;
1856
- try {
1857
- const plan = operation === 'merge'
1858
- ? pendingImport.mergePlan
1859
- : { operation: 'replace', nodeIdMap: {}, edgeIdMap: {} };
1860
- const result = await api('/api/import/apply', {
1861
- method: 'POST',
1862
- body: JSON.stringify({
1863
- existingRecipe: draft,
1864
- importedRecipe: pendingImport.importedRecipe,
1865
- plan
1866
- })
1867
- });
1868
- draft = normalizeDraftGraph(structuredClone(result.recipe));
1869
- positions = new Map();
1870
- ensurePositions();
1871
- selectedIds.clear();
1872
- selectedId = null;
1873
- captureHistory();
1874
- renderGraph();
1875
- renderRecipeDetails();
1876
- validateDraft();
1877
- byId('import-dialog').close();
1878
- notify(`${operation === 'merge' ? 'Merged' : 'Replaced'} canvas from validated JSON.`);
1879
- } catch (error) {
1880
- byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1881
- }
1110
+ function maybeOpenOnboarding() {
1111
+ const dialog = byId('goal-dialog');
1112
+ if (!eventsReady || catalog.live || dialog.open || onboardingDismissed) return;
1113
+ dialog.showModal();
1882
1114
  }
1883
1115
 
1884
- function exportWorkflowJson() {
1885
- const blob = new Blob([`${JSON.stringify(authoringRecipe(), null, 2)}\n`], { type: 'application/json' });
1886
- const link = document.createElement('a');
1887
- link.href = URL.createObjectURL(blob);
1888
- link.download = `${draft.id}.workflow.json`;
1889
- link.click();
1890
- URL.revokeObjectURL(link.href);
1116
+ function setConnectionLost(lost, message) {
1117
+ byId('live-connection-state').hidden = !lost;
1118
+ byId('live-connection-message').textContent = lost
1119
+ ? (message || 'Studio connection lost. Your last valid Run view is preserved.')
1120
+ : '';
1891
1121
  }
1892
1122
 
1893
- function createCustomAgentFromForm(event) {
1894
- event.preventDefault();
1895
- const id = uniqueNodeId('agent');
1896
- const name = byId('custom-name').value.trim();
1897
- const prompt = byId('custom-prompt').value.trim();
1898
- const error = validDisplayName(name);
1899
- if (error || !prompt) return notify(error || 'Custom Agent prompt is required.');
1900
- const artifact = byId('custom-output').value.trim() || `${id}-report`;
1901
- const node = {
1902
- id,
1903
- type: 'agent',
1904
- displayName: name,
1905
- prompt,
1906
- capabilityRefs: csv(byId('custom-capabilities').value),
1907
- mcpRefs: csv(byId('custom-mcp').value),
1908
- inputArtifacts: csv(byId('custom-inputs').value),
1909
- outputArtifacts: [{ artifact, schema: 'schemas/report.schema.json' }],
1910
- tokenLimit: Number(byId('custom-tokens').value),
1911
- timeoutMs: Number(byId('custom-timeout').value) * 1000,
1912
- retry: { maxAttempts: Number(byId('custom-retries').value), backoffMs: 1000 }
1913
- };
1914
- draft.nodes.push(node);
1915
- if (pendingConnectionSource) {
1916
- draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, id), from: pendingConnectionSource, to: id });
1917
- pendingConnectionSource = null;
1918
- }
1919
- syncDependencies();
1920
- const center = worldAtCanvasCenter();
1921
- positions.set(id, { x: center.x - NODE_WIDTH / 2, y: center.y - NODE_PORT_Y });
1922
- captureHistory();
1923
- renderGraph();
1924
- selectNode(id);
1925
- validateDraft();
1926
- byId('custom-dialog').close();
1123
+ function followedRunId() {
1124
+ return pinnedRunId || catalog.currentRunId || catalog.live?.run?.runId || null;
1927
1125
  }
1928
1126
 
1929
- function zoomAt(nextScale, clientX, clientY) {
1930
- const scale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));
1931
- const rect = byId('canvas').getBoundingClientRect();
1932
- const x = clientX ?? rect.left + rect.width / 2;
1933
- const y = clientY ?? rect.top + rect.height / 2;
1934
- const world = screenToWorld(x, y);
1935
- viewport.scale = scale;
1936
- viewport.x = x - rect.left - world.x * scale;
1937
- viewport.y = y - rect.top - world.y * scale;
1938
- applyViewport();
1939
- saveLayoutSoon();
1127
+ function eventTouchesFollowed(event) {
1128
+ const followed = followedRunId();
1129
+ if (!followed) return true;
1130
+ if (!event.runId) return true;
1131
+ return event.runId === followed;
1940
1132
  }
1941
1133
 
1942
- function handleWheel(event) {
1943
- event.preventDefault();
1944
- setFollowExecution(false);
1945
- if (event.ctrlKey || event.metaKey) {
1946
- zoomAt(viewport.scale * Math.exp(-event.deltaY * 0.002), event.clientX, event.clientY);
1947
- } else {
1948
- viewport.x -= event.deltaX;
1949
- viewport.y -= event.deltaY;
1950
- applyViewport();
1951
- saveLayoutSoon();
1952
- }
1134
+ async function loadLive(runId) {
1135
+ const query = runId ? `?runId=${encodeURIComponent(runId)}` : '';
1136
+ const result = await api(`/api/live${query}`);
1137
+ catalog.live = result.live;
1138
+ liveArtifacts = result.live?.artifacts || {};
1139
+ lifecycleEvents = result.live?.lifecycle?.events || lifecycleEvents;
1140
+ agentPresence = result.live?.presence || agentPresence;
1141
+ syncGoalFromLive();
1142
+ renderLive();
1143
+ if (workspace === 'wiring') renderGraph();
1144
+ return result.live;
1953
1145
  }
1954
1146
 
1955
- function autoLayout({ record = true } = {}) {
1956
- positions = defaultGraphPositions();
1957
- renderGraph();
1958
- fitView();
1959
- if (record) captureHistory();
1960
- saveLayoutSoon();
1147
+ function applyEvent(event) {
1148
+ if (!event || event.type === 'hello') return;
1149
+ if (event.type === 'resync') {
1150
+ resync();
1151
+ return;
1152
+ }
1153
+ lastEventSeq = Math.max(lastEventSeq, Number(event.seq) || 0);
1154
+ if (event.type === 'current.changed') {
1155
+ catalog.currentRunId = event.payload?.runId || event.runId;
1156
+ if (!pinnedRunId) loadLive(catalog.currentRunId).then(() => maybeOpenOnboarding()).catch(() => {});
1157
+ return;
1158
+ }
1159
+ if (!eventTouchesFollowed(event) && event.type !== 'run.created') return;
1160
+ if (event.type === 'run.created' || event.type === 'run.state') {
1161
+ if (catalog.live?.run && event.runId === catalog.live.run.runId) {
1162
+ Object.assign(catalog.live.run, event.payload || {});
1163
+ }
1164
+ if (event.type === 'run.created' && !catalog.live) loadLive(event.runId).catch(() => {});
1165
+ } else if (event.type === 'lifecycle') {
1166
+ const incoming = event.payload?.events || [];
1167
+ lifecycleEvents = lifecycleEvents.concat(incoming).slice(-100);
1168
+ if (event.payload?.presence) agentPresence = event.payload;
1169
+ else if (catalog.live) catalog.live.lifecycle = event.payload;
1170
+ } else if (event.type === 'presence') {
1171
+ agentPresence = event.payload || agentPresence;
1172
+ if (catalog.live) catalog.live.presence = agentPresence;
1173
+ } else if (String(event.type).startsWith('artifact.')) {
1174
+ liveArtifacts[event.type] = event.payload;
1175
+ if (catalog.live) {
1176
+ catalog.live.artifacts = catalog.live.artifacts || {};
1177
+ catalog.live.artifacts[event.type] = event.payload;
1178
+ }
1179
+ }
1180
+ scheduleLiveRender();
1961
1181
  }
1962
1182
 
1963
- function fitView() {
1964
- ensurePositions();
1965
- if (!positions.size) return;
1966
- const rect = byId('canvas').getBoundingClientRect();
1967
- const values = [...positions.values()];
1968
- const minX = Math.min(...values.map((position) => position.x));
1969
- const minY = Math.min(...values.map((position) => position.y));
1970
- const maxX = Math.max(...values.map((position) => position.x + NODE_WIDTH));
1971
- const maxY = Math.max(...values.map((position) => position.y + 140));
1972
- const padding = 100;
1973
- viewport.scale = Math.max(MIN_ZOOM, Math.min(1.35, Math.min(
1974
- (rect.width - padding * 2) / Math.max(1, maxX - minX),
1975
- (rect.height - padding * 2) / Math.max(1, maxY - minY)
1976
- )));
1977
- viewport.x = (rect.width - (maxX - minX) * viewport.scale) / 2 - minX * viewport.scale;
1978
- viewport.y = (rect.height - (maxY - minY) * viewport.scale) / 2 - minY * viewport.scale;
1979
- applyViewport();
1980
- saveLayoutSoon();
1183
+ function parseSseBlock(block) {
1184
+ let type = 'message';
1185
+ let data = '';
1186
+ let id = '';
1187
+ for (const line of block.split('\n')) {
1188
+ if (line.startsWith('event:')) type = line.slice(6).trim();
1189
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
1190
+ else if (line.startsWith('id:')) id = line.slice(3).trim();
1191
+ }
1192
+ if (!data) return { type, event: null, id };
1193
+ try {
1194
+ return { type, event: JSON.parse(data), id };
1195
+ } catch {
1196
+ return { type, event: null, id };
1197
+ }
1981
1198
  }
1982
1199
 
1983
- function captureHistory({ reset = false } = {}) {
1984
- const snapshot = JSON.stringify({ draft, positions: Object.fromEntries(positions) });
1985
- if (reset) {
1986
- history = [snapshot];
1987
- historyIndex = 0;
1988
- } else if (history[historyIndex] !== snapshot) {
1989
- history = history.slice(0, historyIndex + 1);
1990
- history.push(snapshot);
1991
- historyIndex = history.length - 1;
1200
+ function dispatchSse(buffer) {
1201
+ const parts = buffer.split('\n\n');
1202
+ const rest = parts.pop();
1203
+ for (const block of parts) {
1204
+ if (!block.trim()) continue;
1205
+ const parsed = parseSseBlock(block);
1206
+ if (parsed.type === 'hello' && parsed.event) {
1207
+ catalog.watchMode = parsed.event.mode || catalog.watchMode;
1208
+ catalog.root = parsed.event.root || catalog.root;
1209
+ catalog.currentRunId = parsed.event.currentRunId;
1210
+ lastEventSeq = parsed.event.seq || lastEventSeq;
1211
+ eventsReady = true;
1212
+ reconnectAttempt = 0;
1213
+ resumeFallbackUsed = false;
1214
+ clearReconnectTimer();
1215
+ setConnectionLost(false);
1216
+ updateChrome();
1217
+ maybeOpenOnboarding();
1218
+ continue;
1219
+ }
1220
+ if (parsed.event) applyEvent(parsed.event);
1992
1221
  }
1993
- byId('undo').disabled = historyIndex <= 0;
1994
- byId('redo').disabled = historyIndex >= history.length - 1;
1222
+ return rest;
1995
1223
  }
1996
1224
 
1997
- function restoreHistory(index) {
1998
- if (index < 0 || index >= history.length) return;
1999
- historyIndex = index;
2000
- const snapshot = JSON.parse(history[index]);
2001
- draft = snapshot.draft;
2002
- positions = new Map(Object.entries(snapshot.positions));
2003
- if (!draft.nodes.some((node) => node.id === selectedId)) selectedId = null;
2004
- renderGraph();
2005
- if (selectedId) selectNode(selectedId);
2006
- else renderRecipeDetails();
2007
- validateDraft();
2008
- saveLayoutSoon();
2009
- byId('undo').disabled = historyIndex <= 0;
2010
- byId('redo').disabled = historyIndex >= history.length - 1;
1225
+ async function consumeEvents(signal) {
1226
+ const params = lastEventSeq > 0 ? `?after=${encodeURIComponent(lastEventSeq)}` : '';
1227
+ const headers = lastEventSeq > 0 ? { 'Last-Event-ID': String(lastEventSeq) } : {};
1228
+ const response = await fetch(`/api/events${params}`, { signal, headers });
1229
+ if (!response.ok) {
1230
+ const error = new Error('Studio event stream failed');
1231
+ error.code = lastEventSeq > 0 ? 'EVENT_RESUME_FAILED' : 'EVENT_STREAM_FAILED';
1232
+ throw error;
1233
+ }
1234
+ const reader = response.body.getReader();
1235
+ const decoder = new TextDecoder();
1236
+ let buffer = '';
1237
+ for (;;) {
1238
+ const { done, value } = await reader.read();
1239
+ if (done) break;
1240
+ buffer += decoder.decode(value, { stream: true });
1241
+ buffer = dispatchSse(buffer);
1242
+ }
1243
+ throw new Error('event stream ended');
2011
1244
  }
2012
1245
 
2013
- function saveLayoutSoon() {
2014
- clearTimeout(layoutTimer);
2015
- if (!loadedRecipeId || draft.id !== loadedRecipeId) return;
2016
- layoutTimer = setTimeout(async () => {
2017
- try {
2018
- await api('/api/layout', {
2019
- method: 'PUT',
2020
- body: JSON.stringify({ recipeId: loadedRecipeId, layout: layoutPayload() })
2021
- });
2022
- } catch {
2023
- // Canvas work remains in memory and install still submits the layout.
2024
- }
2025
- }, 350);
1246
+ function clearReconnectTimer() {
1247
+ if (reconnectTimer == null) return;
1248
+ clearTimeout(reconnectTimer);
1249
+ reconnectTimer = null;
2026
1250
  }
2027
1251
 
2028
- async function validateDraft() {
2029
- const sequence = ++validationSequence;
2030
- try {
2031
- const result = await api('/api/validate', { method: 'POST', body: JSON.stringify({ recipe: draft }) });
2032
- if (sequence !== validationSequence) return;
2033
- const hash = result.plans[0].graphHash;
2034
- byId('integrity').textContent = `VALID / ${hash.slice(0, 8)}…${hash.slice(-4)}`;
2035
- byId('integrity').className = 'valid';
2036
- byId('review').disabled = false;
2037
- byId('review-data').textContent = JSON.stringify({
2038
- recipe: draft.id,
2039
- version: draft.version,
2040
- modes: result.plans.map((plan) => plan.mode),
2041
- nodes: draft.nodes.length,
2042
- graphHashes: result.plans.map((plan) => plan.graphHash)
2043
- }, null, 2);
2044
- } catch (error) {
2045
- if (sequence !== validationSequence) return;
2046
- byId('integrity').textContent = `INVALID / ${error.message}`;
2047
- byId('integrity').className = 'invalid';
2048
- byId('review').disabled = true;
2049
- }
1252
+ function scheduleReconnect() {
1253
+ if (reconnectTimer != null) return;
1254
+ setConnectionLost(true);
1255
+ const delay = RECONNECT_BACKOFF_MS[Math.min(reconnectAttempt, RECONNECT_BACKOFF_MS.length - 1)];
1256
+ reconnectAttempt += 1;
1257
+ reconnectTimer = setTimeout(() => {
1258
+ reconnectTimer = null;
1259
+ startEventStream();
1260
+ }, delay);
1261
+ reconnectTimer?.unref?.();
2050
1262
  }
2051
1263
 
2052
- function renderLive() {
2053
- const live = catalog.live;
2054
- if (!live) {
2055
- byId('run-summary').textContent = 'No active run';
2056
- byId('active-stage').textContent = 'No active run';
2057
- byId('activity').textContent = 'Waiting for a recipe-bound workflow.';
2058
- byId('events').innerHTML = '';
2059
- byId('budget').textContent = '—';
2060
- byId('meter').style.width = '0';
2061
- byId('agent-presence').textContent = 'Agent unavailable';
2062
- byId('agent-presence').className = 'agent-presence unknown';
2063
- const dock = byId('run-activity-dock');
2064
- if (dock) dock.hidden = true;
2065
- updateRuntimePresentation();
1264
+ function startEventStream() {
1265
+ if (typeof AbortController !== 'function') {
1266
+ setConnectionLost(true, 'Studio connection lost. Your last valid Run view is preserved.');
2066
1267
  return;
2067
1268
  }
2068
- const lifecycleNodeId = activeLifecycleNodeId();
2069
- const active = live.plan.nodes.find((node) => node.id === lifecycleNodeId)
2070
- || live.plan.nodes.find((node) => live.nodes[node.id].status === 'RUNNING')
2071
- || live.plan.nodes.find((node) => live.nodes[node.id].status === 'READY');
2072
- const runtimeNode = active ? live.nodes[active.id] : null;
2073
- const lifecycle = activeLifecycleEvent();
2074
- byId('run-summary').textContent = active ? `${active.id} · ${runtimeNode.status}` : `Run ${live.run.state}`;
2075
- byId('active-stage').textContent = active?.id || 'Run complete';
2076
- byId('activity').textContent = lifecycle?.message ||
2077
- (active ? runtimeNode.activity || `${runtimeNode.status} · attempt ${runtimeNode.attempts}` : `Final state: ${live.run.state}`);
2078
- const journeyStatuses = new Set(['pending', 'active', 'complete']);
2079
- const degradedSources = live.journey?.degradedSources || [];
2080
- byId('run-journey').innerHTML = (live.journey?.steps || []).map((step) => {
2081
- const status = String(step?.status || '').toLowerCase();
2082
- const safeStatus = journeyStatuses.has(status) ? status : 'unknown';
2083
- const label = String(step?.id || '').replaceAll('_', ' ');
2084
- const suffix = safeStatus === 'unknown' ? ' (status unavailable)' : '';
2085
- const blocked = step?.blocked
2086
- ? (live.journey?.pendingQuestions == null
2087
- ? ' · unanswered count unavailable'
2088
- : ` · ${Number(live.journey.pendingQuestions)} unanswered`)
2089
- : '';
2090
- return `<li class="${safeStatus}">${escapeHtml(label + suffix + blocked)}</li>`;
2091
- }).join('') + (degradedSources.length
2092
- ? `<li class="unknown">${escapeHtml(`${degradedSources.join(' and ')} unavailable — journey may be incomplete`)}</li>`
2093
- : '');
2094
- const presenceLabel = {
2095
- WORKING: 'Agent working',
2096
- IDLE: 'Agent appears idle',
2097
- DISCONNECTED: 'Agent disconnected',
2098
- UNKNOWN: 'Waiting for Agent'
2099
- }[agentPresence.status] || 'Waiting for Agent';
2100
- byId('agent-presence').textContent = presenceLabel;
2101
- byId('agent-presence').className = `agent-presence ${agentPresence.status.toLowerCase()}`;
2102
- const spent = live.budget.spentThisRun;
2103
- const limit = live.budget.perRunTokenLimit;
2104
- byId('meter').style.width = `${Math.min(100, limit ? (spent / limit) * 100 : 0)}%`;
2105
- byId('budget').textContent = `${spent.toLocaleString()} / ${limit.toLocaleString()} TOKENS`;
2106
- const liveEventsHtml = lifecycleEvents.slice(-7).reverse().map((event) => `
2107
- <p class="${event.type === 'NODE_ACTIVITY' || event.type.includes('START') ? 'event-active' : ''}">
2108
- ${escapeHtml(event.at.slice(11, 19))} · ${escapeHtml(event.type)} · ${escapeHtml(event.message)}
2109
- </p>
2110
- `).join('') || live.events.slice(-7).reverse().map((event) => `
2111
- <p>${escapeHtml(event.at.slice(11, 19))} · ${escapeHtml(event.type)}</p>
2112
- `).join('');
2113
- const eventsDetailNote = live.summary?.eventsTruncated
2114
- ? '<p class="muted">Older workflow events are kept out of live polling; node detail and lifecycle stream load them on demand.</p>'
2115
- : '';
2116
- byId('events').innerHTML = liveEventsHtml + eventsDetailNote;
2117
- renderRunActivityDock(live, active, runtimeNode, lifecycle);
2118
- updateRuntimePresentation();
2119
- followActiveNode();
2120
- }
2121
-
2122
- function renderRunActivityDock(live, active, runtimeNode, lifecycle) {
2123
- const dock = byId('run-activity-dock');
2124
- if (!dock) return;
2125
- dock.hidden = false;
2126
- byId('run-activity-scope').textContent = active ? 'NODE ACTIVITY' : 'RUN ACTIVITY';
2127
- byId('run-activity-title').textContent = active ? displayName(active) : `Run ${live.run.state}`;
2128
- byId('run-activity-message').textContent = lifecycle?.message ||
2129
- runtimeNode?.activity || (active ? runtimeNode?.status : 'Waiting for the next persisted event.');
2130
- byId('run-activity-status').textContent = runtimeNode?.status || agentPresence.status || live.run.state;
2131
- const inspect = byId('inspect-live-node');
2132
- inspect.hidden = !active;
2133
- inspect.dataset.nodeId = active?.id || '';
2134
- byId('run-activity-timeline').innerHTML = lifecycleEvents.slice(-4).reverse().map((event) => `
2135
- <span><time>${escapeHtml(String(event.at || '').slice(11, 19))}</time>${escapeHtml(event.message || event.type)}</span>
2136
- `).join('');
2137
- }
2138
-
2139
- function maybeOpenOnboarding() {
2140
- const dialog = byId('goal-dialog');
2141
- if (catalog.live || dialog.open || onboardingDismissed) return;
2142
- dialog.showModal();
1269
+ if (eventAbort) eventAbort.abort();
1270
+ eventAbort = new AbortController();
1271
+ consumeEvents(eventAbort.signal).catch((error) => {
1272
+ if (error?.name === 'AbortError') return;
1273
+ if (error?.code === 'EVENT_RESUME_FAILED' && !resumeFallbackUsed) {
1274
+ resumeFallbackUsed = true;
1275
+ resync();
1276
+ return;
1277
+ }
1278
+ scheduleReconnect();
1279
+ });
2143
1280
  }
2144
1281
 
2145
- async function refreshLive() {
1282
+ async function resync() {
1283
+ clearReconnectTimer();
1284
+ reconnectAttempt = 0;
2146
1285
  try {
2147
- const result = await api('/api/live');
2148
- catalog.live = result.live;
1286
+ const result = await api('/api/bootstrap');
1287
+ catalog = { ...catalog, ...result };
1288
+ liveArtifacts = result.live?.artifacts || liveArtifacts;
1289
+ lifecycleEvents = result.live?.lifecycle?.events || lifecycleEvents;
1290
+ agentPresence = result.live?.presence || agentPresence;
1291
+ lastEventSeq = result.eventSeq || lastEventSeq;
1292
+ eventsReady = true;
1293
+ setConnectionLost(false);
1294
+ updateChrome();
2149
1295
  syncGoalFromLive();
2150
- await refreshLifecycle(catalog.live?.run?.runId);
2151
- await refreshGoalDraft(catalog.live?.run?.runId);
2152
- await hydrateGoalFromLive();
2153
- byId('live-connection-state').hidden = true;
2154
1296
  renderLive();
2155
- await refreshSelectedCheckout();
2156
- await refreshCheckoutInteractions();
2157
- if (!byId('runs-view').hidden) await loadRuns();
2158
1297
  maybeOpenOnboarding();
1298
+ startEventStream();
2159
1299
  return true;
2160
1300
  } catch {
2161
- // A transient refresh failure must not discard the last valid draft or Run snapshot.
2162
- byId('live-connection-message').textContent =
2163
- 'Studio connection lost. Your last valid Run view is preserved.';
2164
- byId('live-connection-state').hidden = false;
1301
+ setConnectionLost(true);
1302
+ scheduleReconnect();
2165
1303
  return false;
2166
1304
  }
2167
1305
  }
2168
1306
 
1307
+ function updateChrome() {
1308
+ if (byId('watched-root')) byId('watched-root').textContent = catalog.root || '—';
1309
+ if (byId('live-mode')) byId('live-mode').textContent = `live: ${catalog.watchMode || 'watch'}`;
1310
+ }
1311
+
2169
1312
  async function loadRecipe() {
2170
1313
  const id = byId('recipe').value;
2171
1314
  const [result, saved] = await Promise.all([
@@ -2178,25 +1321,24 @@ async function loadRecipe() {
2178
1321
  selectedId = null;
2179
1322
  selectedIds.clear();
2180
1323
  selectedEdgeId = null;
2181
- byId('inspector-panel').classList.remove('open');
2182
1324
  positions = new Map(Object.entries(saved.layout?.positions || {}));
2183
1325
  ensurePositions();
2184
1326
  viewport = saved.layout?.viewport || { x: 0, y: 0, scale: 1 };
2185
1327
  renderGraph();
2186
1328
  if (!saved.layout || (draft.nodes.length <= 12 && viewport.scale < 0.45)) fitView();
2187
- renderRecipeDetails();
2188
1329
  captureHistory({ reset: true });
2189
- validateDraft();
1330
+ await validateDraft();
2190
1331
  }
2191
1332
 
2192
1333
  async function refreshCatalog(selectedRecipe) {
2193
- catalog = await api('/api/bootstrap');
1334
+ const result = await api('/api/bootstrap');
1335
+ catalog = { ...catalog, ...result };
1336
+ updateChrome();
2194
1337
  const selector = byId('recipe');
2195
1338
  selector.innerHTML = catalog.recipes.map((recipe) => (
2196
1339
  `<option value="${escapeHtml(recipe.id)}">${escapeHtml(recipe.id)} · v${escapeHtml(recipe.version)}</option>`
2197
1340
  )).join('');
2198
1341
  if (selectedRecipe && catalog.recipes.some((recipe) => recipe.id === selectedRecipe)) selector.value = selectedRecipe;
2199
- renderPalette();
2200
1342
  syncGoalFromLive();
2201
1343
  renderLive();
2202
1344
  }
@@ -2208,41 +1350,21 @@ function bindCanvas() {
2208
1350
  selectedId = null;
2209
1351
  if (!event.shiftKey) selectedIds.clear();
2210
1352
  updateSelection();
2211
- renderRecipeDetails();
2212
- byId('inspector-panel').classList.remove('open');
2213
1353
  if (event.button === 1 || spacePressed) beginPan(event);
2214
- else if (event.button === 0) beginLasso(event);
2215
1354
  }
2216
1355
  });
2217
1356
  canvas.addEventListener('pointermove', handlePointerMove);
2218
1357
  canvas.addEventListener('pointerup', finishPointer);
2219
1358
  canvas.addEventListener('pointercancel', finishPointer);
2220
1359
  canvas.addEventListener('wheel', handleWheel, { passive: false });
2221
- canvas.addEventListener('dragover', (event) => {
2222
- if (!event.dataTransfer.types.includes('application/x-ael-node-type')) return;
2223
- event.preventDefault();
2224
- canvas.classList.add('drop-ready');
2225
- });
2226
- canvas.addEventListener('dragleave', () => canvas.classList.remove('drop-ready'));
2227
- canvas.addEventListener('drop', (event) => {
2228
- event.preventDefault();
2229
- canvas.classList.remove('drop-ready');
2230
- const type = event.dataTransfer.getData('application/x-ael-node-type');
2231
- if (type) addNode(type, screenToWorld(event.clientX, event.clientY));
2232
- });
2233
1360
  byId('auto-layout').onclick = () => autoLayout();
2234
1361
  byId('fit-view').onclick = fitView;
2235
- byId('fit-view-rail').onclick = fitView;
2236
- byId('zoom-in').onclick = () => zoomAt(viewport.scale * 1.2);
2237
- byId('zoom-out').onclick = () => zoomAt(viewport.scale / 1.2);
2238
1362
  byId('undo').onclick = () => restoreHistory(historyIndex - 1);
2239
1363
  byId('redo').onclick = () => restoreHistory(historyIndex + 1);
2240
- byId('follow-execution').onclick = () => setFollowExecution(!followExecution);
2241
- setFollowExecution(followExecution);
2242
1364
  }
2243
1365
 
2244
1366
  function editableTarget(target) {
2245
- return target.matches('input,textarea,select,[contenteditable="true"]');
1367
+ return target.matches?.('input,textarea,select,[contenteditable="true"]');
2246
1368
  }
2247
1369
 
2248
1370
  document.addEventListener('keydown', (event) => {
@@ -2258,84 +1380,42 @@ document.addEventListener('keydown', (event) => {
2258
1380
  } else if (modifier && event.key.toLowerCase() === 'y') {
2259
1381
  event.preventDefault();
2260
1382
  restoreHistory(historyIndex + 1);
2261
- } else if (modifier && event.key.toLowerCase() === 'a' && byId('canvas').contains(document.activeElement)) {
2262
- event.preventDefault();
2263
- selectedIds = new Set(draft.nodes.map((node) => node.id));
2264
- selectedId = [...selectedIds].at(-1) || null;
2265
- updateSelection();
2266
1383
  } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId) {
2267
1384
  event.preventDefault();
2268
1385
  deleteEdge(selectedEdgeId);
2269
- } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedIds.size) {
2270
- event.preventDefault();
2271
- deleteSelectedNode();
2272
1386
  }
2273
1387
  });
2274
1388
  document.addEventListener('keyup', (event) => {
2275
1389
  if (event.code === 'Space') spacePressed = false;
2276
1390
  });
2277
- window.addEventListener('blur', () => { spacePressed = false; });
2278
-
2279
- byId('copy').onclick = async () => {
2280
- try {
2281
- const handoff = await api('/api/handoff?audience=developer');
2282
- await navigator.clipboard.writeText(handoff.brief);
2283
- notify('Redacted developer brief copied.');
2284
- } catch (error) {
2285
- notify(error.message);
2286
- }
2287
- };
2288
-
2289
- byId('download').onclick = async () => {
2290
- try {
2291
- const handoff = await api('/api/handoff?audience=agent');
2292
- const blob = new Blob([JSON.stringify(handoff.bundle, null, 2)], { type: 'application/json' });
2293
- const link = document.createElement('a');
2294
- link.href = URL.createObjectURL(blob);
2295
- link.download = `${handoff.bundle.runId}.ael-handoff.json`;
2296
- link.click();
2297
- URL.revokeObjectURL(link.href);
2298
- notify('Integrity-bound handoff exported.');
2299
- } catch (error) {
2300
- notify(error.message);
2301
- }
2302
- };
2303
1391
 
2304
- byId('record-decision').onclick = async () => {
2305
- if (!catalog.live) return notify('Start a workflow run before recording a decision.');
2306
- try {
2307
- await api('/api/decision', {
2308
- method: 'POST',
2309
- body: JSON.stringify({
2310
- runId: catalog.live.run.runId,
2311
- summary: byId('decision-summary').value,
2312
- rationale: byId('decision-rationale').value,
2313
- consequences: []
2314
- })
2315
- });
2316
- byId('decision-summary').value = '';
2317
- byId('decision-rationale').value = '';
2318
- notify('Redacted decision recorded for handoff.');
2319
- } catch (error) {
2320
- notify(error.message);
2321
- }
1392
+ byId('review').onclick = () => {
1393
+ if (byId('review').disabled) return;
1394
+ byId('confirm').showModal();
2322
1395
  };
2323
-
2324
- byId('review').onclick = () => byId('confirm').showModal();
2325
- byId('cancel').onclick = () => byId('confirm').close();
2326
1396
  byId('install').onclick = async () => {
2327
1397
  try {
1398
+ const recipe = authoringRecipe();
1399
+ const exists = catalog.recipes.some((item) => item.id === recipe.id && item.source !== 'builtin');
1400
+ if (source === 'builtin') {
1401
+ recipe.id = `${recipe.id}-local`;
1402
+ recipe.version = 1;
1403
+ } else if (exists) {
1404
+ recipe.version = Number(recipe.version) + 1;
1405
+ }
1406
+ const replacing = catalog.recipes.some((item) => item.id === recipe.id && item.source !== 'builtin');
2328
1407
  await api('/api/install', {
2329
1408
  method: 'POST',
2330
1409
  body: JSON.stringify({
2331
- recipe: draft,
1410
+ recipe,
2332
1411
  layout: layoutPayload(),
2333
- replace: catalog.recipes.some((recipe) => recipe.id === draft.id)
1412
+ replace: replacing,
1413
+ baseRecipeId: loadedRecipeId
2334
1414
  })
2335
1415
  });
2336
1416
  byId('confirm').close();
2337
- notify('Recipe and private canvas layout installed atomically.');
2338
- await refreshCatalog(draft.id);
1417
+ notify('Wiring installed. The compiler accepted the graph.');
1418
+ await refreshCatalog(recipe.id);
2339
1419
  await loadRecipe();
2340
1420
  } catch (error) {
2341
1421
  notify(error.message);
@@ -2349,93 +1429,13 @@ function notify(text) {
2349
1429
  setTimeout(() => { message.style.display = 'none'; }, 4000);
2350
1430
  }
2351
1431
 
2352
- function openLoopDialog() {
2353
- const members = draft.nodes.filter((node) => selectedIds.has(node.id));
2354
- if (members.length < 2) return notify('Select at least two steps for a Loop Group.');
2355
- if ((draft.loopGroups || []).some((group) => group.nodeIds.some((id) => selectedIds.has(id)))) {
2356
- return notify('A step can only belong to one Loop Group.');
2357
- }
2358
- const options = members.map((node) =>
2359
- `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
2360
- ).join('');
2361
- for (const id of ['loop-entry', 'loop-decision', 'loop-repeat-target']) byId(id).innerHTML = options;
2362
- const incomingEntry = members.find((node) =>
2363
- draft.edges.some((edge) => edge.to === node.id && !selectedIds.has(edge.from))
2364
- ) || members[0];
2365
- const outgoing = draft.edges.find((edge) =>
2366
- selectedIds.has(edge.from) && !selectedIds.has(edge.to)
2367
- );
2368
- if (!outgoing) return notify('Connect the Loop decision step to its Continue step first.');
2369
- const decision = outgoing
2370
- ? members.find((node) => node.id === outgoing.from)
2371
- : members.find((node) => ['decision', 'judge', 'condition'].includes(node.type)) || members.at(-1);
2372
- const exitIds = new Set(draft.edges
2373
- .filter((edge) => selectedIds.has(edge.from) && !selectedIds.has(edge.to))
2374
- .map((edge) => edge.to));
2375
- const exitCandidates = draft.nodes.filter((node) => exitIds.has(node.id));
2376
- byId('loop-exit-target').innerHTML = exitCandidates.map((node) =>
2377
- `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
2378
- ).join('');
2379
- byId('loop-entry').value = incomingEntry.id;
2380
- byId('loop-repeat-target').value = incomingEntry.id;
2381
- byId('loop-decision').value = decision.id;
2382
- if (outgoing) byId('loop-exit-target').value = outgoing.to;
2383
- byId('loop-name').value = '';
2384
- byId('loop-dialog').showModal();
2385
- }
2386
-
2387
- function createLoopGroupFromForm(event) {
2388
- event.preventDefault();
2389
- const display = byId('loop-name').value.trim();
2390
- const repeatOutcome = byId('loop-repeat-outcome').value.trim();
2391
- const exitOutcome = byId('loop-exit-outcome').value.trim();
2392
- if (repeatOutcome === exitOutcome) return notify('Repeat and Continue outcomes must be different.');
2393
- let id = slug(display || 'iteration-loop');
2394
- const occupied = new Set((draft.loopGroups || []).map((group) => group.id));
2395
- for (let suffix = 2; occupied.has(id); suffix += 1) id = `${slug(display || 'iteration-loop')}-${suffix}`;
2396
- const loopGroup = {
2397
- id,
2398
- displayName: display,
2399
- nodeIds: draft.nodes.filter((node) => selectedIds.has(node.id)).map((node) => node.id),
2400
- entryNodeId: byId('loop-entry').value,
2401
- decisionNodeId: byId('loop-decision').value,
2402
- repeatTargetId: byId('loop-repeat-target').value,
2403
- exitTargetId: byId('loop-exit-target').value,
2404
- maxIterations: Number(byId('loop-max').value),
2405
- repeatOutcome,
2406
- exitOutcome,
2407
- repeatLabel: byId('loop-repeat-label').value.trim(),
2408
- exitLabel: byId('loop-exit-label').value.trim()
2409
- };
2410
- draft.loopGroups.push(loopGroup);
2411
- captureHistory();
2412
- renderGraph();
2413
- validateDraft();
2414
- byId('loop-dialog').close();
2415
- notify(`Loop Group “${display}” created.`);
2416
- }
2417
-
2418
1432
  async function initialize() {
2419
- await refreshCatalog('default');
2420
1433
  byId('recipe').onchange = loadRecipe;
2421
1434
  bindCanvas();
2422
- byId('toggle-library').onclick = () => byId('library-panel').classList.toggle('open');
2423
- byId('close-library').onclick = () => byId('library-panel').classList.remove('open');
2424
- byId('show-workflows').onclick = () => showWorkspace('workflows');
1435
+ byId('show-live').onclick = () => showWorkspace('live');
2425
1436
  byId('show-runs').onclick = () => showWorkspace('runs');
1437
+ byId('show-wiring').onclick = () => showWorkspace('wiring');
2426
1438
  byId('run-search').oninput = loadRuns;
2427
- for (const id of ['run-status', 'run-mode', 'run-from', 'run-to']) byId(id).onchange = loadRuns;
2428
- byId('import-json').onclick = () => byId('import-dialog').showModal();
2429
- byId('export-json').onclick = exportWorkflowJson;
2430
- byId('preview-import').onclick = previewImport;
2431
- byId('import-file').onchange = async (event) => {
2432
- const [file] = event.currentTarget.files;
2433
- if (file) byId('import-source').value = await file.text();
2434
- };
2435
- byId('merge-import').onclick = () => applyImport('merge');
2436
- byId('replace-import').onclick = () => applyImport('replace');
2437
- byId('create-custom').onclick = () => byId('custom-dialog').showModal();
2438
- byId('custom-form').onsubmit = createCustomAgentFromForm;
2439
1439
  byId('open-goal').onclick = () => {
2440
1440
  renderGoalState();
2441
1441
  byId('goal-dialog').showModal();
@@ -2445,42 +1445,20 @@ async function initialize() {
2445
1445
  byId('review-goal').onclick = reviewGoal;
2446
1446
  byId('confirm-freeze').onclick = freezeGoalFromForm;
2447
1447
  byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
2448
- byId('duplicate-selection').onclick = duplicateSelectedNode;
2449
- byId('delete-selection').onclick = deleteSelectedNode;
2450
- byId('create-loop-group').onclick = openLoopDialog;
2451
- byId('loop-form').onsubmit = createLoopGroupFromForm;
2452
- document.querySelectorAll('[data-close]').forEach((button) => {
1448
+ byId('retry-live-connection').onclick = resync;
1449
+ document.querySelectorAll?.('[data-close]')?.forEach?.((button) => {
2453
1450
  button.onclick = () => byId(button.dataset.close).close();
2454
1451
  });
2455
- document.querySelectorAll('.dialog-maximize').forEach((button) => {
1452
+ document.querySelectorAll?.('.dialog-maximize')?.forEach?.((button) => {
2456
1453
  button.onclick = () => button.closest('dialog').classList.toggle('maximized');
2457
1454
  });
2458
- byId('workflow-settings').onclick = () => {
2459
- selectedId = null;
2460
- updateSelection();
2461
- renderRecipeDetails();
2462
- byId('inspector-panel').classList.add('open');
2463
- };
2464
- byId('close-inspector').onclick = () => byId('inspector-panel').classList.remove('open');
2465
- byId('toggle-execution').onclick = () => byId('execution-panel').classList.toggle('open');
2466
- byId('close-execution').onclick = () => byId('execution-panel').classList.remove('open');
2467
- byId('open-live-details').onclick = () => byId('execution-panel').classList.add('open');
2468
- byId('inspect-live-node').onclick = async (event) => {
2469
- const nodeId = event.currentTarget.dataset.nodeId;
2470
- if (!activeRunId || !nodeId) return;
2471
- showWorkspace('runs');
2472
- await loadRuns();
2473
- await loadRunDetail(activeRunId);
2474
- await loadNodeIo(activeRunId, nodeId);
2475
- };
2476
- byId('retry-live-connection').onclick = refreshLive;
2477
1455
  byId('goal-dialog').addEventListener('close', () => {
2478
1456
  onboardingDismissed = true;
2479
1457
  });
1458
+ showWorkspace('live');
1459
+ await refreshCatalog('default');
2480
1460
  await loadRecipe();
2481
- await refreshLive();
2482
- clearInterval(liveTimer);
2483
- liveTimer = setInterval(refreshLive, 1800);
1461
+ startEventStream();
2484
1462
  }
2485
1463
 
2486
1464
  initialize().catch((error) => notify(error.message));