create-pmos 0.591.0 → 0.593.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`:
@@ -31,7 +40,10 @@
31
40
  * askOf({ ini, board, brief, directions, base?, round?, from? }) PURE → the ✦ ask's proposal line (without at/by)
32
41
  * waiting(P, ini) PURE → the open round on the initiative { id, group, round, keys } | null (P: lib/proposals.js fold; keys: the
33
42
  * first round's versions that rendered, the ones a feedback sentence may name)
34
- * baseOf(P, ini, key) PURE → { of, round, file, title } | null what a feedback round on `key` builds on
43
+ * baseOf(P, ini, key, { from?, of? }) PURE → { of, round, file, title } | null what a feedback round on `key` builds on (start: the
44
+ * current version, lib/proposals.js currentOf, unless the PM said Continue from version n)
45
+ * contextOf(cur, { ini, ws, rt }) PURE → the line the initiative chat's agent reads before every message while a prototype exists: the
46
+ * version, its folder and files, and the one command that makes the next version (never a loose HTML file)
35
47
  * promptOf(o) PURE · scaffoldOf(roots) → { css, from }
36
48
  * create(deps) → { start(input), propose(input), cancel(id, why), running(ini), status() } and the module-level shortcuts below,
37
49
  * round(input) → Promise<{ ok, round: { id, n, keys, directions }, runs } | { ok: false, error }> once create() ran (W2 builds on it)
@@ -52,6 +64,17 @@ const DEFAULT_DIRECTIONS = Object.freeze([
52
64
  Object.freeze({ key: 'B', title: 'The one thing that matters most leads; the rest folds away' }),
53
65
  Object.freeze({ key: 'C', title: 'A different shape: a timeline, a stack of cards or a step-by-step flow' }),
54
66
  ]);
67
+ // one version, the default since 2026-11-17 (Wawan: "viewer shows the prototype one at a time unless stated to have multiple versions")
68
+ const ONE_DIRECTION = Object.freeze([Object.freeze({ key: 'A', title: 'The idea as asked: the plainest honest version' })]);
69
+ // 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
70
+ // diagram and copywriting document"; design Prototype by chatting, agreed 23:31): DATA the Viewer draws, not pages. The version's own run
71
+ // 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
72
+ // read from the prototype's own data-copy text, so it can never disagree with what the screen says.
73
+ const PARTS = Object.freeze([
74
+ Object.freeze({ kind: 'flow', title: 'The flow', name: 'flow.json' }),
75
+ Object.freeze({ kind: 'lanes', title: 'Who does what', name: 'lanes.json' }),
76
+ Object.freeze({ kind: 'tweaks', title: 'Tweaks', name: 'tweaks.json', optional: true }),
77
+ ]);
55
78
  const SCAFFOLD_MAX = 12000;
56
79
  const FROM = Object.freeze({ chat: 'Your ask in the initiative chat', cli: 'pmos lab round', meeting: 'Said in the meeting' });
57
80
 
@@ -64,14 +87,46 @@ const ms = (iso) => Date.parse(iso || '') || 0;
64
87
  /* ── what a sentence asks for ── */
65
88
  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
89
  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. */
90
+ // Wawan 2026-11-17 20:25: "iterative, like Claude Code design work": one prototype unless the PM asks for several, and any change sentence
91
+ // while one is open changes it. A change sentence starts with a change word; a question or a plain remark does not.
92
+ 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;
93
+ // 2026-11-18 ("Improve the prototype based on the PRD" got "I can't find the rendered files"): a word that asks for work on what is there counts
94
+ // as a change of the prototype when the sentence names it (the prototype, a version, a screen, the layout, the design, or its letter)
95
+ const WORK_RE = /^\s*(?:please\s+|can you\s+|could you\s+|now\s+|ok(?:ay)?,?\s+|yes,?\s+)?(improve|update|refine|rework|redo|rebuild|redesign|restyle|polish|fix|adjust|tweak|iterate( on)?|apply|continue|cover|base|follow|align|write)\b/i;
96
+ const PROTO_NOUN_RE = /\b(prototype|version|screens?|page|layout|design|mock ?up|ui|viewer|canvas|flow|swimlane|copy)\b/i;
97
+ const COUNT_RE = /\b(\d|two|three|a few|some|(?:a )?couple of)\s+(ways|options|versions|takes|directions|variants)\b/i;
98
+ const WORDS = { two: 2, three: 3, 'a few': 3, some: 3, 'couple of': 2, 'a couple of': 2 };
99
+ /** 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
100
+ * the element the PM pointed at, "[From version 2]" after Continue from version 2. → { text, point: { el, label } | null, from: n | null } */
101
+ const POINT_RE = /^\s*\[On: ([^\]·]{1,80}?)(?: · ([A-Za-z0-9_-]{1,60}))?\]\s*/;
102
+ const FROMV_RE = /^\s*\[From version (\d{1,3})\]\s*/;
103
+ function marksOf(text) {
104
+ let t = String(text == null ? '' : text), point = null, from = null, m;
105
+ for (let i = 0; i < 2; i += 1) {
106
+ if ((m = POINT_RE.exec(t))) { point = { label: one(m[1], 80), el: m[2] || '' }; t = t.slice(m[0].length); }
107
+ else if ((m = FROMV_RE.exec(t))) { from = Number(m[1]) || null; t = t.slice(m[0].length); }
108
+ }
109
+ return { text: t, point, from };
110
+ }
111
+ /** PURE. → { kind: 'new', brief, count } | { kind: 'feedback', base, brief, point?, from? } | null. count is 1 unless the sentence asks for
112
+ * several ("show 3 ways": 2 or 3). A feedback sentence counts only while a round waits on the initiative (waiting: its keys): "B, but …"
113
+ * names a version; a change sentence ("make the alert orange") means the one version open, when exactly one is. With an element pointed at
114
+ * (the canvas's Point), any sentence that is not a question is a change of that element. */
69
115
  function intentOf(text, { waiting = null } = {}) {
70
- const t = one(text, 600);
116
+ const mk = marksOf(text);
117
+ const t = one(mk.text, 600);
71
118
  if (!t || t.startsWith('/')) return null;
119
+ const keys = waiting ? (waiting.keys || []) : [];
120
+ const extra = { ...(mk.point ? { point: mk.point } : {}), ...(mk.from ? { from: mk.from } : {}) };
72
121
  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 };
122
+ if (f && keys.includes(f[1].toUpperCase())) return { kind: 'feedback', base: f[1].toUpperCase(), brief: t, ...extra };
123
+ if (NEW_RE.test(t)) {
124
+ const m = COUNT_RE.exec(t);
125
+ let count = 1;
126
+ if (m) { const w = m[1].toLowerCase(); count = /^\d$/.test(w) ? Number(w) : WORDS[w] || 3; }
127
+ return { kind: 'new', brief: t, count: Math.min(3, Math.max(1, count)) };
128
+ }
129
+ if (keys.length === 1 && (CHANGE_RE.test(t) || (WORK_RE.test(t) && (PROTO_NOUN_RE.test(t) || /\b[A-C]\b/.test(t))) || ((mk.point || mk.from) && !/\?\s*$/.test(t)))) return { kind: 'feedback', base: keys[0], brief: t, ...extra };
75
130
  return null;
76
131
  }
77
132
  /** 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,18 +174,21 @@ function waiting(P, ini) {
119
174
  const keys = ((root && root.data && root.data.specimens) || []).map((s) => s.key);
120
175
  return { id: p.id, group: p.group, round: p.group === 'improved' ? Number(d.round) || 2 : 1, keys };
121
176
  }
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) {
177
+ /** PURE. A feedback round on `key`: the newest first round on the initiative, the newest proven file of that key (or of version `from`,
178
+ * after Continue from version n), and the next round's number. The version's companions live next to its file (PARTS). */
179
+ function baseOf(P, ini, key, { from = null, of = '' } = {}) {
124
180
  if (!P || !KEYS.includes(key)) return null;
125
181
  const all = [...P.props.values()].filter((p) => p.ini === ini);
126
182
  const roots = all.filter((p) => p.group === 'prototyped').sort((a, b) => ms(b.at) - ms(a.at));
127
- const root = roots.find((r) => ((r.data || {}).specimens || []).some((s) => s.key === key));
183
+ const has = (r) => ((r.data || {}).specimens || []).some((s) => s.key === key);
184
+ const root = (of && roots.find((r) => r.id === of && has(r))) || roots.find(has);
128
185
  if (!root) return null;
129
186
  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
187
  const spec = root.data.specimens.find((s) => s.key === key);
131
- const last = rounds.filter((r) => r.data.base === key && r.data.file).pop();
188
+ const mine = rounds.filter((r) => r.data.base === key && r.data.file);
189
+ const pick = from === 1 ? null : from ? mine.find((r) => Number(r.data.round) === Number(from)) : mine[mine.length - 1];
132
190
  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 };
191
+ return { of: root.id, round: n, file: pick ? pick.data.file : spec.file, title: spec.title, from: pick ? Number(pick.data.round) : 1 };
134
192
  }
135
193
 
136
194
  /* ── the scaffold and the prompt ── */
@@ -157,44 +215,200 @@ function scaffoldOf(roots) {
157
215
  }
158
216
  return { css: '', from: [] };
159
217
  }
160
- /** PURE. One run's prompt. o: { brief, key, title, file, info: { title, description, intent }, scaffold: { css }, base?: { file, title, abs } } */
218
+ /** PURE. One run's prompt. o: { brief, key, title, file, dir (the run's folder), info: { title, description, intent }, scaffold: { css },
219
+ * base?: { file, title, abs }, alone?, refs?, point?: { el, label }, edits?: { copy, vars } } */
161
220
  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.');
221
+ const info = o.info || {}, L = [], dir = o.dir || path.dirname(o.file || '');
222
+ 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
223
  L.push('', `The idea: ${one(o.brief, 600)}`);
165
224
  if (info.title) L.push(`The initiative: ${one(info.title, 160)}${info.description ? ' · ' + one(info.description, 400) : ''}`);
166
225
  if (info.intent) L.push(`What the product wants (its Intent): ${one(info.intent, 400)}`);
226
+ if (/\b(prd|brief|spec|brd|requirements?|document|doc)\b/i.test(String(o.brief || ''))) L.push('The idea names a document of the initiative: find it in this repository with Glob (planning/, docs/) and read it first. Build from what it says.');
227
+ // 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
228
+ // according to it, or as user prompted")
229
+ 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
230
  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.' : '.'));
231
+ L.push('', `This is a new version of prototype ${o.key} (${one(o.base.title, 140)}). Read the last version first: ${o.base.abs}`,
232
+ `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.`);
233
+ } 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.');
234
+ else L.push('', `Your direction, ${o.key}: ${one(o.title, 200)}. Other runs take the other directions: keep yours clearly different.`);
235
+ 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.`);
236
+ const ed = o.edits || {}, ec = Object.entries(ed.copy || {}), ev = Object.entries(ed.vars || {});
237
+ if (ec.length || ev.length) {
238
+ L.push('', 'The PM edited the last version in place. Keep these exactly, unless their words change them:');
239
+ for (const [k, v] of ec.slice(0, 40)) L.push(`- the text of data-copy="${k}": ${one(v, 200)}`);
240
+ for (const [k, v] of ev.slice(0, 20)) L.push(`- the CSS variable ${k}: ${one(v, 40)} (set it in :root)`);
241
+ }
242
+ // the design sprint's good practice, silent (Wawan 2026-11-17: "the design sprint runs in silent"): a target user, one question, real
243
+ // content, Goldilocks fidelity. Never a step the PM has to fill in.
244
+ 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.');
245
+ L.push('', `Write these files with the Write tool, in this order, in ${dir}:`,
246
+ `1. ${o.file}: the prototype. Write it FIRST: the PM sees it as soon as it lands.`,
247
+ ' - One self-contained HTML page: inline CSS only, no script, no network, no image files. Real draft copy, never lorem ipsum or a placeholder.',
248
+ ` - 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.`,
249
+ ' - 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.',
250
+ ' - What the user taps to move on carries data-go="<screen id>" (a button, a row, a link with href="#<screen id>").',
251
+ ' - 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>".',
252
+ ' - 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).',
253
+ ' - Spacing, corner radius and colour warmth read CSS custom properties set in :root (for example --gap, --radius, --accent), so a slider can change them.',
254
+ ' - 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.',
255
+ ' - 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>.',
256
+ `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"? }] }] }.`,
257
+ ' - 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").',
258
+ ' - 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.',
259
+ `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.`,
260
+ `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.`,
261
+ 'Write nothing else and do not read anything else' + (o.base || (o.refs || []).length ? ' but what is named above.' : '.'));
178
262
  if (o.scaffold && o.scaffold.css) L.push('', 'The stylesheet:', '```css', o.scaffold.css, '```');
179
263
  return L.join('\n');
180
264
  }
181
265
 
266
+ /* ── the companions as data (PARTS): each check is PURE and keeps only what is well formed ── */
267
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,59}$/;
268
+ const arr = (v, n) => (Array.isArray(v) ? v.slice(0, n) : []);
269
+ /** PURE. flow.json → { screens, decisions, edges, scenarios } | { error }. Ids are unique; an edge joins two known nodes; a scenario's
270
+ * steps name known screens. A screen the prototype does not have is still drawn (the Viewer says it cannot show it). */
271
+ function flowOf(j) {
272
+ if (!isObj(j)) return { error: 'flow.json is not a JSON object' };
273
+ 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);
274
+ const screens = arr(j.screens, 24).map(node).filter(Boolean);
275
+ const decisions = arr(j.decisions, 12).map(node).filter(Boolean);
276
+ if (!screens.length) return { error: 'flow.json has no screens' };
277
+ const sid = new Set(screens.map((x) => x.id));
278
+ 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) } : {}) }));
279
+ const sids = new Set();
280
+ const scenarios = arr(j.scenarios, 6).map((c) => {
281
+ if (!isObj(c) || !ID.test(str(c.id)) || sids.has(c.id)) return null;
282
+ 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) } : {}) }));
283
+ if (!steps.length) return null;
284
+ sids.add(c.id);
285
+ return { id: c.id, name: one(c.name || c.id, 60), description: one(c.description, 200), steps };
286
+ }).filter(Boolean);
287
+ return { screens, decisions, edges, scenarios };
288
+ }
289
+ /** PURE. lanes.json → { lanes: [{ id, name, steps: [{ n, title, screen? }] }] } | { error }. Each n is used once across the lanes. */
290
+ function lanesOf(j, { screens = null } = {}) {
291
+ if (!isObj(j)) return { error: 'lanes.json is not a JSON object' };
292
+ const ids = new Set(), ns = new Set();
293
+ const lanes = arr(j.lanes, 8).map((l) => {
294
+ if (!isObj(l) || !ID.test(str(l.id)) || ids.has(l.id)) return null;
295
+ ids.add(l.id);
296
+ const steps = [];
297
+ for (const t of arr(l.steps, 30)) {
298
+ if (!isObj(t) || !Number.isInteger(t.n) || t.n < 1 || t.n > 99 || ns.has(t.n) || !str(t.title)) continue;
299
+ ns.add(t.n);
300
+ steps.push({ n: t.n, title: one(t.title, 80), ...(ID.test(str(t.screen)) && (!screens || screens.has(t.screen)) ? { screen: t.screen } : {}) });
301
+ }
302
+ steps.sort((a, b) => a.n - b.n);
303
+ return { id: l.id, name: one(l.name || l.id, 40), steps };
304
+ }).filter(Boolean);
305
+ if (!lanes.length || !ns.size) return { error: 'lanes.json has no lanes with steps' };
306
+ return { lanes };
307
+ }
308
+ /** PURE. tweaks.json → { tweaks: [{ var, label, min, max, step, unit, value, el? }] } | { error }. */
309
+ function tweaksOf(j) {
310
+ if (!isObj(j)) return { error: 'tweaks.json is not a JSON object' };
311
+ const seen = new Set();
312
+ const tweaks = arr(j.tweaks, 6).map((t) => {
313
+ if (!isObj(t) || !/^--[a-z][a-z0-9-]{0,40}$/i.test(str(t.var)) || seen.has(t.var)) return null;
314
+ const min = Number(t.min), max = Number(t.max);
315
+ if (!Number.isFinite(min) || !Number.isFinite(max) || !(min < max)) return null;
316
+ seen.add(t.var);
317
+ const value = Number.isFinite(Number(t.value)) ? Math.min(max, Math.max(min, Number(t.value))) : min;
318
+ 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 } : {}) };
319
+ }).filter(Boolean);
320
+ return { tweaks };
321
+ }
322
+ const decode = (s) => String(s).replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, '&');
323
+ /** PURE. The prototype's own words: every element with data-copy="key" → { key: text } (its first text, tags taken out), in page order. */
324
+ function copyOf(html) {
325
+ 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;
326
+ let m, n = 0;
327
+ while ((m = re.exec(String(html || ''))) && n < 80) {
328
+ if (m[2] in out) continue;
329
+ const text = one(decode(m[3].replace(/<[^>]*>/g, ' ')), 300);
330
+ if (text) { out[m[2]] = text; n += 1; }
331
+ }
332
+ return out;
333
+ }
334
+ /** PURE. What one version changed against the last: { flow, lanes, copy, steps: [n], keys: [copy key] } and the line the chat says,
335
+ * "step 3, the swimlane and the copy" ('' when nothing beside the prototype changed). prev / cur: { flow?, lanes?, copy? }. */
336
+ function changesOf(prev, cur) {
337
+ const p = prev || {}, c = cur || {}, J = (v) => JSON.stringify(v || null);
338
+ 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; };
339
+ const a = stepsOf(p.lanes), b = stepsOf(c.lanes), steps = [];
340
+ for (const [n, v] of b) if (a.get(n) !== v) steps.push(n);
341
+ const pc = p.copy || {}, cc = c.copy || {}, keys = Object.keys(cc).filter((k) => pc[k] !== cc[k]);
342
+ 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 };
343
+ if (!prev) return { ...out, line: '' };
344
+ const parts = [];
345
+ if (out.steps.length && out.steps.length <= 3) parts.push((out.steps.length === 1 ? 'step ' : 'steps ') + andOf(out.steps.map(String)));
346
+ if (out.flow) parts.push('the flow');
347
+ if (out.lanes) parts.push('the swimlane');
348
+ if (out.copy) parts.push('the copy');
349
+ return { ...out, line: andOf(parts) };
350
+ }
351
+ const andOf = (xs) => (xs.length <= 1 ? xs.join('') : xs.slice(0, -1).join(', ') + ' and ' + xs[xs.length - 1]);
352
+ /** The data next to a version's file: { flow?, lanes?, copy?, tweaks?, edits? }, each one only when it is there and well formed. */
353
+ function partsAt(abs) {
354
+ const dir = path.dirname(abs), out = {};
355
+ const rd = (n) => { try { return JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8')); } catch { return null; } };
356
+ const f = flowOf(rd('flow.json')); if (!f.error) out.flow = f;
357
+ 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;
358
+ const t = tweaksOf(rd('tweaks.json')); if (!t.error && t.tweaks.length) out.tweaks = t;
359
+ const c = rd('copy.json'); if (isObj(c)) out.copy = c;
360
+ const e = editsOf(rd('edits.json')); if (Object.keys(e.copy).length || Object.keys(e.vars).length) out.edits = e;
361
+ return out;
362
+ }
363
+ /** PURE. edits.json (the PM's in-place copy edits and tweaks, POST /api/lab/edit) → { copy: { key: text }, vars: { --var: value } }. */
364
+ function editsOf(j) {
365
+ const copy = {}, vars = {};
366
+ 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);
367
+ 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);
368
+ return { copy, vars };
369
+ }
370
+
371
+ /** The one sentence a version says about itself: <meta name="pmos-changed" content="…"> in its head, or ''. */
372
+ function saidOf(abs) {
373
+ let head = ''; try { head = fs.readFileSync(abs, 'utf8').slice(0, 20000); } catch { return ''; }
374
+ 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);
375
+ return m ? one(m[1].replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, '&'), 160) : '';
376
+ }
377
+
378
+ /** PURE. What the initiative chat's agent is told before the PM's words while the initiative has a prototype (cur: lib/proposals.js
379
+ * currentOf; rt: the runtime folder). 2026-11-18: asked to "Improve the prototype based on the PRD", the chat found no files and asked the
380
+ * PM for a path; asked to "Rebuild A", it tried the idle lab's `pmos lab file` and wrote a loose a2.html in its scratchpad instead of a
381
+ * version in the Viewer. → '' when there is no prototype. */
382
+ function contextOf(cur, { ini, ws = '', rt = null } = {}) {
383
+ if (!cur || !cur.file || !ini) return '';
384
+ const abs = (rt && LAB.specimenPath(rt, cur.file)) || cur.file, dir = path.dirname(abs);
385
+ const wsf = ws ? ` --ws ${ws}` : '';
386
+ return `[PMOS] This initiative's prototype is Version ${cur.n} (${cur.key}${cur.said ? ': "' + one(cur.said, 140) + '"' : ''}), open in the Viewer beside this chat. `
387
+ + `Its files are in ${dir}: ${path.basename(abs)} (the prototype), flow.json, lanes.json, copy.json, tweaks.json, and edits.json (the PM's own edits in the Viewer). Read them to answer questions about it. `
388
+ + `To change, improve or rebuild it, in any words, run exactly: \`pmos lab round ${ini}${wsf} --base ${cur.key} --chat --brief "<what to change, with the PM's words and anything you read, under 600 characters>"\` `
389
+ + `and say in one line what will change: PMOS makes Version ${cur.n + 1} in about a minute and tells you when it is in the Viewer. `
390
+ + 'Never write the prototype yourself, never write an HTML file in a scratchpad or elsewhere, and never use `pmos lab file`: that is for the background lab only.';
391
+ }
392
+
182
393
  /* ── the proposal line of a round ── */
394
+ const fin = (x) => x.state === 'ok' || x.state === 'not made' || x.state === 'none';
395
+ const partsLine = (s) => Object.fromEntries((s.parts || []).map((x) => [x.kind, x.state === 'not made' ? 'not made: ' + one(x.why, 120) : x.state]));
183
396
  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 } : {}) }));
397
+ 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
398
  const ok = R.slots.filter((s) => s.state === 'ok');
186
- const done = R.slots.every((s) => s.state === 'ok' || s.state === 'not made');
399
+ const done = R.slots.every((s) => fin(s) && (s.parts || []).every(fin));
187
400
  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() };
401
+ 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
402
  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
403
  why: one(`You asked: "${R.brief}"`, 300), sources: [{ label: FROM[R.from] || FROM.chat }], items: [] };
191
404
  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 } };
405
+ return { ...base, group: 'prototyped', type: 'new', title: one(`Round 1 · ${R.slots.length === 1 ? 'one version' : R.slots.length + ' ways'}: ${R.brief}`, 140),
406
+ data: { round: 1, specimens: ok.map((s) => ({ key: s.key, title: s.title, caption: s.said || '', file: s.file })), checked, live } };
194
407
  }
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 } };
408
+ const s = R.slots[0], ch = s.changes || null;
409
+ return { ...base, group: 'improved', type: 'round', title: one(`Version ${R.n} of ${R.base}: ${R.brief}`, 140),
410
+ 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 } : {}),
411
+ ...(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
412
  }
199
413
 
200
414
  /* ── the engine ── */
@@ -208,7 +422,7 @@ function create(deps) {
208
422
  const warn = deps.warn || (() => {});
209
423
  const now = () => (deps.now ? deps.now() : Date.now());
210
424
  const render = deps.render || ((abs) => E.renderCheck(abs, { phone: true })); // proven at 390 px too: the viewport pin
211
- const pollMs = deps.pollMs || 1000;
425
+ const pollMs = deps.pollMs || 1000;
212
426
  const budgetMs = deps.budgetMs || BUDGET_MS;
213
427
  const rounds = new Map(); // id → round
214
428
 
@@ -246,13 +460,14 @@ function create(deps) {
246
460
  return { ws, ini, pr, dir: pr.dir, info: info || { title: ini }, board };
247
461
  }
248
462
 
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 } */
463
+ /** Start a round now. input: { ws, board?, ini, brief, base?, from?: chat|cli|meeting, fromV? (Continue from version n), point?: { el,
464
+ * label }, directions?|dirs?, count?, refs?, step?: 1|2, by? } → { ok, round: { id, n, keys, directions, proposal }, runs } | { ok: false, error } */
251
465
  function start(input = {}) {
252
466
  const rt = deps.runtimeDir ? deps.runtimeDir() : null;
253
467
  if (!rt) return { ok: false, error: 'no runtime state folder' };
254
468
  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' };
469
+ const mk = marksOf(input.brief);
470
+ const brief = one(mk.text, 600); if (!brief) return { ok: false, error: 'brief is the PM\'s sentence: what to show' };
256
471
  // the off switch (`pmos ai off live-round`, or every AI job off) holds it, as it holds every other job
257
472
  let off = null; try { off = require('./ai-guard.js').off(JOB, { env: deps.env || process.env, settingsDir: rt }); } catch { off = null; }
258
473
  if (off) return { ok: false, error: 'live rounds are off: ' + off };
@@ -260,31 +475,38 @@ function create(deps) {
260
475
  const t = now(), id = 'lr' + t.toString(36) + crypto.randomBytes(3).toString('hex');
261
476
  const from = FROM[input.from] ? input.from : 'chat', step = Number(input.step) === 2 ? 2 : 1;
262
477
  const P = PR.read(c.dir);
478
+ const fromV = Number(input.fromV) || mk.from || null;
479
+ const point = isObj(input.point) ? { el: ID.test(str(input.point.el)) ? input.point.el : '', label: one(input.point.label, 80) } : mk.point;
263
480
  let base = '', b = null, dirs;
264
481
  if (input.base) {
265
482
  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` };
483
+ // the version the initiative is at now (lib/proposals.js currentOf), unless the PM said Continue from version n
484
+ const cur = fromV ? null : PR.currentOf(P, c.ini);
485
+ b = cur && cur.key === base ? baseOf(P, c.ini, base, { from: cur.n, of: cur.of }) : baseOf(P, c.ini, base, { from: fromV });
486
+ if (!b) return { ok: false, error: `there is no proven version ${base} on this initiative yet: ask for a first one` };
268
487
  dirs = [{ key: base, title: b.title }];
269
488
  } else {
270
- dirs = Array.isArray(input.directions) && input.directions.length ? input.directions : input.dirs ? parseDirs(input.dirs) : DEFAULT_DIRECTIONS;
489
+ dirs = Array.isArray(input.directions) && input.directions.length ? input.directions : input.dirs ? parseDirs(input.dirs) : Number(input.count) === 1 ? ONE_DIRECTION : DEFAULT_DIRECTIONS;
271
490
  if (!dirs) return { ok: false, error: 'dirs is 2 or 3 directions, "A: …|B: …|C: …"' };
272
491
  }
273
492
  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,
493
+ // 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
494
+ 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);
495
+ 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,
496
+ point: point && (point.el || point.label) ? point : null,
275
497
  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: '' })),
498
+ slots: dirs.map((d) => ({ key: d.key, title: one(d.title, 140), state: 'working', run: '', session: null, file: '', size: -1, why: '', dims: '', parts: [] })),
277
499
  timer: null, budget: null, ended: false };
278
500
  rounds.set(id, R);
279
501
  write(R);
280
- if (base) lesson(c.dir, c.ini, `Round ${R.n} of ${base}: ${brief}`, input.by || 'agent:live-round');
502
+ 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
503
  for (const s of R.slots) launch(R, s, { info: c.info, scaffold, b });
282
504
  R.timer = setInterval(() => { poll(R).catch((e) => warn('live round poll', e)); }, pollMs);
283
505
  if (R.timer.unref) R.timer.unref();
284
506
  R.budget = setTimeout(() => over(R), budgetMs);
285
507
  if (R.budget.unref) R.budget.unref();
286
508
  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) };
509
+ 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
510
  }
289
511
 
290
512
  function launch(R, s, { info, scaffold, b }) {
@@ -293,14 +515,16 @@ function create(deps) {
293
515
  const folder = path.join(LAB.specimenDir(R.rt), R.id, s.key);
294
516
  s.file = R.id + '/' + s.key + '/' + s.key.toLowerCase() + '.html';
295
517
  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; }
518
+ 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: '' }));
519
+ 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
520
  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 });
521
+ const edits = baseAbs ? partsAt(baseAbs).edits || null : null;
522
+ 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
523
  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
524
  let session = null;
301
525
  try {
302
526
  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)] : [],
527
+ initialInput: prompt + '\r', initiative: R.ini, writePaths: [folder], addDirs: addDirsOf(baseAbs, R.refs),
304
528
  onDone: (res) => { ended(R, s, res).catch((e) => warn('live round end', e)); } });
305
529
  } catch (e) { warn('live round spawn', e); }
306
530
  s.session = session;
@@ -309,16 +533,29 @@ function create(deps) {
309
533
  notMade(R, s, (session && session.note) || 'the run could not start in the background');
310
534
  }
311
535
  }
536
+ const addDirsOf = (baseAbs, refs) => [...new Set([...(baseAbs ? [path.dirname(baseAbs)] : []), ...(refs || []).map((r) => path.dirname(r))])];
312
537
 
313
538
  function write(R) {
314
539
  try { fs.appendFileSync(PR.ledgerFile(R.dir), JSON.stringify(roundLine(R, now())) + '\n'); } catch (e) { warn('live round proposal', e); }
315
540
  }
541
+ /** 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). */
542
+ function tell(R, text) {
543
+ if (R.from !== 'chat' || typeof deps.tell !== 'function') return;
544
+ try { deps.tell(R.ws, R.ini, text); } catch (e) { warn('live round tell', e); }
545
+ }
546
+ /** A version that was not made: its companions go with it (nothing to draw them next to). */
316
547
  function notMade(R, s, why) {
317
548
  if (s.state === 'ok' || s.state === 'not made') return;
318
549
  s.state = 'not made'; s.why = one(why, 200);
550
+ for (const x of s.parts || []) if (x.state === 'working') { x.state = 'none'; }
319
551
  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
552
  write(R); settle(R);
321
553
  }
554
+ function partNotMade(R, s, x, why) {
555
+ if (x.state !== 'working') return;
556
+ if (x.optional) { x.state = 'none'; } else { x.state = 'not made'; x.why = one(why, 200); }
557
+ write(R); settle(R);
558
+ }
322
559
  async function prove(R, s, cost = null) {
323
560
  if (s.state !== 'working') return;
324
561
  s.state = 'proving';
@@ -329,41 +566,84 @@ function create(deps) {
329
566
  else { try { v = await render(s.abs); } catch (e) { v = { ok: false, why: 'it did not open: ' + one(e && e.message, 120) }; } }
330
567
  if (s.state !== 'proving') return; // stopped while it rendered (Undo, the budget)
331
568
  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}`;
569
+ s.state = 'ok'; s.dims = `${v.w}×${v.h}`; s.said = saidOf(s.abs);
570
+ // copy.json is PMOS's, read from the prototype's own words, so the Page copy card can never disagree with the screen
571
+ 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
572
  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 */ }
573
+ 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); }
574
+ // one version at a time: the newest proven version IS the initiative's prototype (2026-11-18: the Experiment card still showed an old
575
+ // round). A round of several ways, or one started in a terminal (a test), waits for the PM's keep (lib/routes-proposals.js liveKept).
576
+ if (deps.artefact && R.slots.length === 1 && R.from !== 'cli') try { deps.artefact(R.dir, { scope: 'experiment:' + R.ini, artefact: 'specimens', field: 'kept', text: one(`Version ${R.n}: ${s.said || s.title} (${LAB.specimenUrl(s.file)})`, 600), sources: [{ label: 'live round', ref: LAB.specimenUrl(s.file) }] }, 'agent:live-round'); } catch (e) { warn('live round kept', e); }
577
+ write(R); settle(R);
578
+ }
579
+ /** A companion lands: it must parse and be well formed (flowOf, lanesOf, tweaksOf), else it is "not made" with the reason. */
580
+ function provePart(R, s, x) {
581
+ if (x.state !== 'working') return;
582
+ let j = null, err = '';
583
+ try { j = JSON.parse(fs.readFileSync(x.abs, 'utf8')); } catch (e) { err = x.name + ' is not JSON'; }
584
+ if (!err) { const v = x.kind === 'flow' ? flowOf(j) : x.kind === 'lanes' ? lanesOf(j) : tweaksOf(j); if (v.error) err = v.error; }
585
+ if (err) return partNotMade(R, s, x, err);
586
+ x.state = 'ok';
336
587
  write(R); settle(R);
337
588
  }
338
589
  async function poll(R) {
339
590
  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;
591
+ for (const x of s.state === 'not made' ? [] : [s, ...(s.parts || [])]) {
592
+ if (x.state !== 'working') continue;
593
+ let size = -1; try { size = fs.statSync(x.abs).size; } catch { size = -1; }
594
+ // a file that stopped growing for one poll has landed: prove it now, before the run ends
595
+ if (size > 0 && size === x.size) { if (x === s) await prove(R, s); else provePart(R, s, x); }
596
+ else x.size = size;
597
+ }
345
598
  }
346
599
  }
347
600
  async function ended(R, s, res = {}) {
348
- if (s.state !== 'working') return;
349
601
  const out = (res && res.result) || {};
350
602
  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');
603
+ if (s.state === 'working') {
604
+ let have = false; try { have = fs.statSync(s.abs).size > 0; } catch { have = false; }
605
+ if (have) await prove(R, s, cost);
606
+ 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');
607
+ }
608
+ // 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)
609
+ for (const x of s.parts || []) {
610
+ if (x.state !== 'working') continue;
611
+ let have = false; try { have = fs.statSync(x.abs).size > 0; } catch { have = false; }
612
+ if (have) provePart(R, s, x); else partNotMade(R, s, x, 'the run ended without writing ' + x.name);
613
+ }
354
614
  }
355
615
  function over(R) {
356
616
  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');
617
+ const busy = [s, ...(s.parts || [])].some((x) => x.state === 'working');
618
+ if (busy && s.session && s.session.state !== 'exited' && deps.stop) try { deps.stop(s.session); } catch { /* best effort */ }
619
+ if (s.state === 'working') notMade(R, s, 'past the 2 minute budget'); // a file being proven finishes its proof
620
+ for (const x of s.parts || []) partNotMade(R, s, x, 'past the 2 minute budget');
360
621
  }
361
622
  }
362
623
  function settle(R) {
363
- if (R.ended || !R.slots.every((s) => s.state === 'ok' || s.state === 'not made')) return;
624
+ // a version whose prototype and companions all landed is done: its run stops (it may still be summing up)
625
+ 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 */ } }
626
+ if (R.ended || !R.slots.every((s) => fin(s) && (s.parts || []).every(fin))) return;
364
627
  R.ended = true;
365
628
  clearInterval(R.timer); clearTimeout(R.budget);
629
+ // what each version changed against the one it was made from: the chat's "Also updated" and the cards' Updated
630
+ if (R.base) {
631
+ const s = R.slots[0], prev = R.baseFile ? LAB.specimenPath(R.rt, R.baseFile) : null;
632
+ if (s.state === 'ok') try { s.changes = changesOf(prev ? partsAt(prev) : {}, partsAt(s.abs)); } catch (e) { warn('live round changes', e); }
633
+ }
366
634
  write(R);
635
+ const ok = R.slots.filter((s) => s.state === 'ok');
636
+ const lost = (s) => [...(s.parts || [])].filter((x) => x.state === 'not made').map((x) => (PARTS.find((p) => p.kind === x.kind) || {}).title || x.kind);
637
+ if (R.slots.length === 1) {
638
+ const s = R.slots[0], v = 'Version ' + R.n;
639
+ if (s.state !== 'ok') tell(R, `[PMOS] ${v} was not made: ${s.why}. Say so to the PM in one line, nothing else.`);
640
+ else {
641
+ const also = s.changes && s.changes.line, miss = lost(s);
642
+ 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.`);
643
+ }
644
+ } else {
645
+ 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.`);
646
+ }
367
647
  // the round stays readable for status() for a while, then goes
368
648
  const t = setTimeout(() => rounds.delete(R.id), 10 * 60 * 1000); if (t.unref) t.unref();
369
649
  }
@@ -372,7 +652,9 @@ function create(deps) {
372
652
  function cancel(id, why = 'stopped: you pressed Undo') {
373
653
  const R = rounds.get(id);
374
654
  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); }
655
+ 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 */ }
656
+ if (s.state === 'working' || s.state === 'proving') { s.state = 'working'; notMade(R, s, why); }
657
+ for (const x of s.parts || []) partNotMade(R, s, x, why);
376
658
  }
377
659
  const dir = R ? R.dir : null;
378
660
  return { ok: !!R, dir };
@@ -403,5 +685,6 @@ function dropCard(dir, propId) { return inst ? inst.dropCard(dir, propId) : fals
403
685
  function running(ini) { return inst ? inst.running(ini) : false; }
404
686
  function status() { return inst ? inst.status() : []; }
405
687
 
406
- module.exports = { JOB, ORIGIN, BUDGET_MS, KEYS, DEFAULT_DIRECTIONS, FROM, intentOf, parseDirs, askOf, waiting, baseOf, scaffoldOf, promptOf, roundLine,
688
+ module.exports = { JOB, ORIGIN, BUDGET_MS, KEYS, DEFAULT_DIRECTIONS, ONE_DIRECTION, PARTS, FROM, marksOf, intentOf, parseDirs, askOf, waiting, baseOf, currentOf: PR.currentOf, contextOf, scaffoldOf, promptOf, saidOf, roundLine,
689
+ flowOf, lanesOf, tweaksOf, copyOf, changesOf, partsAt, editsOf,
407
690
  create, install, round, startNow, proposeNow, cancel, dropCard, running, status };