create-pmos 0.316.0 → 0.318.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.
Files changed (43) hide show
  1. package/package.json +1 -1
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-board-test.js +2 -2
  7. package/workspace/briefing-premium-initiative-test.js +5 -10
  8. package/workspace/briefing-premium-insights-test.js +1 -1
  9. package/workspace/briefing-premium-products-test.js +9 -4
  10. package/workspace/briefing-premium-test.js +12 -10
  11. package/workspace/briefing-premium-work-test.js +1 -1
  12. package/workspace/guide/briefing-premium.md +21 -16
  13. package/workspace/lib/briefing-premium-agent.js +5 -0
  14. package/workspace/lib/capacity-governor.js +5 -3
  15. package/workspace/lib/driver-run.js +46 -7
  16. package/workspace/lib/driver.js +5 -1
  17. package/workspace/lib/headless.js +40 -3
  18. package/workspace/lib/insights-premium.js +1 -1
  19. package/workspace/lib/orchestrator-gate.js +2 -1
  20. package/workspace/lib/orchestrator-health.js +7 -3
  21. package/workspace/lib/orchestrator-quota.js +84 -0
  22. package/workspace/lib/orchestrator-spawn.js +3 -2
  23. package/workspace/lib/routes-briefing-premium.js +1 -1
  24. package/workspace/lib/routes-report-design.js +6 -2
  25. package/workspace/lib/routes-report-structure.js +27 -6
  26. package/workspace/package-lock.json +2 -2
  27. package/workspace/package.json +1 -1
  28. package/workspace/premium-studio-test.js +4 -4
  29. package/workspace/public/pm/premium-board.js +3 -2
  30. package/workspace/public/pm/premium-initiative.js +2 -1
  31. package/workspace/public/pm/premium-insights.js +3 -2
  32. package/workspace/public/pm/premium-shell.js +147 -7
  33. package/workspace/public/pm/premium-work.js +3 -1
  34. package/workspace/public/pm/premium.css +47 -2
  35. package/workspace/public/pm/premium.js +16 -23
  36. package/workspace/public/premium-board.html +2 -6
  37. package/workspace/public/premium-initiative.html +1 -5
  38. package/workspace/public/premium-insights.html +1 -5
  39. package/workspace/public/premium-work.html +2 -6
  40. package/workspace/public/premium.html +3 -7
  41. package/workspace/server.js +27 -5
  42. package/workspace/test-lists/agent-orchestrator-c.json +5 -3
  43. package/workspace/test-lists/agent-orchestrator-e2e.json +9 -0
@@ -4,7 +4,9 @@
4
4
  * jobs that need no human run headless).
5
5
  *
6
6
  * kindFor({ agent, origin, skill, env }) → 'notes' | 'skill' | 'ask' | 'drive' | 'scan-web' | 'scan-repo' | 'scan-research-web' | 'scan-research-repo' | 'report-setup' | 'report-find' | 'core-doc' | 'report-design' | 'report-structure-pull' | 'report-sample-fetch' | 'report-structure' | 'report-structure-dry' | null (null: open a pane, as before)
7
- * argsFor(kind, { modelArgs, addDirs, writePaths }) → the argv after `claude` (writePaths: the one render file a report-design job may write)
7
+ * argsFor(kind, { modelArgs, addDirs, writePaths }) → the argv after `claude` (writePaths: the one render file a report-design job may write;
8
+ * for the skill kind, the folders the run may write in, from skillWriteDirs)
9
+ * skillWriteDirs(skill, { root, scratch }) → the absolute folders a background skill run may write in: its scratch folder and the state folders its skill writes
8
10
  * parseResult(stdout) → { ok, text, isError, turns, durationMs, costUsd, denied[] }
9
11
  * streamLines(line) → { log: [lines], result: object|null } one stream-json event, for the live log
10
12
  * logLines(result, exitCode) → the lines the read-only log pane shows at the end
@@ -55,6 +57,9 @@
55
57
  * connector write tool, nothing that sends. The server validates the file before it lands. Neither kind ever runs in a pane.
56
58
  */
57
59
 
60
+ const fs = require('fs');
61
+ const path = require('path');
62
+
58
63
  // The skills whose every start runs headless: they read, file a result for PMOS, and send nothing out.
59
64
  const HEADLESS_SKILLS = Object.freeze([
60
65
  'day-check', 'calendar-sync', 'jira-sync', 'my-work-read', 'report-biweekly', 'report-template',
@@ -93,6 +98,15 @@ const REPORT_STRUCTURE_DRY_ORIGINS = Object.freeze(['report-structure-dry:']);
93
98
  // report-structure-gaps: Test pull reads ONE source for the last complete period (origin `report-structure-pull:<id>:<source>`).
94
99
  const REPORT_STRUCTURE_PULL_ORIGINS = Object.freeze(['report-structure-pull:']);
95
100
  const WRITE_PATH_KINDS = Object.freeze(['report-design', 'report-sample-fetch', 'report-structure', 'report-structure-dry', 'report-structure-pull']); // kinds whose one writable file the caller names (argsFor writePaths)
101
+ const WRITE_DIR_KINDS = Object.freeze(['skill']); // kinds whose writable folders the caller names (argsFor writePaths, each folder and what is under it)
102
+ // A background skill run reads untrusted text (Jira, mail, calendar), so it may write only in its own scratch folder and in the state folders its skill writes
103
+ // by hand. Every other write goes through a `pmos` verb, which checks what it writes. The folders are relative to <state>: `pmos/state/` if it exists, else
104
+ // `planning/` (the rule each skill states). A skill not named here writes only in its scratch folder.
105
+ const SKILL_WRITE_DIRS = Object.freeze({
106
+ 'report-biweekly': Object.freeze(['reports/biweekly', 'reports/definitions']), // its notes in the draft, and a proposed definition when none exists
107
+ 'report-template': Object.freeze(['reports']), // its notes and <slot>.data.json in <state>/reports/<template id>/; the id is the schedule's args
108
+ 'memory-groom': Object.freeze(['memory/proposals']), // the one proposal file
109
+ });
96
110
 
97
111
  // What each kind may use. Read-only search is always allowed. The notes passes write their JSON (and rename the .tmp
98
112
  // file) in their notes folder, which --add-dir opens to them; the skills also run `pmos` verbs and repository scripts.
@@ -130,7 +144,8 @@ const TOOLS = Object.freeze({
130
144
  // The pull run: the same read tools as the dry run. One source, one JSON file, no Bash, no web fetch, nothing that sends.
131
145
  'report-structure-pull': Object.freeze(['Read', 'Glob', 'Grep']),
132
146
  // `node` runs only the two repository scripts the skills name (report-biweekly, memory-groom): a bare `node *` could run anything, a send or a push included.
133
- skill: Object.freeze(['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash(pmos *)', 'Bash(node scripts/workflow-state.js)', 'Bash(node scripts/workflow-state.js *)',
147
+ // The skill runs: no Write or Edit of their own. argsFor adds Write and Edit for the folders skillWriteDirs names (its scratch folder, and its skill's state folders).
148
+ skill: Object.freeze(['Read', 'Glob', 'Grep', 'Bash(pmos *)', 'Bash(node scripts/workflow-state.js)', 'Bash(node scripts/workflow-state.js *)',
134
149
  'Bash(node scripts/pmos-memory.js *)', 'Bash(node pmos/scripts/pmos-memory.js *)',
135
150
  'Bash(git log *)', 'Bash(git status *)', 'Bash(git diff *)', 'Bash(ls *)', 'Bash(date *)']),
136
151
  });
@@ -175,6 +190,14 @@ function argsFor(kind, { modelArgs = [], addDirs = [], writePaths = [] } = {}) {
175
190
  tools.push(`Write(/${s})`, `Edit(/${s})`);
176
191
  }
177
192
  }
193
+ // A background skill run may write in the folders the server names (its scratch folder, its skill's state folders) and nowhere else: absolute paths, no wildcard of their own.
194
+ if (WRITE_DIR_KINDS.includes(kind)) {
195
+ for (const p of Array.isArray(writePaths) ? writePaths : []) {
196
+ const s = String(p || '').replace(/\/+$/, '');
197
+ if (!s.startsWith('/') || /[\s,*?()\[\]{}]/.test(s) || s.includes('..')) continue;
198
+ tools.push(`Write(/${s}/**)`, `Edit(/${s}/**)`);
199
+ }
200
+ }
178
201
  // stream-json needs --verbose in print mode; it adds the step events, and the last line is the same result object as `json`.
179
202
  const argv = ['-p', '--output-format', 'stream-json', '--verbose', '--no-session-persistence', ...modelArgs, '--allowedTools', tools.join(',')];
180
203
  // A web run gets no directory at all, whatever the caller passes: it must not be able to read the repository.
@@ -182,6 +205,20 @@ function argsFor(kind, { modelArgs = [], addDirs = [], writePaths = [] } = {}) {
182
205
  return argv;
183
206
  }
184
207
 
208
+ /** The absolute folders a background skill run may write in: its scratch folder, then the state folders SKILL_WRITE_DIRS names for its skill. */
209
+ function skillWriteDirs(skill, { root, scratch } = {}) {
210
+ const dirs = [];
211
+ if (scratch) dirs.push(path.resolve(String(scratch)));
212
+ const rel = SKILL_WRITE_DIRS[String(skill || '')];
213
+ if (rel && root) {
214
+ const r = path.resolve(String(root));
215
+ let state = path.join(r, 'planning');
216
+ try { if (fs.statSync(path.join(r, 'pmos', 'state')).isDirectory()) state = path.join(r, 'pmos', 'state'); } catch { /* no pmos/state: the state folder is planning/ */ }
217
+ for (const d of rel) dirs.push(path.join(state, d));
218
+ }
219
+ return dirs;
220
+ }
221
+
185
222
  function timeoutMs(env) {
186
223
  const n = Number((env || process.env).PMOS_HEADLESS_TIMEOUT_MS);
187
224
  return Number.isFinite(n) && n > 0 ? n : DEFAULT_TIMEOUT_MS;
@@ -293,4 +330,4 @@ function logLines(r, exitCode) {
293
330
  return out;
294
331
  }
295
332
 
296
- module.exports = { HEADLESS_SKILLS, HEADLESS_ORIGINS, ASK_ORIGINS, DRIVE_ORIGINS, SCAN_WEB_ORIGINS, SCAN_REPO_ORIGINS, SCAN_RESEARCH_WEB_ORIGINS, SCAN_RESEARCH_REPO_ORIGINS, WEB_KINDS, REPORT_SETUP_ORIGINS, REPORT_FIND_ORIGINS, CORE_DOC_ORIGINS, REPORT_DESIGN_ORIGINS, REPORT_SAMPLE_FETCH_ORIGINS, REPORT_STRUCTURE_ORIGINS, REPORT_STRUCTURE_DRY_ORIGINS, TOOLS, DEFAULT_TIMEOUT_MS, kindFor, argsFor, timeoutMs, parseResult, streamLines, outcomeOf, signedOut, SIGNED_OUT_WHY, logLines, switchedOff };
333
+ module.exports = { HEADLESS_SKILLS, HEADLESS_ORIGINS, ASK_ORIGINS, DRIVE_ORIGINS, SCAN_WEB_ORIGINS, SCAN_REPO_ORIGINS, SCAN_RESEARCH_WEB_ORIGINS, SCAN_RESEARCH_REPO_ORIGINS, WEB_KINDS, REPORT_SETUP_ORIGINS, REPORT_FIND_ORIGINS, CORE_DOC_ORIGINS, REPORT_DESIGN_ORIGINS, REPORT_SAMPLE_FETCH_ORIGINS, REPORT_STRUCTURE_ORIGINS, REPORT_STRUCTURE_DRY_ORIGINS, TOOLS, SKILL_WRITE_DIRS, DEFAULT_TIMEOUT_MS, kindFor, argsFor, skillWriteDirs, timeoutMs, parseResult, streamLines, outcomeOf, signedOut, SIGNED_OUT_WHY, logLines, switchedOff };
@@ -189,7 +189,7 @@ function build(facts) {
189
189
  const off = offOf(charts);
190
190
  const board = f.board || {};
191
191
  const model = {
192
- header: { text: (f.pending ? 'Reading the records · ' : '') + 'Real data' + (missing.length ? ' · not read: ' + missing.join(', ') : '') },
192
+ header: { text: (f.pending ? 'Reading the records · ' : '') + 'Real data' + (missing.length ? ' · not read: ' + missing.join(', ') : ''), missing },
193
193
  board: { ws: board.ws || null, id: board.id || null, name: board.name || 'Insights', switcher: (f.boards || []).map((b) => ({ ws: b.ws, id: b.id, name: b.name })) },
194
194
  charts, mine, mineGone, mineSaved: mineAll, noSeries, dashboards, rows: charts,
195
195
  findings: findings.length ? findings : [{ kind: 'calm', key: null, text: charts.length ? (charts.some((c) => c.target !== null) ? 'Nothing stands out. No measure moved much, and none is far behind its line.' : 'Nothing stands out. No measure here has a target, so the series can only be described.') : '' }],
@@ -15,7 +15,8 @@
15
15
  * <dir>/orchestrator-day.json { day, count }: runs started today, kept on disk so a restart does not reset the daily cap
16
16
  * <dir>/orchestrator-stop.json the stop switch (lib/orchestrator-ledger.js)
17
17
  * An unreadable or invalid settings file means the defaults, and the status says so. QUOTA: the Claude CLI shows no usage figure this
18
- * module can read, so `quota` is null unless the caller supplies one; the daily cap is the backstop then (PRD: never unlimited). */
18
+ * module can read. The server supplies the usage-limit hold that a failed headless run left (lib/orchestrator-quota.js gateQuota); with
19
+ * no hold, the daily cap is the backstop (PRD: never unlimited). */
19
20
  const fs = require('fs');
20
21
  const path = require('path');
21
22
  const G = require('./capacity-governor.js');
@@ -1,23 +1,27 @@
1
1
  'use strict';
2
2
  /* orchestrator-health.js — what is wrong with the machine the orchestrator works on, in words (initiative agent-orchestrator, PRD "Keeping the Mac mini up").
3
3
  *
4
- * rows({ now, stopped, lastTickAt, tickMs, diskFreeFrac, loginHeld, backup, pause }) → [{ id, level: 'warn' | 'bad', text }]
4
+ * rows({ now, stopped, lastTickAt, tickMs, diskFreeFrac, loginHeld, quotaHold, backup, pause }) → [{ id, level: 'warn' | 'bad', text }]
5
5
  * diskFreeFrac(dir) → 0..1 | null the free share of the disk that holds `dir`
6
6
  *
7
7
  * Only a problem is a row: a healthy machine returns []. `backup` = { configured, lastOkAt, lastError, isDefault?, dir? } from lib/state-backup.js. `pause` = the
8
- * task types lib/orchestrator-keeprate.js lists as never kept in 14 days.
8
+ * task types lib/orchestrator-keeprate.js lists as never kept in 14 days. `quotaHold` = { until, why } from lib/orchestrator-quota.js read(), or null.
9
9
  * Pure but for diskFreeFrac. The Briefing and the status route show these rows; no row starts or stops anything. */
10
10
  const fs = require('fs');
11
+ const Q = require('./orchestrator-quota.js');
11
12
 
12
13
  const HOUR = 3600 * 1000;
13
14
 
14
- function rows({ now = Date.now(), stopped = false, lastTickAt = null, tickMs = 60000, diskFreeFrac = null, loginHeld = false, backup = null, pause = [] } = {}) {
15
+ function rows({ now = Date.now(), stopped = false, lastTickAt = null, tickMs = 60000, diskFreeFrac = null, loginHeld = false, quotaHold = null, backup = null, pause = [] } = {}) {
15
16
  const out = [];
16
17
  if (stopped) out.push({ id: 'stopped', level: 'warn', text: 'The orchestrator is stopped. Nothing new starts until you press Resume.' });
17
18
  if (!stopped && lastTickAt !== null && now - lastTickAt > Math.max(5 * tickMs, 5 * 60000)) {
18
19
  out.push({ id: 'tick', level: 'bad', text: `The workspace has not run its background tick for ${Math.round((now - lastTickAt) / 60000)} minutes.` });
19
20
  }
20
21
  if (loginHeld) out.push({ id: 'login', level: 'bad', text: 'Claude is signed out on this computer, so background runs are on hold. Sign in again with /login in a workspace terminal.' });
22
+ if (quotaHold && Number.isFinite(quotaHold.until) && quotaHold.until > now) {
23
+ out.push({ id: 'quota', level: 'warn', text: `${quotaHold.why || 'Claude usage limit'} until ${Q.clock(quotaHold.until, now)}. No new orchestrator run starts before then; runs you start yourself are not held.` });
24
+ }
21
25
  if (Number.isFinite(diskFreeFrac)) {
22
26
  if (diskFreeFrac < 0.05) out.push({ id: 'disk', level: 'bad', text: `The disk is almost full (${Math.round(diskFreeFrac * 100)}% free).` });
23
27
  else if (diskFreeFrac < 0.15) out.push({ id: 'disk', level: 'warn', text: `The disk is getting full (${Math.round(diskFreeFrac * 100)}% free).` });
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+ /* orchestrator-quota.js — the governor's quota reading, taken from what a failed headless `claude -p` run printed (initiative agent-orchestrator,
3
+ * PRD "Capacity governor": below the quota reserve, no new orchestrator run starts). The CLI shows no usage figure, but a run that hits the
4
+ * limit says so. That run sets a hold until the reset time it names, and lib/orchestrator-gate.js starts nothing new until the hold ends.
5
+ *
6
+ * detect(text, { now }) → { until, why } | null the hold that a failed run's text asks for (pure)
7
+ * record(dir, hold, now?) writes the hold, or extends the one on file; a shorter hold never shortens a longer one
8
+ * read(dir, now?) → { until, why, at } | null the hold in force now; an ended or unreadable one is null
9
+ * gateQuota(dir, now?) → { heldUntil, reason } | null the `quota` shape lib/capacity-governor.js decide() reads
10
+ * clock(until, now) → '15:00', or 'Tue 15:00' when the reset is not today (host-local time)
11
+ *
12
+ * STATE: <dir>/orchestrator-quota.json { v: 1, until, why, at }. Only a run that FAILED is read (the caller decides), so a run whose own answer is
13
+ * about rate limits sets no hold. A text that names no reset time gets a default: 1 hour for a usage or rate limit, 15 minutes for an overloaded
14
+ * service. A hold never goes past 8 days, so a wrong epoch cannot stop the orchestrator for good. A run the PM starts by hand is never held. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+
18
+ const MIN = 60000, HOUR = 60 * MIN;
19
+ const DEFAULT_MS = HOUR, OVERLOADED_MS = 15 * MIN, MAX_MS = 8 * 24 * HOUR;
20
+ const FILE = 'orchestrator-quota.json';
21
+
22
+ const LIMIT_RE = /usage limit|rate[ _-]?limit|too many requests|\b(?:http|status|api error):?\s*429\b|limit (?:will )?resets?|out of (?:extra )?usage|weekly limit|session limit|\b\d+-hour limit|limit reached[^\n]{0,40}resets?/i;
23
+ const OVERLOADED_RE = /overloaded|\b(?:http|status|api error):?\s*529\b/i;
24
+ const EPOCH_RE = /usage limit reached\|(\d{10,13})/i;
25
+ // "resets 3pm", "reset at 15:00", "resets at 3:30 PM (Europe/London)": the next such clock time on the host's own clock.
26
+ const CLOCK_RE = /resets?\s+(?:at\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/i;
27
+
28
+ function nextClock(now, h, m) {
29
+ const d = new Date(now); d.setHours(h, m, 0, 0);
30
+ if (d.getTime() <= now) d.setDate(d.getDate() + 1);
31
+ return d.getTime();
32
+ }
33
+
34
+ function detect(text, { now = Date.now() } = {}) {
35
+ const t = String(text || '');
36
+ const overloaded = OVERLOADED_RE.test(t);
37
+ if (!LIMIT_RE.test(t) && !overloaded) return null;
38
+ let until = null;
39
+ const e = EPOCH_RE.exec(t);
40
+ if (e) { const v = +e[1]; until = e[1].length >= 13 ? v : v * 1000; }
41
+ if (until === null) {
42
+ const c = CLOCK_RE.exec(t);
43
+ if (c) {
44
+ let h = +c[1]; const m = c[2] ? +c[2] : 0, ap = c[3] ? c[3].toLowerCase() : null;
45
+ if (ap === 'pm' && h < 12) h += 12; else if (ap === 'am' && h === 12) h = 0;
46
+ if (h < 24 && m < 60) until = nextClock(now, h, m);
47
+ }
48
+ }
49
+ const limited = LIMIT_RE.test(t);
50
+ if (until === null || !Number.isFinite(until) || until <= now) until = now + (limited ? DEFAULT_MS : OVERLOADED_MS);
51
+ until = Math.min(until, now + MAX_MS);
52
+ return { until, why: limited ? 'Claude usage limit' : 'Claude is overloaded' };
53
+ }
54
+
55
+ const readJson = (f) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
56
+
57
+ function read(dir, now = Date.now()) {
58
+ const o = readJson(path.join(dir, FILE));
59
+ if (!o || !Number.isFinite(o.until) || o.until <= now) return null;
60
+ return { until: Math.min(o.until, now + MAX_MS), why: typeof o.why === 'string' ? o.why : 'Claude usage limit', at: Number.isFinite(o.at) ? o.at : null };
61
+ }
62
+
63
+ function record(dir, hold, now = Date.now()) {
64
+ if (!hold || !Number.isFinite(hold.until) || hold.until <= now) return read(dir, now);
65
+ const cur = read(dir, now);
66
+ if (cur && cur.until >= hold.until) return cur;
67
+ const o = { v: 1, until: hold.until, why: hold.why || 'Claude usage limit', at: now };
68
+ try { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, FILE), JSON.stringify(o) + '\n'); } catch { /* the daily cap is still the backstop */ }
69
+ return { until: o.until, why: o.why, at: o.at };
70
+ }
71
+
72
+ const pad = (n) => String(n).padStart(2, '0');
73
+ function clock(until, now = Date.now()) {
74
+ const d = new Date(until), n = new Date(now);
75
+ const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
76
+ return d.toDateString() === n.toDateString() ? hm : `${d.toLocaleDateString('en-US', { weekday: 'short' })} ${hm}`;
77
+ }
78
+
79
+ function gateQuota(dir, now = Date.now()) {
80
+ const h = read(dir, now);
81
+ return h ? { heldUntil: h.until, reason: `${h.why} until ${clock(h.until, now)}: no new orchestrator run starts before then.` } : null;
82
+ }
83
+
84
+ module.exports = { detect, read, record, gateQuota, clock, FILE, DEFAULT_MS, OVERLOADED_MS, MAX_MS };
@@ -6,14 +6,15 @@
6
6
  *
7
7
  * `spawn(spec)` is used ONLY by the schedule ticks (the core documents, the weekly report finder). A run the PM starts by a press uses the
8
8
  * plain spawn and is never counted or held. Before it starts a run the wrapper asks gate.mayStart. A held start returns an exited session
9
- * row with a note, which the callers already read as "could not start"; they try again on their next tick, so nothing is lost or refused.
9
+ * row with a note and `held: true`, which the callers already read as "could not start"; they try again on their next tick, so nothing is
10
+ * lost or refused. The report design and report structure ticks also use it (lib/routes-report-design.js sweep, routes-report-structure.js checks).
10
11
  * A run that started is counted toward the day's cap (gate.granted). The count of running runs adds the Driver's runs to the runs
11
12
  * started here that have not ended, so the cap covers all orchestrator work together. */
12
13
  function wrap({ gate, spawn, driverRunning = () => 0 }) {
13
14
  const live = new Set();
14
15
  const prune = () => { for (const s of [...live]) if (!s || s.state === 'exited') live.delete(s); };
15
16
  const running = () => { prune(); return live.size + (Number(driverRunning()) || 0); };
16
- function held(reason) { return { id: null, state: 'exited', headless: null, note: `held by the capacity governor: ${reason}` }; }
17
+ function held(reason) { return { id: null, state: 'exited', headless: null, held: true, note: `held by the capacity governor: ${reason}` }; }
17
18
  return {
18
19
  running,
19
20
  spawn(spec) {
@@ -75,7 +75,7 @@ async function post(req, res, url, ctx) {
75
75
  }
76
76
  if (act === 'ask') {
77
77
  let wsId; try { const w = merged && sk ? { id: sk.ws } : ctx.getWs && ctx.getWs(url.searchParams.get('ws') || null); wsId = w && w.id; } catch { wsId = undefined; }
78
- const a = Ag.ask({ runtimeDir, key: b.key, text: b.text, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || /^src:/.test(String(b.key || '')) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
78
+ const a = Ag.ask({ runtimeDir, key: b.key, text: b.text, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
79
79
  ctx.json(res, a.body, a.status);
80
80
  return true;
81
81
  }
@@ -320,10 +320,14 @@ function attach(factory) {
320
320
  });
321
321
  });
322
322
  }
323
- /** On the tick: a slot drafted after the design was saved, with no render, is rendered (a draft the CLI wrote). */
323
+ /**
324
+ * On the tick: a slot drafted after the design was saved, with no render, is rendered (a draft the CLI wrote). The render starts through
325
+ * ctx.spawnScheduled (the capacity governor) when the server gives one. A held start writes no error, so the next tick tries the slot again.
326
+ */
324
327
  function sweep(ctx) {
325
328
  if (!ctx) return [];
326
329
  lastCtx = ctx;
330
+ const sctx = typeof ctx.spawnScheduled === 'function' ? { ...ctx, spawnSession: ctx.spawnScheduled } : ctx;
327
331
  const started = [];
328
332
  const list = typeof ctx.workspaceList === 'function' ? ctx.workspaceList() : [ctx.getWs(null)].filter(Boolean);
329
333
  for (const w of list) {
@@ -350,7 +354,7 @@ function sweep(ctx) {
350
354
  if (mt < savedMs) continue;
351
355
  const sha = D.docSha(c.md);
352
356
  if (st.errors.some((e) => e.slot === c.slot && e.sha === sha)) continue;
353
- const r = startCycle(ctx, w, cadence, rel);
357
+ const r = startCycle(sctx, w, cadence, rel);
354
358
  if (r.ok) started.push(rel);
355
359
  }
356
360
  }
@@ -348,8 +348,11 @@ function failSteps(kind, stepId, reason, base) {
348
348
  return steps;
349
349
  }
350
350
 
351
- /** Start (or restart) the check of one Chrome or computer source. → { ok, check } | refusal. Never throws. */
352
- function startCheck(ctx, w, id, sourceId, { plan } = {}) {
351
+ /**
352
+ * Start (or restart) the check of one Chrome or computer source. → { ok, check } | refusal. Never throws. `scheduled` (a check the schedule tick
353
+ * starts) uses ctx.spawnScheduled, the capacity governor: a held start leaves the check as it was, so sweepHolds starts it again on a later tick.
354
+ */
355
+ function startCheck(ctx, w, id, sourceId, { plan, scheduled = false } = {}) {
353
356
  try {
354
357
  const root = w.root;
355
358
  const f = sourceOf(root, id, sourceId, plan);
@@ -395,13 +398,20 @@ function startCheck(ctx, w, id, sourceId, { plan } = {}) {
395
398
  `- Numbers to read: ${users.length ? users.map((c) => `${c.name || c.id} (${c.from || 'not said'}; ${c.how || 'not said'})`).join(' | ') : 'none named yet'}`,
396
399
  `- Step ids to report: ${S.CHECK_STEPS[kind].map(([sid]) => sid).join(', ')}`, `- Output path: ${pending}`];
397
400
  const job = { run, since: Date.now(), pending, sessionId: null, kind };
401
+ const before = S.readCheck(root, id, sourceId);
398
402
  checkJobs.set(key, job);
399
403
  writeRunning(base);
404
+ const spawn = scheduled && typeof ctx.spawnScheduled === 'function' ? ctx.spawnScheduled : ctx.spawnSession;
400
405
  let s = null;
401
406
  try {
402
- s = ctx.spawnSession({ name: 'Report source check', agent: 'claude', ws: w.id, origin: `report-source-check:${id}:${sourceId}`, cwd: p.rel,
407
+ s = spawn({ name: 'Report source check', agent: 'claude', ws: w.id, origin: `report-source-check:${id}:${sourceId}`, cwd: p.rel,
403
408
  initialInput: `${skill}\n\nThis job:\n${lines.join('\n')}\n\nWrite the JSON to the output path, then close your tab and stop. Send and change nothing.\r`, launchFlags: flags });
404
409
  } catch (e) { s = { state: 'exited', note: String((e && e.message) || e) }; }
410
+ if (s && s.held) { // held by the capacity governor: not a failed check; put back what was there and try again on a later tick
411
+ if (checkJobs.get(key) === job) checkJobs.delete(key);
412
+ try { if (before) S.writeCheck(root, id, before); else fs.unlinkSync(path.join(S.paths(root, id).checks, `${sourceId}.json`)); } catch { /* none */ }
413
+ return { ok: false, status: 409, held: true, error: s.note || 'held by the capacity governor' };
414
+ }
405
415
  if (!s || s.state === 'exited') return { ok: true, check: finishCheck(root, id, sourceId, kind, failSteps(kind, 'session', `A session could not start: ${(s && s.note) || 'no session'}`, base), { job }) };
406
416
  job.sessionId = s.id;
407
417
  return { ok: true, check: S.readCheck(root, id, sourceId) };
@@ -473,18 +483,20 @@ function draftBlock(root, id, { note } = {}) {
473
483
  * Before a scheduled draft: re-check each Chrome or computer source of the saved structure. → { hold: false, block } to draft now, or { hold: true }
474
484
  * when a check is running or failed (sweep() starts the draft later). A report with no such source drafts now.
475
485
  */
476
- function beforeDraft(ctx, w, id, sched) {
486
+ function beforeDraft(ctx, w, id, sched, { scheduled = false } = {}) {
477
487
  try {
478
488
  const root = w.root;
479
489
  const sp = savedPlan(root, id);
480
490
  if (!sp) return { hold: false, block: '' };
481
491
  if (!sp.outside.length) return { hold: false, block: draftBlock(root, id) };
482
492
  if (readHold(root, id)) return { hold: true };
493
+ const held = [];
483
494
  for (const src of sp.outside) {
484
- startCheck(ctx, w, id, src.id, { plan: sp.plan }); // a check already running (409) is the one this draft waits for
495
+ const r = startCheck(ctx, w, id, src.id, { plan: sp.plan, scheduled }); // a check already running (409) is the one this draft waits for; a held one is retried by sweepHolds
496
+ if (r && r.held) held.push(src.id);
485
497
  }
486
498
  fs.mkdirSync(S.paths(root, id).dir, { recursive: true });
487
- fs.writeFileSync(holdFile(root, id), JSON.stringify({ since: new Date().toISOString(), sched: sched ? sched.id : null, sources: sp.outside.map((s) => s.id), saved: sp.n }) + '\n');
499
+ fs.writeFileSync(holdFile(root, id), JSON.stringify({ since: new Date().toISOString(), sched: sched ? sched.id : null, sources: sp.outside.map((s) => s.id), saved: sp.n, ...(held.length ? { held } : {}) }) + '\n');
488
500
  return { hold: true };
489
501
  } catch (e) { return { hold: false, block: '' }; }
490
502
  }
@@ -501,6 +513,15 @@ function sweepHolds(ctx, w) {
501
513
  if (!hold) continue;
502
514
  try { settleChecks(ctx, w, id); } catch { /* next tick */ }
503
515
  const since = Date.parse(hold.since);
516
+ // a check the capacity governor held (hold.held) has no answer since the hold and no job: start it again (through the governor)
517
+ try {
518
+ const sp = savedPlan(w.root, id); const now = S.readChecks(w.root, id);
519
+ for (const sid of (sp && Array.isArray(hold.held) ? hold.held : [])) {
520
+ const c = now[sid];
521
+ if (checkJobs.has(checkKey(w.root, id, sid)) || (c && (c.running || Date.parse(c.at) >= since - 1000))) continue;
522
+ startCheck(ctx, w, id, sid, { plan: sp.plan, scheduled: true });
523
+ }
524
+ } catch { /* next tick */ }
504
525
  const checks = S.readChecks(w.root, id);
505
526
  const wanted = (Array.isArray(hold.sources) ? hold.sources : []).map((sid) => ({ sid, c: checks[sid] }));
506
527
  const done = wanted.every((x) => x.c && !x.c.running && Date.parse(x.c.at) >= since - 1000);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.316.0",
3
+ "version": "0.318.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.316.0",
9
+ "version": "0.318.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.316.0",
3
+ "version": "0.318.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -63,10 +63,10 @@ const saved = async () => { const j = await (await fetch(BASE + '/api/insights-p
63
63
  const open = async (sel) => { await p.click(sel); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !!document.querySelector('#oMain .stu'))); await sleep(300); };
64
64
  const shut = async () => { for (let i = 0; i < 2 && await p.evaluate(() => document.querySelector('#dlg').classList.contains('on')); i++) { await p.keyboard.press('Escape'); await sleep(150); } };
65
65
 
66
- /* O0: the crumb's Studio pill, as the mockup has it, opens the Studio on the dashboard shown */
67
- ok('O0 the crumb has a Studio pill with the sparkle', await p.evaluate(() => { const b = document.querySelector('#crAsk'); return !!b && b.textContent.trim() === 'Studio' && !!b.querySelector('svg') && b.getAttribute('aria-label') === 'Open the Insight Studio'; }));
66
+ /* O0: the bar's Chat button opens the Studio on the dashboard shown (premium-topbar: the Studio is this page's chat) */
67
+ ok('O0 the bar has the Chat button, no label, named for the Studio (premium-topbar)', await p.evaluate(() => { const b = document.querySelector('#crAsk'); return !!b && b.textContent.trim() === '' && !!b.querySelector('svg') && b.getAttribute('aria-label') === 'Open the Insight Studio'; }));
68
68
  await open('#crAsk');
69
- ok('O0b the Studio pill opens the Studio', await p.evaluate(() => /^Insight Studio · /.test(document.querySelector('#dEye').textContent)));
69
+ ok('O0b Chat opens the Studio', await p.evaluate(() => /^Insight Studio · /.test(document.querySelector('#dEye').textContent)));
70
70
  await shut();
71
71
  /* O: New dashboard opens the Studio */
72
72
  await open('#pdNew');
@@ -168,7 +168,7 @@ const saved = async () => { const j = await (await fetch(BASE + '/api/insights-p
168
168
  await q.goto(BASE + '/premium-insights.html');
169
169
  await until(() => q.evaluate(() => !!document.querySelector('#pdNew')));
170
170
  const pill = await q.evaluate(() => { const b = document.querySelector('#crAsk'), r = b.getBoundingClientRect(); return { txt: b.textContent.trim(), w: r.width, h: r.height, right: r.right, vw: innerWidth, vis: !!b.offsetParent }; });
171
- ok(`F0 at 390 px (${theme}) the Studio pill shows its label, fits the width and is as tall as the crumb's other buttons`, pill.txt === 'Studio' && pill.vis && pill.right <= pill.vw && Math.round(pill.h) >= 34, JSON.stringify(pill));
171
+ ok(`F0 at 390 px (${theme}) the Chat button shows, fits the width and is 44 px`, pill.vis && pill.right <= pill.vw && Math.round(pill.h) >= 44 && Math.round(pill.w) >= 44, JSON.stringify(pill));
172
172
  await q.click('#pdNew'); await until(() => q.evaluate(() => !!document.querySelector('#oMain .stu'))); await sleep(400);
173
173
  // measured once the dialog has finished opening: its rise animation scales the targets while it runs
174
174
  const measure = () => q.evaluate(() => {
@@ -4,7 +4,7 @@
4
4
  * and the board's own presses of pm/premium-acts.js (initiative premium-board-actions): the New asks card, New initiative, and a row's menu (move,
5
5
  * hold, cancel, archive and their Undo). Issue it on a document draft, read in a dialog, is POST /api/core-docs/issue (initiative premium-core-doc-issue). */
6
6
  import { pmPost } from './http.js';
7
- import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, AI, store, crumbHtml, wireCrumb, kv, H, openAddDoc } from './premium-shell.js';
7
+ import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, AI, store, crumbHtml, wireCrumb, kv, H, openAddDoc, setPageGaps } from './premium-shell.js';
8
8
  import { issueBody } from './premium-doc-edit.js';
9
9
  import { mountDocSheet } from './premium-doc-sheet.js';
10
10
  import * as MT from './premium-metric-tiles.js';
@@ -30,10 +30,11 @@ function drawHead() {
30
30
  if (!crumbed) {
31
31
  crumbed = true;
32
32
  const boards = M.board.switcher || [];
33
- $('#crumbHost').innerHTML = crumbHtml({ board: M.board.name || 'Board', boards, ask: 'Ask about this board' });
33
+ $('#crumbHost').innerHTML = crumbHtml({ page: 'Board', board: M.board.name || 'Board', boards, ask: 'Ask about this board' });
34
34
  wireCrumb({ boards, board: M.board.id, goBoard: (ws, id) => location.assign('/premium-board.html?ws=' + encodeURIComponent(ws) + '&board=' + encodeURIComponent(id)), ask: () => openRow(rowOf('board:this-board')) });
35
35
  }
36
36
  $('#snap').textContent = M.header.text;
37
+ setPageGaps(((M.header && M.header.missing) || []).length);
37
38
  $('#snap').title = 'Every figure on this page comes from a record of the board. A date, owner or progress shows only when one was set.';
38
39
  $('#brief').textContent = '';
39
40
  }
@@ -6,7 +6,7 @@
6
6
  * premium-board-actions, pm/premium-acts.js): move to the next stage or back, hold, cancel, archive, resume, reopen and restore, each with Undo. Nothing here issues a document. */
7
7
  import { pmPost } from './http.js';
8
8
  import { mountDocSheet } from './premium-doc-sheet.js';
9
- import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, CHEV, crumbHtml, wireCrumb, AI, openAddDoc } from './premium-shell.js';
9
+ import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, CHEV, crumbHtml, wireCrumb, AI, openAddDoc, setPageGaps } from './premium-shell.js';
10
10
  import { barHtml, onBar, closeMenu } from './premium-acts.js';
11
11
 
12
12
  let M = null; // the model
@@ -257,6 +257,7 @@ function draw() {
257
257
  }
258
258
  $('#iH1').textContent = M.title; document.title = 'PMOS · ' + M.title;
259
259
  $('#snap').textContent = M.header.text;
260
+ setPageGaps(((M.header && M.header.missing) || []).length);
260
261
  $('#snap').title = 'Every figure on this page comes from a record. A date, owner or progress shows only when one was set.';
261
262
  const keepQ = $('#dmQ') && document.activeElement === $('#dmQ');
262
263
  closeMenu();
@@ -6,7 +6,7 @@
6
6
  * draft, PRD R2 to R4). premium-studio-chart adds a saved chart (POST /api/premium-charts/save, PRD C1, C10) and its four forms (C3). premium-studio-report
7
7
  * adds New report and Shape it in the Studio, whose presses are POST /api/report-setups/setup | from-dashboard and POST /api/report-structure/turn | remove |
8
8
  * revert | accept (PRD R5 to R8). Nothing else posts, and nothing is sent outward. */
9
- import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv } from './premium-shell.js';
9
+ import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps } from './premium-shell.js';
10
10
  import { pmPost, pmGet } from './http.js';
11
11
  import { openStudio } from './premium-studio.js';
12
12
  import { openReport } from './premium-report-read.js';
@@ -28,10 +28,11 @@ function drawHead() {
28
28
  if (!crumbed) {
29
29
  crumbed = true;
30
30
  const boards = M.board.switcher || [];
31
- $('#crumbHost').innerHTML = crumbHtml({ board: M.board.name || 'Insights', boards, ask: 'Open the Insight Studio', label: 'Studio' });
31
+ $('#crumbHost').innerHTML = crumbHtml({ page: 'Insights', board: M.board.name || 'Insights', boards, ask: 'Open the Insight Studio' });
32
32
  wireCrumb({ boards, board: M.board.id, goBoard: (ws, id) => location.assign('/premium-insights.html?ws=' + encodeURIComponent(ws) + '&board=' + encodeURIComponent(id)), ask: () => { const D = curDash(); if (D && D.saved) openDashEdit(D); else if (M.charts.length) openDashEdit(null); else openReportEdit(null); } }); // the mockup's Studio pill: the saved dashboard shown, else a new dashboard, else a report when no measure has a series
33
33
  }
34
34
  $('#snap').textContent = M.header.text;
35
+ setPageGaps(((M.header && M.header.missing) || []).length);
35
36
  $('#snap').title = 'Every figure on this page comes from a KR metric record. A measure with fewer than two readings is listed, not drawn.';
36
37
  $('#brief').textContent = M.empty || '';
37
38
  }