create-pmos 0.580.0 → 0.582.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.
- package/package.json +27 -33
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/changelog.json +26 -0
- package/workspace/guide/agent-capabilities.md +24 -3
- package/workspace/guide/cli.md +3 -2
- package/workspace/guide/notes.md +4 -3
- package/workspace/lib/bg-queue.js +7 -3
- package/workspace/lib/grill-runs.js +2 -0
- package/workspace/lib/grill.js +1 -1
- package/workspace/lib/headless.js +8 -2
- package/workspace/lib/idle-lab-engine.js +11 -3
- package/workspace/lib/idle-lab.js +15 -4
- package/workspace/lib/job-graph.js +4 -0
- package/workspace/lib/lab-cli.js +26 -2
- package/workspace/lib/live-round-meeting.js +167 -0
- package/workspace/lib/live-round.js +407 -0
- package/workspace/lib/meeting-focus.js +42 -10
- package/workspace/lib/orchestrator-keeprate.js +3 -0
- package/workspace/lib/proposals.js +5 -2
- package/workspace/lib/routes-briefing-premium.js +27 -2
- package/workspace/lib/routes-lab.js +20 -3
- package/workspace/lib/routes-meeting-focus.js +57 -3
- package/workspace/lib/routes-proposals.js +39 -3
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/cozy-lab.css +12 -0
- package/workspace/public/pm/cozy-lab.js +42 -7
- package/workspace/public/pm/cozy-rec-now.css +2 -0
- package/workspace/public/pm/cozy-rec-now.js +27 -8
- package/workspace/public/pm/ini-props.js +7 -3
- package/workspace/run-tests.js +35 -0
- package/workspace/server.js +28 -0
- package/workspace/test-lists/live-round.json +9 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* live-round-meeting.js — round 1 is ready before the meeting (initiative live-round-meeting, part 2; brief /mnt/project-files/live-round/briefs.md W2).
|
|
3
|
+
*
|
|
4
|
+
* WHEN. Job `meeting-prewarm`, step 2 of the shared queue (lib/bg-queue.js, "due at a set time"): it looks once a minute and does not wait
|
|
5
|
+
* for the idle clock. The off switch is `pmos ai off meeting-prewarm`.
|
|
6
|
+
*
|
|
7
|
+
* WHAT. Candidate kind `prototype-meeting`: a meeting that starts in the next 60 minutes whose agenda (the invite's lines, lib/meeting-focus.js
|
|
8
|
+
* topicsFrom), its title or its material (lib/meeting-material.js) names an initiative that is
|
|
9
|
+
* - open and in Triage or Discover (or with no stage yet),
|
|
10
|
+
* - with no prototype yet (no `prototyped` or `improved` proposal on it, in any state),
|
|
11
|
+
* - with no round waiting for the PM (lib/live-round.js waiting) and none running (running), and
|
|
12
|
+
* - not tried in the last 7 days (the same retry as the idle lab).
|
|
13
|
+
* An initiative is named by its id, by the meeting's own initiative, or by its title (two words or more) inside one of those lines.
|
|
14
|
+
*
|
|
15
|
+
* HOW. One round at a time: lib/live-round.js round({ ws, board, ini, brief, from: 'meeting', step: 2 }) — three directions, each specimen
|
|
16
|
+
* proved before it shows. So round 1 waits under the initiative's ✦ at minute 0. In the meeting, ✓ on a Show it? offer starts the next round
|
|
17
|
+
* (lib/routes-meeting-focus.js). Nothing is written to a product repository; the specimens stay in the runtime folder (D60, D65).
|
|
18
|
+
*
|
|
19
|
+
* LEDGER <runtime>/idle-lab/meeting-prewarm.jsonl, append-only:
|
|
20
|
+
* { at, kind: 'start', key, ws, ini, event, round } a round started for a meeting
|
|
21
|
+
* { at, kind: 'fail', key, ws, ini, event, error } it could not start (it counts as tried, so it waits 7 days)
|
|
22
|
+
*
|
|
23
|
+
* KIND · JOB · AHEAD_MS · RETRY_MS
|
|
24
|
+
* namesOf(event, material) PURE → [text] the lines that can name an initiative
|
|
25
|
+
* named(texts, ini, event) PURE → boolean
|
|
26
|
+
* candidates({ events, products, material, now, tried, waiting, running }) PURE → [{ kind, ws, board, ini, title, event, key, why, brief }]
|
|
27
|
+
* read(rt) · tried(rt) → Map key → ms of its last try
|
|
28
|
+
* create(deps) → { tick(turn), status() }
|
|
29
|
+
*/
|
|
30
|
+
const fs = require('fs');
|
|
31
|
+
const path = require('path');
|
|
32
|
+
const F = require('./meeting-focus.js');
|
|
33
|
+
|
|
34
|
+
const KIND = 'prototype-meeting';
|
|
35
|
+
const JOB = 'meeting-prewarm';
|
|
36
|
+
const AHEAD_MS = 60 * 60000; // a meeting in the next hour
|
|
37
|
+
const RETRY_MS = 7 * 864e5; // the idle lab's retry: a key that was tried waits a week
|
|
38
|
+
const EARLY = /triage|discover|intake|idea/i;
|
|
39
|
+
const CLOSED = /^(done|stopped|archived|won't do|closed)$/i;
|
|
40
|
+
const PROTO_GROUPS = new Set(['prototyped', 'improved']);
|
|
41
|
+
|
|
42
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
43
|
+
const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
44
|
+
const fileOf = (rt) => path.join(rt, 'idle-lab', 'meeting-prewarm.jsonl');
|
|
45
|
+
const clock = (ms) => { const d = new Date(ms); return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); };
|
|
46
|
+
|
|
47
|
+
/** PURE. The lines of a meeting that can name an initiative: its title, purpose, invite lines, and its material's titles and paths. */
|
|
48
|
+
function namesOf(event, material) {
|
|
49
|
+
const e = event || {};
|
|
50
|
+
const out = [str(e.title), str(e.purpose), str(e.description).slice(0, 2000)];
|
|
51
|
+
for (const t of F.topicsFrom(e, null)) out.push(t.text);
|
|
52
|
+
for (const m of Array.isArray(material) ? material : []) {
|
|
53
|
+
const it = (m && m.item) || m || {};
|
|
54
|
+
out.push(str(it.title), str(it.ref), str(m && m.topic));
|
|
55
|
+
}
|
|
56
|
+
return out.filter(Boolean);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** PURE. Does one of the lines name the initiative? By id (as a whole word), by the meeting's own initiative, or by a title of two words or more. */
|
|
60
|
+
function named(texts, ini, event) {
|
|
61
|
+
const e = event || {};
|
|
62
|
+
const own = e.initiative && typeof e.initiative === 'object' ? e.initiative.id : e.initiative;
|
|
63
|
+
if (own && String(own) === ini.ini) return true;
|
|
64
|
+
const hay = (texts || []).map((t) => ' ' + F.norm(t) + ' ');
|
|
65
|
+
const id = F.norm(ini.ini);
|
|
66
|
+
if (id && hay.some((h) => h.includes(' ' + id + ' '))) return true;
|
|
67
|
+
const title = F.norm(ini.title);
|
|
68
|
+
if (title && title !== id && title.split(' ').length >= 2 && hay.some((h) => h.includes(' ' + title + ' '))) return true;
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** PURE. The prototype-meeting candidates, soonest meeting first, at most one per initiative.
|
|
73
|
+
* events: calendar events [{ id, title, at, end, initiative?, steps?, purpose? }]; products: as the idle lab reads them
|
|
74
|
+
* [{ ws, inis: [{ ini, board, title, stage, closed }], P (lib/proposals.js fold) }]; material(event) → its items;
|
|
75
|
+
* waiting(P, ini) → the open round or null; running(ini) → boolean; tried: Map key → ms. */
|
|
76
|
+
function candidates({ events = [], products = [], material = () => [], now = Date.now(), tried = new Map(), waiting = () => null, running = () => false } = {}) {
|
|
77
|
+
const soon = (events || []).filter((e) => { const s = Date.parse(e && e.at); return e && e.id && Number.isFinite(s) && s > now && s - now <= AHEAD_MS && !e.declined && !e.cancelled; })
|
|
78
|
+
.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
|
|
79
|
+
const out = []; const seen = new Set();
|
|
80
|
+
for (const ev of soon) {
|
|
81
|
+
let mat = []; try { mat = material(ev) || []; } catch { mat = []; }
|
|
82
|
+
const texts = namesOf(ev, mat);
|
|
83
|
+
for (const pr of products || []) {
|
|
84
|
+
if (!pr || !pr.ws) continue;
|
|
85
|
+
const props = pr.P && pr.P.props ? [...pr.P.props.values()] : [];
|
|
86
|
+
for (const i of pr.inis || []) {
|
|
87
|
+
if (!i || !i.ini || i.closed || CLOSED.test(str(i.stage)) || (i.stage && !EARLY.test(i.stage))) continue;
|
|
88
|
+
const key = `proto-meeting:${pr.ws}:${i.ini}`;
|
|
89
|
+
if (seen.has(key)) continue;
|
|
90
|
+
if (!named(texts, i, ev)) continue;
|
|
91
|
+
if (props.some((p) => p && p.ini === i.ini && PROTO_GROUPS.has(p.group))) continue; // it has a prototype already
|
|
92
|
+
let w = null; try { w = waiting(pr.P, i.ini); } catch { w = null; }
|
|
93
|
+
if (w) continue; // no second round while one waits
|
|
94
|
+
let r = false; try { r = !!running(i.ini); } catch { r = false; }
|
|
95
|
+
if (r) continue;
|
|
96
|
+
if (tried.has(key) && now - tried.get(key) < RETRY_MS) continue;
|
|
97
|
+
seen.add(key);
|
|
98
|
+
const at = Date.parse(ev.at);
|
|
99
|
+
const title = one(i.title || i.ini, 120);
|
|
100
|
+
out.push({ kind: KIND, ws: pr.ws, board: i.board || '', ini: i.ini, title, key,
|
|
101
|
+
event: { id: String(ev.id), title: one(ev.title, 160), at: ev.at },
|
|
102
|
+
why: `"${one(ev.title, 80)}" at ${clock(at)} names it, and it has no prototype yet.`,
|
|
103
|
+
brief: `Round 1 for the meeting "${one(ev.title, 120)}": show 3 different ways ${title} could look and work, so the room can react to something real.` });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function read(rt) {
|
|
111
|
+
let raw = ''; try { raw = fs.readFileSync(fileOf(rt), 'utf8'); } catch { return []; }
|
|
112
|
+
const out = [];
|
|
113
|
+
for (const l of raw.split('\n')) { if (!l.trim()) continue; try { out.push(JSON.parse(l)); } catch { /* a torn line */ } }
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
function tried(rt) {
|
|
117
|
+
const m = new Map();
|
|
118
|
+
for (const l of read(rt)) if (l && l.key) m.set(l.key, Math.max(m.get(l.key) || 0, Number(l.at) || 0));
|
|
119
|
+
return m;
|
|
120
|
+
}
|
|
121
|
+
function append(rt, row) {
|
|
122
|
+
fs.mkdirSync(path.dirname(fileOf(rt)), { recursive: true });
|
|
123
|
+
fs.appendFileSync(fileOf(rt), JSON.stringify(row) + '\n');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** deps: { runtimeDir(), events(now), products(), material(event)?, round?, waiting?, running?, off?(), warn?, queue? }
|
|
127
|
+
* round / waiting / running default to lib/live-round.js. */
|
|
128
|
+
function create(deps = {}) {
|
|
129
|
+
const warn = deps.warn || (() => {});
|
|
130
|
+
const LR = () => { try { return require('./live-round.js'); } catch { return null; } };
|
|
131
|
+
const roundOf = () => deps.round || (LR() && LR().round) || null;
|
|
132
|
+
let busy = false; let last = null; let cache = { at: 0, p: null };
|
|
133
|
+
|
|
134
|
+
async function tick(turn = {}) {
|
|
135
|
+
const now = turn.now || Date.now();
|
|
136
|
+
const rt = deps.runtimeDir ? deps.runtimeDir() : null;
|
|
137
|
+
if (!rt || busy) return { started: null, busy };
|
|
138
|
+
if (deps.off) { let o = null; try { o = deps.off(); } catch { o = null; } if (o) return (last = { started: null, off: o }); }
|
|
139
|
+
const round = roundOf();
|
|
140
|
+
if (typeof round !== 'function') return (last = { started: null, why: 'live rounds are not in this version' });
|
|
141
|
+
let events = []; try { events = deps.events(now) || []; } catch (e) { warn('meeting prewarm events', e); events = []; }
|
|
142
|
+
if (!events.some((e) => { const t = Date.parse(e && e.at); return Number.isFinite(t) && t > now && t - now <= AHEAD_MS; })) return (last = { started: null });
|
|
143
|
+
// the products are read at most every 5 minutes, and only when a meeting is in the next hour
|
|
144
|
+
if (!cache.p || now - cache.at > 5 * 60000) { try { cache = { at: now, p: deps.products() || [] }; } catch (e) { warn('meeting prewarm products', e); cache = { at: now, p: [] }; } }
|
|
145
|
+
const products = cache.p;
|
|
146
|
+
const lr = LR();
|
|
147
|
+
const cands = candidates({ events, products, now, tried: tried(rt),
|
|
148
|
+
material: deps.material || ((ev) => require('./meeting-material.js').forMeeting(rt, ev)),
|
|
149
|
+
waiting: deps.waiting || (lr && lr.waiting) || (() => null),
|
|
150
|
+
running: deps.running || (lr && lr.running) || (() => false) });
|
|
151
|
+
const c = cands[0];
|
|
152
|
+
if (!c) return (last = { started: null });
|
|
153
|
+
busy = true;
|
|
154
|
+
try {
|
|
155
|
+
let r;
|
|
156
|
+
try { r = await round({ ws: c.ws, board: c.board || undefined, ini: c.ini, brief: c.brief, from: 'meeting', step: 2, by: null }); } catch (e) { r = { ok: false, error: (e && e.message) || 'the round did not start' }; }
|
|
157
|
+
const base = { at: now, key: c.key, ws: c.ws, ini: c.ini, event: c.event };
|
|
158
|
+
if (r && r.ok) { append(rt, { ...base, kind: 'start', round: r.round && r.round.id ? String(r.round.id) : null }); return (last = { started: c.ini, kind: KIND, round: r.round || null }); }
|
|
159
|
+
append(rt, { ...base, kind: 'fail', error: one(r && r.error, 200) || 'no answer' });
|
|
160
|
+
return (last = { started: null, failed: c.ini, error: r && r.error });
|
|
161
|
+
} finally { busy = false; }
|
|
162
|
+
}
|
|
163
|
+
if (deps.queue && typeof deps.queue.register === 'function') deps.queue.register(JOB, (turn) => { tick(turn).catch((e) => warn('meeting prewarm tick', e)); });
|
|
164
|
+
return { tick, status: () => last };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
module.exports = { KIND, JOB, AHEAD_MS, RETRY_MS, namesOf, named, candidates, read, tried, create, fileOf };
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* live-round.js — the live round (initiative live-round, W1 of "live prototyping", Wawan "Build" 2026-11-17; brief
|
|
3
|
+
* /mnt/project-files/live-round/briefs.md, doc WLChVojr1PbQjowmHnSQxE). The PM asks to see an idea, at any moment: alone in the initiative
|
|
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
|
+
* 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
|
+
*
|
|
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.
|
|
11
|
+
*
|
|
12
|
+
* 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
|
+
* new THREE headless runs in parallel, one specimen each (origin `live-round:<ws>:<ini>:<run>:<A|B|C>`, headless kind `live-round`:
|
|
14
|
+
* Read and Glob, and Write only in the run's own folder <runtime>/idle-lab/specimens/<round>/<key>/). Files group `prototyped`.
|
|
15
|
+
* feedback ONE run on the base specimen (it reads the earlier file). Files group `improved`, `changed` = the PM's sentence.
|
|
16
|
+
* Each run gets a per-product scaffold (scaffoldOf: the product's tokens.css and the head of its components.css, else PMOS's own), the
|
|
17
|
+
* initiative's name, description and Intent, and the viewport pin (dry run finding a: 2 of 9 ran wider than the phone and were cut off).
|
|
18
|
+
* A 2-minute budget: a run past it is stopped and its slot says "not made" with the reason.
|
|
19
|
+
* PROOF PER FILE (proven-only rule). PMOS watches each run's folder. When a file lands and stops growing it opens it in a headless browser
|
|
20
|
+
* (lib/idle-lab-engine.js renderCheck, at desk width and at 390 px: a version wider than the phone is not proven) and only then puts it on the card. The card exists from the start, so the PM sees honest state: a
|
|
21
|
+
* slot is working, made (a thumbnail) or not made (why). Nothing is written to a product repository before ✓ (D60, D65).
|
|
22
|
+
* LESSONS. Every feedback sentence is a Lessons line of the experiment (lib/artefacts.js); ✓ and ✕ add theirs (lib/routes-proposals.js).
|
|
23
|
+
* The specimens a round made are Specimens lines; the one the PM keeps is its `kept` field.
|
|
24
|
+
*
|
|
25
|
+
* THE LEDGERS. The proposal lines are lib/proposals.js's (one id per round; the newest line for an id wins, so each proven file rewrites it).
|
|
26
|
+
* Each run's start and end are lines of <runtime>/idle-lab/runs.jsonl (job `live-round`), so its cost counts with the idle lab's.
|
|
27
|
+
*
|
|
28
|
+
* JOB · BUDGET_MS · KEYS · DEFAULT_DIRECTIONS · ORIGIN
|
|
29
|
+
* intentOf(text, { waiting }) PURE → { kind: 'new' | 'feedback', brief, base? } | null what a chat sentence asks for
|
|
30
|
+
* parseDirs(text) PURE → [{ key, title }] | null "A: …|B: …|C: …"
|
|
31
|
+
* askOf({ ini, board, brief, directions, base?, round?, from? }) PURE → the ✦ ask's proposal line (without at/by)
|
|
32
|
+
* waiting(P, ini) PURE → the open round on the initiative { id, group, round, keys } | null (P: lib/proposals.js fold; keys: the
|
|
33
|
+
* 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
|
|
35
|
+
* promptOf(o) PURE · scaffoldOf(roots) → { css, from }
|
|
36
|
+
* create(deps) → { start(input), propose(input), cancel(id, why), running(ini), status() } and the module-level shortcuts below,
|
|
37
|
+
* round(input) → Promise<{ ok, round: { id, n, keys, directions }, runs } | { ok: false, error }> once create() ran (W2 builds on it)
|
|
38
|
+
*/
|
|
39
|
+
const fs = require('fs');
|
|
40
|
+
const path = require('path');
|
|
41
|
+
const crypto = require('crypto');
|
|
42
|
+
const PR = require('./proposals.js');
|
|
43
|
+
const LAB = require('./idle-lab.js');
|
|
44
|
+
const E = require('./idle-lab-engine.js');
|
|
45
|
+
|
|
46
|
+
const JOB = 'live-round';
|
|
47
|
+
const ORIGIN = 'live-round';
|
|
48
|
+
const BUDGET_MS = 2 * 60 * 1000;
|
|
49
|
+
const KEYS = Object.freeze(['A', 'B', 'C']);
|
|
50
|
+
const DEFAULT_DIRECTIONS = Object.freeze([
|
|
51
|
+
Object.freeze({ key: 'A', title: 'Summary first: the plainest layout, a few rows and a quiet meta line' }),
|
|
52
|
+
Object.freeze({ key: 'B', title: 'The one thing that matters most leads; the rest folds away' }),
|
|
53
|
+
Object.freeze({ key: 'C', title: 'A different shape: a timeline, a stack of cards or a step-by-step flow' }),
|
|
54
|
+
]);
|
|
55
|
+
const SCAFFOLD_MAX = 12000;
|
|
56
|
+
const FROM = Object.freeze({ chat: 'Your ask in the initiative chat', cli: 'pmos lab round', meeting: 'Said in the meeting' });
|
|
57
|
+
|
|
58
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
59
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
60
|
+
const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
61
|
+
const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 10);
|
|
62
|
+
const ms = (iso) => Date.parse(iso || '') || 0;
|
|
63
|
+
|
|
64
|
+
/* ── what a sentence asks for ── */
|
|
65
|
+
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
|
+
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. */
|
|
69
|
+
function intentOf(text, { waiting = null } = {}) {
|
|
70
|
+
const t = one(text, 600);
|
|
71
|
+
if (!t || t.startsWith('/')) return null;
|
|
72
|
+
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 };
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
/** 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. */
|
|
78
|
+
function parseDirs(text) {
|
|
79
|
+
const parts = String(text == null ? '' : text).split(/\s*[|\n]\s*/).map((x) => x.trim()).filter(Boolean);
|
|
80
|
+
const out = [];
|
|
81
|
+
for (const p of parts) {
|
|
82
|
+
const m = /^([A-C])\s*[:.)\-–—·]\s*(.{2,})$/.exec(p);
|
|
83
|
+
if (!m || out.some((x) => x.key === m[1])) return null;
|
|
84
|
+
out.push({ key: m[1], title: one(m[2], 140) });
|
|
85
|
+
}
|
|
86
|
+
return out.length >= 2 && out.length <= 3 ? out : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* ── the ✦ ask ── */
|
|
90
|
+
const askId = (ini, brief, base) => PR.idOf(ini, 'live', base ? 'feedback' : 'new', hash(one(brief, 600) + '|' + (base || '')));
|
|
91
|
+
/** PURE. The ✦ ask's proposal line, without at and by. */
|
|
92
|
+
function askOf({ ini, board = '', brief, directions = DEFAULT_DIRECTIONS, base = '', round = 0, title = '', from = 'chat' }) {
|
|
93
|
+
const b = one(brief, 300);
|
|
94
|
+
const src = [{ label: FROM[from] || FROM.chat }];
|
|
95
|
+
if (base) {
|
|
96
|
+
return { kind: 'propose', ini, board, run: '', id: askId(ini, brief, base), group: 'live', type: 'feedback', section: 'check',
|
|
97
|
+
title: one(`Round ${round} of ${base}: ${b}`, 140), why: one(`PMOS will make one new version of ${base}${title ? ' (' + title + ')' : ''} from your words.`, 300),
|
|
98
|
+
sources: src, items: [], data: { brief: b, base, round, directions: [] } };
|
|
99
|
+
}
|
|
100
|
+
const d = (directions || DEFAULT_DIRECTIONS).slice(0, 3);
|
|
101
|
+
return { kind: 'propose', ini, board, run: '', id: askId(ini, brief, ''), group: 'live', type: 'new', section: 'check',
|
|
102
|
+
title: one(`PMOS will show ${d.length} ways: ${b}`, 140), why: one(d.map((x) => x.key + ' · ' + x.title).join('; '), 300),
|
|
103
|
+
sources: src, items: [], data: { brief: b, directions: d.map((x) => ({ key: x.key, title: one(x.title, 140) })) } };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/* ── what waits, and what a feedback round builds on ── */
|
|
107
|
+
function stateOf(P, kept, p) { return kept.has(p.id) ? 'kept' : P.drops.has(PR.sigOf(p)) ? 'dropped' : 'open'; }
|
|
108
|
+
/** PURE. The newest open prototype round on `ini` (a live one or the idle lab's): { id, group, round, keys } | null. */
|
|
109
|
+
function waiting(P, ini) {
|
|
110
|
+
if (!P) return null;
|
|
111
|
+
const kept = PR.keptIds(P);
|
|
112
|
+
const mine = [...P.props.values()].filter((p) => p.ini === ini && (p.group === 'prototyped' || p.group === 'improved') && stateOf(P, kept, p) === 'open')
|
|
113
|
+
.sort((a, b) => ms(b.at) - ms(a.at));
|
|
114
|
+
const p = mine[0];
|
|
115
|
+
if (!p) return null;
|
|
116
|
+
const d = p.data || {};
|
|
117
|
+
// the keys a feedback sentence may name: every version of the first round that rendered (a round of B keeps A and C open to feedback too)
|
|
118
|
+
const root = p.group === 'prototyped' ? p : P.props.get(d.of);
|
|
119
|
+
const keys = ((root && root.data && root.data.specimens) || []).map((s) => s.key);
|
|
120
|
+
return { id: p.id, group: p.group, round: p.group === 'improved' ? Number(d.round) || 2 : 1, keys };
|
|
121
|
+
}
|
|
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) {
|
|
124
|
+
if (!P || !KEYS.includes(key)) return null;
|
|
125
|
+
const all = [...P.props.values()].filter((p) => p.ini === ini);
|
|
126
|
+
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));
|
|
128
|
+
if (!root) return null;
|
|
129
|
+
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
|
+
const spec = root.data.specimens.find((s) => s.key === key);
|
|
131
|
+
const last = rounds.filter((r) => r.data.base === key && r.data.file).pop();
|
|
132
|
+
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 };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/* ── the scaffold and the prompt ── */
|
|
137
|
+
const stripComments = (css) => String(css || '').replace(/\/\*[\s\S]*?\*\//g, '').replace(/\n\s*\n+/g, '\n').trim();
|
|
138
|
+
/** The product's token sheet and the head of its component sheet, the first folder that has them (dry run finding b: assemble from what
|
|
139
|
+
* exists). roots: folders to look in, the product's first, PMOS's own last. → { css, from: [paths] } */
|
|
140
|
+
function scaffoldOf(roots) {
|
|
141
|
+
const rel = ['public/pm', 'workspace/public/pm', 'src/styles', 'styles', 'public/css', 'css'];
|
|
142
|
+
for (const r of roots || []) {
|
|
143
|
+
if (!r) continue;
|
|
144
|
+
for (const d of rel) {
|
|
145
|
+
const t = path.join(r, d, 'tokens.css');
|
|
146
|
+
let tokens = ''; try { tokens = fs.readFileSync(t, 'utf8'); } catch { continue; }
|
|
147
|
+
let comp = '', cf = path.join(r, d, 'components.css'); try { comp = fs.readFileSync(cf, 'utf8'); } catch { cf = null; }
|
|
148
|
+
let css = stripComments(tokens);
|
|
149
|
+
if (comp) {
|
|
150
|
+
// whole rules only: cut the component sheet at the last closing brace that fits
|
|
151
|
+
const room = Math.max(0, SCAFFOLD_MAX - css.length - 1), c = stripComments(comp);
|
|
152
|
+
const cut = c.length <= room ? c : c.slice(0, c.lastIndexOf('}', room) + 1);
|
|
153
|
+
if (cut) css += '\n' + cut;
|
|
154
|
+
}
|
|
155
|
+
return { css: css.slice(0, SCAFFOLD_MAX + 2000), from: [t, cf].filter(Boolean) };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { css: '', from: [] };
|
|
159
|
+
}
|
|
160
|
+
/** PURE. One run's prompt. o: { brief, key, title, file, info: { title, description, intent }, scaffold: { css }, base?: { file, title, abs } } */
|
|
161
|
+
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.');
|
|
164
|
+
L.push('', `The idea: ${one(o.brief, 600)}`);
|
|
165
|
+
if (info.title) L.push(`The initiative: ${one(info.title, 160)}${info.description ? ' · ' + one(info.description, 400) : ''}`);
|
|
166
|
+
if (info.intent) L.push(`What the product wants (its Intent): ${one(info.intent, 400)}`);
|
|
167
|
+
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.' : '.'));
|
|
178
|
+
if (o.scaffold && o.scaffold.css) L.push('', 'The stylesheet:', '```css', o.scaffold.css, '```');
|
|
179
|
+
return L.join('\n');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/* ── the proposal line of a round ── */
|
|
183
|
+
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 } : {}) }));
|
|
185
|
+
const ok = R.slots.filter((s) => s.state === 'ok');
|
|
186
|
+
const done = R.slots.every((s) => s.state === 'ok' || s.state === 'not made');
|
|
187
|
+
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() };
|
|
189
|
+
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
|
+
why: one(`You asked: "${R.brief}"`, 300), sources: [{ label: FROM[R.from] || FROM.chat }], items: [] };
|
|
191
|
+
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 } };
|
|
194
|
+
}
|
|
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 } };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/* ── the engine ── */
|
|
201
|
+
/**
|
|
202
|
+
* deps: { runtimeDir() → folder, product(ws) → { w: { id, root }, dir } | null, info(ws, ini) → { title, board, description?, intent? } | null,
|
|
203
|
+
* spawn(spec) → session (server spawnSession: { name, agent, ws, origin, initialInput, initiative, writePaths, addDirs, onDone }),
|
|
204
|
+
* stop(session), render?(abs) → Promise<{ ok, w, h, why? }>, artefact?(dir, line) (lib/artefacts.js set, as agent:live-round),
|
|
205
|
+
* ownRoot? (PMOS's own folder, for the scaffold), pollMs?, budgetMs?, now?() , warn(what, e) }
|
|
206
|
+
*/
|
|
207
|
+
function create(deps) {
|
|
208
|
+
const warn = deps.warn || (() => {});
|
|
209
|
+
const now = () => (deps.now ? deps.now() : Date.now());
|
|
210
|
+
const render = deps.render || ((abs) => E.renderCheck(abs, { phone: true })); // proven at 390 px too: the viewport pin
|
|
211
|
+
const pollMs = deps.pollMs || 1000;
|
|
212
|
+
const budgetMs = deps.budgetMs || BUDGET_MS;
|
|
213
|
+
const rounds = new Map(); // id → round
|
|
214
|
+
|
|
215
|
+
function lesson(dir, ini, text, by = 'agent:live-round') {
|
|
216
|
+
if (!deps.artefact || !dir) return;
|
|
217
|
+
try { deps.artefact(dir, { scope: 'experiment:' + ini, artefact: 'lessons', field: 'line', text: one(text, 600), sources: [{ label: 'live round' }] }, by); } catch (e) { warn('live round lesson', e); }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** File the ✦ ask. input: { ws, board?, ini, brief, base?, dirs? (text) | directions?, from? } → { ok, id, said } | { ok: false, error } */
|
|
221
|
+
function propose(input = {}) {
|
|
222
|
+
const c = context(input); if (c.error) return { ok: false, error: c.error };
|
|
223
|
+
const brief = one(input.brief, 600); if (!brief) return { ok: false, error: 'brief is the PM\'s sentence: what to show' };
|
|
224
|
+
const P = PR.read(c.dir);
|
|
225
|
+
let line;
|
|
226
|
+
if (input.base) {
|
|
227
|
+
const key = String(input.base).toUpperCase(), b = baseOf(P, input.ini, key);
|
|
228
|
+
if (!b) return { ok: false, error: `there is no proven specimen ${key} on this initiative yet: ask for a first round` };
|
|
229
|
+
line = askOf({ ini: input.ini, board: c.board, brief, base: key, round: b.round, title: b.title, from: input.from });
|
|
230
|
+
} else {
|
|
231
|
+
const dirs = Array.isArray(input.directions) ? input.directions : input.dirs ? parseDirs(input.dirs) : DEFAULT_DIRECTIONS;
|
|
232
|
+
if (!dirs) return { ok: false, error: 'dirs is 2 or 3 directions, "A: …|B: …|C: …"' };
|
|
233
|
+
line = askOf({ ini: input.ini, board: c.board, brief, directions: dirs, from: input.from });
|
|
234
|
+
}
|
|
235
|
+
PR.append(c.dir, { by: input.by || null }, line);
|
|
236
|
+
return { ok: true, id: line.id, said: line.title };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function context(input) {
|
|
240
|
+
const ws = str(input.ws), ini = str(input.ini);
|
|
241
|
+
if (!ws || !ini || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/.test(ini)) return { error: 'ws and ini name the product and the initiative' };
|
|
242
|
+
const pr = deps.product(ws);
|
|
243
|
+
if (!pr || !pr.dir) return { error: 'that product has no PMOS state folder' };
|
|
244
|
+
let info = null; try { info = deps.info ? deps.info(ws, ini) : null; } catch (e) { warn('live round info', e); }
|
|
245
|
+
const board = str(input.board) || (info && info.board) || '';
|
|
246
|
+
return { ws, ini, pr, dir: pr.dir, info: info || { title: ini }, board };
|
|
247
|
+
}
|
|
248
|
+
|
|
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 } */
|
|
251
|
+
function start(input = {}) {
|
|
252
|
+
const rt = deps.runtimeDir ? deps.runtimeDir() : null;
|
|
253
|
+
if (!rt) return { ok: false, error: 'no runtime state folder' };
|
|
254
|
+
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' };
|
|
256
|
+
// the off switch (`pmos ai off live-round`, or every AI job off) holds it, as it holds every other job
|
|
257
|
+
let off = null; try { off = require('./ai-guard.js').off(JOB, { env: deps.env || process.env, settingsDir: rt }); } catch { off = null; }
|
|
258
|
+
if (off) return { ok: false, error: 'live rounds are off: ' + off };
|
|
259
|
+
if (running(c.ini)) return { ok: false, error: 'a round is already running on this initiative: it ends within 2 minutes' };
|
|
260
|
+
const t = now(), id = 'lr' + t.toString(36) + crypto.randomBytes(3).toString('hex');
|
|
261
|
+
const from = FROM[input.from] ? input.from : 'chat', step = Number(input.step) === 2 ? 2 : 1;
|
|
262
|
+
const P = PR.read(c.dir);
|
|
263
|
+
let base = '', b = null, dirs;
|
|
264
|
+
if (input.base) {
|
|
265
|
+
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` };
|
|
268
|
+
dirs = [{ key: base, title: b.title }];
|
|
269
|
+
} else {
|
|
270
|
+
dirs = Array.isArray(input.directions) && input.directions.length ? input.directions : input.dirs ? parseDirs(input.dirs) : DEFAULT_DIRECTIONS;
|
|
271
|
+
if (!dirs) return { ok: false, error: 'dirs is 2 or 3 directions, "A: …|B: …|C: …"' };
|
|
272
|
+
}
|
|
273
|
+
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,
|
|
275
|
+
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: '' })),
|
|
277
|
+
timer: null, budget: null, ended: false };
|
|
278
|
+
rounds.set(id, R);
|
|
279
|
+
write(R);
|
|
280
|
+
if (base) lesson(c.dir, c.ini, `Round ${R.n} of ${base}: ${brief}`, input.by || 'agent:live-round');
|
|
281
|
+
for (const s of R.slots) launch(R, s, { info: c.info, scaffold, b });
|
|
282
|
+
R.timer = setInterval(() => { poll(R).catch((e) => warn('live round poll', e)); }, pollMs);
|
|
283
|
+
if (R.timer.unref) R.timer.unref();
|
|
284
|
+
R.budget = setTimeout(() => over(R), budgetMs);
|
|
285
|
+
if (R.budget.unref) R.budget.unref();
|
|
286
|
+
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) };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function launch(R, s, { info, scaffold, b }) {
|
|
291
|
+
const t = now();
|
|
292
|
+
s.run = R.id + '-' + s.key.toLowerCase();
|
|
293
|
+
const folder = path.join(LAB.specimenDir(R.rt), R.id, s.key);
|
|
294
|
+
s.file = R.id + '/' + s.key + '/' + s.key.toLowerCase() + '.html';
|
|
295
|
+
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; }
|
|
297
|
+
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 });
|
|
299
|
+
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
|
+
let session = null;
|
|
301
|
+
try {
|
|
302
|
+
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)] : [],
|
|
304
|
+
onDone: (res) => { ended(R, s, res).catch((e) => warn('live round end', e)); } });
|
|
305
|
+
} catch (e) { warn('live round spawn', e); }
|
|
306
|
+
s.session = session;
|
|
307
|
+
if (!session || session.state === 'exited' || session.headless !== JOB) {
|
|
308
|
+
if (session && session.state !== 'exited' && deps.stop) try { deps.stop(session); } catch { /* best effort */ }
|
|
309
|
+
notMade(R, s, (session && session.note) || 'the run could not start in the background');
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function write(R) {
|
|
314
|
+
try { fs.appendFileSync(PR.ledgerFile(R.dir), JSON.stringify(roundLine(R, now())) + '\n'); } catch (e) { warn('live round proposal', e); }
|
|
315
|
+
}
|
|
316
|
+
function notMade(R, s, why) {
|
|
317
|
+
if (s.state === 'ok' || s.state === 'not made') return;
|
|
318
|
+
s.state = 'not made'; s.why = one(why, 200);
|
|
319
|
+
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
|
+
write(R); settle(R);
|
|
321
|
+
}
|
|
322
|
+
async function prove(R, s, cost = null) {
|
|
323
|
+
if (s.state !== 'working') return;
|
|
324
|
+
s.state = 'proving';
|
|
325
|
+
let st = null; try { st = fs.statSync(s.abs); } catch { st = null; }
|
|
326
|
+
let v;
|
|
327
|
+
if (!st || !st.isFile()) v = { ok: false, why: 'the run ended without writing its file' };
|
|
328
|
+
else if (st.size > 2e6) v = { ok: false, why: 'the file is over 2 MB' };
|
|
329
|
+
else { try { v = await render(s.abs); } catch (e) { v = { ok: false, why: 'it did not open: ' + one(e && e.message, 120) }; } }
|
|
330
|
+
if (s.state !== 'proving') return; // stopped while it rendered (Undo, the budget)
|
|
331
|
+
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}`;
|
|
333
|
+
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 */ }
|
|
336
|
+
write(R); settle(R);
|
|
337
|
+
}
|
|
338
|
+
async function poll(R) {
|
|
339
|
+
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;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
async function ended(R, s, res = {}) {
|
|
348
|
+
if (s.state !== 'working') return;
|
|
349
|
+
const out = (res && res.result) || {};
|
|
350
|
+
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');
|
|
354
|
+
}
|
|
355
|
+
function over(R) {
|
|
356
|
+
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');
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function settle(R) {
|
|
363
|
+
if (R.ended || !R.slots.every((s) => s.state === 'ok' || s.state === 'not made')) return;
|
|
364
|
+
R.ended = true;
|
|
365
|
+
clearInterval(R.timer); clearTimeout(R.budget);
|
|
366
|
+
write(R);
|
|
367
|
+
// the round stays readable for status() for a while, then goes
|
|
368
|
+
const t = setTimeout(() => rounds.delete(R.id), 10 * 60 * 1000); if (t.unref) t.unref();
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Undo of a ✓ that started a round: the runs stop, and the card goes (a drop line written by PMOS, so it teaches nothing). */
|
|
372
|
+
function cancel(id, why = 'stopped: you pressed Undo') {
|
|
373
|
+
const R = rounds.get(id);
|
|
374
|
+
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); }
|
|
376
|
+
}
|
|
377
|
+
const dir = R ? R.dir : null;
|
|
378
|
+
return { ok: !!R, dir };
|
|
379
|
+
}
|
|
380
|
+
/** Undo needs the card's id when the round ended long ago: drop the newest line of that proposal. */
|
|
381
|
+
function dropCard(dir, propId) {
|
|
382
|
+
try {
|
|
383
|
+
const P = PR.read(dir), p = P.props.get(propId);
|
|
384
|
+
if (p && !P.drops.has(PR.sigOf(p))) PR.append(dir, { by: 'pmos:live-round' }, { kind: 'drop', ini: p.ini, sig: PR.sigOf(p), id: p.id, group: p.group, type: p.type });
|
|
385
|
+
return true;
|
|
386
|
+
} catch (e) { warn('live round undo', e); return false; }
|
|
387
|
+
}
|
|
388
|
+
function running(ini) { for (const R of rounds.values()) if (R.ini === ini && !R.ended) return true; return false; }
|
|
389
|
+
function status() { return [...rounds.values()].map((R) => ({ id: R.id, ws: R.ws, ini: R.ini, ended: R.ended, slots: R.slots.map((s) => ({ key: s.key, state: s.state, why: s.why })) })); }
|
|
390
|
+
|
|
391
|
+
return { start, propose, cancel, dropCard, running, status, _rounds: rounds, _poll: poll };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/* ── the module-level shortcuts (server.js calls create once; W2, the routes and the CLI route call these) ── */
|
|
395
|
+
let inst = null;
|
|
396
|
+
function install(deps) { inst = create(deps); return inst; }
|
|
397
|
+
const NOT_READY = 'live rounds are not ready: the PMOS server has not started them';
|
|
398
|
+
function round(input) { return Promise.resolve(inst ? inst.start(input) : { ok: false, error: NOT_READY }); }
|
|
399
|
+
function startNow(input) { return inst ? inst.start(input) : { ok: false, error: NOT_READY }; }
|
|
400
|
+
function proposeNow(input) { return inst ? inst.propose(input) : { ok: false, error: NOT_READY }; }
|
|
401
|
+
function cancel(id, why) { return inst ? inst.cancel(id, why) : { ok: false }; }
|
|
402
|
+
function dropCard(dir, propId) { return inst ? inst.dropCard(dir, propId) : false; }
|
|
403
|
+
function running(ini) { return inst ? inst.running(ini) : false; }
|
|
404
|
+
function status() { return inst ? inst.status() : []; }
|
|
405
|
+
|
|
406
|
+
module.exports = { JOB, ORIGIN, BUDGET_MS, KEYS, DEFAULT_DIRECTIONS, FROM, intentOf, parseDirs, askOf, waiting, baseOf, scaffoldOf, promptOf, roundLine,
|
|
407
|
+
create, install, round, startNow, proposeNow, cancel, dropCard, running, status };
|