create-pmos 0.590.0 → 0.592.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.
@@ -4,10 +4,19 @@
4
4
  * or with stakeholders in the room. PMOS shows THREE ways in about a minute, each one only after it renders; a sentence of feedback makes the
5
5
  * next round of one of them. The idle lab (lib/idle-lab-engine.js) waits for the PM to step away; this does not wait for anything.
6
6
  *
7
- * AGENT PROPOSES, PM APPROVES. A chat sentence ("show 3 ways", "prototype this") files ONE ✦ ask (group `live`, type new): "PMOS will show
8
- * 3 ways: A …, B …, C …". A feedback sentence while a round waits ("B, but lead with the risk") files the ✦ ask of type feedback: "Round n of
9
- * B: …". ✓ on the ask starts the round (lib/routes-proposals.js), ✕ drops it with an optional reason, Undo stops a round that runs and takes
10
- * its card away. `pmos lab round` starts one without the chat (D98: an agent does what it was asked); `--propose` files the ask instead.
7
+ * ITERATIVE, LIKE CLAUDE CODE DESIGN WORK (Wawan 2026-11-17 20:25, initiative live-round-iterative). "prototype this" in the initiative chat
8
+ * starts ONE version at once (lib/routes-briefing-premium.js liveAsk → startNow, count 1): no ✦ ask, no ✓. It opens in the Viewer as soon
9
+ * as it renders, and the chat says in one line what was made (deps.tell: the version's own <meta name="pmos-changed"> sentence goes to the
10
+ * chat's session). Any change sentence while that one version is open ("make the alert orange") is the next round of it, the same way.
11
+ * PROTOTYPE BY CHATTING (design agreed 2026-11-17 23:31, https://claude.ai/artifact/9fxuukKr3XixwkGFMTfeba): the run that makes a version
12
+ * also writes its companions as DATA next to it (PARTS: flow.json, lanes.json, tweaks.json; PMOS writes copy.json from the prototype's
13
+ * data-copy text), and the Viewer draws them as one canvas (pm/cozy-proto.js). The chat is told once per round, "Version n" first, with
14
+ * what the version changed beside the prototype (changesOf: "Also updated: step 3, the swimlane and the copy"). The canvas's marks before
15
+ * the PM's words (marksOf: the element pointed at, Continue from version n) and the PM's in-place edits (edits.json) reach the next run.
16
+ * "show 3 ways" is the exception: the chat's Claude picks three directions and starts them with `pmos lab round --dirs` (no --propose), side
17
+ * by side in the Viewer. The design sprint's good practice runs silently in the prompt (a target user, one question, real content, Goldilocks
18
+ * fidelity), never as a step. The older ✦ ask (group `live`, `--propose`) still exists for the CLI and the meeting companion: ✓ on it starts
19
+ * the round (lib/routes-proposals.js), ✕ drops it, Undo stops a round that runs and takes its card away.
11
20
  *
12
21
  * THE ROUND. Step 1 of the shared queue (lib/bg-queue.js: what the PM asked for starts at once, never on the idle clock, never held).
13
22
  * new THREE headless runs in parallel, one specimen each (origin `live-round:<ws>:<ini>:<run>:<A|B|C>`, headless kind `live-round`:
@@ -52,6 +61,17 @@ const DEFAULT_DIRECTIONS = Object.freeze([
52
61
  Object.freeze({ key: 'B', title: 'The one thing that matters most leads; the rest folds away' }),
53
62
  Object.freeze({ key: 'C', title: 'A different shape: a timeline, a stack of cards or a step-by-step flow' }),
54
63
  ]);
64
+ // one version, the default since 2026-11-17 (Wawan: "viewer shows the prototype one at a time unless stated to have multiple versions")
65
+ const ONE_DIRECTION = Object.freeze([Object.freeze({ key: 'A', title: 'The idea as asked: the plainest honest version' })]);
66
+ // the companions of every version (Wawan 2026-11-17 20:32: "at the same time it generated the swimlane diagram and user workflow or steps
67
+ // diagram and copywriting document"; design Prototype by chatting, agreed 23:31): DATA the Viewer draws, not pages. The version's own run
68
+ // writes them next to the prototype, so the screens, the steps and the copy keys are the same ids everywhere. copy.json is PMOS's: it is
69
+ // read from the prototype's own data-copy text, so it can never disagree with what the screen says.
70
+ const PARTS = Object.freeze([
71
+ Object.freeze({ kind: 'flow', title: 'The flow', name: 'flow.json' }),
72
+ Object.freeze({ kind: 'lanes', title: 'Who does what', name: 'lanes.json' }),
73
+ Object.freeze({ kind: 'tweaks', title: 'Tweaks', name: 'tweaks.json', optional: true }),
74
+ ]);
55
75
  const SCAFFOLD_MAX = 12000;
56
76
  const FROM = Object.freeze({ chat: 'Your ask in the initiative chat', cli: 'pmos lab round', meeting: 'Said in the meeting' });
57
77
 
@@ -64,14 +84,42 @@ const ms = (iso) => Date.parse(iso || '') || 0;
64
84
  /* ── what a sentence asks for ── */
65
85
  const NEW_RE = /\b(show (me )?(\d|two|three|a few|some|(a )?couple of) (ways|options|versions|takes|directions|variants)|(show|let me see|can i see) (it|this|what (it|this) (could|would) look like)|prototype (this|it|that)|mock (this|it|that) up|mock ?up|sketch (this|it|that)( out)?|live round)\b/i;
66
86
  const FEEDBACK_RE = /^\s*(?:(?:take|keep|go with|try|use|make)\s+)?([A-C])(?:\s*[,:;.\-–—]\s*|\s+(?=but\b|with\b|and\b|without\b|more\b|less\b|fewer\b|only\b|lead\b|move\b|drop\b|add\b))(.{3,})$/i;
67
- /** PURE. → { kind: 'new', brief } | { kind: 'feedback', base, brief } | null. A feedback sentence counts only while a round waits on the
68
- * initiative (waiting: its keys), and it names one of them. */
87
+ // Wawan 2026-11-17 20:25: "iterative, like Claude Code design work": one prototype unless the PM asks for several, and any change sentence
88
+ // while one is open changes it. A change sentence starts with a change word; a question or a plain remark does not.
89
+ const CHANGE_RE = /^\s*(?:please\s+|can you\s+|could you\s+|now\s+)?(change|make|add|drop|remove|move|put|use|try|lead|swap|replace|turn|show|hide|fewer|more|less|bigger|smaller|larger|instead|but|also|without|with|give|start|end|rename|call|colou?r|shorten|simplify|keep|take out|bring|flip|split|merge|stack|sort|group|open|close|round|tighten|loosen|lighten|darken|center|centre|align)\b/i;
90
+ const COUNT_RE = /\b(\d|two|three|a few|some|(?:a )?couple of)\s+(ways|options|versions|takes|directions|variants)\b/i;
91
+ const WORDS = { two: 2, three: 3, 'a few': 3, some: 3, 'couple of': 2, 'a couple of': 2 };
92
+ /** PURE. The marks the canvas puts before the PM's words (pm/cozy-proto.js through pm/home-chat.js): "[On: Screen list · screen-list]" for
93
+ * the element the PM pointed at, "[From version 2]" after Continue from version 2. → { text, point: { el, label } | null, from: n | null } */
94
+ const POINT_RE = /^\s*\[On: ([^\]·]{1,80}?)(?: · ([A-Za-z0-9_-]{1,60}))?\]\s*/;
95
+ const FROMV_RE = /^\s*\[From version (\d{1,3})\]\s*/;
96
+ function marksOf(text) {
97
+ let t = String(text == null ? '' : text), point = null, from = null, m;
98
+ for (let i = 0; i < 2; i += 1) {
99
+ if ((m = POINT_RE.exec(t))) { point = { label: one(m[1], 80), el: m[2] || '' }; t = t.slice(m[0].length); }
100
+ else if ((m = FROMV_RE.exec(t))) { from = Number(m[1]) || null; t = t.slice(m[0].length); }
101
+ }
102
+ return { text: t, point, from };
103
+ }
104
+ /** PURE. → { kind: 'new', brief, count } | { kind: 'feedback', base, brief, point?, from? } | null. count is 1 unless the sentence asks for
105
+ * several ("show 3 ways": 2 or 3). A feedback sentence counts only while a round waits on the initiative (waiting: its keys): "B, but …"
106
+ * names a version; a change sentence ("make the alert orange") means the one version open, when exactly one is. With an element pointed at
107
+ * (the canvas's Point), any sentence that is not a question is a change of that element. */
69
108
  function intentOf(text, { waiting = null } = {}) {
70
- const t = one(text, 600);
109
+ const mk = marksOf(text);
110
+ const t = one(mk.text, 600);
71
111
  if (!t || t.startsWith('/')) return null;
112
+ const keys = waiting ? (waiting.keys || []) : [];
113
+ const extra = { ...(mk.point ? { point: mk.point } : {}), ...(mk.from ? { from: mk.from } : {}) };
72
114
  const f = FEEDBACK_RE.exec(t);
73
- if (f && waiting && (waiting.keys || []).includes(f[1].toUpperCase())) return { kind: 'feedback', base: f[1].toUpperCase(), brief: t };
74
- if (NEW_RE.test(t)) return { kind: 'new', brief: t };
115
+ if (f && keys.includes(f[1].toUpperCase())) return { kind: 'feedback', base: f[1].toUpperCase(), brief: t, ...extra };
116
+ if (NEW_RE.test(t)) {
117
+ const m = COUNT_RE.exec(t);
118
+ let count = 1;
119
+ if (m) { const w = m[1].toLowerCase(); count = /^\d$/.test(w) ? Number(w) : WORDS[w] || 3; }
120
+ return { kind: 'new', brief: t, count: Math.min(3, Math.max(1, count)) };
121
+ }
122
+ if (keys.length === 1 && (CHANGE_RE.test(t) || ((mk.point || mk.from) && !/\?\s*$/.test(t)))) return { kind: 'feedback', base: keys[0], brief: t, ...extra };
75
123
  return null;
76
124
  }
77
125
  /** PURE. "A: plain list|B: risk first|C: timeline" (or one per line) → [{ key, title }] with 2 or 3 different keys A–C, else null. */
@@ -119,8 +167,9 @@ function waiting(P, ini) {
119
167
  const keys = ((root && root.data && root.data.specimens) || []).map((s) => s.key);
120
168
  return { id: p.id, group: p.group, round: p.group === 'improved' ? Number(d.round) || 2 : 1, keys };
121
169
  }
122
- /** PURE. A feedback round on `key`: the newest first round on the initiative, the newest proven file of that key, and the next round's number. */
123
- function baseOf(P, ini, key) {
170
+ /** PURE. A feedback round on `key`: the newest first round on the initiative, the newest proven file of that key (or of version `from`,
171
+ * after Continue from version n), and the next round's number. The version's companions live next to its file (PARTS). */
172
+ function baseOf(P, ini, key, { from = null } = {}) {
124
173
  if (!P || !KEYS.includes(key)) return null;
125
174
  const all = [...P.props.values()].filter((p) => p.ini === ini);
126
175
  const roots = all.filter((p) => p.group === 'prototyped').sort((a, b) => ms(b.at) - ms(a.at));
@@ -128,9 +177,10 @@ function baseOf(P, ini, key) {
128
177
  if (!root) return null;
129
178
  const rounds = all.filter((p) => p.group === 'improved' && p.data && p.data.of === root.id).sort((a, b) => (a.data.round || 0) - (b.data.round || 0));
130
179
  const spec = root.data.specimens.find((s) => s.key === key);
131
- const last = rounds.filter((r) => r.data.base === key && r.data.file).pop();
180
+ const mine = rounds.filter((r) => r.data.base === key && r.data.file);
181
+ const pick = from === 1 ? null : from ? mine.find((r) => Number(r.data.round) === Number(from)) : mine[mine.length - 1];
132
182
  const n = rounds.length ? Math.max(...rounds.map((r) => Number(r.data.round) || 1)) + 1 : 2;
133
- return { of: root.id, round: n, file: last ? last.data.file : spec.file, title: spec.title };
183
+ return { of: root.id, round: n, file: pick ? pick.data.file : spec.file, title: spec.title, from: pick ? Number(pick.data.round) : 1 };
134
184
  }
135
185
 
136
186
  /* ── the scaffold and the prompt ── */
@@ -157,44 +207,184 @@ function scaffoldOf(roots) {
157
207
  }
158
208
  return { css: '', from: [] };
159
209
  }
160
- /** PURE. One run's prompt. o: { brief, key, title, file, info: { title, description, intent }, scaffold: { css }, base?: { file, title, abs } } */
210
+ /** PURE. One run's prompt. o: { brief, key, title, file, dir (the run's folder), info: { title, description, intent }, scaffold: { css },
211
+ * base?: { file, title, abs }, alone?, refs?, point?: { el, label }, edits?: { copy, vars } } */
161
212
  function promptOf(o) {
162
- const info = o.info || {}, L = [];
163
- L.push('You make ONE lookable prototype specimen for a product manager, live: they are waiting for it now. Be quick: no planning, no questions, no summary.');
213
+ const info = o.info || {}, L = [], dir = o.dir || path.dirname(o.file || '');
214
+ L.push('You make ONE lookable, clickable prototype for a product manager, live: they are waiting for it now. Be quick: no planning, no questions, no summary.');
164
215
  L.push('', `The idea: ${one(o.brief, 600)}`);
165
216
  if (info.title) L.push(`The initiative: ${one(info.title, 160)}${info.description ? ' · ' + one(info.description, 400) : ''}`);
166
217
  if (info.intent) L.push(`What the product wants (its Intent): ${one(info.intent, 400)}`);
218
+ // an image, a sketch or a file the PM attached (Wawan 2026-11-17: "when user upload the image, it takes it as reference and builds
219
+ // according to it, or as user prompted")
220
+ for (const r of o.refs || []) L.push(`The PM attached a reference (an image, a sketch or a file): ${r}. Read it first with the Read tool. Build from it (its layout, hierarchy and colours) unless the PM's words above say otherwise ("only the colours", "ignore the layout"). In your pmos-changed line, say what you took from it.`);
167
221
  if (o.base) {
168
- L.push('', `This is a new round of specimen ${o.key} (${one(o.base.title, 140)}). Read the last version first: ${o.base.abs}`,
169
- `Change what the PM asked for in the idea above, usually one thing, and keep the rest as it was.`);
170
- } else L.push('', `Your direction, ${o.key}: ${one(o.title, 200)}. Other runs take the other directions: keep yours clearly different.`);
171
- L.push('', `Write the specimen with the Write tool as ONE file, exactly: ${o.file}`,
172
- 'Rules for the file:',
173
- '- One self-contained HTML page: inline CSS only, no script, no network, no image files. Real draft copy, never lorem ipsum or a placeholder.',
174
- '- Pin it to the viewport: the main card is max-width 390px and width 100%, nothing wider than the screen (img, table and pre included: max-width 100%), no horizontal scroll at 390px. At desk width it sits centred.',
175
- '- Use ONLY the colours, type and spacing of the stylesheet below: paste it in a <style> tag, then add only the layout you need.',
176
- '- Put a short name of this version in <title>.',
177
- 'Write nothing else and do not read anything else' + (o.base ? ' but the last version.' : '.'));
222
+ L.push('', `This is a new version of prototype ${o.key} (${one(o.base.title, 140)}). Read the last version first: ${o.base.abs}`,
223
+ `and its companions next to it (flow.json, lanes.json, tweaks.json in ${path.dirname(o.base.abs)}). Change what the PM asked for in the idea above, usually one thing, and keep the rest as it was, ids and copy keys included.`);
224
+ } else if (o.alone) L.push('', 'This is the one version the PM sees: make the plainest honest version of the idea, not a showcase.');
225
+ else L.push('', `Your direction, ${o.key}: ${one(o.title, 200)}. Other runs take the other directions: keep yours clearly different.`);
226
+ if (o.point && (o.point.el || o.point.label)) L.push('', `The PM pointed at one element: ${o.point.el ? 'data-el="' + one(o.point.el, 60) + '"' : ''}${o.point.label ? ' ("' + one(o.point.label, 80) + '")' : ''}. Their words are about that element: change it, and only what must follow from it.`);
227
+ const ed = o.edits || {}, ec = Object.entries(ed.copy || {}), ev = Object.entries(ed.vars || {});
228
+ if (ec.length || ev.length) {
229
+ L.push('', 'The PM edited the last version in place. Keep these exactly, unless their words change them:');
230
+ for (const [k, v] of ec.slice(0, 40)) L.push(`- the text of data-copy="${k}": ${one(v, 200)}`);
231
+ for (const [k, v] of ev.slice(0, 20)) L.push(`- the CSS variable ${k}: ${one(v, 40)} (set it in :root)`);
232
+ }
233
+ // the design sprint's good practice, silent (Wawan 2026-11-17: "the design sprint runs in silent"): a target user, one question, real
234
+ // content, Goldilocks fidelity. Never a step the PM has to fill in.
235
+ L.push('', 'Good practice, in the background: work out from the initiative who this is for and the one question the prototype must answer, and build for that. Real content from the initiative, never placeholders. Just real enough to react to, not polished. 2 to 6 screens.');
236
+ L.push('', `Write these files with the Write tool, in this order, in ${dir}:`,
237
+ `1. ${o.file}: the prototype. Write it FIRST: the PM sees it as soon as it lands.`,
238
+ ' - One self-contained HTML page: inline CSS only, no script, no network, no image files. Real draft copy, never lorem ipsum or a placeholder.',
239
+ ` - In <head>, one line for the PM: <meta name="pmos-changed" content="…"> with ONE short sentence of what ${o.base ? 'you changed' : 'you made and for whom'}, in plain words, under 140 characters.`,
240
+ ' - Each screen is a <section data-screen="<id>" data-label="<screen name>">; the first one is where the user starts. PMOS shows one screen at a time.',
241
+ ' - What the user taps to move on carries data-go="<screen id>" (a button, a row, a link with href="#<screen id>").',
242
+ ' - Every element the PM may point at (a card, a list, a button, a heading, the alert) carries data-el="<short-id>" and data-label="<its name in plain words>".',
243
+ ' - Every piece of visible text the PM may edit is in an element with data-copy="<key>" (unique keys, kebab-case, the text only inside it).',
244
+ ' - Spacing, corner radius and colour warmth read CSS custom properties set in :root (for example --gap, --radius, --accent), so a slider can change them.',
245
+ ' - Pin it to the viewport: the main card is max-width 390px and width 100%, nothing wider than the screen, no horizontal scroll at 390px. At desk width it sits centred.',
246
+ ' - Use ONLY the colours, type and spacing of the stylesheet below: paste it in a <style> tag, then add only the layout you need. Put a short name of this version in <title>.',
247
+ `2. ${path.join(dir, 'flow.json')}: the user's flow, drawn like a flow builder. JSON: { "screens": [{ "id", "title" }], "decisions": [{ "id", "title" }], "edges": [{ "from", "to", "label"? }], "scenarios": [{ "id", "name", "description", "steps": [{ "screen", "tap"?, "say"? }] }] }.`,
248
+ ' - Screen ids are the data-screen ids. A decision is a question the user or the product answers ("Raining?"); its edges carry the answers as labels ("Yes", "No").',
249
+ ' - Scenarios: the main path first, then one per branch (2 to 4 in all). Each step names its screen and the data-el the user taps there to move on ("tap"); the last step has no tap.',
250
+ `3. ${path.join(dir, 'lanes.json')}: who does what. JSON: { "lanes": [{ "id", "name", "steps": [{ "n", "title", "screen"? }] }] }. One lane per actor (the user, the product, and the people or systems the initiative names). n numbers the steps across all lanes in the order they happen (1, 2, 3 …); "screen" is the data-screen the step shows, when it shows one.`,
251
+ `4. ${path.join(dir, 'tweaks.json')} (optional): { "tweaks": [{ "var": "--gap", "label": "Spacing", "min": 4, "max": 32, "step": 1, "unit": "px", "value": 16, "el"? }] }, at most 6, for the custom properties the prototype reads. "el" is the data-el a tweak belongs to; without it, it is for the whole screen.`,
252
+ 'Write nothing else and do not read anything else' + (o.base || (o.refs || []).length ? ' but what is named above.' : '.'));
178
253
  if (o.scaffold && o.scaffold.css) L.push('', 'The stylesheet:', '```css', o.scaffold.css, '```');
179
254
  return L.join('\n');
180
255
  }
181
256
 
257
+ /* ── the companions as data (PARTS): each check is PURE and keeps only what is well formed ── */
258
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,59}$/;
259
+ const arr = (v, n) => (Array.isArray(v) ? v.slice(0, n) : []);
260
+ /** PURE. flow.json → { screens, decisions, edges, scenarios } | { error }. Ids are unique; an edge joins two known nodes; a scenario's
261
+ * steps name known screens. A screen the prototype does not have is still drawn (the Viewer says it cannot show it). */
262
+ function flowOf(j) {
263
+ if (!isObj(j)) return { error: 'flow.json is not a JSON object' };
264
+ const seen = new Set(), node = (x) => (isObj(x) && ID.test(str(x.id)) && !seen.has(x.id) ? (seen.add(x.id), { id: x.id, title: one(x.title || x.id, 80) }) : null);
265
+ const screens = arr(j.screens, 24).map(node).filter(Boolean);
266
+ const decisions = arr(j.decisions, 12).map(node).filter(Boolean);
267
+ if (!screens.length) return { error: 'flow.json has no screens' };
268
+ const sid = new Set(screens.map((x) => x.id));
269
+ const edges = arr(j.edges, 60).filter((e) => isObj(e) && seen.has(e.from) && seen.has(e.to) && e.from !== e.to).map((e) => ({ from: e.from, to: e.to, ...(str(e.label) ? { label: one(e.label, 24) } : {}) }));
270
+ const sids = new Set();
271
+ const scenarios = arr(j.scenarios, 6).map((c) => {
272
+ if (!isObj(c) || !ID.test(str(c.id)) || sids.has(c.id)) return null;
273
+ const steps = arr(c.steps, 20).filter((t) => isObj(t) && sid.has(t.screen)).map((t) => ({ screen: t.screen, ...(ID.test(str(t.tap)) ? { tap: t.tap } : {}), ...(str(t.say) ? { say: one(t.say, 140) } : {}) }));
274
+ if (!steps.length) return null;
275
+ sids.add(c.id);
276
+ return { id: c.id, name: one(c.name || c.id, 60), description: one(c.description, 200), steps };
277
+ }).filter(Boolean);
278
+ return { screens, decisions, edges, scenarios };
279
+ }
280
+ /** PURE. lanes.json → { lanes: [{ id, name, steps: [{ n, title, screen? }] }] } | { error }. Each n is used once across the lanes. */
281
+ function lanesOf(j, { screens = null } = {}) {
282
+ if (!isObj(j)) return { error: 'lanes.json is not a JSON object' };
283
+ const ids = new Set(), ns = new Set();
284
+ const lanes = arr(j.lanes, 8).map((l) => {
285
+ if (!isObj(l) || !ID.test(str(l.id)) || ids.has(l.id)) return null;
286
+ ids.add(l.id);
287
+ const steps = [];
288
+ for (const t of arr(l.steps, 30)) {
289
+ if (!isObj(t) || !Number.isInteger(t.n) || t.n < 1 || t.n > 99 || ns.has(t.n) || !str(t.title)) continue;
290
+ ns.add(t.n);
291
+ steps.push({ n: t.n, title: one(t.title, 80), ...(ID.test(str(t.screen)) && (!screens || screens.has(t.screen)) ? { screen: t.screen } : {}) });
292
+ }
293
+ steps.sort((a, b) => a.n - b.n);
294
+ return { id: l.id, name: one(l.name || l.id, 40), steps };
295
+ }).filter(Boolean);
296
+ if (!lanes.length || !ns.size) return { error: 'lanes.json has no lanes with steps' };
297
+ return { lanes };
298
+ }
299
+ /** PURE. tweaks.json → { tweaks: [{ var, label, min, max, step, unit, value, el? }] } | { error }. */
300
+ function tweaksOf(j) {
301
+ if (!isObj(j)) return { error: 'tweaks.json is not a JSON object' };
302
+ const seen = new Set();
303
+ const tweaks = arr(j.tweaks, 6).map((t) => {
304
+ if (!isObj(t) || !/^--[a-z][a-z0-9-]{0,40}$/i.test(str(t.var)) || seen.has(t.var)) return null;
305
+ const min = Number(t.min), max = Number(t.max);
306
+ if (!Number.isFinite(min) || !Number.isFinite(max) || !(min < max)) return null;
307
+ seen.add(t.var);
308
+ const value = Number.isFinite(Number(t.value)) ? Math.min(max, Math.max(min, Number(t.value))) : min;
309
+ return { var: t.var, label: one(t.label || t.var.slice(2), 30), min, max, step: Number(t.step) > 0 ? Number(t.step) : (max - min) / 20, unit: /^(px|rem|em|%|deg|)$/.test(str(t.unit)) ? str(t.unit) : '', value, ...(ID.test(str(t.el)) ? { el: t.el } : {}) };
310
+ }).filter(Boolean);
311
+ return { tweaks };
312
+ }
313
+ const decode = (s) => String(s).replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, '&');
314
+ /** PURE. The prototype's own words: every element with data-copy="key" → { key: text } (its first text, tags taken out), in page order. */
315
+ function copyOf(html) {
316
+ const out = {}, re = /<([a-z][a-z0-9]*)\b[^>]*\sdata-copy=["']([A-Za-z0-9][A-Za-z0-9_.-]{0,59})["'][^>]*>([\s\S]*?)<\/\1\s*>/gi;
317
+ let m, n = 0;
318
+ while ((m = re.exec(String(html || ''))) && n < 80) {
319
+ if (m[2] in out) continue;
320
+ const text = one(decode(m[3].replace(/<[^>]*>/g, ' ')), 300);
321
+ if (text) { out[m[2]] = text; n += 1; }
322
+ }
323
+ return out;
324
+ }
325
+ /** PURE. What one version changed against the last: { flow, lanes, copy, steps: [n], keys: [copy key] } and the line the chat says,
326
+ * "step 3, the swimlane and the copy" ('' when nothing beside the prototype changed). prev / cur: { flow?, lanes?, copy? }. */
327
+ function changesOf(prev, cur) {
328
+ const p = prev || {}, c = cur || {}, J = (v) => JSON.stringify(v || null);
329
+ const stepsOf = (L) => { const m = new Map(); for (const l of (L && L.lanes) || []) for (const t of l.steps) m.set(t.n, l.id + '|' + t.title); return m; };
330
+ const a = stepsOf(p.lanes), b = stepsOf(c.lanes), steps = [];
331
+ for (const [n, v] of b) if (a.get(n) !== v) steps.push(n);
332
+ const pc = p.copy || {}, cc = c.copy || {}, keys = Object.keys(cc).filter((k) => pc[k] !== cc[k]);
333
+ const out = { flow: !!c.flow && J(p.flow) !== J(c.flow), lanes: !!c.lanes && J(p.lanes) !== J(c.lanes), copy: !!c.copy && (keys.length > 0 || Object.keys(pc).some((k) => !(k in cc))), steps: steps.sort((x, y) => x - y), keys };
334
+ if (!prev) return { ...out, line: '' };
335
+ const parts = [];
336
+ if (out.steps.length && out.steps.length <= 3) parts.push((out.steps.length === 1 ? 'step ' : 'steps ') + andOf(out.steps.map(String)));
337
+ if (out.flow) parts.push('the flow');
338
+ if (out.lanes) parts.push('the swimlane');
339
+ if (out.copy) parts.push('the copy');
340
+ return { ...out, line: andOf(parts) };
341
+ }
342
+ const andOf = (xs) => (xs.length <= 1 ? xs.join('') : xs.slice(0, -1).join(', ') + ' and ' + xs[xs.length - 1]);
343
+ /** The data next to a version's file: { flow?, lanes?, copy?, tweaks?, edits? }, each one only when it is there and well formed. */
344
+ function partsAt(abs) {
345
+ const dir = path.dirname(abs), out = {};
346
+ const rd = (n) => { try { return JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8')); } catch { return null; } };
347
+ const f = flowOf(rd('flow.json')); if (!f.error) out.flow = f;
348
+ const l = lanesOf(rd('lanes.json'), { screens: out.flow ? new Set(out.flow.screens.map((x) => x.id)) : null }); if (!l.error) out.lanes = l;
349
+ const t = tweaksOf(rd('tweaks.json')); if (!t.error && t.tweaks.length) out.tweaks = t;
350
+ const c = rd('copy.json'); if (isObj(c)) out.copy = c;
351
+ const e = editsOf(rd('edits.json')); if (Object.keys(e.copy).length || Object.keys(e.vars).length) out.edits = e;
352
+ return out;
353
+ }
354
+ /** PURE. edits.json (the PM's in-place copy edits and tweaks, POST /api/lab/edit) → { copy: { key: text }, vars: { --var: value } }. */
355
+ function editsOf(j) {
356
+ const copy = {}, vars = {};
357
+ if (isObj(j) && isObj(j.copy)) for (const [k, v] of Object.entries(j.copy).slice(0, 80)) if (/^[A-Za-z0-9][A-Za-z0-9_.-]{0,59}$/.test(k) && typeof v === 'string') copy[k] = one(v, 300);
358
+ if (isObj(j) && isObj(j.vars)) for (const [k, v] of Object.entries(j.vars).slice(0, 12)) if (/^--[a-z][a-z0-9-]{0,40}$/i.test(k) && /^-?\d{1,4}(\.\d{1,3})?(px|rem|em|%|deg)?$/.test(String(v))) vars[k] = String(v);
359
+ return { copy, vars };
360
+ }
361
+
362
+ /** The one sentence a version says about itself: <meta name="pmos-changed" content="…"> in its head, or ''. */
363
+ function saidOf(abs) {
364
+ let head = ''; try { head = fs.readFileSync(abs, 'utf8').slice(0, 20000); } catch { return ''; }
365
+ const m = /<meta\s+name=["']pmos-changed["']\s+content=["']([^"']{1,300})["']/i.exec(head) || /<meta\s+content=["']([^"']{1,300})["']\s+name=["']pmos-changed["']/i.exec(head);
366
+ return m ? one(m[1].replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, '&'), 160) : '';
367
+ }
368
+
182
369
  /* ── the proposal line of a round ── */
370
+ const fin = (x) => x.state === 'ok' || x.state === 'not made' || x.state === 'none';
371
+ const partsLine = (s) => Object.fromEntries((s.parts || []).map((x) => [x.kind, x.state === 'not made' ? 'not made: ' + one(x.why, 120) : x.state]));
183
372
  function roundLine(R, now) {
184
- const slots = R.slots.map((s) => ({ key: s.key, title: s.title, state: s.state, ...(s.file && s.state === 'ok' ? { file: s.file } : {}), ...(s.why ? { why: one(s.why, 200) } : {}), ...(s.dims ? { dims: s.dims } : {}) }));
373
+ const slots = R.slots.map((s) => ({ key: s.key, title: s.title, state: s.state, ...(s.file && s.state === 'ok' ? { file: s.file } : {}), ...(s.why ? { why: one(s.why, 200) } : {}), ...(s.dims ? { dims: s.dims } : {}), ...(s.said ? { said: s.said } : {}), ...((s.parts || []).length ? { parts: partsLine(s) } : {}) }));
185
374
  const ok = R.slots.filter((s) => s.state === 'ok');
186
- const done = R.slots.every((s) => s.state === 'ok' || s.state === 'not made');
375
+ const done = R.slots.every((s) => fin(s) && (s.parts || []).every(fin));
187
376
  const checked = ok.length ? (ok.length === 1 ? 'It opened and rendered' : `All ${ok.length} opened and rendered`) + ' in a headless browser (' + ok.map((s) => s.dims).join(', ') + ')' : '';
188
- const live = { id: R.id, brief: R.brief, from: R.from, step: R.step, done, slots, startedAt: new Date(R.start).toISOString() };
377
+ const live = { id: R.id, brief: R.brief, from: R.from, step: R.step, done, slots, ...(R.point ? { point: R.point } : {}), ...(R.refs.length ? { refs: R.refs.length } : {}), startedAt: new Date(R.start).toISOString() };
189
378
  const base = { kind: 'propose', at: new Date(now).toISOString(), by: null, ini: R.ini, board: R.board, run: R.id, id: R.propId, section: 'check',
190
379
  why: one(`You asked: "${R.brief}"`, 300), sources: [{ label: FROM[R.from] || FROM.chat }], items: [] };
191
380
  if (!R.base) {
192
- return { ...base, group: 'prototyped', type: 'new', title: one(`Round 1 · ${R.slots.length} ways: ${R.brief}`, 140),
193
- data: { round: 1, specimens: ok.map((s) => ({ key: s.key, title: s.title, caption: '', file: s.file })), checked, live } };
381
+ return { ...base, group: 'prototyped', type: 'new', title: one(`Round 1 · ${R.slots.length === 1 ? 'one version' : R.slots.length + ' ways'}: ${R.brief}`, 140),
382
+ data: { round: 1, specimens: ok.map((s) => ({ key: s.key, title: s.title, caption: s.said || '', file: s.file })), checked, live } };
194
383
  }
195
- const s = R.slots[0];
196
- return { ...base, group: 'improved', type: 'round', title: one(`Round ${R.n} of ${R.base}: ${R.brief}`, 140),
197
- data: { round: R.n, of: R.of, base: R.base, changed: one(R.brief, 200), file: s.state === 'ok' ? s.file : '', checked, live } };
384
+ const s = R.slots[0], ch = s.changes || null;
385
+ return { ...base, group: 'improved', type: 'round', title: one(`Version ${R.n} of ${R.base}: ${R.brief}`, 140),
386
+ data: { round: R.n, of: R.of, base: R.base, from: R.fromV || R.n - 1, changed: one(R.brief, 200), file: s.state === 'ok' ? s.file : '', ...(s.said ? { said: s.said } : {}),
387
+ ...(ch ? { updated: { flow: ch.flow, lanes: ch.lanes, copy: ch.copy, steps: ch.steps, keys: ch.keys.slice(0, 20) }, also: ch.line } : {}), checked, live } };
198
388
  }
199
389
 
200
390
  /* ── the engine ── */
@@ -208,7 +398,7 @@ function create(deps) {
208
398
  const warn = deps.warn || (() => {});
209
399
  const now = () => (deps.now ? deps.now() : Date.now());
210
400
  const render = deps.render || ((abs) => E.renderCheck(abs, { phone: true })); // proven at 390 px too: the viewport pin
211
- const pollMs = deps.pollMs || 1000;
401
+ const pollMs = deps.pollMs || 1000;
212
402
  const budgetMs = deps.budgetMs || BUDGET_MS;
213
403
  const rounds = new Map(); // id → round
214
404
 
@@ -246,13 +436,14 @@ function create(deps) {
246
436
  return { ws, ini, pr, dir: pr.dir, info: info || { title: ini }, board };
247
437
  }
248
438
 
249
- /** Start a round now. input: { ws, board?, ini, brief, base?, directions?|dirs?, from?: chat|cli|meeting, step?: 1|2, by? }
250
- * → { ok, round: { id, n, keys, directions }, runs } | { ok: false, error } */
439
+ /** Start a round now. input: { ws, board?, ini, brief, base?, from?: chat|cli|meeting, fromV? (Continue from version n), point?: { el,
440
+ * label }, directions?|dirs?, count?, refs?, step?: 1|2, by? } → { ok, round: { id, n, keys, directions, proposal }, runs } | { ok: false, error } */
251
441
  function start(input = {}) {
252
442
  const rt = deps.runtimeDir ? deps.runtimeDir() : null;
253
443
  if (!rt) return { ok: false, error: 'no runtime state folder' };
254
444
  const c = context(input); if (c.error) return { ok: false, error: c.error };
255
- const brief = one(input.brief, 600); if (!brief) return { ok: false, error: 'brief is the PM\'s sentence: what to show' };
445
+ const mk = marksOf(input.brief);
446
+ const brief = one(mk.text, 600); if (!brief) return { ok: false, error: 'brief is the PM\'s sentence: what to show' };
256
447
  // the off switch (`pmos ai off live-round`, or every AI job off) holds it, as it holds every other job
257
448
  let off = null; try { off = require('./ai-guard.js').off(JOB, { env: deps.env || process.env, settingsDir: rt }); } catch { off = null; }
258
449
  if (off) return { ok: false, error: 'live rounds are off: ' + off };
@@ -260,31 +451,36 @@ function create(deps) {
260
451
  const t = now(), id = 'lr' + t.toString(36) + crypto.randomBytes(3).toString('hex');
261
452
  const from = FROM[input.from] ? input.from : 'chat', step = Number(input.step) === 2 ? 2 : 1;
262
453
  const P = PR.read(c.dir);
454
+ const fromV = Number(input.fromV) || mk.from || null;
455
+ const point = isObj(input.point) ? { el: ID.test(str(input.point.el)) ? input.point.el : '', label: one(input.point.label, 80) } : mk.point;
263
456
  let base = '', b = null, dirs;
264
457
  if (input.base) {
265
458
  base = String(input.base).toUpperCase();
266
- b = baseOf(P, c.ini, base);
267
- if (!b) return { ok: false, error: `there is no proven specimen ${base} on this initiative yet: ask for a first round` };
459
+ b = baseOf(P, c.ini, base, { from: fromV });
460
+ if (!b) return { ok: false, error: `there is no proven version ${base} on this initiative yet: ask for a first one` };
268
461
  dirs = [{ key: base, title: b.title }];
269
462
  } else {
270
- dirs = Array.isArray(input.directions) && input.directions.length ? input.directions : input.dirs ? parseDirs(input.dirs) : DEFAULT_DIRECTIONS;
463
+ dirs = Array.isArray(input.directions) && input.directions.length ? input.directions : input.dirs ? parseDirs(input.dirs) : Number(input.count) === 1 ? ONE_DIRECTION : DEFAULT_DIRECTIONS;
271
464
  if (!dirs) return { ok: false, error: 'dirs is 2 or 3 directions, "A: …|B: …|C: …"' };
272
465
  }
273
466
  const scaffold = scaffoldOf([c.pr.w && c.pr.w.root, deps.ownRoot || path.resolve(__dirname, '..')]);
274
- const R = { id, ws: c.ws, ini: c.ini, board: c.board, dir: c.dir, rt, brief, from, step, start: t, base, of: b ? b.of : '', n: b ? b.round : 1,
467
+ // refs: files the PM attached (absolute paths under the chat's own folder, lib/chat-files.js), a sketch from the canvas's Draw too
468
+ const refs = (Array.isArray(input.refs) ? input.refs : []).filter((r) => typeof r === 'string' && path.isAbsolute(r) && !/[\n\r\t\v\f,*?()[\]{}]/.test(r)).slice(0, 4);
469
+ const R = { id, ws: c.ws, ini: c.ini, board: c.board, dir: c.dir, rt, brief, from, step, start: t, base, of: b ? b.of : '', n: b ? b.round : 1, fromV: b ? b.from : null, baseFile: b ? b.file : '', refs,
470
+ point: point && (point.el || point.label) ? point : null,
275
471
  propId: base ? PR.idOf(c.ini, 'improved', 'round', b.of + ':' + b.round) : PR.idOf(c.ini, 'prototyped', 'live', id),
276
- slots: dirs.map((d) => ({ key: d.key, title: one(d.title, 140), state: 'working', run: '', session: null, file: '', size: -1, why: '', dims: '' })),
472
+ slots: dirs.map((d) => ({ key: d.key, title: one(d.title, 140), state: 'working', run: '', session: null, file: '', size: -1, why: '', dims: '', parts: [] })),
277
473
  timer: null, budget: null, ended: false };
278
474
  rounds.set(id, R);
279
475
  write(R);
280
- if (base) lesson(c.dir, c.ini, `Round ${R.n} of ${base}: ${brief}`, input.by || 'agent:live-round');
476
+ if (base) lesson(c.dir, c.ini, `Version ${R.n} of ${base}${R.point ? ' (' + (R.point.label || R.point.el) + ')' : ''}: ${brief}`, input.by || 'agent:live-round');
281
477
  for (const s of R.slots) launch(R, s, { info: c.info, scaffold, b });
282
478
  R.timer = setInterval(() => { poll(R).catch((e) => warn('live round poll', e)); }, pollMs);
283
479
  if (R.timer.unref) R.timer.unref();
284
480
  R.budget = setTimeout(() => over(R), budgetMs);
285
481
  if (R.budget.unref) R.budget.unref();
286
482
  settle(R);
287
- return { ok: true, round: { id, n: R.n, keys: R.slots.map((s) => s.key), directions: R.slots.map((s) => ({ key: s.key, title: s.title })), proposal: R.propId }, runs: R.slots.map((s) => s.run) };
483
+ return { ok: true, round: { id, n: R.n, keys: R.slots.map((s) => s.key), directions: R.slots.map((s) => ({ key: s.key, title: s.title })), proposal: R.propId, parts: PARTS.map((x) => x.kind) }, runs: R.slots.map((s) => s.run) };
288
484
  }
289
485
 
290
486
  function launch(R, s, { info, scaffold, b }) {
@@ -293,14 +489,16 @@ function create(deps) {
293
489
  const folder = path.join(LAB.specimenDir(R.rt), R.id, s.key);
294
490
  s.file = R.id + '/' + s.key + '/' + s.key.toLowerCase() + '.html';
295
491
  s.abs = path.join(folder, s.key.toLowerCase() + '.html');
296
- try { fs.mkdirSync(folder, { recursive: true }); } catch (e) { s.state = 'not made'; s.why = 'its folder could not be made'; warn('live round folder', e); return; }
492
+ s.parts = PARTS.map((x) => ({ kind: x.kind, name: x.name, optional: !!x.optional, file: R.id + '/' + s.key + '/' + x.name, abs: path.join(folder, x.name), state: 'working', size: -1, why: '' }));
493
+ try { fs.mkdirSync(folder, { recursive: true }); } catch (e) { s.parts.forEach((x) => { x.state = 'none'; }); s.state = 'not made'; s.why = 'its folder could not be made'; warn('live round folder', e); return; }
297
494
  const baseAbs = b ? LAB.specimenPath(R.rt, b.file) : null;
298
- const prompt = promptOf({ brief: R.brief, key: s.key, title: s.title, file: s.abs, info, scaffold, base: b ? { title: b.title, abs: baseAbs } : null });
495
+ const edits = baseAbs ? partsAt(baseAbs).edits || null : null;
496
+ const prompt = promptOf({ brief: R.brief, key: s.key, title: s.title, file: s.abs, dir: folder, info, scaffold, base: b ? { title: b.title, abs: baseAbs } : null, alone: R.slots.length === 1, refs: R.refs, point: R.point, edits });
299
497
  E.appendRun(R.rt, { kind: 'start', run: s.run, job: JOB, ws: R.ws, ini: R.ini, key: `live:${R.id}:${s.key}`, budget: 0, step: R.step, from: R.from }, t);
300
498
  let session = null;
301
499
  try {
302
500
  session = deps.spawn({ name: 'Prototyping ' + s.key + ' · ' + one(info.title || R.ini, 50), agent: 'claude', ws: R.ws, origin: `${ORIGIN}:${R.ws}:${R.ini}:${s.run}:${s.key}`,
303
- initialInput: prompt + '\r', initiative: R.ini, writePaths: [folder], addDirs: baseAbs ? [path.dirname(baseAbs)] : [],
501
+ initialInput: prompt + '\r', initiative: R.ini, writePaths: [folder], addDirs: addDirsOf(baseAbs, R.refs),
304
502
  onDone: (res) => { ended(R, s, res).catch((e) => warn('live round end', e)); } });
305
503
  } catch (e) { warn('live round spawn', e); }
306
504
  s.session = session;
@@ -309,16 +507,29 @@ function create(deps) {
309
507
  notMade(R, s, (session && session.note) || 'the run could not start in the background');
310
508
  }
311
509
  }
510
+ const addDirsOf = (baseAbs, refs) => [...new Set([...(baseAbs ? [path.dirname(baseAbs)] : []), ...(refs || []).map((r) => path.dirname(r))])];
312
511
 
313
512
  function write(R) {
314
513
  try { fs.appendFileSync(PR.ledgerFile(R.dir), JSON.stringify(roundLine(R, now())) + '\n'); } catch (e) { warn('live round proposal', e); }
315
514
  }
515
+ /** What the chat's Claude is told once the round settles: only for a round the chat asked for, through deps.tell(ws, ini, text). */
516
+ function tell(R, text) {
517
+ if (R.from !== 'chat' || typeof deps.tell !== 'function') return;
518
+ try { deps.tell(R.ws, R.ini, text); } catch (e) { warn('live round tell', e); }
519
+ }
520
+ /** A version that was not made: its companions go with it (nothing to draw them next to). */
316
521
  function notMade(R, s, why) {
317
522
  if (s.state === 'ok' || s.state === 'not made') return;
318
523
  s.state = 'not made'; s.why = one(why, 200);
524
+ for (const x of s.parts || []) if (x.state === 'working') { x.state = 'none'; }
319
525
  try { E.appendRun(R.rt, { kind: 'end', run: s.run, ok: false, cost: null, ms: Math.max(0, now() - R.start), filed: 0, dropped: [s.why] }, now()); } catch { /* the card says it */ }
320
526
  write(R); settle(R);
321
527
  }
528
+ function partNotMade(R, s, x, why) {
529
+ if (x.state !== 'working') return;
530
+ if (x.optional) { x.state = 'none'; } else { x.state = 'not made'; x.why = one(why, 200); }
531
+ write(R); settle(R);
532
+ }
322
533
  async function prove(R, s, cost = null) {
323
534
  if (s.state !== 'working') return;
324
535
  s.state = 'proving';
@@ -329,41 +540,81 @@ function create(deps) {
329
540
  else { try { v = await render(s.abs); } catch (e) { v = { ok: false, why: 'it did not open: ' + one(e && e.message, 120) }; } }
330
541
  if (s.state !== 'proving') return; // stopped while it rendered (Undo, the budget)
331
542
  if (!v || !v.ok) { s.state = 'working'; return notMade(R, s, 'not proven: ' + ((v && v.why) || 'it did not render')); }
332
- s.state = 'ok'; s.dims = `${v.w}×${v.h}`;
543
+ s.state = 'ok'; s.dims = `${v.w}×${v.h}`; s.said = saidOf(s.abs);
544
+ // copy.json is PMOS's, read from the prototype's own words, so the Page copy card can never disagree with the screen
545
+ try { fs.writeFileSync(path.join(path.dirname(s.abs), 'copy.json'), JSON.stringify(copyOf(fs.readFileSync(s.abs, 'utf8')), null, 1)); } catch (e) { warn('live round copy', e); }
333
546
  try { E.appendRun(R.rt, { kind: 'end', run: s.run, ok: true, cost, ms: Math.max(0, now() - R.start), filed: 1, dropped: [] }, now()); } catch { /* the card says it */ }
334
- if (deps.artefact) try { deps.artefact(R.dir, { scope: 'experiment:' + R.ini, artefact: 'specimens', field: 'specimen', text: one(`${R.base ? 'Round ' + R.n + ' of ' + s.key : 'Round 1 · ' + s.key}: ${s.title} (${LAB.specimenUrl(s.file)})`, 600), sources: [{ label: 'live round', ref: LAB.specimenUrl(s.file) }] }, 'agent:live-round'); } catch (e) { warn('live round specimen', e); }
335
- if (s.session && s.session.state !== 'exited' && deps.stop) try { deps.stop(s.session); } catch { /* it ends by itself */ }
547
+ if (deps.artefact) try { deps.artefact(R.dir, { scope: 'experiment:' + R.ini, artefact: 'specimens', field: 'specimen', text: one(`${R.base ? 'Version ' + R.n + ' of ' + s.key : 'Round 1 · ' + s.key}: ${s.title} (${LAB.specimenUrl(s.file)})`, 600), sources: [{ label: 'live round', ref: LAB.specimenUrl(s.file) }] }, 'agent:live-round'); } catch (e) { warn('live round specimen', e); }
548
+ write(R); settle(R);
549
+ }
550
+ /** A companion lands: it must parse and be well formed (flowOf, lanesOf, tweaksOf), else it is "not made" with the reason. */
551
+ function provePart(R, s, x) {
552
+ if (x.state !== 'working') return;
553
+ let j = null, err = '';
554
+ try { j = JSON.parse(fs.readFileSync(x.abs, 'utf8')); } catch (e) { err = x.name + ' is not JSON'; }
555
+ if (!err) { const v = x.kind === 'flow' ? flowOf(j) : x.kind === 'lanes' ? lanesOf(j) : tweaksOf(j); if (v.error) err = v.error; }
556
+ if (err) return partNotMade(R, s, x, err);
557
+ x.state = 'ok';
336
558
  write(R); settle(R);
337
559
  }
338
560
  async function poll(R) {
339
561
  for (const s of R.slots) {
340
- if (s.state !== 'working') continue;
341
- let size = -1; try { size = fs.statSync(s.abs).size; } catch { size = -1; }
342
- // a file that stopped growing for one poll has landed: prove it now, before the run ends
343
- if (size > 0 && size === s.size) await prove(R, s);
344
- else s.size = size;
562
+ for (const x of s.state === 'not made' ? [] : [s, ...(s.parts || [])]) {
563
+ if (x.state !== 'working') continue;
564
+ let size = -1; try { size = fs.statSync(x.abs).size; } catch { size = -1; }
565
+ // a file that stopped growing for one poll has landed: prove it now, before the run ends
566
+ if (size > 0 && size === x.size) { if (x === s) await prove(R, s); else provePart(R, s, x); }
567
+ else x.size = size;
568
+ }
345
569
  }
346
570
  }
347
571
  async function ended(R, s, res = {}) {
348
- if (s.state !== 'working') return;
349
572
  const out = (res && res.result) || {};
350
573
  const cost = Number.isFinite(out.costUsd) ? Math.round(out.costUsd * 10000) / 10000 : null;
351
- let have = false; try { have = fs.statSync(s.abs).size > 0; } catch { have = false; }
352
- if (have) return prove(R, s, cost);
353
- notMade(R, s, res && res.timedOut ? 'the run timed out' : res && res.stopped ? 'the run was stopped' : (res && res.note) || 'the run ended without writing its file');
574
+ if (s.state === 'working') {
575
+ let have = false; try { have = fs.statSync(s.abs).size > 0; } catch { have = false; }
576
+ if (have) await prove(R, s, cost);
577
+ else notMade(R, s, res && res.timedOut ? 'the run timed out' : res && res.stopped ? 'the run was stopped' : (res && res.note) || 'the run ended without writing its file');
578
+ }
579
+ // the run is over: a companion it wrote is proven now, one it did not write is not made (an optional one is simply not there)
580
+ for (const x of s.parts || []) {
581
+ if (x.state !== 'working') continue;
582
+ let have = false; try { have = fs.statSync(x.abs).size > 0; } catch { have = false; }
583
+ if (have) provePart(R, s, x); else partNotMade(R, s, x, 'the run ended without writing ' + x.name);
584
+ }
354
585
  }
355
586
  function over(R) {
356
587
  for (const s of R.slots) {
357
- if (s.state !== 'working') continue; // a file being proven finishes its proof
358
- if (s.session && s.session.state !== 'exited' && deps.stop) try { deps.stop(s.session); } catch { /* best effort */ }
359
- notMade(R, s, 'past the 2 minute budget');
588
+ const busy = [s, ...(s.parts || [])].some((x) => x.state === 'working');
589
+ if (busy && s.session && s.session.state !== 'exited' && deps.stop) try { deps.stop(s.session); } catch { /* best effort */ }
590
+ if (s.state === 'working') notMade(R, s, 'past the 2 minute budget'); // a file being proven finishes its proof
591
+ for (const x of s.parts || []) partNotMade(R, s, x, 'past the 2 minute budget');
360
592
  }
361
593
  }
362
594
  function settle(R) {
363
- if (R.ended || !R.slots.every((s) => s.state === 'ok' || s.state === 'not made')) return;
595
+ // a version whose prototype and companions all landed is done: its run stops (it may still be summing up)
596
+ for (const s of R.slots) if (fin(s) && (s.parts || []).every(fin) && s.session && s.session.state !== 'exited' && deps.stop && !s.stopped) { s.stopped = true; try { deps.stop(s.session); } catch { /* it ends by itself */ } }
597
+ if (R.ended || !R.slots.every((s) => fin(s) && (s.parts || []).every(fin))) return;
364
598
  R.ended = true;
365
599
  clearInterval(R.timer); clearTimeout(R.budget);
600
+ // what each version changed against the one it was made from: the chat's "Also updated" and the cards' Updated
601
+ if (R.base) {
602
+ const s = R.slots[0], prev = R.baseFile ? LAB.specimenPath(R.rt, R.baseFile) : null;
603
+ if (s.state === 'ok') try { s.changes = changesOf(prev ? partsAt(prev) : {}, partsAt(s.abs)); } catch (e) { warn('live round changes', e); }
604
+ }
366
605
  write(R);
606
+ const ok = R.slots.filter((s) => s.state === 'ok');
607
+ const lost = (s) => [...(s.parts || [])].filter((x) => x.state === 'not made').map((x) => (PARTS.find((p) => p.kind === x.kind) || {}).title || x.kind);
608
+ if (R.slots.length === 1) {
609
+ const s = R.slots[0], v = 'Version ' + R.n;
610
+ if (s.state !== 'ok') tell(R, `[PMOS] ${v} was not made: ${s.why}. Say so to the PM in one line, nothing else.`);
611
+ else {
612
+ const also = s.changes && s.changes.line, miss = lost(s);
613
+ tell(R, `[PMOS] ${v} is in the Viewer${s.said ? ': "' + s.said + '"' : ''}.${also ? ' Also updated: ' + also + '.' : ''}${miss.length ? ' Not made this time: ' + andOf(miss) + '.' : ''} Reply to the PM starting with "${v}: ", then one or two sentences on what ${R.base ? 'changed' : 'it shows and for whom'}${also ? ', then "Also updated: ' + also + '."' : ''}. Nothing else. Do not build anything here.`);
614
+ }
615
+ } else {
616
+ tell(R, `[PMOS] ${ok.length ? andOf(ok.map((s) => s.key)) + (ok.length === 1 ? ' is' : ' are') + ' in the Viewer\'s tray' : 'None of the versions was made'}${ok.length ? ': ' + ok.map((s) => s.key + ' "' + (s.said || s.title) + '"').join('; ') : ''}.${R.slots.filter((s) => s.state !== 'ok').map((s) => ' ' + s.key + ' was not made: ' + s.why + '.').join('')} Reply to the PM starting with "Version 1: ", then one short line per version, and that they tap one in the tray to preview it, then keep it or close it. Nothing else.`);
617
+ }
367
618
  // the round stays readable for status() for a while, then goes
368
619
  const t = setTimeout(() => rounds.delete(R.id), 10 * 60 * 1000); if (t.unref) t.unref();
369
620
  }
@@ -372,7 +623,9 @@ function create(deps) {
372
623
  function cancel(id, why = 'stopped: you pressed Undo') {
373
624
  const R = rounds.get(id);
374
625
  if (R) for (const s of R.slots) {
375
- if (s.state === 'working' || s.state === 'proving') { if (s.session && s.session.state !== 'exited' && deps.stop) try { deps.stop(s.session); } catch { /* best effort */ } s.state = 'working'; notMade(R, s, why); }
626
+ if (s.session && s.session.state !== 'exited' && deps.stop && [s, ...(s.parts || [])].some((x) => x.state === 'working' || x.state === 'proving')) try { deps.stop(s.session); } catch { /* best effort */ }
627
+ if (s.state === 'working' || s.state === 'proving') { s.state = 'working'; notMade(R, s, why); }
628
+ for (const x of s.parts || []) partNotMade(R, s, x, why);
376
629
  }
377
630
  const dir = R ? R.dir : null;
378
631
  return { ok: !!R, dir };
@@ -403,5 +656,6 @@ function dropCard(dir, propId) { return inst ? inst.dropCard(dir, propId) : fals
403
656
  function running(ini) { return inst ? inst.running(ini) : false; }
404
657
  function status() { return inst ? inst.status() : []; }
405
658
 
406
- module.exports = { JOB, ORIGIN, BUDGET_MS, KEYS, DEFAULT_DIRECTIONS, FROM, intentOf, parseDirs, askOf, waiting, baseOf, scaffoldOf, promptOf, roundLine,
659
+ module.exports = { JOB, ORIGIN, BUDGET_MS, KEYS, DEFAULT_DIRECTIONS, ONE_DIRECTION, PARTS, FROM, marksOf, intentOf, parseDirs, askOf, waiting, baseOf, scaffoldOf, promptOf, saidOf, roundLine,
660
+ flowOf, lanesOf, tweaksOf, copyOf, changesOf, partsAt, editsOf,
407
661
  create, install, round, startNow, proposeNow, cancel, dropCard, running, status };