create-pmos 0.316.0 → 0.317.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.316.0",
3
+ "version": "0.317.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@2924deb
1
+ kernel-source: pmos@01b4719
2
2
  assembled: 2026-10-19
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-10-19T13:57:37Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T14:26:43Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-10-19T13:57:37Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T14:26:43Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-10-19T13:57:37Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-19T14:26:43Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -14,8 +14,8 @@
14
14
  *
15
15
  * It only decides whether a NEW run may start. It never ends a run: a run in progress drains by itself when the PM comes back.
16
16
  * A run the PM starts by hand is not its business (see session-budget.js).
17
- * Quota: when the CLI's remaining usage is known and below the reserve, nothing starts. When it is not known, the daily cap
18
- * is the backstop, so an unreadable quota never means unlimited.
17
+ * Quota: when the CLI's remaining usage is known and below the reserve, nothing starts; nor before a usage-limit hold ends. When it is
18
+ * not known, the daily cap is the backstop, so an unreadable quota never means unlimited.
19
19
  * Pure but for memFreeFrac and cpuPerCore, which take their readers as arguments. */
20
20
  const fs = require('fs');
21
21
  const os = require('os');
@@ -71,7 +71,8 @@ function modeOf({ now, lastActivityAt, settings } = {}) {
71
71
  return inHours && active ? 'working' : 'away';
72
72
  }
73
73
 
74
- /** load: { memFreeFrac: 0..1 | null, cpuPerCore: number | null }; quota: { remainingPct: 0..100 } | null. */
74
+ /** load: { memFreeFrac: 0..1 | null, cpuPerCore: number | null }; quota: { remainingPct?: 0..100, heldUntil?: ms, reason? } | null.
75
+ * heldUntil is a hold set by a run that hit the usage limit (lib/orchestrator-quota.js): nothing starts before it. */
75
76
  function decide({ now, lastActivityAt, settings, running = 0, startedToday = 0, load, quota, stopped = false } = {}) {
76
77
  const s = settings || DEFAULTS;
77
78
  const mode = modeOf({ now, lastActivityAt, settings: s });
@@ -80,6 +81,7 @@ function decide({ now, lastActivityAt, settings, running = 0, startedToday = 0,
80
81
  if (stopped) return no('The orchestrator is stopped.');
81
82
  if (running >= cap) return no(`${running} orchestrator runs are live (limit ${cap} while ${mode}).`);
82
83
  if (startedToday >= s.dailyCap) return no(`${startedToday} runs started today (daily limit ${s.dailyCap}).`);
84
+ if (quota && Number.isFinite(quota.heldUntil) && quota.heldUntil > now) return no(quota.reason || 'Claude usage limit reached: no new run starts until it resets.');
83
85
  if (quota && Number.isFinite(quota.remainingPct) && quota.remainingPct < s.quotaReservePct) {
84
86
  return no(`Claude usage left is ${Math.round(quota.remainingPct)}%, below the ${s.quotaReservePct}% reserve.`);
85
87
  }
@@ -23,6 +23,24 @@ const path = require('path');
23
23
  const D = require('./driver.js');
24
24
  const facts = require('./driver-facts.js');
25
25
  const proactive = require('./proactive.js');
26
+ const crypto = require('crypto');
27
+ const tasks = require('./orchestrator-ledger.js');
28
+
29
+ /* agent-orchestrator (done-criterion 7): every wake a run answers is one task in the orchestrator's task ledger (tasks.jsonl, beside
30
+ * driver.jsonl). A run start starts its tasks; a run end finishes them. After a restart, lib/orchestrator-ledger.js recover() decides:
31
+ * a task on its first run is requeued, so the dead run's `run-end` hands its wake back to the queue and ONE more run answers it;
32
+ * a task on its second run fails with its reason and is not started again. The ledger is the orchestrator's, not a control-graph record. */
33
+ const taskIdOf = (wakeKey) => 'driver.' + crypto.createHash('sha1').update(String(wakeKey)).digest('hex').slice(0, 16);
34
+ function tasksStart(dir, wakeLines, runId, now) {
35
+ for (const w of wakeLines) {
36
+ const id = taskIdOf(w.key);
37
+ tasks.open(dir, { id, job: 'driver', trigger: w.reason, subject: w.key }, now);
38
+ tasks.started(dir, id, runId, now);
39
+ }
40
+ }
41
+ function tasksEnd(dir, wakeKeys, outcome, now) {
42
+ for (const k of wakeKeys || []) tasks.finished(dir, taskIdOf(k), outcome, now);
43
+ }
26
44
 
27
45
  // A run that fails because the Claude login has expired fails again for every other target. Holding the next runs for this long (their
28
46
  // wakes stay queued) stops one expired login from filing hundreds of failed runs; the first run after the wait is the probe.
@@ -98,7 +116,9 @@ function create(deps) {
98
116
  const board = group.board || null;
99
117
  if (!skill) {
100
118
  D.append(file, { ev: 'run-start', run: runId, target: group.target, board, wakes: group.wakes, session: null }, { now });
101
- D.append(file, { ev: 'run-end', run: runId, ok: false, reason: `the ${kind === 'work' ? 'work-unblock' : 'initiative-drive'} skill is not installed`, agent_run: agentRun(runId, group.target, false, now) }, { now });
119
+ const reason = `the ${kind === 'work' ? 'work-unblock' : 'initiative-drive'} skill is not installed`;
120
+ D.append(file, { ev: 'run-end', run: runId, ok: false, reason, agent_run: agentRun(runId, group.target, false, now) }, { now });
121
+ taskLedger(() => { tasksStart(path.dirname(file), wakeLines, runId, now); tasksEnd(path.dirname(file), group.wakes, { ok: false, reason }, now); });
102
122
  return;
103
123
  }
104
124
  const prompt = `${skill}\n\nThis run:\n${describe(w, group.target, wakeLines, state, factsNow).map((l) => '- ' + l).join('\n')}\n\nFile every result with \`pmos driver propose\`. Send nothing, edit nothing.`;
@@ -107,7 +127,7 @@ function create(deps) {
107
127
  session = deps.spawn({
108
128
  name: `Driver · ${kind} ${group.target.id}`, ws: w.id, origin: `drive:${kind}:${group.target.id}`, initialInput: prompt + '\r',
109
129
  initiative: kind === 'initiative' ? group.target.id : undefined,
110
- onDone: (r) => endRun(file, runId, group.target, r),
130
+ onDone: (r) => endRun(file, runId, group.target, r, group.wakes),
111
131
  });
112
132
  } catch (e) { warn('driver run', e); }
113
133
  D.append(file, { ev: 'run-start', run: runId, target: group.target, board, wakes: group.wakes, session: session ? session.id : null }, { now });
@@ -115,16 +135,22 @@ function create(deps) {
115
135
  // A start that did not become a headless run (no `claude` on the PATH, a refused model choice, a pane because headless
116
136
  // is off) is a failed run. It counts against the day, as every failed run does. Never leave a driver in a pane.
117
137
  if (session && session.headless !== 'drive' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
118
- D.append(file, { ev: 'run-end', run: runId, ok: false, reason: (session && session.note) || 'the run could not start as a background run', agent_run: agentRun(runId, group.target, false, now) }, { now });
138
+ const reason = (session && session.note) || 'the run could not start as a background run';
139
+ D.append(file, { ev: 'run-end', run: runId, ok: false, reason, agent_run: agentRun(runId, group.target, false, now) }, { now });
140
+ taskLedger(() => { tasksStart(path.dirname(file), wakeLines, runId, now); tasksEnd(path.dirname(file), group.wakes, { ok: false, reason }, now); });
119
141
  return;
120
142
  }
121
143
  active.set(runId, { target: group.target, ledger: file, session: session.id });
144
+ taskLedger(() => tasksStart(path.dirname(file), wakeLines, runId, now));
122
145
  }
123
146
 
124
147
  const agentRun = (runId, target, ok, now) => ({ run_id: runId, initiative_id: target.kind === 'initiative' ? target.id : null, kind: 'driver', target_kind: target.kind,
125
148
  ok, human_corrections: 0, builder_model: 'not recorded in the repo', created_at: new Date(now == null ? Date.now() : now).toISOString() });
126
149
 
127
- function endRun(file, runId, target, r) {
150
+ // The task ledger is bookkeeping for the restart: a failed write is reported and never stops or fails a run.
151
+ function taskLedger(fn) { try { fn(); } catch (e) { warn('orchestrator task ledger', e); } }
152
+
153
+ function endRun(file, runId, target, r, wakeKeys) {
128
154
  active.delete(runId);
129
155
  const res = (r && r.result) || {};
130
156
  const ok = !!(r && !r.timedOut && !r.stopped && r.code === 0 && res.ok && !res.isError);
@@ -135,6 +161,7 @@ function create(deps) {
135
161
  D.append(file, { ev: 'run-end', run: runId, ok, ...(reason ? { reason } : {}), ...(res.denied && res.denied.length ? { denied: res.denied } : {}),
136
162
  agent_run: agentRun(runId, target, ok) });
137
163
  } catch (e) { warn('driver run end', e); }
164
+ taskLedger(() => tasksEnd(path.dirname(file), wakeKeys, { ok, reason }));
138
165
  }
139
166
 
140
167
  /* `sweepNow` (Refresh now, data-refresh-settings R8) runs the unblock sweep at once, inside or outside the window. */
@@ -153,9 +180,21 @@ function create(deps) {
153
180
  try {
154
181
  let state = readState(file);
155
182
  if (!state.epoch) { D.append(file, { ev: 'epoch' }, { now }); state = readState(file); summary.epoch++; }
156
- // Runs that were alive when the server stopped are over; they keep their place in the day's count.
157
- for (const r of state.runs.values()) {
158
- if (!r.end && !active.has(r.run)) D.append(file, { ev: 'run-end', run: r.run, ok: false, reason: 'interrupted: the workspace restarted', agent_run: agentRun(r.run, r.target, false, now) }, { now });
183
+ // Runs that were alive when the server stopped are over; they keep their place in the day's count. The task ledger decides
184
+ // what happens to their wakes (agent-orchestrator, criterion 7): a first interruption hands them back to the queue (`requeue`),
185
+ // so one more run answers them; a second fails them with the reason. A run from before the task ledger has no task: it only ends.
186
+ const dead = [...state.runs.values()].filter((r) => !r.end && !active.has(r.run));
187
+ if (dead.length) {
188
+ let rec = { requeued: [], failed: [] };
189
+ taskLedger(() => { rec = tasks.recover(dir, new Set(active.keys()), now); });
190
+ const requeued = new Set(rec.requeued); const failed = new Set(rec.failed);
191
+ for (const r of dead) {
192
+ const requeue = r.wakes.filter((k) => requeued.has(taskIdOf(k)));
193
+ const twice = r.wakes.some((k) => failed.has(taskIdOf(k)));
194
+ const reason = 'interrupted: the workspace restarted' + (requeue.length ? '; it runs once more' : twice ? '; interrupted twice, not started again' : '');
195
+ D.append(file, { ev: 'run-end', run: r.run, ok: false, reason, ...(requeue.length ? { requeue } : {}), agent_run: agentRun(r.run, r.target, false, now) }, { now });
196
+ }
197
+ state = readState(file);
159
198
  }
160
199
  const boardOf = (id) => { try { return deps.boardOf(w, id); } catch { return null; } };
161
200
  let created = [];
@@ -30,7 +30,8 @@
30
30
  * pause|resume { target, by } · mode { board, mode, by } PM only, as above. `board` '*' is every board.
31
31
  * wake { key, target, board, reason: created|moved|answered|stuck, blocker? } queued: a run should start
32
32
  * run-start { run, target, board, wakes: [key], session } one per run
33
- * run-end { run, ok, reason?, agent_run } agent_run is the run record the correction rate reads
33
+ * run-end { run, ok, reason?, agent_run, requeue? } agent_run is the run record the correction rate reads; requeue
34
+ * [key] (a run a restart interrupted, lib/driver-run.js): those wakes of the run go back to the queue for one more run
34
35
  * refused { target, wakes: [key], reason } a wake the rules turned away, recorded
35
36
  * blocker { key, day, target, board, code, owner: 'pm'|'agent', text } the sweep's finding, once per key per day
36
37
  * epoch { } the first scan of this ledger: older events do not wake
@@ -249,6 +250,9 @@ function fold(lines) {
249
250
  const r = s.runs.get(l.run);
250
251
  if (!r || r.end) break;
251
252
  r.end = l.at || null; r.ok = l.ok === true; r.reason = typeof l.reason === 'string' ? l.reason : null; r.agent_run = isObj(l.agent_run) ? l.agent_run : null;
253
+ // agent-orchestrator: a run a restart interrupted hands back the wakes the task ledger requeued (lib/orchestrator-ledger.js
254
+ // recover), so ONE more run answers them. Only a wake of this run that it started can go back to the queue.
255
+ if (Array.isArray(l.requeue)) for (const k of l.requeue) { const w = wakeBy.get(k); if (w && w.state === 'started' && r.wakes.includes(k)) w.state = 'queued'; }
252
256
  break;
253
257
  }
254
258
  case 'refused': {
@@ -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 };
@@ -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) {
@@ -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.317.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.317.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.317.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",
@@ -2492,7 +2492,7 @@ function fireSchedule(sched, opts = {}) {
2492
2492
  const rsm = require('./lib/routes-report-structure.js');
2493
2493
  const sp = rsm.savedPlan(root, String(sched.args)); if (sp) structured = { id: String(sched.args), saved: sp.n };
2494
2494
  if (opts.release) prompt += rsm.draftBlock(root, String(sched.args), { note: opts.note || null });
2495
- else { const gate = rsm.beforeDraft(reportStructureCtx(), w, String(sched.args), sched); if (gate.hold) held = true; else prompt += gate.block || ''; }
2495
+ else { const gate = rsm.beforeDraft(reportStructureCtx(), w, String(sched.args), sched, { scheduled: !!opts.scheduled }); if (gate.hold) held = true; else prompt += gate.block || ''; }
2496
2496
  } catch (e) { warnWriteFail('report structure (draft gate)', e); }
2497
2497
  }
2498
2498
  // The schedule's recorded profile travels with the process it creates (profiles R8.3). Only an
@@ -2552,7 +2552,8 @@ function fireSchedule(sched, opts = {}) {
2552
2552
  }
2553
2553
  function checkDueSchedules() {
2554
2554
  let fired = 0;
2555
- for (const s of readSchedules()) { try { if (scheduleLogic.isDue(s)) { fireSchedule(s); fired++; } } catch {} }
2555
+ // A fire from this tick is `scheduled`: the source checks of a structured report's draft start through the capacity governor (run-now is a press).
2556
+ for (const s of readSchedules()) { try { if (scheduleLogic.isDue(s)) { fireSchedule(s, { scheduled: true }); fired++; } } catch {} }
2556
2557
  // R11 — a one-off whose moment passed while nothing was running is marked missed and off, never caught up.
2557
2558
  try {
2558
2559
  const list = readSchedules(); let changed = false;
@@ -2583,7 +2584,9 @@ const dashboardScheduleTick = () => {
2583
2584
  // window, and starts its short headless runs. Everything it decides is in lib/driver.js; this only hands it the server's parts.
2584
2585
  // agent-orchestrator: the capacity governor in front of every run the orchestrator may start. The Driver asks it before each start; the status route reads it.
2585
2586
  // PMOS_TICK_MS is the suites' fast clock: a suite runs beside forty others, so the machine-load check is skipped there (the rest of the gate applies).
2586
- const orchGate = require('./lib/orchestrator-gate.js').create({ dir: STATE, ...(process.env.PMOS_TICK_MS ? { load: () => null } : { defaultBackupDir: path.join(require('os').homedir(), 'pmos-backups') }) });
2587
+ // The quota reading is the usage-limit hold a failed headless run left (lib/orchestrator-quota.js; set where a headless run ends, startHeadless).
2588
+ const orchQuota = require('./lib/orchestrator-quota.js');
2589
+ const orchGate = require('./lib/orchestrator-gate.js').create({ dir: STATE, quota: () => orchQuota.gateQuota(STATE), ...(process.env.PMOS_TICK_MS ? { load: () => null } : { defaultBackupDir: path.join(require('os').homedir(), 'pmos-backups') }) });
2587
2590
  const driver = driverRunLib.create({
2588
2591
  mayStart: ({ running }) => orchGate.mayStart({ running }),
2589
2592
  started: () => orchGate.granted(),
@@ -2621,7 +2624,7 @@ const orchKeepRate = () => {
2621
2624
  const orchHealth = () => {
2622
2625
  const backupLib = require('./lib/state-backup.js'), log = backupLib.readLog(STATE);
2623
2626
  return require('./lib/orchestrator-health.js').rows({ now: Date.now(), stopped: orchGate.status({}).stopped, lastTickAt: orchLastTickAt, tickMs: TICK_MS,
2624
- diskFreeFrac: require('./lib/orchestrator-health.js').diskFreeFrac(STATE), loginHeld: driver.loginHeld(),
2627
+ diskFreeFrac: require('./lib/orchestrator-health.js').diskFreeFrac(STATE), loginHeld: driver.loginHeld(), quotaHold: orchQuota.read(STATE),
2625
2628
  backup: { configured: !!orchGate.backupDir(), lastOkAt: log.lastOkAt, lastError: log.lastError, isDefault: orchGate.backupIsDefault(), dir: orchGate.backupDir() }, pause: orchKeepRate().pause });
2626
2629
  };
2627
2630
  // agent-orchestrator: the Checker. One read-only run per ended Driver run with open drafts, started through the gate, one start per tick.
@@ -2713,8 +2716,10 @@ const reportFinder = reportFinderLib.create({
2713
2716
  });
2714
2717
  // report-design-studio: a cycle drafted for a report whose design is saved is rendered to match it. A draft written in this process starts its job at
2715
2718
  // once (lib/routes-report-design.js listens to report-draft.js writeDraft); this tick catches a draft the `pmos report draft` CLI wrote (the schedule).
2719
+ // agent-orchestrator: the render the sweep starts uses spawnScheduled (the capacity governor); a held start is tried again on the next tick. A press uses spawnSession.
2716
2720
  const reportDesignCtx = () => ({ getWs, workspaceList: () => [...workspaces.values()], runtimeDir: STATE,
2717
2721
  spawnSession: (spec) => spawnSession({ ...spec, autoDelete: undefined }),
2722
+ spawnScheduled: (spec) => orchSpawn.spawn({ ...spec, autoDelete: undefined }),
2718
2723
  skillPrompt: (skillId, w) => { const t = taskById(skillId, w ? w.root : SELF_ROOT); return t && t.prompt ? t.prompt : null; },
2719
2724
  stopSession: (id) => { const x = sessions.get(String(id || '')); if (x && x.child) stopHeadless(x); } });
2720
2725
  const reportDesignTick = () => {
@@ -2724,9 +2729,11 @@ const reportDesignTick = () => {
2724
2729
  try { require('./lib/routes-report-design.js').attach(reportDesignCtx); } catch { /* a checkout without the module still starts */ }
2725
2730
  // report-structure: the structure jobs, the source checks (interactive sessions started like Work's approved steps, STEP_FLAGS) and the draft gate.
2726
2731
  // The tick collects check answers and starts the drafts that waited for a failing source (4 hours, then without it).
2732
+ // agent-orchestrator: the checks of a draft the schedule tick fired, and the tick's retries of them, use spawnScheduled (the capacity governor). A press uses spawnSession.
2727
2733
  const reportStructureCtx = () => ({ getWs, workspaceList: () => [...workspaces.values()], runtimeDir: STATE, stepFlags: STEP_FLAGS,
2728
2734
  scheduleStore: { read: readSchedules, write: writeSchedules }, sessionAlive: (id) => { const x = sessions.get(String(id || '')); return !!x && x.state !== 'exited'; },
2729
2735
  spawnSession: (spec) => spawnSession({ ...spec, autoDelete: undefined }),
2736
+ spawnScheduled: (spec) => orchSpawn.spawn({ ...spec, autoDelete: undefined }),
2730
2737
  skillPrompt: (skillId, w) => { const t = taskById(skillId, w ? w.root : SELF_ROOT); return t && t.prompt ? t.prompt : null; },
2731
2738
  stopSession: (id) => { const x = sessions.get(String(id || '')); if (x && x.child) stopHeadless(x); },
2732
2739
  // a check session is a pane: end it when its answer is in (the skill closes its tab and stops; this is the backstop)
@@ -3758,7 +3765,7 @@ function sendToSession(id, text) {
3758
3765
  * session's state keeps working; it has no pty and no tmux, and `child` is the process. The log is read-only. */
3759
3766
  function startHeadless(base, workdir, kind, launchArgs, env, initialInput, addDirs, onDone, writePaths) {
3760
3767
  const prompt = safeFirstInput(String(initialInput).replace(/\r+$/, ''));
3761
- // report-design-studio: writePaths names the one render file a report-design run may write (lib/headless.js ignores it for every other kind).
3768
+ // report-design-studio: writePaths names the one render file a report-design run may write; for a skill run, the folders it may write in (lib/headless.js ignores it for every other kind).
3762
3769
  const args = headlessLib.argsFor(kind, { modelArgs: launchArgs, addDirs: Array.isArray(addDirs) ? addDirs : [], writePaths: Array.isArray(writePaths) ? writePaths : [] });
3763
3770
  const s = { ...base, cwd: workdir, state: 'working', pty: null, tmux: null, headless: kind, child: null,
3764
3771
  note: '', buf: '', cols: 80, rows: 24, clients: new Set(), created: nowISO(), lastOutputAt: Date.now() };
@@ -3829,6 +3836,11 @@ function startHeadless(base, workdir, kind, launchArgs, env, initialInput, addDi
3829
3836
  s.outcome = headlessLib.outcomeOf(r, { code, signal, timedOut, stopped: !!s.stoppedByPm, timeoutMin });
3830
3837
  if (!s.outcome.ok && err.trim() && !r.ok) s.outcome.why += ' ' + err.trim().split('\n').filter(Boolean).pop().slice(0, 200);
3831
3838
  if (s.note !== 'exited (code 0)') say(`\x1b[38;5;203m[${s.note}]\x1b[0m\n`);
3839
+ // agent-orchestrator: a failed run that hit the Claude usage limit holds new orchestrator starts until the reset it names (lib/orchestrator-quota.js).
3840
+ // Only a failed run is read, so a run whose answer is about rate limits sets no hold.
3841
+ if (!timedOut && !s.stoppedByPm && (code !== 0 || !r.ok || r.isError)) {
3842
+ try { const hold = orchQuota.detect([r.isError || !r.ok ? r.text : '', err.slice(-4000), resultLine ? '' : out.slice(-4000)].join('\n')); if (hold) orchQuota.record(STATE, hold); } catch (e) { warnWriteFail('usage-limit hold', e); }
3843
+ }
3832
3844
  persist(s); pushSessions();
3833
3845
  // page-starts-agent: a caller that started this run from the page reads its result here (a proposal, never a write).
3834
3846
  // A caller may answer { failed: why } when the run ended without doing its job (a core-doc run that wrote no draft): the run then
@@ -3995,6 +4007,16 @@ function spawnSessionInner({ name, agent, cwd, ws, origin, initialInput, profile
3995
4007
  // ── the headless path (workspace-headless-jobs): a background job that needs no human runs as `claude -p`, with
3996
4008
  // no pane, the same environment and model, a fixed tool list and the prompt on stdin (lib/headless.js says which).
3997
4009
  const hkind = initialInput ? headlessLib.kindFor({ agent, origin: tag, skill: modelAsk && modelAsk.skill }) : null;
4010
+ // A background skill run reads untrusted text, so it writes only in a scratch folder of its own and in the state folders its skill writes
4011
+ // (lib/headless.js skillWriteDirs). The prompt names the scratch folder, and the folder is removed when the run ends.
4012
+ if (hkind === 'skill') {
4013
+ let dir = null;
4014
+ try { dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'pmos-skill-'))); } catch { /* no scratch folder: the run writes only its state folders */ }
4015
+ if (dir) { base.scratchDir = dir; initialInput = String(initialInput).replace(/\r+$/, '') + `\n\nThis session's scratch folder is ${dir}. Write temporary files there only; it is removed when the run ends.`; }
4016
+ let repo = workdir; try { repo = fs.realpathSync(workdir); } catch { /* keep the path as given */ }
4017
+ return startHeadless(base, workdir, hkind, argv, penv, initialInput, [...(Array.isArray(addDirs) ? addDirs : []), ...(dir ? [dir] : [])], onDone,
4018
+ headlessLib.skillWriteDirs(modelAsk && modelAsk.skill, { root: repo, scratch: dir }));
4019
+ }
3998
4020
  if (hkind) return startHeadless(base, workdir, hkind, argv, penv, initialInput, addDirs, onDone, writePaths);
3999
4021
 
4000
4022
  // ── the tmux path: the process outlives this server, and we re-attach to it live (R7) ──
@@ -1,13 +1,15 @@
1
1
  {
2
- "_comment": "agent-orchestrator: the keep-rate report (the success measure), the advisory Checker and the tool lists of the reading workers (node, no server).",
2
+ "_comment": "agent-orchestrator: the keep-rate report (the success measure), the advisory Checker, the tool lists of the reading workers and the usage-limit hold that is the governor's quota reading (node, no server).",
3
3
  "modules": [
4
4
  "orchestrator-keeprate.test.js",
5
5
  "orchestrator-checker.test.js",
6
- "orchestrator-readers.test.js"
6
+ "orchestrator-readers.test.js",
7
+ "orchestrator-quota.test.js"
7
8
  ],
8
9
  "seconds": {
9
10
  "orchestrator-keeprate.test.js": 1,
10
11
  "orchestrator-checker.test.js": 1,
11
- "orchestrator-readers.test.js": 1
12
+ "orchestrator-readers.test.js": 1,
13
+ "orchestrator-quota.test.js": 1
12
14
  }
13
15
  }
@@ -0,0 +1,9 @@
1
+ {
2
+ "_comment": "agent-orchestrator: done-criteria 5 and 7 on a real server with a stub claude: the status, Needs and sessions routes answer under full Driver load in working mode, and a server SIGKILLed mid-run answers the interrupted wake once more after the restart, then, killed again, fails it with the reason and never runs it a third time.",
3
+ "modules": [
4
+ "orchestrator-load-restart.test.js"
5
+ ],
6
+ "seconds": {
7
+ "orchestrator-load-restart.test.js": 20
8
+ }
9
+ }