ai-engineering-loop 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.
@@ -173,7 +175,7 @@ See the [`core/`](core/) documentation for the full runtime, evidence, recipe, s
173
175
 
174
176
  ## Works locally, delivers anywhere
175
177
 
176
- Your living project context and Run evidence are stored under `.ai-engineering-loop/` and kept out of normal commits. Delivery adapters support:
178
+ 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
179
 
178
180
  - Standard Git
179
181
  - 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);
@@ -1563,6 +1586,46 @@ function handleStudio() {
1563
1586
  });
1564
1587
  }
1565
1588
 
1589
+ function handleInteraction() {
1590
+ const action = args[1] || 'list';
1591
+ const runId = argValue('--run');
1592
+ const message = argValue('--message');
1593
+ const actor = argValue('--by');
1594
+ try {
1595
+ if (!runId) {
1596
+ const error = new Error('interaction requires --run <id>');
1597
+ error.code = 'INVALID_USAGE';
1598
+ throw error;
1599
+ }
1600
+ let result;
1601
+ if (action === 'list') {
1602
+ result = listRunInteractions(CWD, runId);
1603
+ } else if (action === 'question') {
1604
+ result = appendRunQuestion(CWD, runId, { message, actor: actor || 'agent' });
1605
+ } else if (action === 'answer') {
1606
+ result = appendRunAnswer(CWD, runId, args[2], { message, actor: actor || 'human' });
1607
+ } else {
1608
+ const error = new Error('interaction must be list, question, or answer');
1609
+ error.code = 'INVALID_USAGE';
1610
+ throw error;
1611
+ }
1612
+ if (process.argv.includes('--json')) console.log(JSON.stringify(result, null, 2));
1613
+ else if (action === 'list') {
1614
+ if (result.questions.length === 0) console.log('No agent questions for this Run.');
1615
+ for (const question of result.questions) {
1616
+ console.log(`Q${question.number} [${question.questionId}] ${question.message}`);
1617
+ console.log(question.answer ? ` Answer: ${question.answer.message}` : ' Waiting for an answer');
1618
+ }
1619
+ } else {
1620
+ log.success(`✓ ${action === 'question' ? 'Question posted' : 'Answer recorded'}`);
1621
+ console.log(`${result.questionId}: ${result.message}`);
1622
+ }
1623
+ } catch (error) {
1624
+ log.error(`${error.code || 'INTERACTION_FAILED'}: ${error.message}`);
1625
+ process.exitCode = 1;
1626
+ }
1627
+ }
1628
+
1566
1629
  // Help Menu
1567
1630
  function printHelp() {
1568
1631
  console.log(`
@@ -1595,6 +1658,10 @@ Commands:
1595
1658
  activity <id> --message <safe progress text> [--json]
1596
1659
  retry <id> [--json]
1597
1660
  approve <id> --yes [--by <name>] [--json]
1661
+ interaction Exchange Run-bound questions with Studio
1662
+ list --run <id> [--json]
1663
+ question --run <id> --message <text> [--by <agent>]
1664
+ answer <question-id> --run <id> --message <text> [--by <name>]
1598
1665
  policy Inspect or update fail-closed runtime controls
1599
1666
  show [--json]
1600
1667
  set [--default-mode <mode>] [--allow-unattended true|false]
@@ -1679,6 +1746,9 @@ switch (command) {
1679
1746
  case 'node':
1680
1747
  handleNode();
1681
1748
  break;
1749
+ case 'interaction':
1750
+ handleInteraction();
1751
+ break;
1682
1752
  case 'policy':
1683
1753
  handlePolicy();
1684
1754
  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,175 @@
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 workflow = workflowStatus(rootDir, { runId });
51
+ return redactedValue({
52
+ run: {
53
+ runId: run.runId,
54
+ displayName: run.displayName,
55
+ task: run.task,
56
+ constraints: run.constraints || '',
57
+ state: run.state,
58
+ createdAt: run.createdAt,
59
+ updatedAt: run.updatedAt
60
+ },
61
+ graphHash: workflow.plan.graphHash,
62
+ nodes: workflow.plan.nodes.map((node, index) => publicNode(node, workflow.state, index)),
63
+ edges: edgesFromPlan(workflow.plan),
64
+ loopGroups: (workflow.plan.loopGroups || []).map((group) => ({
65
+ ...group,
66
+ runtime: workflow.state.loopGroups[group.id] || null
67
+ })),
68
+ readOnly: true
69
+ });
70
+ }
71
+
72
+ function safeArtifact(rootDir, runId, artifact) {
73
+ if (!artifact?.path) return null;
74
+ try {
75
+ return { descriptor: artifact, preview: inspectRunArtifact(rootDir, runId, artifact.path) };
76
+ } catch (error) {
77
+ return { descriptor: artifact, unavailable: true, code: error.code || 'HISTORY_ARTIFACT_UNAVAILABLE' };
78
+ }
79
+ }
80
+
81
+ function runNodeIo(rootDir, runId, nodeId) {
82
+ const run = loadRun(rootDir, runId);
83
+ const workflow = workflowStatus(rootDir, { runId });
84
+ const node = workflow.plan.nodes.find((candidate) => candidate.id === nodeId);
85
+ if (!node) throw checkoutError(`Node ${nodeId} is not part of Run ${runId}`, 'RUN_NODE_NOT_FOUND');
86
+ const runtime = workflow.state.nodes[nodeId] || {};
87
+ const upstream = (node.dependsOn || []).map((id) => {
88
+ const upstreamState = workflow.state.nodes[id] || {};
89
+ return {
90
+ nodeId: id,
91
+ status: upstreamState.status || 'PENDING',
92
+ artifact: safeArtifact(rootDir, runId, upstreamState.artifact)
93
+ };
94
+ });
95
+ const relevantEvents = workflow.events.filter((event) =>
96
+ event.nodeId === nodeId ||
97
+ event.type === 'WORKFLOW_CREATED' ||
98
+ (event.changes || []).some((change) => change.nodeId === nodeId)
99
+ ).map(({ initialNodes, ...event }) => event);
100
+ return redactedValue({
101
+ runId,
102
+ node: publicNode(node, workflow.state, workflow.plan.nodes.indexOf(node)),
103
+ input: {
104
+ task: node.dependsOn?.length ? null : run.task,
105
+ constraints: node.dependsOn?.length ? null : (run.constraints || ''),
106
+ goal: node.dependsOn?.length ? null : (run.goal || null),
107
+ dependencies: upstream
108
+ },
109
+ output: {
110
+ status: runtime.status || 'PENDING',
111
+ reason: runtime.reason || null,
112
+ loopGroupId: runtime.loopGroupId || null,
113
+ loopIteration: runtime.loopIteration || null,
114
+ artifact: safeArtifact(rootDir, runId, runtime.artifact)
115
+ },
116
+ evidence: safeArtifact(rootDir, runId, runtime.artifact),
117
+ timeline: relevantEvents
118
+ });
119
+ }
120
+
121
+ function authoringNode(node) {
122
+ const omitted = new Set(['dependsOn', 'order', 'legacyGate', 'capabilities', 'status']);
123
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !omitted.has(key)));
124
+ }
125
+
126
+ function duplicateRunAsRecipe(rootDir, runId, { recipeId } = {}) {
127
+ const workflow = workflowStatus(rootDir, { runId });
128
+ const id = String(recipeId || `${workflow.plan.recipe.id || 'workflow'}-copy`).trim();
129
+ const recipe = {
130
+ schemaVersion: 1,
131
+ id,
132
+ name: `${workflow.plan.recipe.name || workflow.plan.recipe.id || 'Workflow'} copy`,
133
+ description: 'Created from an immutable Run plan.',
134
+ version: 1,
135
+ compatibleModes: [workflow.plan.mode],
136
+ nodes: workflow.plan.nodes.map(authoringNode),
137
+ edges: edgesFromPlan(workflow.plan),
138
+ loopGroups: workflow.plan.loopGroups || []
139
+ };
140
+ const validation = validateRecipe(recipe);
141
+ if (!validation.valid) {
142
+ throw checkoutError(`Run cannot be duplicated: ${validation.errors.join('; ')}`, 'INVALID_RUN_DUPLICATE');
143
+ }
144
+ return { sourceRunId: runId, recipe, validation, installed: false };
145
+ }
146
+
147
+ function studioAgentHandoff(rootDir, runId) {
148
+ const run = loadRun(rootDir, runId);
149
+ const commandRoot = `npx ai-engineering-loop interaction`;
150
+ return redactedValue({
151
+ runId,
152
+ externalDispatch: false,
153
+ prompt: [
154
+ `Continue AI Engineering Loop Run ${runId}.`,
155
+ `Task: ${run.task}`,
156
+ run.constraints ? `Constraints: ${run.constraints}` : null,
157
+ 'Read the Run state and evidence before acting.',
158
+ `When blocked, ask with: ${commandRoot} question --run ${runId} --message "Your question"`,
159
+ `Poll answers with: ${commandRoot} list --run ${runId} --json`,
160
+ 'Do not create a sibling Run or claim completion without Run-bound evidence.'
161
+ ].filter(Boolean).join('\n'),
162
+ commands: {
163
+ inspect: `npx ai-engineering-loop status --run ${runId}`,
164
+ question: `${commandRoot} question --run ${runId} --message "Your question"`,
165
+ answers: `${commandRoot} list --run ${runId} --json`
166
+ }
167
+ });
168
+ }
169
+
170
+ module.exports = {
171
+ duplicateRunAsRecipe,
172
+ runCheckout,
173
+ runNodeIo,
174
+ studioAgentHandoff
175
+ };
@@ -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
  }