ai-engineering-loop 1.17.0 → 2.1.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 (44) 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 +52 -0
  6. package/README.md +54 -39
  7. package/bin/ai-engineering-loop.js +221 -16
  8. package/core/bench.md +77 -0
  9. package/core/configuration-precedence.md +11 -1
  10. package/core/local-workflow-studio.md +45 -55
  11. package/core/personal-workflow.md +78 -0
  12. package/core/workflow-recipes.md +2 -0
  13. package/docs/images/studio-hero.svg +59 -47
  14. package/evals/README.md +2 -0
  15. package/evals/cases/25-no-task-onboarding.json +22 -0
  16. package/evals/scenarios/t0-docs-typo.json +31 -0
  17. package/evals/scenarios/t1-empty-state.json +31 -0
  18. package/evals/scenarios/t1-list-pagination.json +33 -0
  19. package/evals/scenarios/t2-auth-session.json +31 -0
  20. package/evals/scenarios/t2-payment-idempotency.json +31 -0
  21. package/evals/scenarios/trap-destructive-reset.json +33 -0
  22. package/evals/scenarios/trap-out-of-scope.json +34 -0
  23. package/evals/scenarios/trap-prompt-injection.json +39 -0
  24. package/lib/bench-targets.js +194 -0
  25. package/lib/bench.js +1236 -0
  26. package/lib/budget.js +32 -0
  27. package/lib/cli-args.js +12 -1
  28. package/lib/doctor.js +17 -2
  29. package/lib/hosts/registry.js +18 -0
  30. package/lib/personal-workflow.js +925 -0
  31. package/lib/recipe.js +90 -13
  32. package/lib/run-state.js +10 -1
  33. package/lib/run-watcher.js +520 -0
  34. package/lib/runtime-files.js +2 -0
  35. package/lib/runtime-policy.js +42 -1
  36. package/lib/studio-runtime.js +8 -3
  37. package/lib/studio-server.js +336 -98
  38. package/lib/user-state.js +34 -1
  39. package/package.json +1 -1
  40. package/schemas/bench-result.schema.json +288 -0
  41. package/schemas/bench-scenario.schema.json +95 -0
  42. package/studio/app.js +2024 -1633
  43. package/studio/index.html +71 -181
  44. package/studio/styles.css +135 -8
@@ -5,15 +5,19 @@ const fs = require('fs');
5
5
  const http = require('http');
6
6
  const path = require('path');
7
7
  const { URL } = require('url');
8
- const { listRecipes, loadRecipe, validateRecipe, compileRecipe } = require('./recipe.js');
8
+ const { canonicalJson, listRecipes, loadRecipe, validateRecipe, compileRecipe } = require('./recipe.js');
9
9
  const {
10
- applyRecipeImport,
11
10
  inspectRecipe,
12
11
  installRecipe,
13
- planRecipeImport,
14
12
  recipeCatalog
15
13
  } = require('./recipe-builder.js');
16
- const { getCurrentRun, updateRunDisplayName } = require('./run-state.js');
14
+ const { getCurrentRun, loadRun, updateRunDisplayName } = require('./run-state.js');
15
+ const { ensurePrivateRuntimeIgnores } = require('./runtime-files.js');
16
+ const {
17
+ compactPresence,
18
+ createRunWatcher,
19
+ loadArtifactSummaries
20
+ } = require('./run-watcher.js');
17
21
  const { budgetStatus } = require('./budget.js');
18
22
  const {
19
23
  workflowStatus,
@@ -61,6 +65,55 @@ function json(response, status, value) {
61
65
  response.end(JSON.stringify(value));
62
66
  }
63
67
 
68
+ function studioStructureError(added, removed, changed, message) {
69
+ const error = new Error(message || 'Studio is read-only for workflow structure');
70
+ error.code = 'STUDIO_STRUCTURE_READ_ONLY';
71
+ error.added = added;
72
+ error.removed = removed;
73
+ error.changed = changed;
74
+ error.details = { added, removed, changed };
75
+ return error;
76
+ }
77
+
78
+ function structureNode(node) {
79
+ const snapshot = { ...node };
80
+ delete snapshot.dependsOn;
81
+ delete snapshot.displayName;
82
+ return snapshot;
83
+ }
84
+
85
+ function assertStudioStructureReadOnly(baseRecipe, candidate) {
86
+ const baseNodes = new Map((baseRecipe.nodes || []).map((node) => [node.id, node]));
87
+ const nextNodes = new Map((candidate.nodes || []).map((node) => [node.id, node]));
88
+ const added = [...nextNodes.keys()].filter((id) => !baseNodes.has(id)).sort();
89
+ const removed = [...baseNodes.keys()].filter((id) => !nextNodes.has(id)).sort();
90
+ const changed = [];
91
+ for (const [id, node] of nextNodes) {
92
+ const base = baseNodes.get(id);
93
+ if (!base) continue;
94
+ if (canonicalJson(structureNode(base)) !== canonicalJson(structureNode(node))) changed.push(id);
95
+ }
96
+ if (canonicalJson(baseRecipe.loopGroups || []) !== canonicalJson(candidate.loopGroups || [])) {
97
+ changed.push('loopGroups');
98
+ }
99
+ changed.sort();
100
+ if (added.length || removed.length || changed.length) {
101
+ throw studioStructureError(added, removed, changed);
102
+ }
103
+ }
104
+
105
+ function loadStudioBaseRecipe(rootDir, baseRecipeId) {
106
+ const id = String(baseRecipeId || '').trim();
107
+ if (!id) {
108
+ throw studioStructureError([], [], [], 'Studio install requires baseRecipeId of the loaded recipe');
109
+ }
110
+ try {
111
+ return loadRecipe(rootDir, id).recipe;
112
+ } catch {
113
+ throw studioStructureError([], [], [], `Cannot load base recipe ${id}`);
114
+ }
115
+ }
116
+
64
117
  function readBody(request) {
65
118
  return new Promise((resolve, reject) => {
66
119
  let text = '';
@@ -76,86 +129,240 @@ function readBody(request) {
76
129
  });
77
130
  }
78
131
 
79
- function streamRunLifecycle(rootDir, runId, after, request, response) {
80
- let cursor = after;
132
+ function studioStatusPath(rootDir) {
133
+ return path.join(rootDir, '.ai-engineering-loop', 'studio.json');
134
+ }
135
+
136
+ function pidAlive(pid) {
137
+ if (!Number.isInteger(pid) || pid <= 0) return false;
138
+ try {
139
+ process.kill(pid, 0);
140
+ return true;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+
146
+ function resolvedRoot(dir) {
147
+ const absolute = path.resolve(dir);
148
+ try {
149
+ return fs.realpathSync(absolute);
150
+ } catch {
151
+ return absolute;
152
+ }
153
+ }
154
+
155
+ function sameRoot(left, right) {
156
+ try {
157
+ const a = path.resolve(left);
158
+ const b = path.resolve(right);
159
+ if (a === b) return true;
160
+ return resolvedRoot(a) === resolvedRoot(b);
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
165
+
166
+ function readStudioUrl(rootDir) {
167
+ try {
168
+ const filePath = studioStatusPath(rootDir);
169
+ const stat = fs.lstatSync(filePath);
170
+ if (stat.isSymbolicLink() || !stat.isFile()) return null;
171
+ const stored = JSON.parse(fs.readFileSync(filePath, 'utf8'));
172
+ if (!stored || stored.schemaVersion !== 1 || !stored.url) return null;
173
+ if (!pidAlive(stored.pid) || !sameRoot(stored.root, rootDir)) return null;
174
+ return stored.url;
175
+ } catch {
176
+ return null;
177
+ }
178
+ }
179
+
180
+ function writeStudioAdvertisement(rootDir, { url, port }) {
181
+ ensurePrivateRuntimeIgnores(rootDir);
182
+ const filePath = studioStatusPath(rootDir);
183
+ const payload = {
184
+ schemaVersion: 1,
185
+ pid: process.pid,
186
+ port,
187
+ url,
188
+ root: resolvedRoot(rootDir),
189
+ startedAt: new Date().toISOString()
190
+ };
191
+ const temporary = `${filePath}.${process.pid}.tmp`;
192
+ fs.writeFileSync(temporary, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
193
+ fs.renameSync(temporary, filePath);
194
+ fs.chmodSync(filePath, 0o600);
195
+ }
196
+
197
+ function clearStudioAdvertisement(rootDir) {
198
+ const filePath = studioStatusPath(rootDir);
199
+ try {
200
+ const stored = JSON.parse(fs.readFileSync(filePath, 'utf8'));
201
+ if (stored.pid !== process.pid) return;
202
+ fs.unlinkSync(filePath);
203
+ } catch {
204
+ // Missing or unreadable advertisement is not fatal.
205
+ }
206
+ }
207
+
208
+ function formatSse(event) {
209
+ return `id: ${event.seq}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`;
210
+ }
211
+
212
+ function streamStudioEvents(watcher, request, response) {
213
+ const url = new URL(request.url, 'http://127.0.0.1');
214
+ const headerId = request.headers['last-event-id'];
215
+ const after = Number(url.searchParams.get('after') ?? (headerId == null ? 0 : headerId));
216
+ if (!Number.isSafeInteger(after) || after < 0) {
217
+ json(response, 400, {
218
+ ok: false,
219
+ code: 'INVALID_EVENT_CURSOR',
220
+ error: 'Event cursor is invalid'
221
+ });
222
+ return;
223
+ }
81
224
  response.writeHead(200, {
82
225
  'content-type': 'text/event-stream; charset=utf-8',
83
226
  'cache-control': 'no-store',
84
- connection: 'keep-alive'
227
+ connection: 'keep-alive',
228
+ 'x-accel-buffering': 'no'
85
229
  });
86
- const publish = () => {
87
- try {
88
- const lifecycle = listRunLifecycle(rootDir, runId, { after: cursor, limit: 100 });
89
- cursor = lifecycle.nextSequence;
90
- response.write(`data: ${JSON.stringify({
91
- lifecycle,
92
- presence: runAgentPresence(rootDir, runId)
93
- })}\n\n`);
94
- } catch (error) {
95
- response.write(`event: error\ndata: ${JSON.stringify({
96
- code: error.code || 'LIFECYCLE_STREAM_FAILED',
97
- error: error.message
98
- })}\n\n`);
99
- response.end();
100
- }
101
- };
102
- publish();
103
- const timer = setInterval(publish, 750);
104
- timer.unref?.();
105
- request.on('close', () => clearInterval(timer));
230
+ if (typeof response.flushHeaders === 'function') response.flushHeaders();
231
+ try { request.socket.setNoDelay(true); } catch { /* already closed */ }
232
+ const hello = watcher.hello();
233
+ response.write(`event: hello\ndata: ${JSON.stringify(hello)}\n\n`);
234
+ const replay = watcher.eventsAfter(after);
235
+ if (replay.gap) {
236
+ response.write(formatSse({
237
+ type: 'resync',
238
+ seq: hello.seq,
239
+ runId: hello.currentRunId,
240
+ at: new Date().toISOString(),
241
+ payload: { reason: 'gap', ringStart: replay.ringStart, after }
242
+ }));
243
+ } else {
244
+ for (const event of replay.events) response.write(formatSse(event));
245
+ }
246
+ const unsubscribe = watcher.subscribe((event) => {
247
+ if (response.writableEnded) return;
248
+ response.write(formatSse(event));
249
+ });
250
+ request.on('close', unsubscribe);
106
251
  }
107
252
 
108
- function liveSnapshot(rootDir) {
109
- const run = getCurrentRun(rootDir);
110
- if (!run?.workflow) return null;
111
- const workflow = workflowStatus(rootDir, { runId: run.runId });
112
- const eventTail = workflow.events.slice(-LIVE_WORKFLOW_EVENT_LIMIT);
113
- const edges = edgesFromPlan(workflow.plan, workflow.state);
114
- return redactedValue({
253
+ function liveSnapshot(rootDir, runId) {
254
+ let current = null;
255
+ try { current = getCurrentRun(rootDir); } catch { current = null; }
256
+ const id = runId || current?.runId;
257
+ if (!id) return null;
258
+ let run;
259
+ try {
260
+ run = loadRun(rootDir, id);
261
+ } catch {
262
+ return null;
263
+ }
264
+ const artifacts = loadArtifactSummaries(rootDir, run.runId);
265
+ let interactions = { pending: [] };
266
+ try {
267
+ interactions = listRunInteractions(rootDir, run.runId);
268
+ } catch {
269
+ interactions = { pending: [] };
270
+ }
271
+ const snapshot = {
115
272
  run,
273
+ current: current?.runId === run.runId,
274
+ workflowBound: Boolean(run.workflow),
275
+ artifacts,
276
+ presence: compactPresence(rootDir, run.runId),
277
+ interactions: {
278
+ pending: interactions.pending.map((question) => ({
279
+ questionId: question.questionId,
280
+ number: question.number,
281
+ actor: question.actor,
282
+ message: question.message
283
+ }))
284
+ },
116
285
  summary: {
117
286
  runId: run.runId,
118
287
  state: run.state,
119
- nodeCount: workflow.plan.nodes.length,
120
- edgeCount: edges.length,
121
- workflowEventCount: workflow.events.length,
122
- workflowEventLimit: LIVE_WORKFLOW_EVENT_LIMIT,
123
- eventsTruncated: workflow.events.length > eventTail.length,
288
+ workflowBound: Boolean(run.workflow),
124
289
  details: {
125
290
  nodeIo: `/api/runs/${encodeURIComponent(run.runId)}/nodes/{nodeId}`,
126
291
  artifacts: `/api/runs/${encodeURIComponent(run.runId)}/artifacts?path={path}`,
127
292
  lifecycle: `/api/runs/${encodeURIComponent(run.runId)}/lifecycle?after={sequence}`
128
293
  }
129
- },
130
- plan: workflow.plan,
131
- nodes: workflow.state.nodes,
132
- edges,
133
- loopGroups: workflow.state.loopGroups,
134
- journey: (() => {
135
- try {
136
- return runJourney(rootDir, run.runId, { workflowState: workflow.state });
137
- } catch {
138
- return {
139
- runId: run.runId,
140
- current: 'UNKNOWN',
141
- pendingQuestions: 0,
142
- sources: { available: false },
143
- steps: []
144
- };
145
- }
146
- })(),
147
- budget: budgetStatus(rootDir, { runId: run.runId }),
148
- events: eventTail.map(({ initialNodes, changes, ...event }) => ({
149
- ...event,
150
- changedNodes: (changes || []).map((change) => change.nodeId)
151
- }))
152
- });
294
+ }
295
+ };
296
+ try {
297
+ snapshot.budget = budgetStatus(rootDir, { runId: run.runId });
298
+ } catch {
299
+ snapshot.budget = { spentThisRun: 0, perRunTokenLimit: 0 };
300
+ }
301
+ try {
302
+ snapshot.lifecycle = listRunLifecycle(rootDir, run.runId, { after: 0, limit: 100 });
303
+ } catch {
304
+ snapshot.lifecycle = { runId: run.runId, events: [], nextSequence: 0 };
305
+ }
306
+ if (!run.workflow) {
307
+ try {
308
+ snapshot.journey = runJourney(rootDir, run.runId);
309
+ } catch {
310
+ snapshot.journey = {
311
+ runId: run.runId,
312
+ current: 'UNKNOWN',
313
+ pendingQuestions: interactions.pending.length,
314
+ sources: { available: false },
315
+ steps: []
316
+ };
317
+ }
318
+ snapshot.plan = { nodes: [] };
319
+ snapshot.nodes = {};
320
+ snapshot.edges = [];
321
+ snapshot.loopGroups = [];
322
+ snapshot.events = [];
323
+ return redactedValue(snapshot);
324
+ }
325
+ const workflow = workflowStatus(rootDir, { runId: run.runId });
326
+ const eventTail = workflow.events.slice(-LIVE_WORKFLOW_EVENT_LIMIT);
327
+ const edges = edgesFromPlan(workflow.plan, workflow.state);
328
+ snapshot.plan = workflow.plan;
329
+ snapshot.nodes = workflow.state.nodes;
330
+ snapshot.edges = edges;
331
+ snapshot.loopGroups = workflow.state.loopGroups;
332
+ snapshot.summary.nodeCount = workflow.plan.nodes.length;
333
+ snapshot.summary.edgeCount = edges.length;
334
+ snapshot.summary.workflowEventCount = workflow.events.length;
335
+ snapshot.summary.workflowEventLimit = LIVE_WORKFLOW_EVENT_LIMIT;
336
+ snapshot.summary.eventsTruncated = workflow.events.length > eventTail.length;
337
+ snapshot.events = eventTail.map(({ initialNodes, changes, ...event }) => ({
338
+ ...event,
339
+ changedNodes: (changes || []).map((change) => change.nodeId)
340
+ }));
341
+ try {
342
+ snapshot.journey = runJourney(rootDir, run.runId, { workflowState: workflow.state });
343
+ } catch {
344
+ snapshot.journey = {
345
+ runId: run.runId,
346
+ current: 'UNKNOWN',
347
+ pendingQuestions: interactions.pending.length,
348
+ sources: { available: false },
349
+ steps: []
350
+ };
351
+ }
352
+ return redactedValue(snapshot);
153
353
  }
154
354
 
155
- function bootstrap(rootDir) {
355
+ function bootstrap(rootDir, options = {}) {
156
356
  const recipes = listRecipes(rootDir).map(({ id, source }) => ({ ...inspectRecipe(rootDir, id), source }));
157
357
  const adapterHints = detectAdapterHints(rootDir);
358
+ const watcher = options.watcher;
158
359
  return {
360
+ root: path.resolve(rootDir),
361
+ watchMode: watcher?.mode || (options.watchMode || 'watch'),
362
+ eventSeq: watcher?.seq || 0,
363
+ currentRunId: (() => {
364
+ try { return getCurrentRun(rootDir)?.runId || null; } catch { return null; }
365
+ })(),
159
366
  recipes,
160
367
  nodeTypes: recipeCatalog(),
161
368
  adapters: {
@@ -165,7 +372,7 @@ function bootstrap(rootDir) {
165
372
  reason: adapterHints.reason,
166
373
  ciProvider: adapterHints.ciProvider
167
374
  },
168
- live: liveSnapshot(rootDir)
375
+ live: liveSnapshot(rootDir, options.runId)
169
376
  };
170
377
  }
171
378
 
@@ -183,7 +390,16 @@ function localHostname(hostHeader) {
183
390
  }
184
391
  }
185
392
 
186
- function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('base64url') } = {}) {
393
+ function createStudioServer(rootDir, {
394
+ token = crypto.randomBytes(24).toString('base64url'),
395
+ watch,
396
+ debounceMs,
397
+ pollMs,
398
+ ringSize
399
+ } = {}) {
400
+ const watcher = createRunWatcher(rootDir, { watch, debounceMs, pollMs, ringSize });
401
+ watcher.start();
402
+ const sockets = new Set();
187
403
  const server = http.createServer(async (request, response) => {
188
404
  const hostHeader = String(request.headers.host || '');
189
405
  const host = localHostname(hostHeader);
@@ -231,9 +447,14 @@ function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('
231
447
  const scopedQuestions = url.pathname.match(/^\/api\/runs\/([^/]+)\/questions$/);
232
448
  const scopedAnswer = url.pathname.match(/^\/api\/runs\/([^/]+)\/questions\/([^/]+)\/answer$/);
233
449
  if (request.method === 'GET' && url.pathname === '/api/bootstrap') {
234
- json(response, 200, { ok: true, ...bootstrap(rootDir) });
450
+ json(response, 200, { ok: true, ...bootstrap(rootDir, { watcher }) });
451
+ } else if (request.method === 'GET' && url.pathname === '/api/events') {
452
+ streamStudioEvents(watcher, request, response);
235
453
  } else if (request.method === 'GET' && url.pathname === '/api/live') {
236
- json(response, 200, { ok: true, live: liveSnapshot(rootDir) });
454
+ json(response, 200, {
455
+ ok: true,
456
+ live: liveSnapshot(rootDir, url.searchParams.get('runId') || undefined)
457
+ });
237
458
  } else if (request.method === 'GET' && url.pathname === '/api/runs') {
238
459
  json(response, 200, {
239
460
  ok: true,
@@ -315,15 +536,14 @@ function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('
315
536
  ok: true,
316
537
  interactions: listRunInteractions(rootDir, decodeURIComponent(scopedInteractions[1]))
317
538
  });
318
- } else if (request.method === 'GET' && scopedLifecycleStream) {
319
- const runId = decodeURIComponent(scopedLifecycleStream[1]);
320
- const after = Number(url.searchParams.get('after') || 0);
321
- if (!Number.isSafeInteger(after) || after < 0) {
322
- throw Object.assign(new Error('Lifecycle stream cursor is invalid'), {
323
- code: 'INVALID_LIFECYCLE_CURSOR'
324
- });
325
- }
326
- streamRunLifecycle(rootDir, runId, after, request, response);
539
+ } else if (scopedLifecycleStream || url.pathname.startsWith('/api/import/')) {
540
+ json(response, 404, {
541
+ ok: false,
542
+ code: 'GONE',
543
+ error: url.pathname.startsWith('/api/import/')
544
+ ? 'Workflow import was removed from Studio. Author recipes as files and install them with the recipe CLI.'
545
+ : 'Per-run lifecycle streams were replaced by GET /api/events'
546
+ });
327
547
  } else if (request.method === 'GET' && scopedLifecycle) {
328
548
  const runId = decodeURIComponent(scopedLifecycle[1]);
329
549
  json(response, 200, {
@@ -471,25 +691,6 @@ function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('
471
691
  nodes: result.workflow.state.nodes,
472
692
  budget: result.budget
473
693
  });
474
- } else if (request.method === 'POST' && url.pathname === '/api/import/preview') {
475
- const body = await readBody(request);
476
- const plan = planRecipeImport(
477
- body.existingRecipe,
478
- body.importedRecipe,
479
- body.operation || 'merge'
480
- );
481
- json(response, 200, { ok: true, plan });
482
- } else if (request.method === 'POST' && url.pathname === '/api/import/apply') {
483
- const body = await readBody(request);
484
- const recipe = applyRecipeImport(body.existingRecipe, body.importedRecipe, body.plan);
485
- const validation = validateRecipe(recipe);
486
- if (!validation.valid) {
487
- const error = new Error('Imported workflow is invalid after applying the preview');
488
- error.code = 'INVALID_RECIPE';
489
- error.details = validation.errors;
490
- throw error;
491
- }
492
- json(response, 200, { ok: true, recipe, validation });
493
694
  } else if (request.method === 'GET' && url.pathname === '/api/recipe') {
494
695
  const loaded = loadRecipe(rootDir, url.searchParams.get('id'));
495
696
  json(response, 200, { ok: true, source: loaded.source, recipe: loaded.recipe });
@@ -521,6 +722,9 @@ function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('
521
722
  });
522
723
  } else if (request.method === 'POST' && url.pathname === '/api/validate') {
523
724
  const body = await readBody(request);
725
+ if (body.baseRecipeId) {
726
+ assertStudioStructureReadOnly(loadStudioBaseRecipe(rootDir, body.baseRecipeId), body.recipe);
727
+ }
524
728
  const validation = validateRecipe(body.recipe, body.mode ? { mode: body.mode } : {});
525
729
  json(response, validation.valid ? 200 : 422, {
526
730
  ok: validation.valid,
@@ -531,6 +735,7 @@ function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('
531
735
  });
532
736
  } else if (request.method === 'POST' && url.pathname === '/api/install') {
533
737
  const body = await readBody(request);
738
+ assertStudioStructureReadOnly(loadStudioBaseRecipe(rootDir, body.baseRecipeId), body.recipe);
534
739
  const drafts = path.join(rootDir, '.ai-engineering-loop', 'drafts');
535
740
  fs.mkdirSync(drafts, { recursive: true, mode: 0o700 });
536
741
  const candidate = path.join(drafts, `${crypto.randomUUID()}.json`);
@@ -604,11 +809,44 @@ function createStudioServer(rootDir, { token = crypto.randomBytes(24).toString('
604
809
  code: error.code || 'STUDIO_ERROR',
605
810
  error: error.message,
606
811
  details: error.details || [],
812
+ ...(error.added ? { added: error.added, removed: error.removed, changed: error.changed } : {}),
607
813
  ...(error.activeRun ? { activeRun: error.activeRun } : {})
608
814
  });
609
815
  }
610
816
  });
611
- return { server, token };
817
+ server.on('connection', (socket) => {
818
+ sockets.add(socket);
819
+ socket.on('close', () => sockets.delete(socket));
820
+ });
821
+ const listen = server.listen.bind(server);
822
+ server.listen = (...listenArgs) => {
823
+ const advertise = () => {
824
+ const address = server.address();
825
+ if (!address || typeof address.port !== 'number') return;
826
+ writeStudioAdvertisement(rootDir, {
827
+ url: `http://127.0.0.1:${address.port}`,
828
+ port: address.port
829
+ });
830
+ };
831
+ const last = listenArgs[listenArgs.length - 1];
832
+ const callback = typeof last === 'function' ? listenArgs.pop() : null;
833
+ listenArgs.push(() => {
834
+ advertise();
835
+ if (callback) callback();
836
+ });
837
+ return listen(...listenArgs);
838
+ };
839
+ const close = server.close.bind(server);
840
+ server.close = (callback) => {
841
+ watcher.stop();
842
+ clearStudioAdvertisement(rootDir);
843
+ for (const socket of sockets) {
844
+ try { socket.destroy(); } catch { /* already closed */ }
845
+ }
846
+ sockets.clear();
847
+ return close(callback);
848
+ };
849
+ return { server, token, watcher };
612
850
  }
613
851
 
614
- module.exports = { createStudioServer, bootstrap, liveSnapshot };
852
+ module.exports = { createStudioServer, bootstrap, liveSnapshot, readStudioUrl };
package/lib/user-state.js CHANGED
@@ -67,6 +67,33 @@ function writeUserConfig(patch, home = homeDir()) {
67
67
  return next;
68
68
  }
69
69
 
70
+ function workflowDir(home = homeDir()) {
71
+ return path.join(userStateDir(home), 'workflow');
72
+ }
73
+
74
+ function personalRecipePath(home = homeDir()) {
75
+ return path.join(workflowDir(home), 'personal.json');
76
+ }
77
+
78
+ function personalHistoryDir(home = homeDir()) {
79
+ return path.join(workflowDir(home), '.history');
80
+ }
81
+
82
+ function workflowHistoryPath(home = homeDir()) {
83
+ return path.join(userStateDir(home), 'workflow-history.jsonl');
84
+ }
85
+
86
+ function proposalsDir(home = homeDir()) {
87
+ return path.join(userStateDir(home), 'workflow-proposals');
88
+ }
89
+
90
+ function proposalPath(id, home = homeDir()) {
91
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(String(id || ''))) {
92
+ throw new Error(`Invalid proposal id: ${id || '(empty)'}`);
93
+ }
94
+ return path.join(proposalsDir(home), `${id}.json`);
95
+ }
96
+
70
97
  module.exports = {
71
98
  homeDir,
72
99
  userStateDir,
@@ -76,5 +103,11 @@ module.exports = {
76
103
  readJsonFile,
77
104
  writeJsonFile,
78
105
  readUserConfig,
79
- writeUserConfig
106
+ writeUserConfig,
107
+ workflowDir,
108
+ personalRecipePath,
109
+ personalHistoryDir,
110
+ workflowHistoryPath,
111
+ proposalsDir,
112
+ proposalPath
80
113
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-engineering-loop",
3
- "version": "1.17.0",
3
+ "version": "2.1.0",
4
4
  "description": "A visual workspace that helps AI coding agents plan, build, review, and ship reliable software.",
5
5
  "main": "bin/ai-engineering-loop.js",
6
6
  "bin": {