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/README.md CHANGED
@@ -53,6 +53,8 @@ npx ai-engineering-loop studio
53
53
 
54
54
  Workflow Studio opens locally in your browser. Your project and run evidence stay on your machine.
55
55
 
56
+ On first setup, `.ai-engineering-loop/` is added to your project’s `.gitignore` so plans and Run evidence stay private by default. Want to share that context with your team? Simply remove that line from `.gitignore`.
57
+
56
58
  ## Meet Workflow Studio
57
59
 
58
60
  Workflow Studio makes agent work feel like a product, not a terminal session.
@@ -63,6 +65,8 @@ Workflow Studio makes agent work feel like a product, not a terminal session.
63
65
  - Add the next step directly from any node
64
66
  - Rename nodes in place without breaking their identity
65
67
  - Select, move, duplicate, or delete groups of nodes
68
+ - Turn selected steps into independent Loop Groups
69
+ - Label repeat and continue paths in plain language
66
70
  - Import and export workflow JSON safely
67
71
  - Create your own prompt-powered Agent nodes
68
72
 
@@ -72,12 +76,34 @@ Write the task in plain language, add the outcomes that matter, and **Freeze** t
72
76
 
73
77
  ### Follow every Run
74
78
 
75
- Runs have human-friendly names instead of cryptic hashes. Search previous work, inspect decisions, view evidence, and see exactly where a workflow stopped.
79
+ Runs have human-friendly names instead of cryptic hashes. Search previous work, open any Run as a read-only workflow, and see exactly where it stopped.
80
+
81
+ Select a node to inspect its real **Input**, **Output**, **Evidence**, and timeline. The canvas shows the actual status of every step, so completed work, failures, approvals, and waiting nodes are easy to understand.
82
+
83
+ ### Continue with your AI agent
84
+
85
+ Use **Copy for AI Agent** to create a ready-to-use handoff for the selected Run. The agent continues with the same Goal, workflow, and evidence instead of starting from scratch.
86
+
87
+ If the agent needs clarification, its questions can appear inside Workflow Studio. You answer them there, and the answer stays attached to the Run.
88
+
89
+ ### Repeat only the steps that need another pass
90
+
91
+ Create multiple independent Loop Groups in one workflow:
92
+
93
+ - Select the steps that belong together
94
+ - Choose where the loop starts and where the decision happens
95
+ - Give repeat and continue paths clear labels such as `NO · RETRY` and `YES · CONTINUE`
96
+ - Set a maximum number of passes
97
+ - Follow a separate `Iteration 2 / 3` counter for each group
98
+
99
+ When a loop reaches its limit, Workflow Studio pauses for approval. You can allow one focused extra pass, continue with the current evidence, or stop the Run safely. Nested and overlapping loops stay disabled so the workflow remains easy to read.
76
100
 
77
101
  ### Execute with confidence
78
102
 
79
103
  The Execute button lives beside the workflow trigger. A Run starts only when the Goal, workflow, mode, and safety checks are ready.
80
104
 
105
+ > **New in v1.9.0:** Run Checkout, AI Agent handoff, live Run questions, and Multiple Loop Groups. [See the release](https://github.com/egagofur/ai-engineering-loop/releases/tag/v1.9.0).
106
+
81
107
  ## One workspace from idea to delivery
82
108
 
83
109
  The experience is organized into four simple moments:
@@ -173,7 +199,7 @@ See the [`core/`](core/) documentation for the full runtime, evidence, recipe, s
173
199
 
174
200
  ## Works locally, delivers anywhere
175
201
 
176
- Your living project context and Run evidence are stored under `.ai-engineering-loop/` and kept out of normal commits. Delivery adapters support:
202
+ Your living project context and Run evidence are stored under `.ai-engineering-loop/` and kept out of normal commits by default. You can remove its `.gitignore` entry whenever you want to share that context. Delivery adapters support:
177
203
 
178
204
  - Standard Git
179
205
  - GitHub
@@ -77,6 +77,11 @@ const {
77
77
  const {
78
78
  PRIVATE_RUNTIME_GITIGNORE
79
79
  } = require('../lib/runtime-files.js');
80
+ const {
81
+ appendRunAnswer,
82
+ appendRunQuestion,
83
+ listRunInteractions
84
+ } = require('../lib/run-interactions.js');
80
85
  const {
81
86
  abortSandbox,
82
87
  captureSandbox,
@@ -143,6 +148,22 @@ function writeContextFile(filePath, content, { overwrite = true } = {}) {
143
148
  return true;
144
149
  }
145
150
 
151
+ function ignoreProjectContextOnFirstInit(rootDir) {
152
+ const filePath = path.join(rootDir, '.gitignore');
153
+ if (fs.existsSync(filePath) && fs.lstatSync(filePath).isSymbolicLink()) {
154
+ const error = new Error('Refusing to update a symlinked project .gitignore');
155
+ error.code = 'UNSAFE_GITIGNORE';
156
+ throw error;
157
+ }
158
+ const current = readFileSafe(filePath) || '';
159
+ const alreadyIgnored = current.split(/\r?\n/)
160
+ .some((line) => line.trim().replace(/\/+$/, '') === '.ai-engineering-loop');
161
+ if (alreadyIgnored) return false;
162
+ const separator = current && !current.endsWith('\n') ? '\n' : '';
163
+ fs.writeFileSync(filePath, `${current}${separator}.ai-engineering-loop/\n`);
164
+ return true;
165
+ }
166
+
146
167
  /**
147
168
  * Colorized console helpers
148
169
  */
@@ -633,6 +654,7 @@ function handleInit() {
633
654
  log.info('AI Engineering Loop — Project Context Bootstrap (init)');
634
655
  log.dim(`Target directory: ${CWD}`);
635
656
 
657
+ const firstInitialization = !fs.existsSync(CONTEXT_DIR);
636
658
  let overwriteCore = true;
637
659
  let trigger = 'init';
638
660
  let impact = 'INITIAL_BOOTSTRAP';
@@ -661,13 +683,14 @@ function handleInit() {
661
683
  log.dim(`> Package Manager: ${discovery.packageManager}`);
662
684
  log.dim(`> Unit Test Command: ${discovery.scripts.testUnit}`);
663
685
 
686
+ if (firstInitialization) ignoreProjectContextOnFirstInit(CWD);
664
687
  generateContextFiles(CWD, discovery, trigger, impact, { overwriteCore });
665
688
 
666
689
  const validation = validateContext(CONTEXT_DIR);
667
690
  if (validation.valid) {
668
691
  log.success('\n✓ Successfully initialized .ai-engineering-loop/ with:');
669
692
  REQUIRED_FILES.forEach((f) => console.log(` - .ai-engineering-loop/${f}`));
670
- log.dim('\nRecommendation: Commit .ai-engineering-loop/ to version control so team agents share context.');
693
+ log.dim('\nProject context is private by default. Remove .ai-engineering-loop/ from .gitignore if you want to share it.');
671
694
  } else {
672
695
  log.error(`\n✗ Initialization validation failed: ${validation.reason}`);
673
696
  process.exit(1);
@@ -845,8 +868,13 @@ function handleRun() {
845
868
  let mode = modeArg ? normalizeMode(modeArg) : (startsNewRun ? policy.defaultMode : null);
846
869
  let workflow = null;
847
870
  let requestedRunId = null;
848
- if (recipeArg) {
849
- const { recipe } = loadRecipe(CWD, recipeArg);
871
+ const selectedRecipeId = recipeArg || (
872
+ startsNewRun
873
+ ? (mode === RUN_MODES.REPORT_ONLY ? 'audit' : 'default')
874
+ : null
875
+ );
876
+ if (selectedRecipeId) {
877
+ const { recipe } = loadRecipe(CWD, selectedRecipeId);
850
878
  if (!mode && current) mode = current.mode;
851
879
  if (startsNewRun && !modeArg && !recipe.compatibleModes.includes(mode)) {
852
880
  if (recipe.compatibleModes.length !== 1) {
@@ -1563,6 +1591,46 @@ function handleStudio() {
1563
1591
  });
1564
1592
  }
1565
1593
 
1594
+ function handleInteraction() {
1595
+ const action = args[1] || 'list';
1596
+ const runId = argValue('--run');
1597
+ const message = argValue('--message');
1598
+ const actor = argValue('--by');
1599
+ try {
1600
+ if (!runId) {
1601
+ const error = new Error('interaction requires --run <id>');
1602
+ error.code = 'INVALID_USAGE';
1603
+ throw error;
1604
+ }
1605
+ let result;
1606
+ if (action === 'list') {
1607
+ result = listRunInteractions(CWD, runId);
1608
+ } else if (action === 'question') {
1609
+ result = appendRunQuestion(CWD, runId, { message, actor: actor || 'agent' });
1610
+ } else if (action === 'answer') {
1611
+ result = appendRunAnswer(CWD, runId, args[2], { message, actor: actor || 'human' });
1612
+ } else {
1613
+ const error = new Error('interaction must be list, question, or answer');
1614
+ error.code = 'INVALID_USAGE';
1615
+ throw error;
1616
+ }
1617
+ if (process.argv.includes('--json')) console.log(JSON.stringify(result, null, 2));
1618
+ else if (action === 'list') {
1619
+ if (result.questions.length === 0) console.log('No agent questions for this Run.');
1620
+ for (const question of result.questions) {
1621
+ console.log(`Q${question.number} [${question.questionId}] ${question.message}`);
1622
+ console.log(question.answer ? ` Answer: ${question.answer.message}` : ' Waiting for an answer');
1623
+ }
1624
+ } else {
1625
+ log.success(`✓ ${action === 'question' ? 'Question posted' : 'Answer recorded'}`);
1626
+ console.log(`${result.questionId}: ${result.message}`);
1627
+ }
1628
+ } catch (error) {
1629
+ log.error(`${error.code || 'INTERACTION_FAILED'}: ${error.message}`);
1630
+ process.exitCode = 1;
1631
+ }
1632
+ }
1633
+
1566
1634
  // Help Menu
1567
1635
  function printHelp() {
1568
1636
  console.log(`
@@ -1595,6 +1663,10 @@ Commands:
1595
1663
  activity <id> --message <safe progress text> [--json]
1596
1664
  retry <id> [--json]
1597
1665
  approve <id> --yes [--by <name>] [--json]
1666
+ interaction Exchange Run-bound questions with Studio
1667
+ list --run <id> [--json]
1668
+ question --run <id> --message <text> [--by <agent>]
1669
+ answer <question-id> --run <id> --message <text> [--by <name>]
1598
1670
  policy Inspect or update fail-closed runtime controls
1599
1671
  show [--json]
1600
1672
  set [--default-mode <mode>] [--allow-unattended true|false]
@@ -1679,6 +1751,9 @@ switch (command) {
1679
1751
  case 'node':
1680
1752
  handleNode();
1681
1753
  break;
1754
+ case 'interaction':
1755
+ handleInteraction();
1756
+ break;
1682
1757
  case 'policy':
1683
1758
  handlePolicy();
1684
1759
  break;
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ const LOOP_ID = /^[a-z][a-z0-9-]{0,63}$/;
4
+ const OUTCOME = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
5
+ const MAX_LOOP_GROUPS = 16;
6
+ const MAX_LOOP_ITERATIONS = 100;
7
+ const MAX_LOOP_LABEL = 40;
8
+
9
+ function clone(value) {
10
+ return JSON.parse(JSON.stringify(value));
11
+ }
12
+
13
+ function reachable(edges, from, to, allowed) {
14
+ const pending = [from];
15
+ const seen = new Set();
16
+ while (pending.length) {
17
+ const current = pending.shift();
18
+ if (current === to) return true;
19
+ if (seen.has(current)) continue;
20
+ seen.add(current);
21
+ for (const edge of edges) {
22
+ if (edge.from === current && allowed.has(edge.to)) pending.push(edge.to);
23
+ }
24
+ }
25
+ return false;
26
+ }
27
+
28
+ function validateLoopGroups(recipe) {
29
+ const errors = [];
30
+ if (recipe.loopGroups == null) return { valid: true, errors };
31
+ if (!Array.isArray(recipe.loopGroups)) return { valid: false, errors: ['loopGroups must be an array'] };
32
+ if (recipe.loopGroups.length > MAX_LOOP_GROUPS) {
33
+ errors.push(`loopGroups exceeds the maximum of ${MAX_LOOP_GROUPS}`);
34
+ }
35
+ const nodes = new Map((recipe.nodes || []).map((node) => [node.id, node]));
36
+ const edges = Array.isArray(recipe.edges) ? recipe.edges : [];
37
+ const groupIds = new Set();
38
+ const owner = new Map();
39
+
40
+ recipe.loopGroups.forEach((group, index) => {
41
+ const location = `loopGroups[${index}]`;
42
+ if (!group || typeof group !== 'object' || Array.isArray(group)) {
43
+ errors.push(`${location} must be an object`);
44
+ return;
45
+ }
46
+ if (!LOOP_ID.test(String(group.id || ''))) errors.push(`${location}.id is invalid`);
47
+ else if (groupIds.has(group.id)) errors.push(`duplicate Loop Group id: ${group.id}`);
48
+ else groupIds.add(group.id);
49
+ if (!String(group.displayName || '').trim() || String(group.displayName).length > 80) {
50
+ errors.push(`${location}.displayName must be between 1 and 80 characters`);
51
+ }
52
+ if (!Array.isArray(group.nodeIds) || group.nodeIds.length < 2) {
53
+ errors.push(`${location}.nodeIds must contain at least two nodes`);
54
+ }
55
+ const members = new Set(group.nodeIds || []);
56
+ if (members.size !== (group.nodeIds || []).length) errors.push(`${location}.nodeIds must be unique`);
57
+ for (const nodeId of members) {
58
+ if (!nodes.has(nodeId)) errors.push(`${location}.nodeIds references unknown node ${nodeId}`);
59
+ if (owner.has(nodeId)) errors.push(`${nodeId} belongs to multiple Loop Groups`);
60
+ else owner.set(nodeId, group.id);
61
+ }
62
+ for (const field of ['entryNodeId', 'decisionNodeId', 'repeatTargetId']) {
63
+ if (!nodes.has(group[field])) errors.push(`${location}.${field} references unknown node ${group[field] || '(missing)'}`);
64
+ else if (!members.has(group[field])) errors.push(`${location}.${field} must belong to the group`);
65
+ }
66
+ if (!nodes.has(group.exitTargetId)) {
67
+ errors.push(`${location}.exitTargetId references unknown node ${group.exitTargetId || '(missing)'}`);
68
+ } else if (members.has(group.exitTargetId)) {
69
+ errors.push(`${location}.exitTargetId must be outside the group`);
70
+ }
71
+ if (group.entryNodeId === group.decisionNodeId) {
72
+ errors.push(`${location}.entryNodeId and decisionNodeId must be different`);
73
+ }
74
+ if (!Number.isSafeInteger(group.maxIterations) ||
75
+ group.maxIterations < 1 || group.maxIterations > MAX_LOOP_ITERATIONS) {
76
+ errors.push(`${location}.maxIterations must be an integer from 1 to ${MAX_LOOP_ITERATIONS}`);
77
+ }
78
+ for (const field of ['repeatOutcome', 'exitOutcome']) {
79
+ if (!OUTCOME.test(String(group[field] || ''))) errors.push(`${location}.${field} is invalid`);
80
+ }
81
+ if (group.repeatOutcome === group.exitOutcome) errors.push(`${location} outcomes must be different`);
82
+ for (const field of ['repeatLabel', 'exitLabel']) {
83
+ const value = String(group[field] || '').trim();
84
+ if (!value || value.length > MAX_LOOP_LABEL || /[\u0000-\u001f\u007f]/.test(value)) {
85
+ errors.push(`${location}.${field} must be 1-${MAX_LOOP_LABEL} printable characters`);
86
+ }
87
+ }
88
+
89
+ for (const edge of edges) {
90
+ const fromInside = members.has(edge.from);
91
+ const toInside = members.has(edge.to);
92
+ if (!fromInside && toInside && edge.to !== group.entryNodeId) {
93
+ errors.push(`${location} may enter only through ${group.entryNodeId}`);
94
+ }
95
+ if (fromInside && !toInside &&
96
+ (edge.from !== group.decisionNodeId || edge.to !== group.exitTargetId)) {
97
+ errors.push(`${location} may exit only from ${group.decisionNodeId} to ${group.exitTargetId}`);
98
+ }
99
+ }
100
+ if (!edges.some((edge) => edge.from === group.decisionNodeId && edge.to === group.exitTargetId)) {
101
+ errors.push(`${location} requires an Edge from decisionNodeId to exitTargetId`);
102
+ }
103
+ if (nodes.has(group.entryNodeId) && nodes.has(group.decisionNodeId)) {
104
+ for (const nodeId of members) {
105
+ if (!reachable(edges, group.entryNodeId, nodeId, members)) {
106
+ errors.push(`${location}.${nodeId} must be reachable from entryNodeId`);
107
+ }
108
+ if (!reachable(edges, nodeId, group.decisionNodeId, members)) {
109
+ errors.push(`${location}.${nodeId} must lead to decisionNodeId`);
110
+ }
111
+ }
112
+ }
113
+ });
114
+ return { valid: errors.length === 0, errors: [...new Set(errors)] };
115
+ }
116
+
117
+ function createLoopGroup(recipe, group) {
118
+ const next = clone(recipe);
119
+ next.loopGroups = [...(next.loopGroups || []), clone(group)];
120
+ const validation = validateLoopGroups(next);
121
+ if (!validation.valid) {
122
+ const error = new Error(`Loop Group is invalid: ${validation.errors.join('; ')}`);
123
+ error.code = 'INVALID_LOOP_GROUP';
124
+ error.details = validation.errors;
125
+ throw error;
126
+ }
127
+ return next;
128
+ }
129
+
130
+ function removeLoopGroup(recipe, groupId) {
131
+ const next = clone(recipe);
132
+ next.loopGroups = (next.loopGroups || []).filter((group) => group.id !== groupId);
133
+ return next;
134
+ }
135
+
136
+ module.exports = {
137
+ LOOP_ID,
138
+ MAX_LOOP_GROUPS,
139
+ MAX_LOOP_ITERATIONS,
140
+ MAX_LOOP_LABEL,
141
+ createLoopGroup,
142
+ removeLoopGroup,
143
+ validateLoopGroups
144
+ };
@@ -34,6 +34,14 @@ const NODE_TYPES = Object.freeze({
34
34
  sideEffect: false,
35
35
  modelRequired: false
36
36
  }),
37
+ decision: Object.freeze({
38
+ label: 'Decision',
39
+ category: 'control',
40
+ builtIn: false,
41
+ mutation: false,
42
+ sideEffect: false,
43
+ modelRequired: false
44
+ }),
37
45
  approval: Object.freeze({
38
46
  label: 'Human Approval',
39
47
  category: 'safety',
@@ -61,11 +61,16 @@ function planGraphMerge(existingRecipe, importedRecipe) {
61
61
  const imported = migrateLegacyRecipe(importedRecipe);
62
62
  const nodeIds = new Set((existing.nodes || []).map((node) => node.id));
63
63
  const edgeIds = new Set((existing.edges || []).map((edge) => edge.id));
64
+ const loopGroupIds = new Set((existing.loopGroups || []).map((group) => group.id));
64
65
  const nodeIdMap = {};
65
66
  const edgeIdMap = {};
67
+ const loopGroupIdMap = {};
66
68
  for (const node of imported.nodes || []) nodeIdMap[node.id] = uniqueId(node.id, nodeIds);
67
69
  for (const edge of imported.edges || []) edgeIdMap[edge.id] = uniqueId(edge.id, edgeIds);
68
- return { nodeIdMap, edgeIdMap };
70
+ for (const group of imported.loopGroups || []) {
71
+ loopGroupIdMap[group.id] = uniqueId(group.id, loopGroupIds);
72
+ }
73
+ return { nodeIdMap, edgeIdMap, loopGroupIdMap };
69
74
  }
70
75
 
71
76
  function mergeGraphs(existingRecipe, importedRecipe, plan) {
@@ -78,7 +83,21 @@ function mergeGraphs(existingRecipe, importedRecipe, plan) {
78
83
  from: plan.nodeIdMap[edge.from],
79
84
  to: plan.nodeIdMap[edge.to]
80
85
  }));
81
- return { ...existing, nodes: [...existing.nodes, ...nodes], edges: [...existing.edges, ...edges] };
86
+ const loopGroups = (imported.loopGroups || []).map((group) => ({
87
+ ...group,
88
+ id: plan.loopGroupIdMap[group.id],
89
+ nodeIds: group.nodeIds.map((nodeId) => plan.nodeIdMap[nodeId]),
90
+ entryNodeId: plan.nodeIdMap[group.entryNodeId],
91
+ decisionNodeId: plan.nodeIdMap[group.decisionNodeId],
92
+ repeatTargetId: plan.nodeIdMap[group.repeatTargetId],
93
+ exitTargetId: plan.nodeIdMap[group.exitTargetId]
94
+ }));
95
+ return {
96
+ ...existing,
97
+ nodes: [...existing.nodes, ...nodes],
98
+ edges: [...existing.edges, ...edges],
99
+ loopGroups: [...(existing.loopGroups || []), ...loopGroups]
100
+ };
82
101
  }
83
102
 
84
103
  module.exports = {
package/lib/recipe.js CHANGED
@@ -17,6 +17,7 @@ const {
17
17
  migrateLegacyRecipe,
18
18
  withDependencies
19
19
  } = require('./recipe-graph.js');
20
+ const { validateLoopGroups } = require('./loop-groups.js');
20
21
 
21
22
  const RECIPE_ID = /^[a-z][a-z0-9-]{0,63}$/;
22
23
  const NODE_ID = /^[a-z][a-z0-9-]{0,63}$/;
@@ -405,6 +406,8 @@ function validateRecipe(recipe, { mode } = {}) {
405
406
  if (dependency === node.id) errors.push(`${node.id} cannot depend on itself`);
406
407
  }
407
408
  }
409
+ const loopValidation = validateLoopGroups(recipe);
410
+ errors.push(...loopValidation.errors);
408
411
  const order = topologicalOrder(projectedNodes, byId, errors);
409
412
  const terminals = projectedNodes.filter((node) => ['report', 'delivery'].includes(node.type));
410
413
  for (const terminal of terminals) {
@@ -467,7 +470,8 @@ function compileRecipe(recipe, { mode } = {}) {
467
470
  sourceHash: sha256(recipe)
468
471
  },
469
472
  mode: selectedMode,
470
- nodes: compiledNodes
473
+ nodes: compiledNodes,
474
+ loopGroups: canonicalize(recipe.loopGroups || [])
471
475
  };
472
476
  return {
473
477
  ...graphMaterial,
@@ -0,0 +1,188 @@
1
+ 'use strict';
2
+
3
+ const { validateRecipe } = require('./recipe.js');
4
+ const { stableEdgeId } = require('./recipe-graph.js');
5
+ const { loadRun } = require('./run-state.js');
6
+ const { inspectRunArtifact } = require('./run-history.js');
7
+ const { redactSecrets } = require('./safe-context.js');
8
+ const { workflowStatus } = require('./workflow-runtime.js');
9
+
10
+ function checkoutError(message, code = 'RUN_CHECKOUT_ERROR') {
11
+ const error = new Error(message);
12
+ error.code = code;
13
+ return error;
14
+ }
15
+
16
+ function fallbackPosition(index) {
17
+ return { x: 100 + (index % 4) * 300, y: 100 + Math.floor(index / 4) * 190 };
18
+ }
19
+
20
+ function redactedValue(value) {
21
+ return JSON.parse(redactSecrets(JSON.stringify(value)).text);
22
+ }
23
+
24
+ function edgesFromPlan(plan) {
25
+ return plan.nodes.flatMap((node) => (node.dependsOn || []).map((from) => ({
26
+ id: stableEdgeId(from, node.id),
27
+ from,
28
+ to: node.id
29
+ })));
30
+ }
31
+
32
+ function publicNode(node, state, index) {
33
+ const runtime = state.nodes[node.id] || {};
34
+ return {
35
+ id: node.id,
36
+ displayName: node.displayName || node.name || node.id,
37
+ type: node.type,
38
+ status: runtime.status || 'PENDING',
39
+ attempts: runtime.attempts || 0,
40
+ reason: runtime.reason || null,
41
+ loopGroupId: runtime.loopGroupId || null,
42
+ loopIteration: runtime.loopIteration || null,
43
+ updatedAt: runtime.updatedAt || null,
44
+ position: fallbackPosition(index)
45
+ };
46
+ }
47
+
48
+ function runCheckout(rootDir, runId) {
49
+ const run = loadRun(rootDir, runId);
50
+ const publicRun = {
51
+ runId: run.runId,
52
+ displayName: run.displayName,
53
+ task: run.task,
54
+ constraints: run.constraints || '',
55
+ state: run.state,
56
+ createdAt: run.createdAt,
57
+ updatedAt: run.updatedAt
58
+ };
59
+ if (!run.workflow) {
60
+ return redactedValue({
61
+ run: publicRun,
62
+ graphHash: null,
63
+ nodes: [],
64
+ edges: [],
65
+ loopGroups: [],
66
+ workflowBound: false,
67
+ readOnly: true
68
+ });
69
+ }
70
+ const workflow = workflowStatus(rootDir, { runId });
71
+ return redactedValue({
72
+ run: publicRun,
73
+ graphHash: workflow.plan.graphHash,
74
+ nodes: workflow.plan.nodes.map((node, index) => publicNode(node, workflow.state, index)),
75
+ edges: edgesFromPlan(workflow.plan),
76
+ loopGroups: (workflow.plan.loopGroups || []).map((group) => ({
77
+ ...group,
78
+ runtime: workflow.state.loopGroups[group.id] || null
79
+ })),
80
+ workflowBound: true,
81
+ readOnly: true
82
+ });
83
+ }
84
+
85
+ function safeArtifact(rootDir, runId, artifact) {
86
+ if (!artifact?.path) return null;
87
+ try {
88
+ return { descriptor: artifact, preview: inspectRunArtifact(rootDir, runId, artifact.path) };
89
+ } catch (error) {
90
+ return { descriptor: artifact, unavailable: true, code: error.code || 'HISTORY_ARTIFACT_UNAVAILABLE' };
91
+ }
92
+ }
93
+
94
+ function runNodeIo(rootDir, runId, nodeId) {
95
+ const run = loadRun(rootDir, runId);
96
+ const workflow = workflowStatus(rootDir, { runId });
97
+ const node = workflow.plan.nodes.find((candidate) => candidate.id === nodeId);
98
+ if (!node) throw checkoutError(`Node ${nodeId} is not part of Run ${runId}`, 'RUN_NODE_NOT_FOUND');
99
+ const runtime = workflow.state.nodes[nodeId] || {};
100
+ const upstream = (node.dependsOn || []).map((id) => {
101
+ const upstreamState = workflow.state.nodes[id] || {};
102
+ return {
103
+ nodeId: id,
104
+ status: upstreamState.status || 'PENDING',
105
+ artifact: safeArtifact(rootDir, runId, upstreamState.artifact)
106
+ };
107
+ });
108
+ const relevantEvents = workflow.events.filter((event) =>
109
+ event.nodeId === nodeId ||
110
+ event.type === 'WORKFLOW_CREATED' ||
111
+ (event.changes || []).some((change) => change.nodeId === nodeId)
112
+ ).map(({ initialNodes, ...event }) => event);
113
+ return redactedValue({
114
+ runId,
115
+ node: publicNode(node, workflow.state, workflow.plan.nodes.indexOf(node)),
116
+ input: {
117
+ task: node.dependsOn?.length ? null : run.task,
118
+ constraints: node.dependsOn?.length ? null : (run.constraints || ''),
119
+ goal: node.dependsOn?.length ? null : (run.goal || null),
120
+ dependencies: upstream
121
+ },
122
+ output: {
123
+ status: runtime.status || 'PENDING',
124
+ reason: runtime.reason || null,
125
+ loopGroupId: runtime.loopGroupId || null,
126
+ loopIteration: runtime.loopIteration || null,
127
+ artifact: safeArtifact(rootDir, runId, runtime.artifact)
128
+ },
129
+ evidence: safeArtifact(rootDir, runId, runtime.artifact),
130
+ timeline: relevantEvents
131
+ });
132
+ }
133
+
134
+ function authoringNode(node) {
135
+ const omitted = new Set(['dependsOn', 'order', 'legacyGate', 'capabilities', 'status']);
136
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !omitted.has(key)));
137
+ }
138
+
139
+ function duplicateRunAsRecipe(rootDir, runId, { recipeId } = {}) {
140
+ const workflow = workflowStatus(rootDir, { runId });
141
+ const id = String(recipeId || `${workflow.plan.recipe.id || 'workflow'}-copy`).trim();
142
+ const recipe = {
143
+ schemaVersion: 1,
144
+ id,
145
+ name: `${workflow.plan.recipe.name || workflow.plan.recipe.id || 'Workflow'} copy`,
146
+ description: 'Created from an immutable Run plan.',
147
+ version: 1,
148
+ compatibleModes: [workflow.plan.mode],
149
+ nodes: workflow.plan.nodes.map(authoringNode),
150
+ edges: edgesFromPlan(workflow.plan),
151
+ loopGroups: workflow.plan.loopGroups || []
152
+ };
153
+ const validation = validateRecipe(recipe);
154
+ if (!validation.valid) {
155
+ throw checkoutError(`Run cannot be duplicated: ${validation.errors.join('; ')}`, 'INVALID_RUN_DUPLICATE');
156
+ }
157
+ return { sourceRunId: runId, recipe, validation, installed: false };
158
+ }
159
+
160
+ function studioAgentHandoff(rootDir, runId) {
161
+ const run = loadRun(rootDir, runId);
162
+ const commandRoot = `npx ai-engineering-loop interaction`;
163
+ return redactedValue({
164
+ runId,
165
+ externalDispatch: false,
166
+ prompt: [
167
+ `Continue AI Engineering Loop Run ${runId}.`,
168
+ `Task: ${run.task}`,
169
+ run.constraints ? `Constraints: ${run.constraints}` : null,
170
+ 'Read the Run state and evidence before acting.',
171
+ `When blocked, ask with: ${commandRoot} question --run ${runId} --message "Your question"`,
172
+ `Poll answers with: ${commandRoot} list --run ${runId} --json`,
173
+ 'Do not create a sibling Run or claim completion without Run-bound evidence.'
174
+ ].filter(Boolean).join('\n'),
175
+ commands: {
176
+ inspect: `npx ai-engineering-loop status --run ${runId}`,
177
+ question: `${commandRoot} question --run ${runId} --message "Your question"`,
178
+ answers: `${commandRoot} list --run ${runId} --json`
179
+ }
180
+ });
181
+ }
182
+
183
+ module.exports = {
184
+ duplicateRunAsRecipe,
185
+ runCheckout,
186
+ runNodeIo,
187
+ studioAgentHandoff
188
+ };
@@ -165,7 +165,7 @@ function inspectRunArtifact(rootDir, runId, relativePath, { maxBytes = MAX_ARTIF
165
165
  }
166
166
  const realDirectory = fs.realpathSync(directory);
167
167
  const realRelative = path.relative(realDirectory, real);
168
- if (stat.isSymbolicLink() || !stat.isFile() ||
168
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 ||
169
169
  realRelative === '..' || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
170
170
  throw historyError('Artifact must be a regular file inside its owning run', 'UNSAFE_HISTORY_PATH');
171
171
  }