ai-engineering-loop 2.8.0 → 2.10.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,339 @@
1
+ 'use strict';
2
+
3
+ const { VIEWS, flowActors, flowCounts, flowWarnings, transitionTable } = require('./flow.js');
4
+
5
+ const TILE_W = 200;
6
+ const TILE_H = 56;
7
+ const TILE_GAP = 56;
8
+ const GUTTER = 280;
9
+ const LINE = 20;
10
+ const PAD = 24;
11
+
12
+ function escapeHtml(value) {
13
+ return String(value ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));
14
+ }
15
+
16
+ const label = (step) => `${step.event}${step.guard ? ` [${step.guard}]` : ''}`;
17
+ const clip = (value, max) => {
18
+ const textValue = String(value ?? '');
19
+ return textValue.length > max ? `${textValue.slice(0, max - 1)}…` : textValue;
20
+ };
21
+ const hotspotText = (step) => (step.hotspot === true ? 'undecided' : step.hotspot);
22
+ const sideCount = (step) => (step.effects || []).filter((effect) => !effect.ac).length;
23
+
24
+ const STYLE = `
25
+ :root{--bg:#f5f7fa;--grid:#e9edf3;--paper:#fff;--ink:#141821;--muted:#4f5867;--line:#cfd6e1;--edge:#475467;--accent:#4338ca;--side:#92400e;--sidebg:#fff3dc;--hot:#b42318;--hotbg:#fee4e2;--ok:#05603a;--okbg:#dcfae6;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;--sans:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
26
+ @media (prefers-color-scheme:dark){:root{--bg:#0d1016;--grid:#171c26;--paper:#161b24;--ink:#eef1f6;--muted:#a8b1c0;--line:#2e3646;--edge:#aab4c4;--accent:#a5b4fc;--side:#fcd27b;--sidebg:#3b2908;--hot:#fda29b;--hotbg:#47150f;--ok:#75e0a7;--okbg:#0b3324}}
27
+ *{box-sizing:border-box}
28
+ html{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
29
+ body{margin:0;background-color:var(--bg);background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:24px 24px;color:var(--ink);font:400 1rem/1.55 var(--sans)}
30
+ .wrap{max-width:72rem;margin:0 auto;padding:2.25rem 1rem 4.5rem}
31
+ header{display:flex;justify-content:space-between;gap:1.5rem;align-items:flex-end;flex-wrap:wrap;margin-bottom:1.25rem}
32
+ h1{font-size:1.75rem;line-height:1.2;letter-spacing:-0.015em;margin:.25rem 0 0;font-weight:650;max-width:40ch;text-wrap:balance}
33
+ h2{font-size:1.125rem;line-height:1.3;margin:0 0 .25rem;font-weight:650}
34
+ .sub{margin:0 0 1rem;color:var(--muted);font-size:.9375rem;max-width:70ch}
35
+ .kicker{margin:0;color:var(--muted);font-family:var(--mono);font-size:.8125rem}
36
+ .counts{display:flex;gap:.625rem;flex-wrap:wrap}
37
+ .count{background:var(--paper);border:1px solid var(--line);border-radius:12px;padding:.5rem .875rem;min-width:7rem}
38
+ .count b{display:block;font-size:1.5rem;line-height:1.2;font-variant-numeric:tabular-nums}.count span{font-size:.8125rem;color:var(--muted)}
39
+ .count.alert b{color:var(--side)}
40
+ .panel{background:var(--paper);border:1px solid var(--line);border-radius:16px;padding:1.5rem;margin-bottom:1.125rem}
41
+ .scroll{overflow-x:auto;margin:0 -0.25rem;padding:0 .25rem}
42
+ .hint{display:none;font-size:.8125rem;color:var(--muted);margin:0 0 .5rem}
43
+ @media (max-width:48rem){.hint{display:block}}
44
+ .scroll:focus-visible{outline:2px solid var(--accent);outline-offset:4px;border-radius:8px}
45
+ .legend{display:flex;gap:.5rem 1.25rem;flex-wrap:wrap;font-size:.875rem;color:var(--muted);margin-top:1rem;padding-top:.875rem;border-top:1px solid var(--line)}
46
+ .legend span{white-space:nowrap}
47
+ .swatch{display:inline-block;width:1.75rem;height:0;margin-right:.5rem;vertical-align:middle;border-top:2px solid var(--edge)}
48
+ .swatch.hot{border-top:2px dashed var(--hot)}
49
+ svg{display:block;max-width:none}
50
+ svg text{font-family:var(--mono);font-size:13px;fill:var(--ink)}
51
+ svg .title{font-family:var(--sans);font-size:15px;font-weight:600}
52
+ svg .meta{fill:var(--muted)}
53
+ svg .tile{fill:var(--paper);stroke:var(--line);stroke-width:1.5}
54
+ svg .tile.initial{stroke:var(--accent);stroke-width:2.5}
55
+ svg .tile.end{stroke-dasharray:2 0;fill:var(--bg)}
56
+ svg .tile.warn{stroke:var(--side);stroke-dasharray:6 4}
57
+ svg .edge{fill:none;stroke:var(--edge);stroke-width:1.5}
58
+ svg .edge.hotspot{stroke:var(--hot);stroke-dasharray:7 5}
59
+ svg .lbl{paint-order:stroke;stroke:var(--paper);stroke-width:6px;stroke-linejoin:round}
60
+ svg .effect{fill:var(--ok)}
61
+ svg .effect.side{fill:var(--side);font-weight:600}
62
+ svg .hotspot-text{fill:var(--hot);font-weight:600}
63
+ svg .lane{fill:var(--bg);stroke:var(--line)}
64
+ svg .lane-name{font-family:var(--sans);font-size:14px;font-weight:600;fill:var(--muted)}
65
+ table.transitions{border-collapse:separate;border-spacing:0;width:100%;font-size:.9375rem}
66
+ table.transitions th,table.transitions td{border-bottom:1px solid var(--line);padding:.625rem .75rem;text-align:start;vertical-align:top}
67
+ table.transitions thead th{color:var(--muted);font-weight:600;font-family:var(--mono);font-size:.8125rem;white-space:nowrap}
68
+ table.transitions tbody th{font-weight:600;white-space:nowrap}
69
+ td.cell.undecided{background:var(--sidebg);color:var(--side);font-weight:650}
70
+ td.cell.invalid{color:var(--muted)}
71
+ td.cell.conflict{background:var(--hotbg);color:var(--hot);font-weight:600}
72
+ .ends{color:var(--muted);font-size:.9375rem;margin:.75rem 0 0}
73
+ .board{display:grid;grid-template-columns:repeat(auto-fill,minmax(15rem,1fr));gap:1rem;counter-reset:frame}
74
+ .frame{background:var(--paper);border:1.5px solid var(--line);border-radius:31.5px;padding:1rem;display:flex;flex-direction:column;gap:.625rem;counter-increment:frame}
75
+ .frame.initial{border-color:var(--accent);border-width:2.5px}
76
+ .screen{border:1px solid var(--line);border-radius:14px;padding:.875rem;min-height:5.5rem;background:var(--bg)}
77
+ .screen small{display:block;font-family:var(--mono);font-size:.75rem;color:var(--muted)}
78
+ .screen small::before{content:"Step " counter(frame)}
79
+ .screen b{font-size:1.0625rem;line-height:1.3;overflow-wrap:break-word}
80
+ .step{font-family:var(--mono);font-size:.875rem;line-height:1.5;border-top:1px dashed var(--line);padding-top:.5rem;overflow-wrap:break-word}
81
+ .step.hotspot{color:var(--hot)}
82
+ .chips{display:flex;flex-wrap:wrap;gap:.375rem;margin-top:.375rem}
83
+ .pill{display:inline-block;font-size:.8125rem;line-height:1.4;padding:.1875rem .625rem;border-radius:999px;background:var(--okbg);color:var(--ok);font-family:var(--mono);overflow-wrap:anywhere}
84
+ .pill.side{background:var(--sidebg);color:var(--side);border:1px dashed var(--side)}
85
+ .pill.side::before{content:"not in AC · "}
86
+ .pill.hotspot{background:var(--hotbg);color:var(--hot)}
87
+ .pill.hotspot::before{content:"decide · "}
88
+ ol.steps{margin:1.25rem 0 0;padding:0;list-style:none;display:grid;gap:.5rem}
89
+ ol.steps li{border-top:1px dashed var(--line);padding-top:.5rem;font-size:.9375rem;max-width:80ch}
90
+ ol.steps b{font-family:var(--mono);font-size:.8125rem;color:var(--muted);margin-right:.5rem}
91
+ ul.notes{margin:0;padding-left:1.125rem;color:var(--muted);max-width:70ch}
92
+ @media (max-width:40rem){h1{font-size:1.375rem}.panel{padding:1rem}}
93
+ `;
94
+
95
+ function legendHtml(view) {
96
+ const items = [
97
+ '<span><i class="swatch"></i>transition</span>',
98
+ '<span><i class="swatch hot"></i>hotspot: decide before freeze</span>',
99
+ '<span><span class="pill">effect · AC-n</span> covered by an AC</span>',
100
+ '<span><span class="pill side">effect</span> side effect</span>'
101
+ ];
102
+ if (view === 'state') items.push('<span><b>?</b> = nobody decided this transition</span>');
103
+ return `<div class="legend">${items.join('')}</div>`;
104
+ }
105
+
106
+ function scrollBox(inner, title, what = 'diagram') {
107
+ return `<p class="hint">Scroll sideways to see the whole ${what} →</p><div class="scroll" tabindex="0" role="region" aria-label="${escapeHtml(title)}">${inner}</div>`;
108
+ }
109
+
110
+ function svg(width, height, body, title) {
111
+ return scrollBox(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(title)}"><defs><marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M2 1L8 5L2 9" fill="none" stroke="context-stroke" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></marker></defs>${body}</svg>`, title);
112
+ }
113
+
114
+ function edgeLabel(step, x, y, anchor = 'start') {
115
+ const total = (step.effects || []).length;
116
+ const side = sideCount(step);
117
+ const effects = total ? `<tspan class="effect${side ? ' side' : ''}"> · ${total} effect${total > 1 ? 's' : ''}${side ? `, ${side} not in AC` : ''}</tspan>` : '';
118
+ const hot = step.hotspot ? `<tspan class="hotspot-text hotspot"> · decide</tspan>` : '';
119
+ return `<text class="lbl" x="${x}" y="${y}" text-anchor="${anchor}"><title>${escapeHtml(label(step))}</title>${escapeHtml(clip(label(step), 28))}${effects}${hot}</text>`;
120
+ }
121
+
122
+ function layering(flow) {
123
+ const states = [...new Set(flow.flatMap((step) => [step.from, step.to]))];
124
+ const outgoing = new Map(states.map((state) => [state, flow.filter((step) => step.from === state && step.to !== state)]));
125
+ const back = new Set();
126
+ const visiting = new Set();
127
+ const done = new Set();
128
+ const visit = (state) => {
129
+ visiting.add(state);
130
+ for (const step of outgoing.get(state)) {
131
+ if (visiting.has(step.to)) back.add(step);
132
+ else if (!done.has(step.to)) visit(step.to);
133
+ }
134
+ visiting.delete(state);
135
+ done.add(state);
136
+ };
137
+ for (const state of states) if (!done.has(state)) visit(state);
138
+ const rank = new Map(states.map((state) => [state, 0]));
139
+ for (let pass = 0; pass < states.length; pass += 1) {
140
+ for (const step of flow) {
141
+ if (step.from === step.to || back.has(step)) continue;
142
+ if (rank.get(step.to) < rank.get(step.from) + 1) rank.set(step.to, rank.get(step.from) + 1);
143
+ }
144
+ }
145
+ return { states, rank, back };
146
+ }
147
+
148
+ function stateSvg(goal) {
149
+ const flow = goal.flow;
150
+ const warned = flowWarnings(flow).join(' ');
151
+ const { states, rank, back } = layering(flow);
152
+ const sources = new Set(flow.map((step) => step.from));
153
+ const forward = flow.filter((step) => step.from !== step.to && !back.has(step));
154
+ const adjacent = forward.filter((step) => rank.get(step.to) - rank.get(step.from) === 1);
155
+ const long = forward.filter((step) => rank.get(step.to) - rank.get(step.from) > 1);
156
+ const rows = new Map();
157
+ for (const state of states) {
158
+ const r = rank.get(state);
159
+ if (!rows.has(r)) rows.set(r, []);
160
+ rows.get(r).push(state);
161
+ }
162
+ const rowCount = Math.max(...rows.keys()) + 1;
163
+ const widest = Math.max(...[...rows.values()].map((list) => list.length));
164
+ const left = PAD + (back.size ? GUTTER : 0);
165
+ const gapAfter = new Map();
166
+ for (let r = 0; r < rowCount; r += 1) {
167
+ const leaving = adjacent.filter((step) => rank.get(step.from) === r).length;
168
+ const arriving = long.filter((step) => rank.get(step.to) === r + 1).length;
169
+ gapAfter.set(r, 36 + (leaving + arriving) * LINE);
170
+ }
171
+ const rowY = new Map();
172
+ let y = PAD + 20;
173
+ for (let r = 0; r < rowCount; r += 1) {
174
+ rowY.set(r, y);
175
+ y += TILE_H + gapAfter.get(r);
176
+ }
177
+ const bodyRight = left + widest * TILE_W + (widest - 1) * TILE_GAP;
178
+ const width = bodyRight + (long.length || flow.some((step) => step.from === step.to) ? GUTTER : 0) + PAD;
179
+ const height = y - gapAfter.get(rowCount - 1) + PAD + 20;
180
+ const pos = new Map();
181
+ for (const [r, list] of rows) {
182
+ const offset = ((widest - list.length) * (TILE_W + TILE_GAP)) / 2;
183
+ list.forEach((state, i) => pos.set(state, { x: left + offset + i * (TILE_W + TILE_GAP), y: rowY.get(r) }));
184
+ }
185
+ const outs = new Map(states.map((state) => [state, adjacent.filter((step) => step.from === state)]));
186
+ const ins = new Map(states.map((state) => [state, forward.filter((step) => step.to === state)]));
187
+ const portX = (list, step, p) => p.x + ((list.indexOf(step) + 1) * TILE_W) / (list.length + 1);
188
+ const edges = [];
189
+ const labels = [];
190
+ const rowSlot = new Map();
191
+ for (const step of adjacent) {
192
+ const a = pos.get(step.from);
193
+ const b = pos.get(step.to);
194
+ const r = rank.get(step.from);
195
+ const slot = rowSlot.get(r) || 0;
196
+ rowSlot.set(r, slot + 1);
197
+ const x1 = portX(outs.get(step.from), step, a);
198
+ const x2 = portX(ins.get(step.to), step, b);
199
+ const mid = a.y + TILE_H + 26 + slot * LINE;
200
+ edges.push(`<path class="edge${step.hotspot ? ' hotspot' : ''}" d="M${x1} ${a.y + TILE_H} V${mid} H${x2} V${b.y - 4}" marker-end="url(#arrow)"/>`);
201
+ labels.push(edgeLabel(step, Math.min(x1, x2) + 10, mid - 5));
202
+ }
203
+ long.forEach((step, i) => {
204
+ const a = pos.get(step.from);
205
+ const b = pos.get(step.to);
206
+ const gx = bodyRight + 24 + i * 14;
207
+ const r = rank.get(step.to) - 1;
208
+ const slot = rowSlot.get(r) || 0;
209
+ rowSlot.set(r, slot + 1);
210
+ const lane = rowY.get(r) + TILE_H + 26 + slot * LINE;
211
+ const x2 = portX(ins.get(step.to), step, b);
212
+ edges.push(`<path class="edge${step.hotspot ? ' hotspot' : ''}" d="M${a.x + TILE_W} ${a.y + TILE_H / 2} H${gx} V${lane} H${x2} V${b.y - 4}" marker-end="url(#arrow)"/>`);
213
+ labels.push(edgeLabel(step, x2 + 10, lane - 5));
214
+ });
215
+ [...back].forEach((step, i) => {
216
+ const a = pos.get(step.from);
217
+ const b = pos.get(step.to);
218
+ const gx = left - 24 - i * 14;
219
+ edges.push(`<path class="edge${step.hotspot ? ' hotspot' : ''}" d="M${a.x} ${a.y + TILE_H / 2} H${gx} V${b.y + TILE_H / 2} H${b.x - 4}" marker-end="url(#arrow)"/>`);
220
+ labels.push(edgeLabel(step, gx - 10, a.y + TILE_H / 2 - 6, 'end'));
221
+ });
222
+ for (const step of flow.filter((item) => item.from === item.to)) {
223
+ const a = pos.get(step.from);
224
+ const yy = a.y + TILE_H / 2;
225
+ edges.push(`<path class="edge${step.hotspot ? ' hotspot' : ''}" d="M${a.x + TILE_W} ${yy - 10} H${a.x + TILE_W + 22} V${yy + 10} H${a.x + TILE_W + 4}" marker-end="url(#arrow)"/>`);
226
+ labels.push(edgeLabel(step, a.x + TILE_W + 30, yy + 4));
227
+ }
228
+ const tiles = states.map((state) => {
229
+ const p = pos.get(state);
230
+ const cls = ['tile', state === flow[0].from ? 'initial' : '', sources.has(state) ? '' : 'end', warned.includes(`"${state}"`) ? 'warn' : ''].filter(Boolean).join(' ');
231
+ const tag = state === flow[0].from ? 'start' : sources.has(state) ? '' : 'end state';
232
+ return `<g><title>${escapeHtml(state)}</title><rect class="${cls}" x="${p.x}" y="${p.y}" width="${TILE_W}" height="${TILE_H}" rx="12"/><text class="title" x="${p.x + TILE_W / 2}" y="${p.y + (tag ? 25 : 33)}" text-anchor="middle">${escapeHtml(clip(state, 22))}</text>${tag ? `<text class="meta" x="${p.x + TILE_W / 2}" y="${p.y + 44}" text-anchor="middle">${tag}</text>` : ''}</g>`;
233
+ }).join('');
234
+ return svg(width, height, `${edges.join('')}${tiles}${labels.join('')}`, `State machine of ${goal.flowSubject || 'the Goal flow'}`);
235
+ }
236
+
237
+ function tableHtml(goal) {
238
+ const table = transitionTable(goal);
239
+ const head = `<thead><tr><th scope="col">state \\ event</th>${table.events.map((event) => `<th scope="col">${escapeHtml(event)}</th>`).join('')}</tr></thead>`;
240
+ const rows = table.rows.map((row) => `<tr><th scope="row">${escapeHtml(row.state)}</th>${table.events.map((event) => {
241
+ const c = row.cells[event];
242
+ if (c.kind === 'undecided') return '<td class="cell undecided">?</td>';
243
+ if (c.kind === 'invalid') return '<td class="cell invalid">invalid</td>';
244
+ const body = c.targets.map((t) => {
245
+ const step = goal.flow.find((item) => item.from === row.state && item.event === event && item.to === t.to);
246
+ const chips = [
247
+ ...(step?.effects || []).map((effect) => `<span class="pill${effect.ac ? '' : ' side'}">${escapeHtml(effect.text)}${effect.ac ? ` · ${escapeHtml(effect.ac)}` : ''}</span>`),
248
+ step?.hotspot ? `<span class="pill hotspot">${escapeHtml(hotspotText(step))}</span>` : ''
249
+ ].filter(Boolean).join('');
250
+ return `→ ${escapeHtml(t.to)}${t.guard ? ` [${escapeHtml(t.guard)}]` : ''}${chips ? `<div class="chips">${chips}</div>` : ''}`;
251
+ }).join('<br>');
252
+ return `<td class="cell ${c.kind}">${c.kind === 'conflict' ? 'conflict: ' : ''}${body}</td>`;
253
+ }).join('')}</tr>`).join('');
254
+ const ends = table.endStates.length ? `<p class="ends">End states: ${table.endStates.map(escapeHtml).join(', ')}</p>` : '';
255
+ return `<section class="panel"><h2>Transition table</h2><p class="sub">Every state × event. Each <b>?</b> is a decision the Goal has not made: add an AC, a non-goal, or list it in <code>forbiddenTransitions</code>.</p>${scrollBox(`<table class="transitions">${head}<tbody>${rows}</tbody></table>`, 'Transition table', 'table')}${ends}</section>`;
256
+ }
257
+
258
+ function storyboardHtml(goal) {
259
+ const flow = goal.flow;
260
+ const states = [...new Set(flow.flatMap((step) => [step.from, step.to]))];
261
+ const frames = states.map((state) => {
262
+ const steps = flow.filter((step) => step.from === state).map((step) => {
263
+ const chips = [
264
+ ...(step.effects || []).map((effect) => `<span class="pill${effect.ac ? '' : ' side'}">${escapeHtml(effect.text)}${effect.ac ? ` · ${escapeHtml(effect.ac)}` : ''}</span>`),
265
+ step.hotspot ? `<span class="pill hotspot">${escapeHtml(hotspotText(step))}</span>` : ''
266
+ ].filter(Boolean).join('');
267
+ return `<div class="step${step.hotspot ? ' hotspot' : ''}">${escapeHtml(`${label(step)} → ${step.to}`)}${chips ? `<div class="chips">${chips}</div>` : ''}</div>`;
268
+ }).join('');
269
+ return `<li class="frame${state === flow[0].from ? ' initial' : ''}"><div class="screen"><small></small><b>${escapeHtml(state)}</b></div>${steps || '<div class="step">End of flow</div>'}</li>`;
270
+ });
271
+ return `<section class="panel"><h2>Storyboard</h2><p class="sub">One card per screen or state, in the order the flow first reaches it. Effects sit under the action that causes them.</p><ol class="board" style="list-style:none;padding:0;margin:0">${frames.join('')}</ol>${legendHtml('storyboard')}</section>`;
272
+ }
273
+
274
+ function lanesSvg(goal) {
275
+ const flow = goal.flow;
276
+ const actors = flowActors(flow);
277
+ const colW = TILE_W + 72;
278
+ const head = 44;
279
+ const effectLines = (step) => (step.effects || []).length + (step.hotspot ? 1 : 0);
280
+ const rowY = [];
281
+ let y = PAD + head;
282
+ for (const step of flow) {
283
+ rowY.push(y);
284
+ y += TILE_H + 34 + effectLines(step) * LINE;
285
+ }
286
+ const width = PAD * 2 + actors.length * colW;
287
+ const height = y + PAD - 20;
288
+ const actorOf = (step) => (step.actor ? String(step.actor).trim() : 'user');
289
+ const colX = (actor) => PAD + actors.indexOf(actor) * colW + (colW - TILE_W) / 2;
290
+ const lanes = actors.map((actor, i) => `<rect class="lane" x="${PAD + i * colW + 6}" y="${PAD}" width="${colW - 12}" height="${height - PAD * 2}" rx="12"/><text class="lane-name" x="${PAD + i * colW + colW / 2}" y="${PAD + 26}" text-anchor="middle">${escapeHtml(clip(actor, 20))}</text>`).join('');
291
+ const parts = [];
292
+ flow.forEach((step, i) => {
293
+ const x = colX(actorOf(step));
294
+ const ty = rowY[i];
295
+ const effects = (step.effects || []).map((effect, k) => `<text class="effect${effect.ac ? '' : ' side'} lbl" x="${x + 4}" y="${ty + TILE_H + 20 + k * LINE}">${escapeHtml(`${effect.ac ? '' : 'not in AC: '}${clip(effect.text, 24)}${effect.ac ? ` · ${effect.ac}` : ''}`)}</text>`).join('');
296
+ const hot = step.hotspot ? `<text class="hotspot-text hotspot lbl" x="${x + 4}" y="${ty + TILE_H + 20 + (step.effects || []).length * LINE}">${escapeHtml(`decide: ${clip(hotspotText(step), 22)}`)}</text>` : '';
297
+ parts.push(`<g><title>${escapeHtml(`${label(step)}: ${step.from} → ${step.to}`)}</title><rect class="tile${step.hotspot ? ' warn' : ''}" x="${x}" y="${ty}" width="${TILE_W}" height="${TILE_H}" rx="10"/><text class="title" x="${x + 12}" y="${ty + 23}">${escapeHtml(clip(label(step), 22))}</text><text class="meta" x="${x + 12}" y="${ty + 43}">${escapeHtml(clip(`${step.from} → ${step.to}`, 24))}</text>${effects}${hot}</g>`);
298
+ if (i > 0) {
299
+ const prev = flow[i - 1];
300
+ const px = colX(actorOf(prev)) + TILE_W / 2;
301
+ const nx = x + TILE_W / 2;
302
+ const from = rowY[i - 1] + TILE_H;
303
+ const mid = ty - 14;
304
+ parts.unshift(`<path class="edge${step.hotspot ? ' hotspot' : ''}" d="M${px} ${from} V${mid} H${nx} V${ty - 4}" marker-end="url(#arrow)"/>`);
305
+ }
306
+ });
307
+ return svg(width, height, `${lanes}${parts.join('')}`, 'Actor lanes');
308
+ }
309
+
310
+ function stepsList(goal) {
311
+ const items = goal.flow.map((step, i) => {
312
+ const effects = (step.effects || []).map((effect) => `<span class="pill${effect.ac ? '' : ' side'}">${escapeHtml(effect.text)}${effect.ac ? ` · ${escapeHtml(effect.ac)}` : ''}</span>`);
313
+ if (step.hotspot) effects.push(`<span class="pill hotspot">${escapeHtml(hotspotText(step))}</span>`);
314
+ return `<li><b>${i + 1}. ${escapeHtml(step.actor ? String(step.actor).trim() : 'user')}</b>${escapeHtml(`${label(step)}: ${step.from} → ${step.to}`)}${effects.length ? `<div class="chips">${effects.join('')}</div>` : ''}</li>`;
315
+ }).join('');
316
+ return `<h3 class="sub" style="margin:1.25rem 0 0">Steps in order</h3><ol class="steps">${items}</ol>`;
317
+ }
318
+
319
+ function renderDiagram(goal, { view, revision, now = new Date(), lang = null } = {}) {
320
+ const contentLang = lang ? ` lang="${escapeHtml(lang)}"` : '';
321
+ if (!VIEWS.includes(view)) throw new Error(`Unknown view "${view}": use state, storyboard or lanes`);
322
+ if (!Array.isArray(goal?.flow) || !goal.flow.length) throw new Error('The Goal has no flow to draw; add flow steps ({from, event, to}) to the draft first');
323
+ const counts = flowCounts(goal);
324
+ const titles = { state: 'State machine', storyboard: 'Storyboard', lanes: 'Actor lanes' };
325
+ let body;
326
+ if (view === 'state') {
327
+ body = `<section class="panel"><h2>${escapeHtml(goal.flowSubject ? `Status of ${goal.flowSubject}` : 'States')}</h2><p class="sub">Read top to bottom. Labels read <code>event [guard]</code>; dashed red lines are transitions still to decide.</p>${stateSvg(goal)}${legendHtml('state')}</section>${tableHtml(goal)}`;
328
+ } else if (view === 'storyboard') {
329
+ body = storyboardHtml(goal);
330
+ } else {
331
+ body = `<section class="panel"><h2>Actor lanes</h2><p class="sub">One column per actor, steps in flow order from top to bottom. Work that runs later (jobs, cron) shows up in its own column.</p>${lanesSvg(goal)}${stepsList(goal)}${legendHtml('lanes')}</section>`;
332
+ }
333
+ const warnings = flowWarnings(goal.flow);
334
+ const notes = warnings.length ? `<section class="panel"><h2>Flow warnings</h2><ul class="notes">${warnings.map((w) => `<li>${escapeHtml(w)}</li>`).join('')}</ul></section>` : '';
335
+ const count = (n, text) => `<div class="count${n ? ' alert' : ''}"><b>${n}</b><span>${escapeHtml(text)}</span></div>`;
336
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(`${titles[view]} · ${clip(goal.objective || 'Goal', 60)}`)}</title><style>${STYLE}</style></head><body><main class="wrap"><header><div><p class="kicker">${escapeHtml(`AEL Goal · ${titles[view]} · revision ${revision ?? 'frozen'} · ${now.toISOString().slice(0, 16).replace('T', ' ')} UTC`)}</p><h1${contentLang}>${escapeHtml(goal.objective || '')}</h1></div><div class="counts">${count(counts.undecided, 'undecided')}${count(counts.hotspots, 'hotspots')}${count(counts.sideEffects, 'side effects')}</div></header><div${contentLang}>${body}</div>${notes}</main></body></html>`;
337
+ }
338
+
339
+ module.exports = { escapeHtml, renderDiagram };
package/lib/flow.js CHANGED
@@ -1,27 +1,54 @@
1
1
  'use strict';
2
2
 
3
- // Goal `flow` (C-21, "All Code Is Slop (Except Mine)" 12:46): a small state
4
- // machine from the user's point of view, so a human can check that the agent
5
- // understood the intent before any code exists, and review it again next to
6
- // the verification artifacts. Plain Markdown tables (no diagram engine), so
7
- // it renders on every host and in every PR.
8
- //
9
- // "flow": [ { "from": "List", "event": "click Export", "to": "Exporting" }, ... ]
3
+ const MAX_STEPS = 40;
4
+ const MAX_EFFECTS = 12;
5
+ const VIEWS = ['state', 'storyboard', 'lanes'];
6
+ const PREFERENCES = ['auto', ...VIEWS, 'off'];
7
+ const TERMINAL = /^(done|end|closed|success|error|failed|cancel(l)?ed)$/i;
8
+
9
+ const text = (value) => String(value ?? '').trim();
10
10
 
11
- function flowProblems(flow) {
11
+ function flowProblems(flow, { acIds = null, forbidden = null } = {}) {
12
12
  if (flow == null) return [];
13
13
  if (!Array.isArray(flow) || !flow.length) return ['flow must be a non-empty array of {from, event, to}'];
14
14
  const problems = [];
15
+ if (flow.length > MAX_STEPS) problems.push(`flow may have at most ${MAX_STEPS} steps (has ${flow.length}); split it into smaller Goals`);
16
+ const knownAcs = acIds ? new Set(acIds) : null;
15
17
  flow.forEach((step, index) => {
16
18
  for (const field of ['from', 'event', 'to']) {
17
- if (!String(step?.[field] || '').trim()) problems.push(`flow[${index}].${field} is required`);
19
+ if (!text(step?.[field])) problems.push(`flow[${index}].${field} is required`);
20
+ }
21
+ if (step?.hotspot !== undefined && step.hotspot !== true && (typeof step.hotspot !== 'string' || !text(step.hotspot))) {
22
+ problems.push(`flow[${index}].hotspot must be a question (string) or true`);
18
23
  }
24
+ if (step?.effects === undefined) return;
25
+ if (!Array.isArray(step.effects)) {
26
+ problems.push(`flow[${index}].effects must be an array`);
27
+ return;
28
+ }
29
+ if (step.effects.length > MAX_EFFECTS) problems.push(`flow[${index}].effects may have at most ${MAX_EFFECTS} items`);
30
+ step.effects.forEach((effect, effectIndex) => {
31
+ if (!text(effect?.text)) problems.push(`flow[${index}].effects[${effectIndex}].text is required`);
32
+ if (effect?.ac !== undefined && knownAcs && !knownAcs.has(effect.ac)) {
33
+ problems.push(`flow[${index}].effects[${effectIndex}].ac ${effect.ac} is not an acceptance criterion id`);
34
+ }
35
+ });
19
36
  });
37
+ if (forbidden != null) {
38
+ if (!Array.isArray(forbidden)) {
39
+ problems.push('forbiddenTransitions must be an array of {from, event}');
40
+ } else {
41
+ const states = new Set(flow.flatMap((step) => [step?.from, step?.to]));
42
+ const events = new Set(flow.map((step) => step?.event));
43
+ forbidden.forEach((pair, index) => {
44
+ if (!states.has(pair?.from)) problems.push(`forbiddenTransitions[${index}].from "${pair?.from}" is not a state in flow`);
45
+ if (!events.has(pair?.event)) problems.push(`forbiddenTransitions[${index}].event "${pair?.event}" is not an event in flow`);
46
+ });
47
+ }
48
+ }
20
49
  return problems;
21
50
  }
22
51
 
23
- // Warnings a reviewer should look at: states nothing leads to (besides the
24
- // first), and states with no way out that are not marked terminal.
25
52
  function flowWarnings(flow) {
26
53
  if (flowProblems(flow).length || !flow) return [];
27
54
  const start = flow[0].from;
@@ -31,13 +58,77 @@ function flowWarnings(flow) {
31
58
  const warnings = [];
32
59
  for (const state of states) {
33
60
  if (state !== start && !targets.has(state)) warnings.push(`"${state}" is never reached from another state`);
34
- if (!sources.has(state) && !/^(done|end|closed|success|error|failed|cancel(l)?ed)$/i.test(state)) {
61
+ if (!sources.has(state) && !TERMINAL.test(state)) {
35
62
  warnings.push(`"${state}" has no way out; mark it terminal (Done/Error) or add the next step`);
36
63
  }
37
64
  }
38
65
  return warnings;
39
66
  }
40
67
 
68
+ function flowActors(flow) {
69
+ return [...new Set((flow || []).map((step) => text(step.actor) || 'user'))];
70
+ }
71
+
72
+ function orderedStates(flow) {
73
+ return [...new Set(flow.flatMap((step) => [step.from, step.to]))];
74
+ }
75
+
76
+ function transitionTable(goal) {
77
+ const flow = goal?.flow || [];
78
+ const events = [...new Set(flow.map((step) => step.event))];
79
+ const fromStates = [...new Set(flow.map((step) => step.from))];
80
+ const endStates = orderedStates(flow).filter((state) => !fromStates.includes(state));
81
+ const forbidden = new Set((goal?.forbiddenTransitions || []).map((pair) => `${pair.from}\u0000${pair.event}`));
82
+ const rows = fromStates.map((state) => {
83
+ const cells = {};
84
+ for (const event of events) {
85
+ const steps = flow.filter((step) => step.from === state && step.event === event);
86
+ const targets = steps.map((step) => ({ to: step.to, guard: text(step.guard) || null, hotspot: step.hotspot || null }));
87
+ if (!steps.length) {
88
+ cells[event] = { kind: forbidden.has(`${state}\u0000${event}`) ? 'invalid' : 'undecided', targets: [] };
89
+ } else if (steps.length === 1) {
90
+ cells[event] = { kind: 'target', targets };
91
+ } else {
92
+ const guards = targets.map((target) => target.guard);
93
+ const distinct = guards.every(Boolean) && new Set(guards).size === guards.length;
94
+ cells[event] = { kind: distinct ? 'targets' : 'conflict', targets };
95
+ }
96
+ }
97
+ return { state, cells };
98
+ });
99
+ return { states: orderedStates(flow), events, rows, endStates };
100
+ }
101
+
102
+ function flowCounts(goal) {
103
+ const flow = goal?.flow || [];
104
+ const table = transitionTable(goal);
105
+ const cells = table.rows.flatMap((row) => Object.values(row.cells));
106
+ return {
107
+ undecided: cells.filter((cell) => cell.kind === 'undecided').length,
108
+ hotspots: flow.filter((step) => step.hotspot).length + cells.filter((cell) => cell.kind === 'conflict').length,
109
+ sideEffects: flow.reduce((sum, step) => sum + (step.effects || []).filter((effect) => !effect.ac).length, 0)
110
+ };
111
+ }
112
+
113
+ function diagramOptions(goal, { preference = 'auto' } = {}) {
114
+ const flow = goal?.flow;
115
+ if (!Array.isArray(flow) || !flow.length || preference === 'off') return [];
116
+ const actors = flowActors(flow);
117
+ const rules = {
118
+ state: [Boolean(text(goal.flowSubject)), `the Goal changes the status of ${text(goal.flowSubject) || 'an entity'}`],
119
+ storyboard: [actors.every((actor) => actor === 'user'), 'every step is a user action'],
120
+ lanes: [actors.length >= 2 && actors.some((actor) => actor !== 'user'), `steps run across ${actors.join(', ')}`]
121
+ };
122
+ const fixed = VIEWS.includes(preference) ? preference : null;
123
+ const options = VIEWS.map((view) => ({
124
+ view,
125
+ recommended: fixed ? view === fixed : rules[view][0],
126
+ reason: fixed && view === fixed ? 'project default (freeze_diagram)' : rules[view][1]
127
+ }));
128
+ if (!options.some((option) => option.recommended)) options.find((option) => option.view === 'state').recommended = true;
129
+ return [...options.filter((option) => option.recommended), ...options.filter((option) => !option.recommended)];
130
+ }
131
+
41
132
  const cell = (value) => String(value ?? '').replace(/\r?\n/g, ' ').replace(/\|/g, '\\|');
42
133
 
43
134
  function renderFlow(flow) {
@@ -45,12 +136,6 @@ function renderFlow(flow) {
45
136
  return ['| From | Event | To |', '|---|---|---|', ...flow.map((step) => `| ${cell(step.from)} | ${cell(step.event)} | ${cell(step.to)} |`)].join('\n');
46
137
  }
47
138
 
48
- // C-25: the same flow as a Mermaid stateDiagram-v2 (GitHub renders it in
49
- // PRs). States get safe ids (s0, s1, ...) with the reader's label attached,
50
- // so any text in a state name keeps the diagram valid. Visualisation only:
51
- // model checking stays with the `formal` key (e.g. pstack /statechart).
52
- const TERMINAL = /^(done|end|closed|success|error|failed|cancel(l)?ed)$/i;
53
-
54
139
  function mermaidText(value) {
55
140
  return String(value ?? '')
56
141
  .replace(/[\r\n]+/g, ' ')
@@ -83,4 +168,4 @@ function renderMermaid(flow) {
83
168
  return lines.join('\n');
84
169
  }
85
170
 
86
- module.exports = { flowProblems, flowWarnings, renderFlow, renderMermaid };
171
+ module.exports = { MAX_EFFECTS, MAX_STEPS, PREFERENCES, VIEWS, diagramOptions, flowActors, flowCounts, flowProblems, flowWarnings, renderFlow, renderMermaid, transitionTable };
package/lib/gates.js CHANGED
@@ -131,7 +131,13 @@ function validateGoalContract(contract) {
131
131
  const errors = [];
132
132
  if (!contract || typeof contract !== 'object') return { valid: false, errors: ['contract must be an object'] };
133
133
  if (!String(contract.objective || '').trim()) errors.push('objective is required');
134
- errors.push(...require('./flow.js').flowProblems(contract.flow)); // C-21
134
+ errors.push(...require('./flow.js').flowProblems(contract.flow, {
135
+ acIds: Array.isArray(contract.acceptanceCriteria) ? contract.acceptanceCriteria.map((criterion) => criterion?.id) : [],
136
+ forbidden: contract.forbiddenTransitions
137
+ }));
138
+ if (contract.plainSummary !== undefined && (typeof contract.plainSummary !== 'string' || !contract.plainSummary.trim() || contract.plainSummary.length > 240)) {
139
+ errors.push('plainSummary must be one sentence of at most 240 characters');
140
+ }
135
141
  if (!Array.isArray(contract.acceptanceCriteria) || contract.acceptanceCriteria.length === 0) {
136
142
  errors.push('acceptanceCriteria must contain at least one item');
137
143
  } else {
@@ -532,8 +538,8 @@ function mergeCommentJustifications(rootDir, run) {
532
538
  }
533
539
  const merged = mergeCommentFindings(ledger, scanRunComments(rootDir, run));
534
540
  if (merged.errors.length) {
535
- throw gateError('Review gate failed (comment-justification finding dropped)', merged.errors,
536
- { why: 'Comments and suppressions are how agents justify skipping the root cause; dropping the finding silently hides that decision.', fix: 'Restore the finding, or record dismissal: {by, evidence} for each one.' });
541
+ throw gateError('Review gate failed (comment or no-comments finding dropped)', merged.errors,
542
+ { why: 'Comments and suppressions are how agents justify skipping the root cause, and new comments in product code are banned by default (C-26); dropping the finding silently hides that decision.', fix: 'Restore the finding, or record dismissal: {by, evidence} for each one.' });
537
543
  }
538
544
  if (merged.added) fs.writeFileSync(filePath, `${JSON.stringify(merged.ledger, null, 2)}\n`, { mode: 0o600 });
539
545
  return merged.added;
@@ -52,6 +52,20 @@ function normalizeMakerIntern(raw) {
52
52
  return s;
53
53
  }
54
54
 
55
+ function parseFreezeDiagramLine(text) {
56
+ const match = String(text || '').match(/\*\*freeze_diagram\*\*:\s*([a-z]+)/i);
57
+ const value = match ? match[1].toLowerCase() : 'auto';
58
+ return ['auto', 'state', 'storyboard', 'lanes', 'off'].includes(value) ? value : 'auto';
59
+ }
60
+
61
+ function readFreezeDiagram(rootDir) {
62
+ try {
63
+ return parseFreezeDiagramLine(fs.readFileSync(path.join(rootDir, '.ai-engineering-loop', 'workflow.md'), 'utf8'));
64
+ } catch {
65
+ return 'auto';
66
+ }
67
+ }
68
+
55
69
  function parseMakerInternLine(text) {
56
70
  const match = String(text || '').match(/\*\*maker_intern\*\*:\s*(.*)/i);
57
71
  if (!match) return DEFAULT_MAKER_INTERN;
@@ -128,6 +142,7 @@ function parseWorkflowMarkdown(text) {
128
142
  after_pass: parseHookLine(text, 'after_pass')
129
143
  },
130
144
  makerIntern: parseMakerInternLine(text),
145
+ freezeDiagram: parseFreezeDiagramLine(text),
131
146
  optionalSkips: parseOptionalSkips(text)
132
147
  };
133
148
  }
@@ -198,7 +213,9 @@ module.exports = {
198
213
  normalizeMakerIntern,
199
214
  workflowMarkdown,
200
215
  lessonsMarkdown,
216
+ parseFreezeDiagramLine,
201
217
  parseWorkflowMarkdown,
218
+ readFreezeDiagram,
202
219
  writeWorkflowOverlay,
203
220
  formatGenerateWorkflowReport,
204
221
  parseWriteArg