ai-engineering-loop 1.2.1 → 1.5.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.
@@ -0,0 +1,692 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { sha256 } = require('./recipe.js');
6
+ const {
7
+ RUN_STATES,
8
+ atomicWriteJson,
9
+ getCurrentRun,
10
+ loadRun,
11
+ runsDir
12
+ } = require('./run-state.js');
13
+
14
+ const NODE_STATES = Object.freeze({
15
+ PENDING: 'PENDING',
16
+ READY: 'READY',
17
+ RUNNING: 'RUNNING',
18
+ PASSED: 'PASSED',
19
+ FAILED: 'FAILED',
20
+ SKIPPED: 'SKIPPED',
21
+ BLOCKED: 'BLOCKED'
22
+ });
23
+ const SUCCESS_STATES = new Set([NODE_STATES.PASSED, NODE_STATES.SKIPPED]);
24
+ const LEGACY_NODE_TYPES = new Set([
25
+ 'goal-contract',
26
+ 'maker',
27
+ 'verification',
28
+ 'devil-advocate',
29
+ 'judge',
30
+ 'report',
31
+ 'delivery'
32
+ ]);
33
+ const LOCK_STALE_MS = 60_000;
34
+
35
+ function runtimeError(message, code = 'WORKFLOW_RUNTIME_FAILED', details = []) {
36
+ const err = new Error(message);
37
+ err.code = code;
38
+ err.details = details;
39
+ return err;
40
+ }
41
+
42
+ function workflowPaths(rootDir, runId) {
43
+ const directory = path.join(runsDir(rootDir), runId);
44
+ return {
45
+ directory,
46
+ plan: path.join(directory, 'plan.json'),
47
+ state: path.join(directory, 'workflow-state.json'),
48
+ events: path.join(directory, 'events.jsonl'),
49
+ lock: path.join(directory, 'workflow.lock')
50
+ };
51
+ }
52
+
53
+ function evaluateCondition(condition, run) {
54
+ const values = {
55
+ 'run.mode': run.mode,
56
+ 'run.state': run.state,
57
+ 'run.iteration': run.iteration,
58
+ 'run.task': run.task
59
+ };
60
+ const actual = values[condition.field];
61
+ switch (condition.operator) {
62
+ case 'equals': return actual === condition.value;
63
+ case 'notEquals': return actual !== condition.value;
64
+ case 'contains':
65
+ return Array.isArray(actual)
66
+ ? actual.includes(condition.value)
67
+ : String(actual || '').includes(String(condition.value));
68
+ case 'matchesAny':
69
+ return Array.isArray(condition.value) && condition.value.includes(actual);
70
+ case 'exists': return actual !== undefined && actual !== null;
71
+ case 'isEmpty': return actual == null || actual === '' || (Array.isArray(actual) && actual.length === 0);
72
+ case 'greaterThan': return typeof actual === 'number' && actual > condition.value;
73
+ case 'lessThan': return typeof actual === 'number' && actual < condition.value;
74
+ default: throw runtimeError(`Unsupported condition operator: ${condition.operator}`, 'INVALID_CONDITION');
75
+ }
76
+ }
77
+
78
+ function refreshNodes(plan, state, run) {
79
+ const changes = [];
80
+ let changed = true;
81
+ while (changed) {
82
+ changed = false;
83
+ for (const node of plan.nodes) {
84
+ const current = state.nodes[node.id];
85
+ if (![NODE_STATES.PENDING, NODE_STATES.BLOCKED].includes(current.status)) continue;
86
+ const dependencies = (node.dependsOn || []).map((id) => state.nodes[id]);
87
+ let nextStatus = current.status;
88
+ let reason = null;
89
+ if (dependencies.some((dependency) => dependency.status === NODE_STATES.FAILED)) {
90
+ nextStatus = NODE_STATES.BLOCKED;
91
+ reason = 'dependency failed';
92
+ } else if (dependencies.every((dependency) => SUCCESS_STATES.has(dependency.status))) {
93
+ if (node.when && !evaluateCondition(node.when, run)) {
94
+ nextStatus = NODE_STATES.SKIPPED;
95
+ reason = 'condition evaluated false';
96
+ } else if (node.type === 'condition') {
97
+ const result = evaluateCondition(node.expression, run);
98
+ nextStatus = result ? NODE_STATES.PASSED : NODE_STATES.SKIPPED;
99
+ reason = `condition evaluated ${result}`;
100
+ } else {
101
+ nextStatus = NODE_STATES.READY;
102
+ }
103
+ } else {
104
+ nextStatus = NODE_STATES.PENDING;
105
+ }
106
+ if (nextStatus !== current.status || current.reason !== reason) {
107
+ const replacement = { ...current, status: nextStatus, reason };
108
+ state.nodes[node.id] = replacement;
109
+ changes.push({ nodeId: node.id, from: current.status, node: replacement });
110
+ changed = true;
111
+ }
112
+ }
113
+ }
114
+ return changes;
115
+ }
116
+
117
+ function eventWithHash(event) {
118
+ return { ...event, hash: sha256(event) };
119
+ }
120
+
121
+ function createWorkflowBundle(plan, runId, { now = new Date(), run } = {}) {
122
+ const runtimeRun = run || {
123
+ runId,
124
+ mode: plan.mode,
125
+ state: RUN_STATES.STARTED,
126
+ iteration: 1,
127
+ task: ''
128
+ };
129
+ const state = {
130
+ schemaVersion: 1,
131
+ runId,
132
+ graphHash: plan.graphHash,
133
+ sequence: 0,
134
+ eventHash: null,
135
+ nodes: Object.fromEntries(plan.nodes.map((node) => [
136
+ node.id,
137
+ {
138
+ status: NODE_STATES.PENDING,
139
+ attempts: 0,
140
+ reason: null,
141
+ updatedAt: now.toISOString()
142
+ }
143
+ ]))
144
+ };
145
+ refreshNodes(plan, state, runtimeRun);
146
+ const event = eventWithHash({
147
+ schemaVersion: 1,
148
+ sequence: 1,
149
+ previousHash: null,
150
+ at: now.toISOString(),
151
+ type: 'WORKFLOW_CREATED',
152
+ runId,
153
+ graphHash: plan.graphHash,
154
+ initialNodes: state.nodes
155
+ });
156
+ state.sequence = event.sequence;
157
+ state.eventHash = event.hash;
158
+ return { plan, state, events: [event] };
159
+ }
160
+
161
+ function readRegularJson(filePath, label) {
162
+ let stat;
163
+ try {
164
+ stat = fs.lstatSync(filePath);
165
+ } catch (cause) {
166
+ throw runtimeError(`Unable to inspect ${label}: ${cause.message}`, 'INVALID_WORKFLOW_STATE');
167
+ }
168
+ if (stat.isSymbolicLink() || !stat.isFile()) {
169
+ throw runtimeError(`${label} must be a regular file`, 'INVALID_WORKFLOW_STATE');
170
+ }
171
+ try {
172
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
173
+ } catch (cause) {
174
+ throw runtimeError(`Unable to read ${label}: ${cause.message}`, 'INVALID_WORKFLOW_STATE');
175
+ }
176
+ }
177
+
178
+ function readEvents(filePath, runId, graphHash) {
179
+ const stat = fs.lstatSync(filePath);
180
+ if (stat.isSymbolicLink() || !stat.isFile()) {
181
+ throw runtimeError('Workflow event log must be a regular file', 'INVALID_WORKFLOW_EVENTS');
182
+ }
183
+ const text = fs.readFileSync(filePath, 'utf8');
184
+ const events = text.split('\n').filter(Boolean).map((line, index) => {
185
+ try {
186
+ return JSON.parse(line);
187
+ } catch (cause) {
188
+ throw runtimeError(`Workflow event ${index + 1} is invalid JSON: ${cause.message}`, 'INVALID_WORKFLOW_EVENTS');
189
+ }
190
+ });
191
+ let previousHash = null;
192
+ events.forEach((event, index) => {
193
+ const { hash, ...material } = event;
194
+ if (
195
+ event.sequence !== index + 1 ||
196
+ event.previousHash !== previousHash ||
197
+ event.runId !== runId ||
198
+ event.graphHash !== graphHash ||
199
+ hash !== sha256(material)
200
+ ) {
201
+ throw runtimeError(`Workflow event ${index + 1} failed integrity validation`, 'INVALID_WORKFLOW_EVENTS');
202
+ }
203
+ previousHash = hash;
204
+ });
205
+ return events;
206
+ }
207
+
208
+ function verifyPlan(plan, expectedHash) {
209
+ const material = {
210
+ schemaVersion: plan.schemaVersion,
211
+ compilerVersion: plan.compilerVersion,
212
+ recipe: plan.recipe,
213
+ mode: plan.mode,
214
+ nodes: plan.nodes
215
+ };
216
+ if (plan.graphHash !== expectedHash || sha256(material) !== plan.graphHash) {
217
+ throw runtimeError('Compiled workflow plan failed integrity validation', 'WORKFLOW_PLAN_TAMPERED');
218
+ }
219
+ }
220
+
221
+ function recoverState(state, events) {
222
+ const created = events[0];
223
+ if (created?.type !== 'WORKFLOW_CREATED' || !created.initialNodes) {
224
+ throw runtimeError('Workflow event log has no valid creation event', 'INVALID_WORKFLOW_EVENTS');
225
+ }
226
+ const recovered = {
227
+ schemaVersion: 1,
228
+ runId: state.runId,
229
+ graphHash: state.graphHash,
230
+ sequence: created.sequence,
231
+ eventHash: created.hash,
232
+ nodes: created.initialNodes
233
+ };
234
+ for (const event of events.slice(1)) {
235
+ for (const change of event.changes || []) recovered.nodes[change.nodeId] = change.node;
236
+ recovered.sequence = event.sequence;
237
+ recovered.eventHash = event.hash;
238
+ }
239
+ return recovered;
240
+ }
241
+
242
+ function loadWorkflow(rootDir, runId) {
243
+ const run = loadRun(rootDir, runId);
244
+ if (!run.workflow) throw runtimeError(`Run ${runId} has no workflow recipe`, 'RUN_HAS_NO_WORKFLOW');
245
+ const paths = workflowPaths(rootDir, runId);
246
+ const plan = readRegularJson(paths.plan, 'workflow plan');
247
+ verifyPlan(plan, run.workflow.graphHash);
248
+ const state = readRegularJson(paths.state, 'workflow state');
249
+ if (state.runId !== runId || state.graphHash !== plan.graphHash) {
250
+ throw runtimeError('Workflow state identity does not match the run', 'INVALID_WORKFLOW_STATE');
251
+ }
252
+ const events = readEvents(paths.events, runId, plan.graphHash);
253
+ const recovered = recoverState(state, events);
254
+ if (JSON.stringify(recovered) !== JSON.stringify(state)) atomicWriteJson(paths.state, recovered);
255
+ return { run, plan, state: recovered, events };
256
+ }
257
+
258
+ function appendEvent(filePath, event) {
259
+ const noFollow = fs.constants.O_NOFOLLOW || 0;
260
+ let descriptor;
261
+ try {
262
+ descriptor = fs.openSync(
263
+ filePath,
264
+ fs.constants.O_APPEND | fs.constants.O_WRONLY | noFollow
265
+ );
266
+ if (!fs.fstatSync(descriptor).isFile()) throw new Error('event log is not a regular file');
267
+ fs.writeSync(descriptor, `${JSON.stringify(event)}\n`);
268
+ fs.fsyncSync(descriptor);
269
+ } finally {
270
+ if (descriptor != null) fs.closeSync(descriptor);
271
+ }
272
+ }
273
+
274
+ function commitChanges(rootDir, workflow, type, changes, metadata = {}, now = new Date()) {
275
+ if (changes.length === 0) return workflow;
276
+ const event = eventWithHash({
277
+ schemaVersion: 1,
278
+ sequence: workflow.state.sequence + 1,
279
+ previousHash: workflow.state.eventHash,
280
+ at: now.toISOString(),
281
+ type,
282
+ runId: workflow.run.runId,
283
+ graphHash: workflow.plan.graphHash,
284
+ changes,
285
+ ...metadata
286
+ });
287
+ const paths = workflowPaths(rootDir, workflow.run.runId);
288
+ appendEvent(paths.events, event);
289
+ workflow.state.sequence = event.sequence;
290
+ workflow.state.eventHash = event.hash;
291
+ atomicWriteJson(paths.state, workflow.state);
292
+ workflow.events.push(event);
293
+ return workflow;
294
+ }
295
+
296
+ function acquireLock(lockPath) {
297
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });
298
+ try {
299
+ const descriptor = fs.openSync(lockPath, 'wx', 0o600);
300
+ fs.writeFileSync(descriptor, JSON.stringify({ pid: process.pid, at: new Date().toISOString() }));
301
+ fs.closeSync(descriptor);
302
+ } catch (cause) {
303
+ if (cause.code !== 'EEXIST') throw cause;
304
+ const age = Date.now() - fs.lstatSync(lockPath).mtimeMs;
305
+ if (age <= LOCK_STALE_MS) throw runtimeError('Workflow is locked by another operation', 'WORKFLOW_LOCKED');
306
+ fs.unlinkSync(lockPath);
307
+ return acquireLock(lockPath);
308
+ }
309
+ }
310
+
311
+ function withWorkflowLock(rootDir, runId, operation) {
312
+ const lockPath = workflowPaths(rootDir, runId).lock;
313
+ acquireLock(lockPath);
314
+ try {
315
+ return operation();
316
+ } finally {
317
+ try {
318
+ fs.unlinkSync(lockPath);
319
+ } catch {
320
+ // A failed cleanup is treated as a stale lock on the next operation.
321
+ }
322
+ }
323
+ }
324
+
325
+ function resolveRunId(rootDir, runId) {
326
+ if (runId) return runId;
327
+ const run = getCurrentRun(rootDir);
328
+ if (!run) throw runtimeError('No current run. Pass --run <id>.', 'NO_CURRENT_RUN');
329
+ return run.runId;
330
+ }
331
+
332
+ function nodeChanges(workflow, nodeId, status, metadata = {}, now = new Date()) {
333
+ const current = workflow.state.nodes[nodeId];
334
+ if (!current) throw runtimeError(`Unknown workflow node: ${nodeId}`, 'UNKNOWN_WORKFLOW_NODE');
335
+ const replacement = {
336
+ ...current,
337
+ status,
338
+ updatedAt: now.toISOString(),
339
+ ...metadata
340
+ };
341
+ workflow.state.nodes[nodeId] = replacement;
342
+ return [{ nodeId, from: current.status, node: replacement }];
343
+ }
344
+
345
+ function assertReady(workflow, nodeId) {
346
+ const node = workflow.plan.nodes.find((candidate) => candidate.id === nodeId);
347
+ if (!node) throw runtimeError(`Unknown workflow node: ${nodeId}`, 'UNKNOWN_WORKFLOW_NODE');
348
+ const runtimeNode = workflow.state.nodes[nodeId];
349
+ if (runtimeNode.status !== NODE_STATES.READY) {
350
+ throw runtimeError(`Node ${nodeId} is ${runtimeNode.status}, not READY`, 'NODE_NOT_READY');
351
+ }
352
+ return node;
353
+ }
354
+
355
+ function safeArtifact(rootDir, artifactPath) {
356
+ if (!artifactPath) throw runtimeError('An artifact path is required', 'ARTIFACT_REQUIRED');
357
+ const absolute = path.resolve(rootDir, artifactPath);
358
+ if (absolute !== rootDir && !absolute.startsWith(`${path.resolve(rootDir)}${path.sep}`)) {
359
+ throw runtimeError('Artifact path must stay inside the repository', 'UNSAFE_ARTIFACT_PATH');
360
+ }
361
+ const realRoot = fs.realpathSync(rootDir);
362
+ const realArtifact = fs.realpathSync(absolute);
363
+ if (!realArtifact.startsWith(`${realRoot}${path.sep}`)) {
364
+ throw runtimeError('Artifact path escapes the repository through a symlink', 'UNSAFE_ARTIFACT_PATH');
365
+ }
366
+ const stat = fs.lstatSync(absolute);
367
+ if (stat.isSymbolicLink() || !stat.isFile()) {
368
+ throw runtimeError('Artifact must be a regular file, not a symlink', 'UNSAFE_ARTIFACT_PATH');
369
+ }
370
+ return {
371
+ absolute,
372
+ descriptor: {
373
+ path: path.relative(rootDir, absolute).split(path.sep).join('/'),
374
+ sha256: sha256(fs.readFileSync(absolute))
375
+ }
376
+ };
377
+ }
378
+
379
+ function validateSchema(value, schema, location = '$') {
380
+ const errors = [];
381
+ const typeMatches = {
382
+ object: value && typeof value === 'object' && !Array.isArray(value),
383
+ array: Array.isArray(value),
384
+ string: typeof value === 'string',
385
+ integer: Number.isSafeInteger(value),
386
+ number: typeof value === 'number' && Number.isFinite(value),
387
+ boolean: typeof value === 'boolean',
388
+ null: value === null
389
+ };
390
+ if (schema.$ref) return [`${location}: $ref is not supported by the runtime validator`];
391
+ const allowedTypes = Array.isArray(schema.type) ? schema.type : [schema.type];
392
+ if (schema.type && !allowedTypes.some((type) => typeMatches[type])) {
393
+ return [`${location}: must be ${allowedTypes.join(' or ')}`];
394
+ }
395
+ if (Object.hasOwn(schema, 'const') && value !== schema.const) errors.push(`${location}: must equal ${JSON.stringify(schema.const)}`);
396
+ if (schema.enum && !schema.enum.includes(value)) errors.push(`${location}: must be one of ${schema.enum.join(', ')}`);
397
+ if (typeof value === 'string') {
398
+ if (schema.minLength != null && value.length < schema.minLength) errors.push(`${location}: is too short`);
399
+ if (schema.maxLength != null && value.length > schema.maxLength) errors.push(`${location}: is too long`);
400
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${location}: does not match ${schema.pattern}`);
401
+ if (schema.format === 'date-time' && Number.isNaN(Date.parse(value))) errors.push(`${location}: must be a date-time`);
402
+ }
403
+ if (typeof value === 'number') {
404
+ if (schema.minimum != null && value < schema.minimum) errors.push(`${location}: is below minimum`);
405
+ if (schema.maximum != null && value > schema.maximum) errors.push(`${location}: exceeds maximum`);
406
+ }
407
+ if (Array.isArray(value)) {
408
+ if (schema.minItems != null && value.length < schema.minItems) errors.push(`${location}: has too few items`);
409
+ if (schema.maxItems != null && value.length > schema.maxItems) errors.push(`${location}: has too many items`);
410
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
411
+ errors.push(`${location}: items must be unique`);
412
+ }
413
+ value.forEach((item, index) => errors.push(...validateSchema(item, schema.items || {}, `${location}[${index}]`)));
414
+ }
415
+ if (typeMatches.object) {
416
+ for (const required of schema.required || []) {
417
+ if (!Object.hasOwn(value, required)) errors.push(`${location}.${required}: is required`);
418
+ }
419
+ for (const [key, child] of Object.entries(schema.properties || {})) {
420
+ if (Object.hasOwn(value, key)) errors.push(...validateSchema(value[key], child, `${location}.${key}`));
421
+ }
422
+ if (schema.additionalProperties === false) {
423
+ for (const key of Object.keys(value)) {
424
+ if (!Object.hasOwn(schema.properties || {}, key)) errors.push(`${location}.${key}: is not allowed`);
425
+ }
426
+ }
427
+ }
428
+ return errors;
429
+ }
430
+
431
+ function assertSupportedSchema(schema, location = '$schema') {
432
+ const supported = new Set([
433
+ '$schema',
434
+ '$id',
435
+ 'title',
436
+ 'description',
437
+ 'type',
438
+ 'required',
439
+ 'properties',
440
+ 'const',
441
+ 'enum',
442
+ 'minLength',
443
+ 'maxLength',
444
+ 'pattern',
445
+ 'format',
446
+ 'minimum',
447
+ 'maximum',
448
+ 'minItems',
449
+ 'maxItems',
450
+ 'uniqueItems',
451
+ 'items',
452
+ 'additionalProperties'
453
+ ]);
454
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
455
+ throw runtimeError(`${location} must be an object`, 'UNSUPPORTED_ARTIFACT_SCHEMA');
456
+ }
457
+ const unknown = Object.keys(schema).filter((key) => !supported.has(key));
458
+ if (unknown.length) {
459
+ throw runtimeError(
460
+ `${location} uses unsupported keywords: ${unknown.join(', ')}`,
461
+ 'UNSUPPORTED_ARTIFACT_SCHEMA'
462
+ );
463
+ }
464
+ if (schema.format && schema.format !== 'date-time') {
465
+ throw runtimeError(`${location} uses unsupported format: ${schema.format}`, 'UNSUPPORTED_ARTIFACT_SCHEMA');
466
+ }
467
+ if (
468
+ schema.additionalProperties != null &&
469
+ typeof schema.additionalProperties !== 'boolean'
470
+ ) {
471
+ throw runtimeError(`${location}.additionalProperties must be boolean`, 'UNSUPPORTED_ARTIFACT_SCHEMA');
472
+ }
473
+ for (const [key, child] of Object.entries(schema.properties || {})) {
474
+ assertSupportedSchema(child, `${location}.properties.${key}`);
475
+ }
476
+ if (schema.items) assertSupportedSchema(schema.items, `${location}.items`);
477
+ }
478
+
479
+ function validateNodeArtifact(rootDir, run, node, artifactPath) {
480
+ const artifact = safeArtifact(rootDir, artifactPath);
481
+ let value;
482
+ try {
483
+ value = JSON.parse(fs.readFileSync(artifact.absolute, 'utf8'));
484
+ } catch (cause) {
485
+ throw runtimeError(`Artifact must be valid JSON: ${cause.message}`, 'INVALID_NODE_ARTIFACT');
486
+ }
487
+ if (value.runId !== run.runId) {
488
+ throw runtimeError(`Artifact runId must be ${run.runId}`, 'INVALID_NODE_ARTIFACT');
489
+ }
490
+ const schemaRelative = node.output?.schema;
491
+ const candidates = [
492
+ { base: rootDir, file: path.resolve(rootDir, schemaRelative) },
493
+ { base: path.resolve(__dirname, '..'), file: path.resolve(__dirname, '..', schemaRelative) }
494
+ ];
495
+ const schemaPath = candidates.find((candidate) => {
496
+ if (!fs.existsSync(candidate.file)) return false;
497
+ const realBase = fs.realpathSync(candidate.base);
498
+ const realFile = fs.realpathSync(candidate.file);
499
+ return realFile.startsWith(`${realBase}${path.sep}`);
500
+ })?.file;
501
+ if (!schemaPath) throw runtimeError(`Artifact schema not found: ${schemaRelative}`, 'INVALID_NODE_ARTIFACT');
502
+ const schema = readRegularJson(schemaPath, 'node artifact schema');
503
+ assertSupportedSchema(schema);
504
+ const errors = validateSchema(value, schema);
505
+ if (errors.length) throw runtimeError('Node artifact failed schema validation', 'INVALID_NODE_ARTIFACT', errors);
506
+ return { ...artifact.descriptor, schema: schemaRelative };
507
+ }
508
+
509
+ function completeWorkflowNode(rootDir, nodeId, { runId, artifact, now = new Date() } = {}) {
510
+ const resolved = resolveRunId(rootDir, runId);
511
+ return withWorkflowLock(rootDir, resolved, () => {
512
+ const workflow = loadWorkflow(rootDir, resolved);
513
+ const node = workflow.plan.nodes.find((candidate) => candidate.id === nodeId);
514
+ if (!node) throw runtimeError(`Unknown workflow node: ${nodeId}`, 'UNKNOWN_WORKFLOW_NODE');
515
+ const currentStatus = workflow.state.nodes[nodeId].status;
516
+ if (![NODE_STATES.READY, NODE_STATES.RUNNING].includes(currentStatus)) {
517
+ throw runtimeError(`Node ${nodeId} is ${currentStatus}, not READY or RUNNING`, 'NODE_NOT_READY');
518
+ }
519
+ if (node.type === 'command') {
520
+ throw runtimeError('Command nodes are disabled in the controlled runtime', 'COMMAND_EXECUTION_DISABLED');
521
+ }
522
+ if (node.type === 'approval' || LEGACY_NODE_TYPES.has(node.type)) {
523
+ throw runtimeError(`Node ${nodeId} must use its dedicated approval or gate command`, 'WRONG_NODE_EXECUTOR');
524
+ }
525
+ let artifactDescriptor = null;
526
+ if (node.type === 'agent') {
527
+ artifactDescriptor = validateNodeArtifact(rootDir, workflow.run, node, artifact);
528
+ } else if (node.type === 'artifact-check') {
529
+ artifactDescriptor = safeArtifact(rootDir, artifact).descriptor;
530
+ }
531
+ let changes = nodeChanges(workflow, nodeId, NODE_STATES.PASSED, {
532
+ attempts: workflow.state.nodes[nodeId].attempts + (currentStatus === NODE_STATES.READY ? 1 : 0),
533
+ reason: null,
534
+ ...(artifactDescriptor ? { artifact: artifactDescriptor } : {})
535
+ }, now);
536
+ changes = changes.concat(refreshNodes(workflow.plan, workflow.state, workflow.run));
537
+ return commitChanges(rootDir, workflow, 'NODE_COMPLETED', changes, { nodeId }, now);
538
+ });
539
+ }
540
+
541
+ function startWorkflowNode(rootDir, nodeId, { runId, now = new Date() } = {}) {
542
+ const resolved = resolveRunId(rootDir, runId);
543
+ return withWorkflowLock(rootDir, resolved, () => {
544
+ const workflow = loadWorkflow(rootDir, resolved);
545
+ const node = assertReady(workflow, nodeId);
546
+ if (node.type === 'command') {
547
+ throw runtimeError('Command nodes are disabled in the controlled runtime', 'COMMAND_EXECUTION_DISABLED');
548
+ }
549
+ if (node.type === 'approval' || LEGACY_NODE_TYPES.has(node.type)) {
550
+ throw runtimeError(`Node ${nodeId} must use its dedicated approval or gate command`, 'WRONG_NODE_EXECUTOR');
551
+ }
552
+ const changes = nodeChanges(workflow, nodeId, NODE_STATES.RUNNING, {
553
+ attempts: workflow.state.nodes[nodeId].attempts + 1,
554
+ reason: null
555
+ }, now);
556
+ return commitChanges(rootDir, workflow, 'NODE_STARTED', changes, { nodeId }, now);
557
+ });
558
+ }
559
+
560
+ function failWorkflowNode(rootDir, nodeId, { runId, reason = 'node execution failed', now = new Date() } = {}) {
561
+ const resolved = resolveRunId(rootDir, runId);
562
+ return withWorkflowLock(rootDir, resolved, () => {
563
+ const workflow = loadWorkflow(rootDir, resolved);
564
+ const current = workflow.state.nodes[nodeId];
565
+ if (!current) throw runtimeError(`Unknown workflow node: ${nodeId}`, 'UNKNOWN_WORKFLOW_NODE');
566
+ if (![NODE_STATES.READY, NODE_STATES.RUNNING].includes(current.status)) {
567
+ throw runtimeError(`Node ${nodeId} cannot fail from ${current.status}`, 'INVALID_NODE_TRANSITION');
568
+ }
569
+ let changes = nodeChanges(workflow, nodeId, NODE_STATES.FAILED, {
570
+ attempts: current.attempts + (current.status === NODE_STATES.READY ? 1 : 0),
571
+ reason: String(reason).slice(0, 500)
572
+ }, now);
573
+ changes = changes.concat(refreshNodes(workflow.plan, workflow.state, workflow.run));
574
+ return commitChanges(rootDir, workflow, 'NODE_FAILED', changes, { nodeId }, now);
575
+ });
576
+ }
577
+
578
+ function retryWorkflowNode(rootDir, nodeId, { runId, now = new Date() } = {}) {
579
+ const resolved = resolveRunId(rootDir, runId);
580
+ return withWorkflowLock(rootDir, resolved, () => {
581
+ const workflow = loadWorkflow(rootDir, resolved);
582
+ const current = workflow.state.nodes[nodeId];
583
+ if (!current) throw runtimeError(`Unknown workflow node: ${nodeId}`, 'UNKNOWN_WORKFLOW_NODE');
584
+ if (![NODE_STATES.FAILED, NODE_STATES.RUNNING].includes(current.status)) {
585
+ throw runtimeError(`Node ${nodeId} cannot retry from ${current.status}`, 'INVALID_NODE_TRANSITION');
586
+ }
587
+ let changes = nodeChanges(workflow, nodeId, NODE_STATES.READY, { reason: null }, now);
588
+ changes = changes.concat(refreshNodes(workflow.plan, workflow.state, workflow.run));
589
+ return commitChanges(rootDir, workflow, 'NODE_RETRIED', changes, { nodeId }, now);
590
+ });
591
+ }
592
+
593
+ function approveWorkflowNode(rootDir, nodeId, { runId, approvedBy = 'human', now = new Date() } = {}) {
594
+ const resolved = resolveRunId(rootDir, runId);
595
+ return withWorkflowLock(rootDir, resolved, () => {
596
+ if (!/^[A-Za-z0-9@._-]{1,64}$/.test(approvedBy)) {
597
+ throw runtimeError('approvedBy must be a short account identifier', 'INVALID_APPROVER');
598
+ }
599
+ const workflow = loadWorkflow(rootDir, resolved);
600
+ const node = assertReady(workflow, nodeId);
601
+ if (node.type !== 'approval') {
602
+ throw runtimeError(`Node ${nodeId} is not an approval node`, 'WRONG_NODE_EXECUTOR');
603
+ }
604
+ let changes = nodeChanges(workflow, nodeId, NODE_STATES.PASSED, {
605
+ attempts: workflow.state.nodes[nodeId].attempts + 1,
606
+ reason: null,
607
+ approvedBy
608
+ }, now);
609
+ changes = changes.concat(refreshNodes(workflow.plan, workflow.state, workflow.run));
610
+ return commitChanges(rootDir, workflow, 'NODE_APPROVED', changes, { nodeId, approvedBy }, now);
611
+ });
612
+ }
613
+
614
+ function descendants(plan, startId) {
615
+ const result = new Set([startId]);
616
+ let changed = true;
617
+ while (changed) {
618
+ changed = false;
619
+ for (const node of plan.nodes) {
620
+ if (!result.has(node.id) && (node.dependsOn || []).some((id) => result.has(id))) {
621
+ result.add(node.id);
622
+ changed = true;
623
+ }
624
+ }
625
+ }
626
+ return result;
627
+ }
628
+
629
+ function applyWorkflowGate(rootDir, gate, { runId, now = new Date() } = {}) {
630
+ const resolved = resolveRunId(rootDir, runId);
631
+ return withWorkflowLock(rootDir, resolved, () => {
632
+ let workflow = loadWorkflow(rootDir, resolved);
633
+ const node = workflow.plan.nodes.find((candidate) => candidate.legacyGate === gate);
634
+ if (!node) throw runtimeError(`Workflow has no node for gate ${gate}`, 'GATE_NOT_IN_WORKFLOW');
635
+ assertReady(workflow, node.id);
636
+ const { applyGate } = require('./gates.js');
637
+ const run = applyGate(rootDir, gate, { runId: resolved });
638
+ workflow.run = run;
639
+ let changes = nodeChanges(workflow, node.id, NODE_STATES.PASSED, {
640
+ attempts: workflow.state.nodes[node.id].attempts + 1,
641
+ reason: null
642
+ }, now);
643
+ if (gate === 'judge' && run.state === RUN_STATES.GOAL_FROZEN) {
644
+ const maker = workflow.plan.nodes.find((candidate) => candidate.type === 'maker');
645
+ for (const resetId of descendants(workflow.plan, maker.id)) {
646
+ const current = workflow.state.nodes[resetId];
647
+ const replacement = {
648
+ status: NODE_STATES.PENDING,
649
+ attempts: current.attempts,
650
+ reason: 'reset for next iteration',
651
+ updatedAt: now.toISOString()
652
+ };
653
+ workflow.state.nodes[resetId] = replacement;
654
+ changes.push({ nodeId: resetId, from: current.status, node: replacement });
655
+ }
656
+ } else if (run.state === RUN_STATES.ESCALATED) {
657
+ for (const candidate of workflow.plan.nodes) {
658
+ const current = workflow.state.nodes[candidate.id];
659
+ if (![NODE_STATES.PASSED, NODE_STATES.SKIPPED].includes(current.status)) {
660
+ const replacement = { ...current, status: NODE_STATES.BLOCKED, reason: 'run escalated', updatedAt: now.toISOString() };
661
+ workflow.state.nodes[candidate.id] = replacement;
662
+ changes.push({ nodeId: candidate.id, from: current.status, node: replacement });
663
+ }
664
+ }
665
+ }
666
+ if (run.state !== RUN_STATES.ESCALATED) {
667
+ changes = changes.concat(refreshNodes(workflow.plan, workflow.state, run));
668
+ }
669
+ workflow = commitChanges(rootDir, workflow, 'GATE_PASSED', changes, { nodeId: node.id, gate }, now);
670
+ return { run, workflow };
671
+ });
672
+ }
673
+
674
+ function workflowStatus(rootDir, { runId } = {}) {
675
+ return loadWorkflow(rootDir, resolveRunId(rootDir, runId));
676
+ }
677
+
678
+ module.exports = {
679
+ NODE_STATES,
680
+ createWorkflowBundle,
681
+ loadWorkflow,
682
+ workflowStatus,
683
+ startWorkflowNode,
684
+ completeWorkflowNode,
685
+ failWorkflowNode,
686
+ retryWorkflowNode,
687
+ approveWorkflowNode,
688
+ applyWorkflowGate,
689
+ evaluateCondition,
690
+ assertSupportedSchema,
691
+ validateSchema
692
+ };