ai-engineering-loop 1.7.0 → 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.
@@ -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,
@@ -118,7 +123,7 @@ const {
118
123
  } = require('../lib/handoff.js');
119
124
  const { createStudioServer } = require('../lib/studio-server.js');
120
125
 
121
- const VERSION = '1.7.0';
126
+ const VERSION = require('../package.json').version;
122
127
  const CWD = process.cwd();
123
128
  const CONTEXT_DIR = path.join(CWD, '.ai-engineering-loop');
124
129
 
@@ -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
  */
@@ -372,7 +393,7 @@ function generateContextFiles(rootDir, discovery, trigger = 'init', impact = 'IN
372
393
 
373
394
  // 0. metadata.json (Baseline)
374
395
  const metadataJson = {
375
- contextVersion: '1.7.0',
396
+ contextVersion: VERSION,
376
397
  generatedAt: new Date().toISOString(),
377
398
  repositoryRevision: currentRevision,
378
399
  projectProfile: discovery.profile,
@@ -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;
@@ -1,6 +1,6 @@
1
1
  # Local Workflow Studio
2
2
 
3
- Workflow Studio is a localhost-only visual control plane for declarative recipes and recipe-bound runs. It does not execute models, shell commands, or arbitrary node code. The existing recipe compiler and controlled workflow runtime remain the source of truth.
3
+ Workflow Studio is a localhost-only visual control plane for declarative recipes and recipe-bound runs. It can create a named run and start the controlled local workflow runtime after an audited Goal Freeze. It does not execute models, shell commands, arbitrary node code, or inject prompts into an external AI conversation. The existing recipe compiler and controlled workflow runtime remain the source of truth.
4
4
 
5
5
  ## Start
6
6
 
@@ -18,17 +18,25 @@ The canvas loads built-in and project recipes through the same APIs as the CLI:
18
18
 
19
19
  1. Select a recipe.
20
20
  2. Fork a protected built-in by changing its ID.
21
- 3. Drag allowlisted node types from the library or click to add them at the viewport center.
22
- 4. Move nodes freely and drag an output port onto another node to create a dependency.
23
- 5. Pan, zoom, fit, auto-layout, and use undo/redo without changing recipe semantics.
24
- 6. Review graph validation and hashes for every compatible mode.
25
- 7. Install only after explicit confirmation.
21
+ 3. Drag allowlisted node types from the library, use the global Add Node control, or use the contextual output `+` to create and connect a successor.
22
+ 4. Move or multi-select nodes, drag an output port to connect existing nodes, and remove a connection from its midpoint control.
23
+ 5. Edit a node Display Name inline without changing its stable Technical ID.
24
+ 6. Import validated JSON through an explicit Replace, Merge with deterministic conflict renaming, or Cancel preview; export the current workflow as JSON.
25
+ 7. Pan, lasso, zoom, fit, auto-layout, and use undo/redo without changing recipe semantics.
26
+ 8. Review graph validation and hashes for every compatible mode.
27
+ 9. Install only after explicit confirmation.
26
28
 
27
29
  Installation writes a private temporary candidate, invokes the existing atomic installer, and removes the candidate. Built-ins cannot be overwritten. Replacing a project recipe still requires the version policy enforced by `recipe install --replace`.
28
30
 
29
31
  Canvas positions and viewport state are not recipe fields and never contribute to the graph hash. Studio stores them under private `.ai-engineering-loop/studio-layouts/` files, validates IDs and coordinate bounds, rejects symlinks, and writes atomically. This keeps visual organization independent from execution semantics.
30
32
 
31
- Visual connections are real `dependsOn` edges. Studio rejects a connection that would introduce a cycle, then the recipe compiler applies the complete safety-backbone and mode validation before installation. Selecting and deleting a node removes its incoming references; undo remains available until the recipe is changed or reloaded.
33
+ Visual connections are first-class `edges[]` with stable Edge IDs and Technical ID endpoints. Legacy `dependsOn` recipes migrate in memory without modifying their source; Save or Export emits the current Edge representation. The compiler projects Edges back to runtime dependencies so legacy and migrated recipes retain the same execution order and graph hash. Studio rejects duplicate, dangling, self-referential, and cyclic Edges, then applies the complete safety-backbone and mode validation before installation.
34
+
35
+ ## Custom Agents
36
+
37
+ **Create Custom Agent** adds an `agent` node with a basic prompt, explicit capability and MCP references, input/output artifact contracts, token limit, timeout, and retry policy. Unsupported authority, arbitrary shell fields, raw secret values, and unsafe schema paths are rejected.
38
+
39
+ A Custom Agent reaching `READY` waits for an external operator. Studio can mark it running, record redacted activity, retry it, or complete it with a valid run-bound evidence artifact. Readiness is not represented as independent model execution.
32
40
 
33
41
  ## Stage 8 delivery adapter
34
42
 
@@ -38,6 +46,10 @@ An adapter belongs to the project, not to one delivery node. For a custom adapte
38
46
 
39
47
  ## Live execution
40
48
 
49
+ The trigger/root node owns the task input and local Execute control. Studio first creates a Run with an immutable Technical ID and human-readable Display Name. A deterministic task-derived name is used when no safe proposal is available. The Goal Contract must contain numbered acceptance criteria with evidence and failure cases and must pass an explicit Goal Freeze before Execute can start the local runtime.
50
+
51
+ Goal Freeze records actor, timestamp, version, and content hash. Unfreeze requires an actor and reason, increments the Goal version, resets the workflow to its Goal gate, and leaves previous evidence bound to the previous version.
52
+
41
53
  For a recipe-bound current run, Studio polls a small live snapshot rather than reloading the recipe catalog. It displays:
42
54
 
43
55
  - current node states and the append-only event stream;
@@ -53,6 +65,12 @@ ai-engineering-loop node activity <node-id> \
53
65
 
54
66
  Activity can only be attached to a `RUNNING` node. It is capped at 240 printable characters, secret-redacted before persistence, and added to the integrity-bound workflow event chain.
55
67
 
68
+ ## Run History
69
+
70
+ The separate **Runs** workspace reads every valid persisted Run rather than replacing Workflows with execution records. It supports text, status, mode, and date filters and shows human-readable names, technical IDs, Goal state, decisions, events, evidence presence, and bounded artifacts. Corrupt Run records are isolated so valid siblings remain available.
71
+
72
+ Run History is read-only. Artifact inspection accepts only regular files inside the owning Run, rejects path traversal and symlinks, enforces a size bound, and redacts recognized secrets before returning content.
73
+
56
74
  ## Decision memory
57
75
 
58
76
  Studio can record a concise decision and rationale against the current run. Decision memory is private runtime data under the run directory, is bounded to 100 entries, and is redacted before persistence. It becomes part of exported handoffs so the next developer or agent receives the “why,” not only the final state.
@@ -82,9 +100,12 @@ Inspection accepts only regular files smaller than 1 MiB inside the repository,
82
100
  Studio improves authoring and observability; it does not weaken runtime gates:
83
101
 
84
102
  - graph validation does not imply execution permission;
103
+ - local execution requires exactly one permitted trigger/root and an audited frozen Goal;
85
104
  - command nodes remain disabled;
105
+ - Custom Agents wait for an external operator and cannot grant undeclared authority;
86
106
  - approvals remain explicit state transitions;
87
107
  - connector edits cannot bypass the required safety backbone;
108
+ - Run History cannot mutate persisted runs or artifacts;
88
109
  - delivery adapters cannot run before Judge `PASS`;
89
110
  - token data comes only from the provider-recorded usage ledger;
90
111
  - handoff integrity proves the bundle has not changed after export, not that every original claim was true.
@@ -0,0 +1,124 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1600" height="900" viewBox="0 0 1600 900" role="img" aria-labelledby="title desc">
2
+ <title id="title">AI Engineering Loop Workflow Studio</title>
3
+ <desc id="desc">A polished dark workflow canvas showing a task moving through goal, maker, review, and delivery nodes.</desc>
4
+ <defs>
5
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
6
+ <stop stop-color="#111512"/>
7
+ <stop offset="1" stop-color="#080a09"/>
8
+ </linearGradient>
9
+ <linearGradient id="glow" x1="0" y1="0" x2="1" y2="1">
10
+ <stop stop-color="#28ad00" stop-opacity=".28"/>
11
+ <stop offset="1" stop-color="#28ad00" stop-opacity="0"/>
12
+ </linearGradient>
13
+ <filter id="shadow" x="-30%" y="-30%" width="160%" height="160%">
14
+ <feDropShadow dx="0" dy="18" stdDeviation="24" flood-color="#000" flood-opacity=".45"/>
15
+ </filter>
16
+ <filter id="soft">
17
+ <feGaussianBlur stdDeviation="55"/>
18
+ </filter>
19
+ <pattern id="grid" width="32" height="32" patternUnits="userSpaceOnUse">
20
+ <path d="M32 0H0V32" fill="none" stroke="#fff" stroke-opacity=".035"/>
21
+ </pattern>
22
+ <marker id="arrow" markerWidth="10" markerHeight="10" refX="8" refY="5" orient="auto">
23
+ <path d="M0 0L10 5L0 10Z" fill="#5b625d"/>
24
+ </marker>
25
+ <style>
26
+ .ui{font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
27
+ .mono{font-family:"SFMono-Regular",Consolas,monospace}
28
+ .eyebrow{font-size:14px;font-weight:700;letter-spacing:2.4px;fill:#7f8881}
29
+ .node-title{font-size:22px;font-weight:700;fill:#f4f6f4}
30
+ .node-copy{font-size:14px;fill:#888f8a}
31
+ .tiny{font-size:12px;fill:#707873}
32
+ .flow{fill:none;stroke:#5b625d;stroke-width:3;marker-end:url(#arrow)}
33
+ </style>
34
+ </defs>
35
+
36
+ <rect width="1600" height="900" fill="url(#bg)"/>
37
+ <circle cx="1240" cy="70" r="330" fill="#28ad00" opacity=".12" filter="url(#soft)"/>
38
+ <circle cx="280" cy="880" r="260" fill="#28ad00" opacity=".08" filter="url(#soft)"/>
39
+
40
+ <g class="ui">
41
+ <text x="110" y="112" font-size="16" font-weight="800" letter-spacing="2" fill="#83db69">AI ENGINEERING LOOP</text>
42
+ <text x="110" y="188" font-size="64" font-weight="750" letter-spacing="-2.8" fill="#f7f9f7">From idea to trusted code.</text>
43
+ <text x="112" y="232" font-size="21" fill="#9da49f">Your AI handles the workflow. You keep the clarity and control.</text>
44
+ </g>
45
+
46
+ <g filter="url(#shadow)">
47
+ <rect x="105" y="290" width="1390" height="510" rx="24" fill="#151816" stroke="#303632"/>
48
+ <rect x="105" y="290" width="1390" height="64" rx="24" fill="#1b1f1c"/>
49
+ <path d="M105 330V354H1495V330" fill="#1b1f1c"/>
50
+ <circle cx="140" cy="322" r="6" fill="#4d544f"/>
51
+ <circle cx="160" cy="322" r="6" fill="#4d544f"/>
52
+ <circle cx="180" cy="322" r="6" fill="#28ad00"/>
53
+ <rect x="680" y="307" width="240" height="30" rx="15" fill="#111411"/>
54
+ <circle cx="704" cy="322" r="6" fill="#28ad00"/>
55
+ <text class="ui tiny" x="720" y="326">Workflow Studio</text>
56
+
57
+ <rect x="105" y="354" width="72" height="446" fill="#101311"/>
58
+ <rect x="123" y="381" width="36" height="36" rx="10" fill="#28ad00"/>
59
+ <path d="M135 393h12v12h-12zM139 389v20M131 399h20" fill="none" stroke="#fff" stroke-width="2"/>
60
+ <circle cx="141" cy="449" r="15" fill="#252a26"/>
61
+ <path d="M134 449h14M141 442v14" stroke="#818982" stroke-width="2"/>
62
+ <circle cx="141" cy="500" r="15" fill="#252a26"/>
63
+ <path d="M134 497h14M134 503h10" stroke="#818982" stroke-width="2"/>
64
+
65
+ <rect x="177" y="354" width="1318" height="446" fill="#111411"/>
66
+ <rect x="177" y="354" width="1318" height="446" fill="url(#grid)"/>
67
+ <ellipse cx="1220" cy="410" rx="300" ry="210" fill="url(#glow)"/>
68
+
69
+ <text class="ui eyebrow" x="222" y="397">WORKFLOW / PRODUCT LAUNCH</text>
70
+ <rect x="1180" y="375" width="262" height="42" rx="9" fill="#1d221e" stroke="#343a35"/>
71
+ <circle cx="1206" cy="396" r="6" fill="#28ad00"/>
72
+ <text class="ui tiny" x="1221" y="400">Goal frozen · ready to run</text>
73
+
74
+ <path class="flow" d="M468 555C515 555 510 486 565 486H596"/>
75
+ <path class="flow" d="M858 486C906 486 900 585 956 585H990"/>
76
+ <path class="flow" d="M1252 585C1304 585 1295 492 1343 492"/>
77
+
78
+ <g>
79
+ <rect x="238" y="470" width="230" height="170" rx="16" fill="#1c211d" stroke="#3b433d"/>
80
+ <rect x="238" y="470" width="6" height="170" rx="3" fill="#28ad00"/>
81
+ <text class="ui eyebrow" x="268" y="503">01 · GOAL</text>
82
+ <text class="ui node-title" x="268" y="543">Define success</text>
83
+ <text class="ui node-copy" x="268" y="572">Clear outcomes, edge cases,</text>
84
+ <text class="ui node-copy" x="268" y="594">and proof before coding.</text>
85
+ <rect x="268" y="612" width="92" height="8" rx="4" fill="#28ad00" opacity=".65"/>
86
+ </g>
87
+
88
+ <g>
89
+ <rect x="596" y="401" width="262" height="170" rx="16" fill="#1c211d" stroke="#3b433d"/>
90
+ <text class="ui eyebrow" x="626" y="434">02 · MAKE</text>
91
+ <text class="ui node-title" x="626" y="474">Build the right thing</text>
92
+ <text class="ui node-copy" x="626" y="503">Your agent plans, implements,</text>
93
+ <text class="ui node-copy" x="626" y="525">and verifies the result.</text>
94
+ <circle cx="816" cy="433" r="8" fill="#28ad00"/>
95
+ </g>
96
+
97
+ <g>
98
+ <rect x="990" y="500" width="262" height="170" rx="16" fill="#1c211d" stroke="#3b433d"/>
99
+ <text class="ui eyebrow" x="1020" y="533">03 · REVIEW</text>
100
+ <text class="ui node-title" x="1020" y="573">Challenge every claim</text>
101
+ <text class="ui node-copy" x="1020" y="602">Independent checks compare</text>
102
+ <text class="ui node-copy" x="1020" y="624">promises with real evidence.</text>
103
+ <rect x="1020" y="642" width="72" height="8" rx="4" fill="#28ad00" opacity=".65"/>
104
+ </g>
105
+
106
+ <g>
107
+ <rect x="1343" y="422" width="112" height="140" rx="16" fill="#28ad00"/>
108
+ <text class="ui" x="1399" y="461" text-anchor="middle" font-size="12" font-weight="800" letter-spacing="1.5" fill="#dff8d7">04</text>
109
+ <path d="M1378 491l14 14 30-34" fill="none" stroke="#fff" stroke-width="7" stroke-linecap="round" stroke-linejoin="round"/>
110
+ <text class="ui" x="1399" y="535" text-anchor="middle" font-size="14" font-weight="750" fill="#fff">DELIVER</text>
111
+ </g>
112
+
113
+ <rect x="224" y="730" width="1218" height="44" rx="12" fill="#191d1a" stroke="#2b312c"/>
114
+ <text class="mono tiny" x="248" y="757">Task</text>
115
+ <text class="ui" x="300" y="757" font-size="14" fill="#c7ccc8">Ship a reliable feature without babysitting every command</text>
116
+ <rect x="1306" y="739" width="118" height="26" rx="7" fill="#28ad00"/>
117
+ <text class="ui" x="1365" y="757" text-anchor="middle" font-size="12" font-weight="750" fill="#fff">EXECUTE</text>
118
+ </g>
119
+
120
+ <g class="ui">
121
+ <text x="112" y="852" font-size="15" fill="#6f7771">Visual workflows · human-friendly runs · evidence you can trust</text>
122
+ <text x="1488" y="852" text-anchor="end" font-size="15" font-weight="700" fill="#28ad00">OPEN SOURCE</text>
123
+ </g>
124
+ </svg>
package/lib/gates.js CHANGED
@@ -181,7 +181,7 @@ function resolveRun(rootDir, runId) {
181
181
  return current;
182
182
  }
183
183
 
184
- function applyGate(rootDir, gate, { runId } = {}) {
184
+ function applyGate(rootDir, gate, { runId, transitionOptions = {} } = {}) {
185
185
  if (!Object.hasOwn(GATE_FILES, gate)) {
186
186
  throw gateError(`Unknown gate: ${gate}. Use ${Object.keys(GATE_FILES).join('|')}`);
187
187
  }
@@ -196,7 +196,8 @@ function applyGate(rootDir, gate, { runId } = {}) {
196
196
  if (!check.valid) throw gateError('Goal Contract gate failed', check.errors);
197
197
  return transitionRun(rootDir, run.runId, RUN_STATES.GOAL_FROZEN, {
198
198
  gate,
199
- artifacts: { goalContract: descriptor(rootDir, filePath) }
199
+ artifacts: { goalContract: descriptor(rootDir, filePath) },
200
+ ...transitionOptions
200
201
  });
201
202
  }
202
203
 
@@ -0,0 +1,130 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { validateGoalContract, hashFile } = require('./gates.js');
6
+ const {
7
+ RUN_STATES,
8
+ atomicWriteJson,
9
+ loadRun,
10
+ runsDir,
11
+ transitionRun
12
+ } = require('./run-state.js');
13
+
14
+ function goalError(message, code, details = []) {
15
+ const error = new Error(message);
16
+ error.code = code;
17
+ error.details = details;
18
+ return error;
19
+ }
20
+
21
+ function actorId(actor) {
22
+ const value = String(actor || '').trim();
23
+ if (!/^[A-Za-z0-9@._-]{1,64}$/.test(value)) {
24
+ throw goalError('Goal actor must be a short account identifier', 'INVALID_GOAL_ACTOR');
25
+ }
26
+ return value;
27
+ }
28
+
29
+ function goalPaths(rootDir, runId, version) {
30
+ const directory = path.join(runsDir(rootDir), runId);
31
+ return {
32
+ draft: path.join(directory, 'goal-draft.json'),
33
+ canonical: path.join(directory, 'goal-contract.json'),
34
+ version: path.join(directory, `goal-contract.v${version}.json`)
35
+ };
36
+ }
37
+
38
+ function saveGoalDraft(rootDir, runId, contract) {
39
+ const run = loadRun(rootDir, runId);
40
+ if (run.goal?.frozen) throw goalError('Frozen Goal must be unfrozen before editing', 'GOAL_IS_FROZEN');
41
+ const value = { ...contract, schemaVersion: 1, runId };
42
+ atomicWriteJson(goalPaths(rootDir, runId, run.goal?.version || 1).draft, value);
43
+ return value;
44
+ }
45
+
46
+ function freezeGoal(rootDir, runId, { actor, now = new Date() } = {}) {
47
+ const run = loadRun(rootDir, runId);
48
+ if (run.state !== RUN_STATES.STARTED || run.goal?.frozen) {
49
+ throw goalError(`Run ${runId} cannot freeze a Goal from ${run.state}`, 'INVALID_GOAL_TRANSITION');
50
+ }
51
+ const version = run.goal?.version || 1;
52
+ const paths = goalPaths(rootDir, runId, version);
53
+ let contract;
54
+ try {
55
+ contract = JSON.parse(fs.readFileSync(paths.draft, 'utf8'));
56
+ } catch (cause) {
57
+ throw goalError(`Goal draft is unavailable: ${cause.message}`, 'GOAL_DRAFT_MISSING');
58
+ }
59
+ const validation = validateGoalContract(contract);
60
+ if (!validation.valid) throw goalError('Goal Contract gate failed', 'GATE_FAILED', validation.errors);
61
+ const human = actorId(actor);
62
+ if (fs.existsSync(paths.version)) {
63
+ throw goalError(`Goal version ${version} already exists`, 'GOAL_VERSION_EXISTS');
64
+ }
65
+ atomicWriteJson(paths.version, contract);
66
+ atomicWriteJson(paths.canonical, contract);
67
+ const hash = hashFile(paths.version);
68
+ const transitionOptions = {
69
+ artifacts: {
70
+ goalContract: {
71
+ path: path.relative(rootDir, paths.version).split(path.sep).join('/'),
72
+ sha256: hash,
73
+ goalVersion: version
74
+ }
75
+ },
76
+ statePatch: {
77
+ goal: { version, frozen: true, hash, actor: human, frozenAt: now.toISOString() }
78
+ },
79
+ historyMetadata: { actor: human, goalVersion: version, goalHash: hash },
80
+ now
81
+ };
82
+ if (run.workflow) {
83
+ const { applyWorkflowGate } = require('./workflow-runtime.js');
84
+ return applyWorkflowGate(rootDir, 'goal', { runId, now, transitionOptions }).run;
85
+ }
86
+ return transitionRun(rootDir, runId, RUN_STATES.GOAL_FROZEN, {
87
+ gate: 'goal',
88
+ ...transitionOptions
89
+ });
90
+ }
91
+
92
+ function unfreezeGoal(rootDir, runId, { actor, reason, now = new Date() } = {}) {
93
+ const run = loadRun(rootDir, runId);
94
+ if (run.state !== RUN_STATES.GOAL_FROZEN || !run.goal?.frozen) {
95
+ throw goalError(`Run ${runId} has no frozen editable Goal`, 'INVALID_GOAL_TRANSITION');
96
+ }
97
+ const why = String(reason || '').trim();
98
+ if (!why || why.length > 500) {
99
+ throw goalError('Unfreeze reason must be 1-500 characters', 'INVALID_UNFREEZE_REASON');
100
+ }
101
+ const human = actorId(actor);
102
+ const transitionOptions = {
103
+ reason: why,
104
+ statePatch: {
105
+ goal: {
106
+ version: run.goal.version + 1,
107
+ frozen: false,
108
+ previousVersion: run.goal.version,
109
+ unfrozenBy: human,
110
+ unfrozenAt: now.toISOString()
111
+ }
112
+ },
113
+ historyMetadata: {
114
+ actor: human,
115
+ goalVersion: run.goal.version,
116
+ nextGoalVersion: run.goal.version + 1
117
+ },
118
+ now
119
+ };
120
+ if (run.workflow) {
121
+ const { unfreezeWorkflowGoal } = require('./workflow-runtime.js');
122
+ return unfreezeWorkflowGoal(rootDir, { runId, transitionOptions, now }).run;
123
+ }
124
+ return transitionRun(rootDir, runId, RUN_STATES.STARTED, {
125
+ gate: 'goal-unfreeze',
126
+ ...transitionOptions
127
+ });
128
+ }
129
+
130
+ module.exports = { saveGoalDraft, freezeGoal, unfreezeGoal };
@@ -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',