ai-engineering-loop 1.8.1 → 1.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/studio/app.js CHANGED
@@ -33,6 +33,7 @@ let goal = { text: '', version: 1, frozen: false };
33
33
  let activeRunId;
34
34
  let pendingImport;
35
35
  let hydratedGoalKey;
36
+ let selectedCheckoutRun;
36
37
 
37
38
  const DISPLAY_NAME_MAX = 80;
38
39
  const ROOT_TYPES = new Set(['goal-contract', 'trigger']);
@@ -75,6 +76,7 @@ function normalizeDraftGraph(recipe) {
75
76
  used.add(id);
76
77
  return { ...edge, id };
77
78
  });
79
+ recipe.loopGroups = Array.isArray(recipe.loopGroups) ? recipe.loopGroups : [];
78
80
  syncDependencies(recipe);
79
81
  return recipe;
80
82
  }
@@ -200,6 +202,72 @@ function edgePath(from, to) {
200
202
  return `M${startX} ${startY} C${startX + bend} ${startY},${endX - bend} ${endY},${endX} ${endY}`;
201
203
  }
202
204
 
205
+ function loopBounds(loopGroup) {
206
+ const points = loopGroup.nodeIds.map((nodeId) => positions.get(nodeId)).filter(Boolean);
207
+ if (!points.length) return null;
208
+ const padding = 44;
209
+ const left = Math.min(...points.map((point) => point.x)) - padding;
210
+ const top = Math.min(...points.map((point) => point.y)) - padding;
211
+ const right = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + padding;
212
+ const bottom = Math.max(...points.map((point) => point.y + 108)) + padding;
213
+ return { left, top, right, bottom, width: right - left, height: bottom - top };
214
+ }
215
+
216
+ function renderLoopGroups() {
217
+ const container = byId('loop-groups');
218
+ container.innerHTML = '';
219
+ for (const loopGroup of draft?.loopGroups || []) {
220
+ const bounds = loopBounds(loopGroup);
221
+ if (!bounds) continue;
222
+ const runtime = catalog.live?.loopGroups?.[loopGroup.id];
223
+ const element = document.createElement('section');
224
+ element.className = `loop-group ${runtime?.status?.toLowerCase() || 'draft'}`;
225
+ element.style.left = `${bounds.left}px`;
226
+ element.style.top = `${bounds.top}px`;
227
+ element.style.width = `${bounds.width}px`;
228
+ element.style.height = `${bounds.height}px`;
229
+ element.innerHTML = `
230
+ <header>
231
+ <span><b>${escapeHtml(loopGroup.displayName)}</b><small>ITERATION ${escapeHtml(runtime?.iteration || 1)} / ${escapeHtml(loopGroup.maxIterations)}</small></span>
232
+ <button type="button" aria-label="Remove ${escapeHtml(loopGroup.displayName)} group">Ungroup</button>
233
+ </header>
234
+ `;
235
+ element.querySelector('button').onclick = (event) => {
236
+ event.stopPropagation();
237
+ draft.loopGroups = draft.loopGroups.filter((candidate) => candidate.id !== loopGroup.id);
238
+ captureHistory();
239
+ renderGraph();
240
+ validateDraft();
241
+ };
242
+ element.querySelector('header').onpointerdown = (event) => {
243
+ if (event.button !== 0 || event.target.closest('button')) return;
244
+ event.preventDefault();
245
+ event.stopPropagation();
246
+ const world = screenToWorld(event.clientX, event.clientY);
247
+ interaction = {
248
+ type: 'group',
249
+ pointerId: event.pointerId,
250
+ groupId: loopGroup.id,
251
+ start: world,
252
+ element: byId('canvas'),
253
+ origins: new Map(loopGroup.nodeIds.map((nodeId) => [nodeId, { ...positions.get(nodeId) }]))
254
+ };
255
+ selectedIds = new Set(loopGroup.nodeIds);
256
+ selectedId = loopGroup.decisionNodeId;
257
+ updateSelection();
258
+ byId('canvas').setPointerCapture(event.pointerId);
259
+ };
260
+ container.append(element);
261
+ }
262
+ }
263
+
264
+ function edgeLoopLabel(edge) {
265
+ const loopGroup = (draft.loopGroups || []).find((candidate) =>
266
+ candidate.decisionNodeId === edge.from && candidate.exitTargetId === edge.to
267
+ );
268
+ return loopGroup ? loopGroup.exitLabel : '';
269
+ }
270
+
203
271
  function stageLabel(node, index) {
204
272
  const stages = {
205
273
  'goal-contract': 'STAGE 01',
@@ -261,7 +329,36 @@ function renderEdges() {
261
329
  };
262
330
  control.onpointerleave = () => control.classList.remove('visible');
263
331
  controls.append(control);
332
+ const label = edgeLoopLabel(edge);
333
+ if (label) {
334
+ const badge = document.createElement('span');
335
+ badge.className = 'edge-label';
336
+ badge.style.left = `${midpoint.x}px`;
337
+ badge.style.top = `${midpoint.y - 22}px`;
338
+ badge.textContent = label;
339
+ controls.append(badge);
340
+ }
264
341
  });
342
+ for (const loopGroup of draft.loopGroups || []) {
343
+ const from = positions.get(loopGroup.decisionNodeId);
344
+ const to = positions.get(loopGroup.repeatTargetId);
345
+ const bounds = loopBounds(loopGroup);
346
+ if (!from || !to || !bounds) continue;
347
+ const returnPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
348
+ returnPath.setAttribute(
349
+ 'd',
350
+ `M${from.x + NODE_WIDTH} ${from.y + NODE_PORT_Y} H${bounds.right + 28} V${bounds.top - 18} H${to.x - 28} V${to.y + NODE_PORT_Y} H${to.x}`
351
+ );
352
+ returnPath.setAttribute('class', 'edge loop-return');
353
+ returnPath.setAttribute('marker-end', 'url(#arrow)');
354
+ group.append(returnPath);
355
+ const label = document.createElement('span');
356
+ label.className = 'edge-label loop-label';
357
+ label.style.left = `${bounds.right + 28}px`;
358
+ label.style.top = `${bounds.top - 18}px`;
359
+ label.textContent = loopGroup.repeatLabel;
360
+ controls.append(label);
361
+ }
265
362
  }
266
363
 
267
364
  function nodeMarkup(node, index) {
@@ -283,6 +380,7 @@ function nodeMarkup(node, index) {
283
380
 
284
381
  function renderGraph() {
285
382
  ensurePositions();
383
+ renderLoopGroups();
286
384
  const container = byId('nodes');
287
385
  container.innerHTML = '';
288
386
  draft.nodes.forEach((node, index) => {
@@ -331,6 +429,11 @@ function updateSelection() {
331
429
  const actions = byId('selection-actions');
332
430
  actions.hidden = selectedIds.size < 2;
333
431
  byId('selection-count').textContent = `${selectedIds.size} nodes`;
432
+ const grouped = [...selectedIds].some((nodeId) =>
433
+ (draft?.loopGroups || []).some((group) => group.nodeIds.includes(nodeId))
434
+ );
435
+ byId('create-loop-group').disabled = grouped;
436
+ byId('create-loop-group').title = grouped ? 'Ungroup selected steps before creating another Loop Group' : '';
334
437
  }
335
438
 
336
439
  function renderRecipeDetails() {
@@ -650,6 +753,13 @@ function applyNodeDetails() {
650
753
  function deleteSelectedNode() {
651
754
  if (!selectedIds.size) return;
652
755
  const removed = new Set(selectedIds);
756
+ const containingGroup = (draft.loopGroups || []).find((group) =>
757
+ group.nodeIds.some((nodeId) => removed.has(nodeId))
758
+ );
759
+ if (containingGroup) {
760
+ notify(`Ungroup “${containingGroup.displayName}” before deleting its steps.`);
761
+ return;
762
+ }
653
763
  draft.nodes = draft.nodes.filter((node) => !removed.has(node.id));
654
764
  draft.edges = draft.edges.filter((edge) => !removed.has(edge.from) && !removed.has(edge.to));
655
765
  syncDependencies();
@@ -833,6 +943,13 @@ function handlePointerMove(event) {
833
943
  }
834
944
  });
835
945
  renderEdges();
946
+ } else if (interaction.type === 'group') {
947
+ const world = screenToWorld(event.clientX, event.clientY);
948
+ const delta = { x: world.x - interaction.start.x, y: world.y - interaction.start.y };
949
+ interaction.origins.forEach((start, id) => {
950
+ positions.set(id, { x: start.x + delta.x, y: start.y + delta.y });
951
+ });
952
+ renderGraph();
836
953
  } else if (interaction.type === 'lasso') {
837
954
  updateLasso(event);
838
955
  } else {
@@ -845,7 +962,7 @@ function handlePointerMove(event) {
845
962
  function finishPointer(event) {
846
963
  if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
847
964
  if (!interaction || interaction.pointerId !== event.pointerId) return;
848
- if (interaction.type === 'node') {
965
+ if (interaction.type === 'node' || interaction.type === 'group') {
849
966
  interaction.element.classList.remove('dragging');
850
967
  captureHistory();
851
968
  } else if (interaction.type === 'lasso') finishLasso();
@@ -997,6 +1114,7 @@ async function ensureStudioRun() {
997
1114
  method: 'POST',
998
1115
  body: JSON.stringify({
999
1116
  task,
1117
+ constraints: byId('goal-constraints').value.trim(),
1000
1118
  displayName: byId('goal-run-name').value.trim(),
1001
1119
  recipeId: loadedRecipeId,
1002
1120
  mode: draft.compatibleModes.includes('ASSISTED') ? 'ASSISTED' : draft.compatibleModes[0]
@@ -1009,6 +1127,14 @@ async function ensureStudioRun() {
1009
1127
 
1010
1128
  async function saveGoalFromForm() {
1011
1129
  try {
1130
+ const task = byId('goal-task').value.trim();
1131
+ if (!byId('goal-text').value.trim()) byId('goal-text').value = task;
1132
+ if (!byId('goal-criteria').value.trim()) {
1133
+ byId('goal-criteria').value = [
1134
+ 'Requested outcome works in its real workflow | Tests and Run-bound evidence demonstrate the result | The requested outcome is unavailable or misleading',
1135
+ 'Existing behavior remains reliable | Compatibility checks pass | A supported existing workflow regresses'
1136
+ ].join('\n');
1137
+ }
1012
1138
  const provisional = goalContractFromForm(activeRunId || 'pending');
1013
1139
  const error = validateGoalForm(provisional);
1014
1140
  if (error) {
@@ -1024,6 +1150,7 @@ async function saveGoalFromForm() {
1024
1150
  goal = { text: contract.objective, criteria: contract.acceptanceCriteria, version: goal.version, frozen: false };
1025
1151
  byId('goal-validation').textContent = '';
1026
1152
  notify('Goal draft saved. It is not frozen yet.');
1153
+ byId('goal-dialog').close();
1027
1154
  return contract;
1028
1155
  } catch (error) {
1029
1156
  byId('goal-validation').textContent = error.message;
@@ -1041,6 +1168,7 @@ function renderGoalState() {
1041
1168
  byId('goal-text').disabled = goal.frozen;
1042
1169
  byId('goal-criteria').disabled = goal.frozen;
1043
1170
  byId('goal-task').disabled = goal.frozen;
1171
+ byId('goal-constraints').disabled = goal.frozen;
1044
1172
  byId('goal-run-name').disabled = goal.frozen;
1045
1173
  byId('save-goal').hidden = goal.frozen;
1046
1174
  byId('review-goal').hidden = goal.frozen;
@@ -1051,6 +1179,8 @@ function renderGoalState() {
1051
1179
  async function reviewGoal() {
1052
1180
  const contract = await saveGoalFromForm();
1053
1181
  if (!contract) return;
1182
+ byId('goal-dialog').showModal();
1183
+ byId('goal-dialog').querySelector('.advanced-goal').open = true;
1054
1184
  byId('goal-review').hidden = false;
1055
1185
  byId('goal-review').innerHTML = `
1056
1186
  <strong>${escapeHtml(contract.objective)}</strong>
@@ -1076,6 +1206,7 @@ async function freezeGoalFromForm() {
1076
1206
  renderGoalState();
1077
1207
  renderGraph();
1078
1208
  notify('Goal frozen with an integrity-bound version.');
1209
+ byId('goal-dialog').close();
1079
1210
  } catch (error) {
1080
1211
  byId('goal-validation').textContent = error.message;
1081
1212
  }
@@ -1099,6 +1230,7 @@ async function unfreezeGoalFromForm() {
1099
1230
  renderGoalState();
1100
1231
  renderGraph();
1101
1232
  notify('Goal unfrozen. Previous evidence remains bound to its prior version.');
1233
+ byId('goal-dialog').close();
1102
1234
  } catch (error) {
1103
1235
  byId('goal-validation').textContent = error.message;
1104
1236
  }
@@ -1111,6 +1243,7 @@ function syncGoalFromLive() {
1111
1243
  goal.version = liveGoal.version || 1;
1112
1244
  goal.frozen = liveGoal.frozen === true;
1113
1245
  if (catalog.live.run.task) byId('goal-task').value = catalog.live.run.task;
1246
+ if (catalog.live.run.constraints) byId('goal-constraints').value = catalog.live.run.constraints;
1114
1247
  if (catalog.live.run.displayName) byId('goal-run-name').value = catalog.live.run.displayName;
1115
1248
  renderGoalState();
1116
1249
  }
@@ -1169,54 +1302,233 @@ async function loadRuns() {
1169
1302
  }
1170
1303
  }
1171
1304
 
1305
+ function runHistoryMarkup(run) {
1306
+ const history = run.history || [];
1307
+ if (!history.length) return '<p class="muted">Waiting for the first Run event.</p>';
1308
+ return history.map((entry) => `
1309
+ <p>
1310
+ <time>${escapeHtml(new Date(entry.at).toLocaleString())}</time>
1311
+ <span><b>${escapeHtml(entry.to)}</b> · ${escapeHtml(entry.gate || 'run update')}</span>
1312
+ </p>
1313
+ `).join('');
1314
+ }
1315
+
1172
1316
  async function loadRunDetail(runId) {
1173
1317
  try {
1174
- const result = await api(`/api/runs/${encodeURIComponent(runId)}`);
1318
+ selectedCheckoutRun = runId;
1319
+ const [result, checkoutResult, interactionResult] = await Promise.all([
1320
+ api(`/api/runs/${encodeURIComponent(runId)}`),
1321
+ api(`/api/runs/${encodeURIComponent(runId)}/checkout`),
1322
+ api(`/api/runs/${encodeURIComponent(runId)}/interactions`)
1323
+ ]);
1175
1324
  const run = result.run;
1176
- const artifacts = Object.values(run.artifacts || {});
1325
+ const checkout = checkoutResult.checkout;
1326
+ const maxX = Math.max(...checkout.nodes.map((node) => node.position.x), 0) + NODE_WIDTH + 80;
1327
+ const maxY = Math.max(...checkout.nodes.map((node) => node.position.y), 0) + 180;
1328
+ const paths = checkout.edges.map((edge) => {
1329
+ const from = checkout.nodes.find((node) => node.id === edge.from);
1330
+ const to = checkout.nodes.find((node) => node.id === edge.to);
1331
+ if (!from || !to) return '';
1332
+ const x1 = from.position.x + NODE_WIDTH;
1333
+ const y1 = from.position.y + NODE_PORT_Y;
1334
+ const x2 = to.position.x;
1335
+ const y2 = to.position.y + NODE_PORT_Y;
1336
+ return `<path d="M ${x1} ${y1} C ${x1 + 70} ${y1}, ${x2 - 70} ${y2}, ${x2} ${y2}"></path>`;
1337
+ }).join('');
1338
+ const checkoutGroups = (checkout.loopGroups || []).map((group) => {
1339
+ const members = checkout.nodes.filter((node) => group.nodeIds.includes(node.id));
1340
+ if (!members.length) return '';
1341
+ const left = Math.min(...members.map((node) => node.position.x)) - 28;
1342
+ const top = Math.min(...members.map((node) => node.position.y)) - 36;
1343
+ const right = Math.max(...members.map((node) => node.position.x + NODE_WIDTH)) + 28;
1344
+ const bottom = Math.max(...members.map((node) => node.position.y + 108)) + 28;
1345
+ 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>`;
1346
+ }).join('');
1347
+ const checkoutBody = checkout.workflowBound
1348
+ ? `
1349
+ <section class="checkout-canvas" style="--checkout-width:${maxX}px;--checkout-height:${maxY}px">
1350
+ <svg viewBox="0 0 ${maxX} ${maxY}" aria-hidden="true">${paths}</svg>
1351
+ ${checkoutGroups}
1352
+ ${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">
1353
+ <small>${escapeHtml(node.type)}${node.loopIteration ? ` · LOOP ${escapeHtml(node.loopIteration)}` : ''}</small><strong>${escapeHtml(node.displayName)}</strong><span data-node-status>${escapeHtml(node.status)}</span>
1354
+ </button>`).join('')}
1355
+ </section>
1356
+ <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>
1357
+ `
1358
+ : `
1359
+ <section class="classic-run">
1360
+ <small>CLASSIC RUN · LIVE TRACKING</small>
1361
+ <h3>This Run started before automatic workflow binding was available.</h3>
1362
+ <p>Goal changes, stage gates, evidence, and Agent questions are still monitored here. New Runs show the full node canvas automatically.</p>
1363
+ <div id="classic-run-timeline" class="timeline">${runHistoryMarkup(run)}</div>
1364
+ </section>
1365
+ `;
1177
1366
  byId('run-detail').innerHTML = `
1178
- <header><small>${escapeHtml(run.status)} · ${escapeHtml(run.mode)}</small><h2>${escapeHtml(run.displayName)}</h2><p>${escapeHtml(run.task)}</p></header>
1179
- <div class="run-name-editor"><label for="run-name-edit">Display Name</label><input id="run-name-edit" maxlength="100" value="${escapeHtml(run.displayName)}"><button id="save-run-name">Rename</button></div>
1180
- <dl><dt>Technical ID</dt><dd>${escapeHtml(run.runId)}</dd><dt>Goal</dt><dd>${run.goalFrozen ? `Frozen V${escapeHtml(run.goalVersion)}` : 'Not frozen'}</dd><dt>Evidence</dt><dd>${run.evidence.present ? 'Present' : 'Absent'}</dd></dl>
1181
- <h3>Artifacts</h3>
1182
- <div class="artifact-list">${artifacts.length ? artifacts.map((artifact) => (
1183
- artifact?.path ? `<button data-artifact="${escapeHtml(artifact.path)}">${escapeHtml(artifact.path)}</button>` : ''
1184
- )).join('') : '<p class="muted">No artifacts recorded.</p>'}</div>
1185
- <h3>Decisions</h3>
1186
- <div class="decision-list">${run.decisions?.length ? run.decisions.map((decision) => `<p><strong>${escapeHtml(decision.summary)}</strong><br><span class="muted">${escapeHtml(decision.rationale)}</span></p>`).join('') : '<p class="muted">No decisions recorded.</p>'}</div>
1187
- <h3>Timeline</h3>
1188
- <div class="timeline">${[...(run.history || []), ...(run.events || [])].sort((left, right) => String(right.at).localeCompare(String(left.at))).map((event) => `<p><time>${escapeHtml(event.at || '')}</time><strong>${escapeHtml(event.type || event.gate || event.to || 'event')}</strong>${escapeHtml(event.reason || event.changedNodes?.join(', ') || '')}</p>`).join('')}</div>
1189
- <pre id="artifact-content" hidden></pre>
1367
+ <header class="checkout-header">
1368
+ <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>
1369
+ <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>
1370
+ </header>
1371
+ <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>
1372
+ ${checkoutBody}
1373
+ <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>
1190
1374
  `;
1191
- byId('save-run-name').onclick = async () => {
1375
+ renderInteractions(interactionResult.interactions);
1376
+ byId('checkout-back').onclick = () => {
1377
+ selectedCheckoutRun = null;
1378
+ 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>';
1379
+ };
1380
+ byId('copy-agent-handoff').onclick = () => copyAgentHandoff(runId);
1381
+ if (checkout.workflowBound) byId('duplicate-run-workflow').onclick = async () => {
1192
1382
  try {
1193
- await api('/api/run/name', {
1194
- method: 'PATCH',
1195
- body: JSON.stringify({
1196
- runId,
1197
- displayName: byId('run-name-edit').value,
1198
- actor: 'studio-user'
1199
- })
1383
+ const duplicate = await api(`/api/runs/${encodeURIComponent(runId)}/duplicate`, {
1384
+ method: 'POST',
1385
+ body: JSON.stringify({ recipeId: `${slug(run.displayName)}-copy` })
1200
1386
  });
1201
- await Promise.all([loadRuns(), loadRunDetail(runId)]);
1387
+ draft = normalizeDraftGraph(structuredClone(duplicate.preview.recipe));
1388
+ positions = new Map(checkout.nodes.map((node) => [node.id, node.position]));
1389
+ loadedRecipeId = null;
1390
+ captureHistory({ reset: true });
1391
+ renderGraph();
1392
+ renderRecipeDetails();
1393
+ validateDraft();
1394
+ showWorkspace('workflows');
1395
+ notify('Run duplicated into a new editable workflow. History was not changed.');
1202
1396
  } catch (error) {
1203
1397
  notify(error.message);
1204
1398
  }
1205
1399
  };
1206
- byId('run-detail').querySelectorAll('[data-artifact]').forEach((button) => {
1400
+ byId('run-detail').querySelectorAll('[data-checkout-node]').forEach((button) => {
1401
+ button.onclick = () => loadNodeIo(runId, button.dataset.checkoutNode);
1402
+ });
1403
+ } catch (error) {
1404
+ byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1405
+ }
1406
+ }
1407
+
1408
+ function renderArtifactPreview(artifact) {
1409
+ if (!artifact) return '<p class="muted">No artifact was recorded for this node.</p>';
1410
+ if (artifact.unavailable) return `<p class="validation-message">Artifact unavailable: ${escapeHtml(artifact.code)}</p>`;
1411
+ 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>`;
1412
+ }
1413
+
1414
+ async function loadNodeIo(runId, nodeId) {
1415
+ const panel = byId('node-io-panel');
1416
+ try {
1417
+ const { io } = await api(`/api/runs/${encodeURIComponent(runId)}/nodes/${encodeURIComponent(nodeId)}`);
1418
+ panel.innerHTML = `
1419
+ <header><small>NODE I/O · ${escapeHtml(io.node.status)}</small><h3>${escapeHtml(io.node.displayName)}</h3></header>
1420
+ <div class="io-grid">
1421
+ <section><h4>Input</h4>${io.input.task ? `<p><b>Task</b><br>${escapeHtml(io.input.task)}</p>` : ''}${io.input.constraints ? `<p><b>Constraints</b><br>${escapeHtml(io.input.constraints)}</p>` : ''}${io.input.dependencies.length ? io.input.dependencies.map((dependency) => `<p><b>${escapeHtml(dependency.nodeId)}</b> · ${escapeHtml(dependency.status)}</p>${renderArtifactPreview(dependency.artifact)}`).join('') : '<p class="muted">Root input from this Run.</p>'}</section>
1422
+ <section><h4>Output</h4><p><b>${escapeHtml(io.output.status)}</b>${io.output.reason ? ` · ${escapeHtml(io.output.reason)}` : ''}</p>${renderArtifactPreview(io.output.artifact)}</section>
1423
+ <section><h4>Evidence</h4>${renderArtifactPreview(io.evidence)}</section>
1424
+ <section><h4>Timeline</h4><div class="timeline">${io.timeline.map((event) => `<p><time>${escapeHtml(event.at)}</time><strong>${escapeHtml(event.type)}</strong></p>`).join('') || '<p class="muted">No node events yet.</p>'}</div></section>
1425
+ </div>`;
1426
+ panel.querySelectorAll('[data-artifact-download]').forEach((button) => {
1207
1427
  button.onclick = async () => {
1208
1428
  try {
1209
- const artifactResult = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifact)}`);
1210
- const output = byId('artifact-content');
1211
- output.hidden = false;
1212
- output.textContent = artifactResult.artifact.content;
1429
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifactDownload)}`);
1430
+ const blob = new Blob([result.artifact.content], { type: 'text/plain' });
1431
+ const link = document.createElement('a');
1432
+ link.href = URL.createObjectURL(blob);
1433
+ link.download = button.dataset.artifactDownload.split('/').at(-1);
1434
+ link.click();
1435
+ URL.revokeObjectURL(link.href);
1213
1436
  } catch (error) {
1214
1437
  notify(error.message);
1215
1438
  }
1216
1439
  };
1217
1440
  });
1218
1441
  } catch (error) {
1219
- byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1442
+ panel.innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1443
+ }
1444
+ }
1445
+
1446
+ function renderInteractions(result) {
1447
+ const target = byId('interaction-list');
1448
+ if (!target) return;
1449
+ target.innerHTML = result.questions.length ? result.questions.map((question) => `
1450
+ <article class="agent-question ${question.answer ? 'answered' : 'pending'}">
1451
+ <small>Q${escapeHtml(question.number)} · ${escapeHtml(question.actor)}</small>
1452
+ <p>${escapeHtml(question.message)}</p>
1453
+ ${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>`}
1454
+ </article>
1455
+ `).join('') : '<p class="muted">No questions yet. The Agent can post Q1, Q2, Q3 from the Run-bound CLI.</p>';
1456
+ target.querySelectorAll('[data-answer]').forEach((form) => {
1457
+ form.onsubmit = async (event) => {
1458
+ event.preventDefault();
1459
+ try {
1460
+ await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/questions/${encodeURIComponent(form.dataset.answer)}/answer`, {
1461
+ method: 'POST',
1462
+ body: JSON.stringify({ message: form.querySelector('textarea').value, actor: 'studio-user' })
1463
+ });
1464
+ await refreshCheckoutInteractions();
1465
+ } catch (error) {
1466
+ notify(error.message);
1467
+ }
1468
+ };
1469
+ });
1470
+ }
1471
+
1472
+ async function refreshCheckoutInteractions() {
1473
+ if (!selectedCheckoutRun || !byId('interaction-list')) return;
1474
+ try {
1475
+ const result = await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/interactions`);
1476
+ renderInteractions(result.interactions);
1477
+ } catch {
1478
+ // Corrupt or unavailable Run data is isolated and does not affect another Run.
1479
+ }
1480
+ }
1481
+
1482
+ async function refreshSelectedCheckout() {
1483
+ const runId = selectedCheckoutRun;
1484
+ if (!runId || !byId('checkout-run-status')) return;
1485
+ try {
1486
+ const [detail, checkoutResult] = await Promise.all([
1487
+ api(`/api/runs/${encodeURIComponent(runId)}`),
1488
+ api(`/api/runs/${encodeURIComponent(runId)}/checkout`)
1489
+ ]);
1490
+ if (selectedCheckoutRun !== runId) return;
1491
+ const run = detail.run;
1492
+ const checkout = checkoutResult.checkout;
1493
+ byId('checkout-run-status').textContent = run.status;
1494
+ byId('checkout-goal-state').textContent = run.goalFrozen
1495
+ ? `Goal frozen V${run.goalVersion}`
1496
+ : 'Goal draft';
1497
+ if (!checkout.workflowBound) {
1498
+ const timeline = byId('classic-run-timeline');
1499
+ if (timeline) timeline.innerHTML = runHistoryMarkup(run);
1500
+ return;
1501
+ }
1502
+ for (const node of checkout.nodes) {
1503
+ const element = document.querySelector(`[data-checkout-node="${CSS.escape(node.id)}"]`);
1504
+ if (!element) continue;
1505
+ for (const status of ['pending', 'ready', 'running', 'passed', 'failed', 'skipped', 'blocked']) {
1506
+ element.classList.remove(`status-${status}`);
1507
+ }
1508
+ element.classList.add(`status-${node.status.toLowerCase()}`);
1509
+ const status = element.querySelector('[data-node-status]');
1510
+ if (status) status.textContent = node.status;
1511
+ }
1512
+ for (const group of checkout.loopGroups || []) {
1513
+ const element = document.querySelector(`[data-checkout-loop="${CSS.escape(group.id)}"]`);
1514
+ if (!element) continue;
1515
+ const counter = element.querySelector('span');
1516
+ if (counter) counter.textContent = `Iteration ${group.runtime?.iteration || 1} / ${group.maxIterations}`;
1517
+ }
1518
+ } catch {
1519
+ // Keep the last valid checkout visible during a transient refresh failure.
1520
+ }
1521
+ }
1522
+
1523
+ async function copyAgentHandoff(runId = activeRunId) {
1524
+ try {
1525
+ if (!runId) await ensureStudioRun();
1526
+ const result = await api(`/api/runs/${encodeURIComponent(runId || activeRunId)}/agent-handoff`);
1527
+ await navigator.clipboard.writeText(result.handoff.prompt);
1528
+ byId('goal-dialog').close();
1529
+ notify('Run-bound prompt copied. Paste it into your AI coding Agent.');
1530
+ } catch (error) {
1531
+ byId('goal-validation').textContent = error.message;
1220
1532
  }
1221
1533
  }
1222
1534
 
@@ -1488,6 +1800,8 @@ async function refreshLive() {
1488
1800
  syncGoalFromLive();
1489
1801
  await hydrateGoalFromLive();
1490
1802
  renderLive();
1803
+ await refreshSelectedCheckout();
1804
+ await refreshCheckoutInteractions();
1491
1805
  } catch {
1492
1806
  // A transient refresh failure must not discard the draft.
1493
1807
  }
@@ -1674,6 +1988,72 @@ function notify(text) {
1674
1988
  setTimeout(() => { message.style.display = 'none'; }, 4000);
1675
1989
  }
1676
1990
 
1991
+ function openLoopDialog() {
1992
+ const members = draft.nodes.filter((node) => selectedIds.has(node.id));
1993
+ if (members.length < 2) return notify('Select at least two steps for a Loop Group.');
1994
+ if ((draft.loopGroups || []).some((group) => group.nodeIds.some((id) => selectedIds.has(id)))) {
1995
+ return notify('A step can only belong to one Loop Group.');
1996
+ }
1997
+ const options = members.map((node) =>
1998
+ `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
1999
+ ).join('');
2000
+ for (const id of ['loop-entry', 'loop-decision', 'loop-repeat-target']) byId(id).innerHTML = options;
2001
+ const incomingEntry = members.find((node) =>
2002
+ draft.edges.some((edge) => edge.to === node.id && !selectedIds.has(edge.from))
2003
+ ) || members[0];
2004
+ const outgoing = draft.edges.find((edge) =>
2005
+ selectedIds.has(edge.from) && !selectedIds.has(edge.to)
2006
+ );
2007
+ if (!outgoing) return notify('Connect the Loop decision step to its Continue step first.');
2008
+ const decision = outgoing
2009
+ ? members.find((node) => node.id === outgoing.from)
2010
+ : members.find((node) => ['decision', 'judge', 'condition'].includes(node.type)) || members.at(-1);
2011
+ const exitIds = new Set(draft.edges
2012
+ .filter((edge) => selectedIds.has(edge.from) && !selectedIds.has(edge.to))
2013
+ .map((edge) => edge.to));
2014
+ const exitCandidates = draft.nodes.filter((node) => exitIds.has(node.id));
2015
+ byId('loop-exit-target').innerHTML = exitCandidates.map((node) =>
2016
+ `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
2017
+ ).join('');
2018
+ byId('loop-entry').value = incomingEntry.id;
2019
+ byId('loop-repeat-target').value = incomingEntry.id;
2020
+ byId('loop-decision').value = decision.id;
2021
+ if (outgoing) byId('loop-exit-target').value = outgoing.to;
2022
+ byId('loop-name').value = '';
2023
+ byId('loop-dialog').showModal();
2024
+ }
2025
+
2026
+ function createLoopGroupFromForm(event) {
2027
+ event.preventDefault();
2028
+ const display = byId('loop-name').value.trim();
2029
+ const repeatOutcome = byId('loop-repeat-outcome').value.trim();
2030
+ const exitOutcome = byId('loop-exit-outcome').value.trim();
2031
+ if (repeatOutcome === exitOutcome) return notify('Repeat and Continue outcomes must be different.');
2032
+ let id = slug(display || 'iteration-loop');
2033
+ const occupied = new Set((draft.loopGroups || []).map((group) => group.id));
2034
+ for (let suffix = 2; occupied.has(id); suffix += 1) id = `${slug(display || 'iteration-loop')}-${suffix}`;
2035
+ const loopGroup = {
2036
+ id,
2037
+ displayName: display,
2038
+ nodeIds: draft.nodes.filter((node) => selectedIds.has(node.id)).map((node) => node.id),
2039
+ entryNodeId: byId('loop-entry').value,
2040
+ decisionNodeId: byId('loop-decision').value,
2041
+ repeatTargetId: byId('loop-repeat-target').value,
2042
+ exitTargetId: byId('loop-exit-target').value,
2043
+ maxIterations: Number(byId('loop-max').value),
2044
+ repeatOutcome,
2045
+ exitOutcome,
2046
+ repeatLabel: byId('loop-repeat-label').value.trim(),
2047
+ exitLabel: byId('loop-exit-label').value.trim()
2048
+ };
2049
+ draft.loopGroups.push(loopGroup);
2050
+ captureHistory();
2051
+ renderGraph();
2052
+ validateDraft();
2053
+ byId('loop-dialog').close();
2054
+ notify(`Loop Group “${display}” created.`);
2055
+ }
2056
+
1677
2057
  async function initialize() {
1678
2058
  await refreshCatalog('default');
1679
2059
  byId('recipe').onchange = loadRecipe;
@@ -1700,14 +2080,20 @@ async function initialize() {
1700
2080
  byId('goal-dialog').showModal();
1701
2081
  };
1702
2082
  byId('save-goal').onclick = saveGoalFromForm;
2083
+ byId('start-agent').onclick = () => copyAgentHandoff();
1703
2084
  byId('review-goal').onclick = reviewGoal;
1704
2085
  byId('confirm-freeze').onclick = freezeGoalFromForm;
1705
2086
  byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
1706
2087
  byId('duplicate-selection').onclick = duplicateSelectedNode;
1707
2088
  byId('delete-selection').onclick = deleteSelectedNode;
2089
+ byId('create-loop-group').onclick = openLoopDialog;
2090
+ byId('loop-form').onsubmit = createLoopGroupFromForm;
1708
2091
  document.querySelectorAll('[data-close]').forEach((button) => {
1709
2092
  button.onclick = () => byId(button.dataset.close).close();
1710
2093
  });
2094
+ document.querySelectorAll('.dialog-maximize').forEach((button) => {
2095
+ button.onclick = () => button.closest('dialog').classList.toggle('maximized');
2096
+ });
1711
2097
  byId('workflow-settings').onclick = () => {
1712
2098
  selectedId = null;
1713
2099
  updateSelection();