create-pmos 0.356.0 → 0.358.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.356.0",
3
+ "version": "0.358.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": {
@@ -32,6 +32,30 @@
32
32
  "audit"
33
33
  ],
34
34
  "pmosChanges": [
35
+ {
36
+ "v": "0.358.0",
37
+ "at": "2026-10-20T11:00:48.565Z",
38
+ "f": 2,
39
+ "prs": [
40
+ {
41
+ "n": 939,
42
+ "t": "Chat sessions end when idle, resume, and cap at 4 live",
43
+ "s": "A chat session that prints nothing for the workspace idle limit (60 minutes by default) is ended, unless its goal is started or a permission prompt is waiting."
44
+ }
45
+ ]
46
+ },
47
+ {
48
+ "v": "0.357.0",
49
+ "at": "2026-10-20T09:57:04.765Z",
50
+ "f": 2,
51
+ "prs": [
52
+ {
53
+ "n": 956,
54
+ "t": "End sessions from the list; idle shells fold into one line",
55
+ "s": "Every row has an End button (×) on hover, on focus and always on touch screens."
56
+ }
57
+ ]
58
+ },
35
59
  {
36
60
  "v": "0.356.0",
37
61
  "at": "2026-10-20T09:37:44.880Z",
@@ -267,30 +291,6 @@
267
291
  "s": "Every chat panel session starts with a Claude Code Stop hook."
268
292
  }
269
293
  ]
270
- },
271
- {
272
- "v": "0.338.0",
273
- "at": "2026-10-20T02:42:22.826Z",
274
- "f": 2,
275
- "prs": [
276
- {
277
- "n": 933,
278
- "t": "/goal in the premium chat panel grills the goal into a SMART goal",
279
- "s": "Typing / opens a short menu with /goal, /compact and /clear."
280
- }
281
- ]
282
- },
283
- {
284
- "v": "0.337.0",
285
- "at": "2026-10-20T02:07:25.408Z",
286
- "f": 2,
287
- "prs": [
288
- {
289
- "n": 832,
290
- "t": "Soft warning in the Sessions dialog when more than six agents work",
291
- "s": "When more than six sessions are in the working state, the dialog shows one note above the list: \"N agents are working at once."
292
- }
293
- ]
294
294
  }
295
295
  ]
296
296
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@6ce4772b
1
+ kernel-source: pmos@da7aa3f0
2
2
  assembled: 2026-10-20
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-20T09:37:41Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-20T11:00:45Z"}
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-20T09:37:41Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-20T11:00:45Z"}
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-20T09:37:41Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-20T11:00:45Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -1,4 +1,28 @@
1
1
  [
2
+ {
3
+ "v": "0.358.0",
4
+ "at": "2026-10-20T11:00:48.565Z",
5
+ "f": 2,
6
+ "prs": [
7
+ {
8
+ "n": 939,
9
+ "t": "Chat sessions end when idle, resume, and cap at 4 live",
10
+ "s": "A chat session that prints nothing for the workspace idle limit (60 minutes by default) is ended, unless its goal is started or a permission prompt is waiting."
11
+ }
12
+ ]
13
+ },
14
+ {
15
+ "v": "0.357.0",
16
+ "at": "2026-10-20T09:57:04.765Z",
17
+ "f": 2,
18
+ "prs": [
19
+ {
20
+ "n": 956,
21
+ "t": "End sessions from the list; idle shells fold into one line",
22
+ "s": "Every row has an End button (×) on hover, on focus and always on touch screens."
23
+ }
24
+ ]
25
+ },
2
26
  {
3
27
  "v": "0.356.0",
4
28
  "at": "2026-10-20T09:37:44.880Z",
@@ -32,6 +32,8 @@ Every premium page has the same top bar. On the left is where you are, then a ro
32
32
  - **Dots.** An orange dot means **Ready**: the session finished its turn and waits for you. A green dot means **Running**. An orange ring means **Maybe blocked**: a call is open and nothing moves, often a permission question. No dot means idle. Ready sessions come first and are bold. Hold the pointer over a row to see its state in words.
33
33
  - **Switch.** Press a row to switch the dialog to that session. A chat opens its own conversation. Any other session shows its conversation from Claude Code's record. You can write to it and answer its permission questions, as in a chat. The viewer shows the session's facts, the question a background run asks with the options it offered, and **Stop**. Stop asks first, and if the session has not exited yet it says so and offers Stop again.
34
34
  - **Fold.** The button at the top of the list folds it to a strip of icons with dots. The button at the top of the viewer folds the viewer to a strip, so the conversation gets the width; press anywhere on the strip to open the viewer again. PMOS remembers both in this browser. When the conversation is hidden, the viewer always shows, so the panel is never empty.
35
+ - **End.** Every row has an **End** button (×) on its right: it shows when the pointer is over the row, and always on a touch screen. An idle session ends at once. A session that is Running, Ready or Maybe blocked asks first, in the row, with **End** and **Keep**. Ending stops the process and removes the row; files it already wrote stay. If it has not exited yet, the toast says so and the row stays.
36
+ - **Idle shells.** A terminal shell with no agent in it and no output for a while folds under **Yours** into one line, "N more idle · Show", with **End all idle**. End all idle ends only those shells, never a goal or a session that needs you. PMOS opens one shell when it starts with no live session; it now checks after your sessions come back, so a restart no longer adds a shell each time.
35
37
  - **When the chat is not full screen,** a chip in the dialog's header shows the loudest dot and, for example, "2 ready". Press it to go full screen with the list. On a phone, it opens the list over the dialog, and a tap on a row switches to that session.
36
38
  - **Sessions in the ⋯ menu** counts the sessions that are Ready or Maybe blocked. It opens the dialog full screen on the session that needs you most. On a phone, it opens the list.
37
39
  - When more than six agents are working at once, a note at the top of the list says how many, and suggests stopping the ones you are not watching. Nothing is stopped for you.
@@ -172,8 +172,11 @@ function chat({ runtimeDir, key, text, model, sessions, wsId, now = new Date() }
172
172
  if (!sessions || typeof sessions.spawn !== 'function') return fail(409, 'this workspace cannot start sessions');
173
173
  const live = chatSessionOf(runtimeDir, key);
174
174
  const alive = !!(live && sessions.alive(live));
175
+ // slice 4 (PRD L2): an ended chat resumes its own Claude Code conversation when the file for it is still there
176
+ const prev = alive ? null : chatRecordOf(runtimeDir, key);
177
+ const resume = !!(prev && prev.claude && typeof sessions.hasConversation === 'function' && sessions.hasConversation(prev.claude));
175
178
  const row = alive ? null : rowFor(model, key);
176
- if (!alive && !row) return fail(404, model ? 'that row is not on the page' : 'the page has not read the repository yet');
179
+ if (!alive && !row && !resume) return fail(404, model ? 'that row is not on the page' : 'the page has not read the repository yet');
177
180
  // slice 2 (PRD G2): `/goal <text>` becomes the PMOS grilling prompt, on record before it reaches the session
178
181
  let msg = q, goal = null;
179
182
  const cmd = Goal.parseCommand(q);
@@ -184,12 +187,40 @@ function chat({ runtimeDir, key, text, model, sessions, wsId, now = new Date() }
184
187
  if (!goal) Goal.resume({ runtimeDir, key, now }); // slice 3: the PM's answer to a goal that needs them sets it going again; a finished one is seen
185
188
  return { status: 200, body: { ok: true, session: live, started: false, ...extra } };
186
189
  }
190
+ makeRoom(runtimeDir, sessions); // slice 4 (PRD L3)
191
+ const claude = resume ? prev.claude : crypto.randomUUID();
192
+ const name = 'chat: ' + clip(row ? row.title : prev.name || key, 60);
187
193
  let s;
188
- try { s = sessions.spawn({ name: 'chat: ' + clip(row.title, 60), agent: 'claude', ws: wsId, origin: 'chat:' + key, initialInput: openingFor(row, msg) + '\r' }); } catch (e) { s = { state: 'exited', note: String((e && e.message) || e).slice(0, 120) }; }
194
+ try { s = sessions.spawn({ name, agent: 'claude', ws: wsId, origin: 'chat:' + key, chatClaude: { id: claude, resume }, initialInput: (resume ? msg : openingFor(row, msg)) + '\r' }); } catch (e) { s = { state: 'exited', note: String((e && e.message) || e).slice(0, 120) }; }
189
195
  if (!s || s.state === 'exited' || !s.id) return fail(409, 'Claude could not start: ' + ((s && s.note) || 'no session'));
190
196
  fs.mkdirSync(runtimeDir, { recursive: true });
191
- fs.appendFileSync(path.join(runtimeDir, CHATS), JSON.stringify({ key, session: s.id, at: now.toISOString() }) + '\n');
192
- return { status: 200, body: { ok: true, session: s.id, started: true, ...extra } };
197
+ fs.appendFileSync(path.join(runtimeDir, CHATS), JSON.stringify({ key, session: s.id, claude, name, at: now.toISOString() }) + '\n');
198
+ return { status: 200, body: { ok: true, session: s.id, started: true, ...(resume ? { resumed: true } : {}), ...extra } };
199
+ }
200
+ /** The last record for a key in premium-chat-sessions.jsonl ({ key, session, claude, name, at }), or null. */
201
+ function chatRecordOf(runtimeDir, key) {
202
+ let t; try { t = fs.readFileSync(path.join(runtimeDir, CHATS), 'utf8'); } catch { return null; }
203
+ let rec = null;
204
+ for (const l of t.split('\n')) { if (!l.trim()) continue; let e; try { e = JSON.parse(l); } catch { continue; } if (e && e.key === key && typeof e.session === 'string') rec = e; }
205
+ if (rec && !UUID_RE.test(String(rec.claude || ''))) rec = { ...rec, claude: null };
206
+ return rec;
207
+ }
208
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
209
+ const MAX_LIVE = 4;
210
+ /** Which live chat session to end so a new one fits (PRD L3), or null. rows: [{ id, origin, lastOutputAt, busy }];
211
+ * busy = working or waiting on a permission prompt. A session whose goal is started is never picked. */
212
+ function pickToEnd(rows, goalStarted, max = MAX_LIVE) {
213
+ const live = (Array.isArray(rows) ? rows : []).filter((r) => r && /^chat:/.test(String(r.origin || '')));
214
+ if (live.length < max) return null;
215
+ const free = live.filter((r) => !r.busy && !goalStarted(String(r.origin).slice(5)));
216
+ free.sort((a, b) => (Number(a.lastOutputAt) || 0) - (Number(b.lastOutputAt) || 0));
217
+ return free.length ? free[0].id : null;
218
+ }
219
+ function makeRoom(runtimeDir, sessions) {
220
+ if (typeof sessions.list !== 'function' || typeof sessions.end !== 'function') return null;
221
+ const id = pickToEnd(sessions.list(), (key) => { const g = Goal.goalOf(runtimeDir, key); return !!(g && g.state === 'started'); });
222
+ if (id) sessions.end(id);
223
+ return id;
193
224
  }
194
225
  /** A permission option ('1'…'9') or Stop ('esc'), typed into the key's live session with no Enter. */
195
226
  function press({ runtimeDir, key, what, sessions }) {
@@ -202,4 +233,4 @@ function press({ runtimeDir, key, what, sessions }) {
202
233
  return { status: 200, body: { ok: true, session: live } };
203
234
  }
204
235
 
205
- module.exports = { ask, chat, press, chatSessionOf, openingFor, threadOf, promptFor, rowFor, settle, KEY_RE, THREADS, CHATS };
236
+ module.exports = { ask, chat, press, chatSessionOf, chatRecordOf, pickToEnd, MAX_LIVE, openingFor, threadOf, promptFor, rowFor, settle, KEY_RE, THREADS, CHATS };
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+ /* lib/first-shell.js — the shell the workspace opens at startup so it is never empty (premium-session-end).
3
+ * Asked only after the restore has finished: before, the running server checked while its sessions were still coming back,
4
+ * saw no live pane on every launch and spawned one more `shell`, which tmux kept. One idle shell per restart piled up in the list. */
5
+ function firstShell(list, { canHost, spawn }) {
6
+ if (!canHost || [...(list || [])].some((s) => s && s.pty)) return false;
7
+ spawn();
8
+ return true;
9
+ }
10
+ module.exports = { firstShell };
@@ -93,4 +93,20 @@ function decide(s, policy, now) {
93
93
  return 'end';
94
94
  }
95
95
 
96
- module.exports = { isAutomatic, normalizePolicy, decide, endedCleanly, DEFAULT_POLICY, FINISH_GRACE_MS, FAILED_KEEP_MS, MANUAL_EXACT, MANUAL_PREFIX };
96
+ /**
97
+ * premium-chat-session L1: 'end' for a live chat panel session (origin `chat:`) idle past the policy's limit, or null.
98
+ * A chat is the PM's own, so decide() never ends it; this one rule does, because its next message resumes the same
99
+ * conversation (lib/briefing-premium-agent.js). Kept while its goal is started (goalStarted) or a permission prompt waits.
100
+ */
101
+ function decideChat(s, policy, now, goalStarted) {
102
+ if (!s || !/^chat:/.test(String(s.origin || '')) || s.state === 'exited' || s.autoDelete === 'never') return null;
103
+ const last = Number(s.lastOutputAt) || 0;
104
+ if (!last || !policy || !policy.idleMinutes) return null;
105
+ if (now - last < policy.idleMinutes * 60 * 1000) return null;
106
+ if (goalStarted) return null;
107
+ const shown = typeof s.shown === 'function' ? s.shown() : s.shown;
108
+ if (shown === 'blocked') return null;
109
+ return 'end';
110
+ }
111
+
112
+ module.exports = { decideChat, isAutomatic, normalizePolicy, decide, endedCleanly, DEFAULT_POLICY, FINISH_GRACE_MS, FAILED_KEEP_MS, MANUAL_EXACT, MANUAL_PREFIX };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.356.0",
3
+ "version": "0.358.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.356.0",
9
+ "version": "0.358.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.356.0",
3
+ "version": "0.358.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",
@@ -8,7 +8,7 @@ import { lineItems, behindOf, refreshTargets, whenRead } from './freshness-words
8
8
  import { splitGoal, shownUser, goalBlockHtml, goalProgressHtml, slashMatches } from './goal-chat.js';
9
9
  import { mdHtml, userHtml, toolLine, webKind } from './chat-md.js';
10
10
  import { padMarkup, padChipMarkup, mountPad, flushPad } from './premium-pad.js';
11
- import { railModel, railHtml, teaser, menuCount, loudestRow, factsOf, titleOf, DOT, WORD } from './session-rail.js';
11
+ import { railModel, railHtml, teaser, menuCount, loudestRow, factsOf, titleOf, endAsks, DOT, WORD } from './session-rail.js';
12
12
  export const $ = (s, r = document) => r.querySelector(s);
13
13
  export const $$ = (s, r = document) => [...r.querySelectorAll(s)];
14
14
  export const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
@@ -884,7 +884,7 @@ export async function openSettings() {
884
884
  * conversations; lib/session-rail.js groups them. Pressing a row switches the dialog to that session: a chat row opens its own conversation,
885
885
  * any other session its transcript. The writes are a page press each: a message or a key (POST /api/session/say|keys), Stop (/api/session/remove)
886
886
  * and an answer to a run's question (/api/runs/answer). The Agent sessions popup this replaces is gone; the ⋯ menu's Sessions opens this. */
887
- const R = { rows: [], goals: {}, model: null, sel: null, shut: [], showAll: false, timer: null, asks: {}, ask: null, busy: false, slow: null, err: '', sidTimer: null,
887
+ const R = { rows: [], goals: {}, model: null, sel: null, shut: [], showAll: false, showIdle: false, ending: null, timer: null, asks: {}, ask: null, busy: false, slow: null, err: '', sidTimer: null,
888
888
  railMin: store.get('pmos.srl.rail') === 'min', viewMin: store.get('pmos.srl.view') === 'min' };
889
889
  const SRL_POLL = 3000, BADGE_POLL = 15000;
890
890
  const desk = () => innerWidth >= 1000;
@@ -904,6 +904,12 @@ function railMount() {
904
904
  $('#srlList').onclick = (e) => {
905
905
  const gh = e.target.closest('[data-sg]'), mo = e.target.closest('[data-smore]'), r = e.target.closest('[data-sid]');
906
906
  if (mo) { R.showAll = !R.showAll; railDraw(); return; }
907
+ const x = e.target.closest('[data-end]'), yes = e.target.closest('[data-endyes]'), no = e.target.closest('[data-endno]'), si = e.target.closest('[data-sidle]'), ei = e.target.closest('[data-endidle]');
908
+ if (si) { R.showIdle = !R.showIdle; railDraw(); return; }
909
+ if (no) { R.ending = null; railDraw(); return; }
910
+ if (x) { const row = R.model && R.model.rows.find((y) => y.id === x.dataset.end); if (!row) return; if (endAsks(row)) { R.ending = row.id; railDraw(); const k = $('#srlList [data-endno]'); if (k) k.focus(); } else endRows([row]); return; }
911
+ if (yes) { const row = R.model && R.model.rows.find((y) => y.id === yes.dataset.endyes); R.ending = null; if (row) endRows([row]); else railDraw(); return; }
912
+ if (ei) { endRows((R.model && R.model.idle) || []); return; }
907
913
  if (gh) { if (R.railMin) { R.railMin = false; store.set('pmos.srl.rail', 'open'); railLayout(); return; } const k = gh.dataset.sg; R.shut = R.shut.includes(k) ? R.shut.filter((x) => x !== k) : [...R.shut, k]; railDraw(); return; }
908
914
  if (r) pickSession(r.dataset.sid);
909
915
  };
@@ -915,9 +921,27 @@ function railLayout() {
915
921
  if (f) { f.title = R.railMin ? 'Open the list' : 'Fold the list'; f.setAttribute('aria-label', f.title); f.setAttribute('aria-pressed', String(R.railMin)); }
916
922
  if (v) { v.title = R.viewMin ? 'Open the viewer' : 'Fold the viewer'; v.setAttribute('aria-label', v.title); v.setAttribute('aria-pressed', String(R.viewMin)); }
917
923
  }
924
+ /* premium-session-end: End from the list. The same POST /api/session/remove as the viewer's Stop; an idle row ends at once, any other row asked
925
+ * first (R.ending). "End all idle" ends only the folded idle shells, never a goal or a session that needs the PM. A session that has not exited
926
+ * yet stays listed and says so; it is never claimed ended. */
927
+ async function endRows(rows) {
928
+ if (!rows.length || R.busy) return;
929
+ R.busy = true;
930
+ const res = await Promise.all(rows.map((r) => pmPost('/api/session/remove', { id: r.id }).catch(() => null)));
931
+ R.busy = false;
932
+ const gone = rows.filter((r, i) => res[i] && res[i].ok && res[i].removed !== false), ids = new Set(gone.map((r) => r.id));
933
+ R.rows = R.rows.filter((x) => !ids.has(x.id));
934
+ if (R.sel && ids.has(R.sel)) { if (S.sid === R.sel) S.sid = null; R.sel = null; sessionCard(null); }
935
+ const left = rows.length - gone.length;
936
+ if (rows.length === 1) toast(gone.length ? 'Ended “' + rows[0].name + '”.' : 'Asked “' + rows[0].name + '” to end. It has not exited yet; press End again.');
937
+ else toast('Ended ' + gone.length + (gone.length === 1 ? ' idle session' : ' idle sessions') + '.' + (left ? ' ' + left + ' did not exit yet.' : ''));
938
+ if (!R.model || !R.rows.some((x) => x.agent === 'shell' && x.shown === 'quiet')) R.showIdle = false;
939
+ railDraw(); railRead();
940
+ }
918
941
  function railDraw() {
919
- const m = R.model = railModel(R.rows, R.goals, { showAll: R.showAll });
920
- const l = $('#srlList'); if (l) putHtml(l, railHtml(m, { sel: R.sel, shut: R.shut, showAll: R.showAll }));
942
+ const m = R.model = railModel(R.rows, R.goals, { showAll: R.showAll, showIdle: R.showIdle });
943
+ if (R.ending && !m.rows.some((x) => x.id === R.ending)) R.ending = null;
944
+ const l = $('#srlList'); if (l) putHtml(l, railHtml(m, { sel: R.sel, shut: R.shut, showAll: R.showAll, showIdle: R.showIdle, ending: R.ending }));
921
945
  const t = $('#sTease'), tz = teaser(m);
922
946
  if (t) {
923
947
  t.hidden = !tz || !t.dataset.on || $('#dlg').classList.contains('full');
@@ -2396,6 +2396,26 @@ button.wl-row[aria-pressed="true"] .wl-tog{background:var(--solid);color:var(--o
2396
2396
  .srl-r.on .srl-h{color:inherit;opacity:.75}
2397
2397
  .srl-more{display:block;width:100%;text-align:left;min-height:32px;padding:4px 8px 4px 36px;border-radius:10px;color:var(--ink-3);font-size:var(--fs-2)}
2398
2398
  .srl-more:hover{background:var(--well);color:var(--ink)}
2399
+ /* premium-session-end: every row has an End button beside it (on hover, on focus, and always on touch screens); idle shells fold into one line */
2400
+ .srl-li{display:flex;align-items:center;gap:2px}
2401
+ .srl-li>.srl-r,.srl-li>.srl-more{flex:1;min-width:0}
2402
+ .srl-x{display:none;width:28px;height:28px;border-radius:8px;place-items:center;color:var(--ink-3);flex:none}
2403
+ .srl-x svg{width:14px;height:14px}
2404
+ .srl-x:hover,.srl-x:focus-visible{background:var(--well);color:var(--ink)}
2405
+ .srl-li:hover .srl-x,.srl-li:focus-within .srl-x{display:grid}
2406
+ @media (hover:none){.srl-x{display:grid}}
2407
+ .srl-li:has(.srl-endall){flex-wrap:wrap;row-gap:4px}
2408
+ .srl-li>.srl-more{white-space:nowrap;flex:1 0 auto}
2409
+ .srl-endall{flex:none;margin-left:36px;min-height:28px;padding:2px 10px;border-radius:999px;border:1px solid var(--hair);color:var(--ink-2);font-size:var(--fs-1);white-space:nowrap}
2410
+ .srl-endall:hover{background:var(--well);color:var(--ink)}
2411
+ .srl-cf{flex-wrap:wrap;gap:6px;padding:6px 8px;margin:2px 0;border-radius:10px;background:var(--spot);font-size:var(--fs-2)}
2412
+ .srl-cf span{flex:1 1 100%;color:var(--ink)}
2413
+ .srl-yes,.srl-no{min-height:28px;padding:2px 12px;border-radius:999px;font-size:var(--fs-2)}
2414
+ .srl-yes{background:var(--solid);color:var(--on-solid)}
2415
+ .srl-no{border:1px solid var(--hair);color:var(--ink-2)}
2416
+ .srl-min .srl-x,.srl-min .srl-endall,.srl-min .srl-cf{display:none!important}
2417
+ .dlg.srl-open .srl-x{display:grid;width:44px;height:44px}
2418
+ .dlg.srl-open .srl-endall,.dlg.srl-open .srl-yes,.dlg.srl-open .srl-no{min-height:44px;font-size:var(--fs-2)}
2399
2419
  .srl-lg{display:flex;flex-wrap:wrap;gap:4px 12px;padding:8px 8px 0;border-top:1px solid var(--hair);font-size:var(--fs-1);color:var(--ink-3)}
2400
2420
  .srl-lg span{display:inline-flex;align-items:center;gap:5px}
2401
2421
  .srl-warn{margin:4px 2px 8px;padding:8px 10px;border-radius:10px;background:var(--spot);font-size:var(--fs-2);color:var(--ink-2)}
@@ -1,7 +1,8 @@
1
1
  /* pm/session-rail.js — the session list beside the chat (initiative premium-session-list, PRD L2). Pure: no DOM, no fetch, so Node tests it.
2
2
  *
3
- * railModel(rows, goals, { showAll }) → { groups: [{ id, title, rows, hidden }], ready, blocked, working, live, warn }
4
- * railHtml(model, { sel, shut, folded }) → the list's markup
3
+ * railModel(rows, goals, { showAll, showIdle }) → { groups: [{ id, title, rows, hidden, idle }], ready, blocked, working, live, warn, idle }
4
+ * railHtml(model, { sel, shut, showAll, showIdle, ending }) → the list's markup; every row has an End button (premium-session-end)
5
+ * endAsks(r) → whether ending this row asks first (anything but an idle session)
5
6
  * teaser(model) → { dot, text } | null the chip in a normal-size chat dialog
6
7
  * menuCount(rows) → how many live sessions need the PM (Ready or Maybe blocked): the ⋯ menu badge
7
8
  * loudestRow(model) → the row the menu's Sessions opens on
@@ -20,7 +21,10 @@ const GROUPS = [['goals', 'Goals'], ['yours', 'Yours'], ['pmos', 'Started by PMO
20
21
 
21
22
  const keyOf = (origin) => (/^chat:/.test(String(origin || '')) ? String(origin).slice(5) : null);
22
23
  const needsYou = (r) => r.state === 'needs' || r.state === 'blocked';
23
- const kindOf = (r) => (r.headless ? 'run' : /^schedule:/.test(r.origin || '') ? 'clock' : r.goal ? 'goal' : r.key ? 'chat' : r.group === 'pmos' ? 'auto' : 'step');
24
+ /** premium-session-end: an idle terminal shell with no agent in it — nothing to read and nothing to answer. Yours folds these into one line. */
25
+ export const idleShell = (r) => r.agent === 'shell' && r.state === 'quiet' && !r.goal && !r.headless;
26
+ export const endAsks = (r) => !(r && r.state === 'quiet');
27
+ const kindOf = (r) => (r.headless || r.agent === 'shell' ? 'run' : /^schedule:/.test(r.origin || '') ? 'clock' : r.goal ? 'goal' : r.key ? 'chat' : r.group === 'pmos' ? 'auto' : 'step');
24
28
 
25
29
  function rowOf(s, goals) {
26
30
  const key = keyOf(s.origin), g = key && goals ? goals[key] : null;
@@ -36,17 +40,17 @@ function rowOf(s, goals) {
36
40
  return r;
37
41
  }
38
42
 
39
- export function railModel(rows, goals = {}, { showAll = false } = {}) {
43
+ export function railModel(rows, goals = {}, { showAll = false, showIdle = false } = {}) {
40
44
  const live = (Array.isArray(rows) ? rows : []).filter((s) => s && s.id && s.shown !== 'exited').map((s) => rowOf(s, goals));
41
45
  live.sort((a, b) => (RANK[b.state] - RANK[a.state]) || (Date.parse(b.created || '') || 0) - (Date.parse(a.created || '') || 0));
42
46
  const groups = GROUPS.map(([id, title]) => {
43
47
  const all = live.filter((r) => r.group === id);
44
- const shown = id === 'pmos' && !showAll ? all.filter(needsYou) : all;
45
- return { id, title, rows: shown, all: all.length, hidden: all.length - shown.length };
48
+ const shown = id === 'pmos' && !showAll ? all.filter(needsYou) : id === 'yours' && !showIdle ? all.filter((r) => !idleShell(r)) : all;
49
+ return { id, title, rows: shown, all: all.length, hidden: id === 'pmos' ? all.length - shown.length : 0, idle: id === 'yours' ? all.filter(idleShell).length : 0 };
46
50
  }).filter((g) => g.all);
47
51
  const n = (st) => live.filter((r) => r.state === st).length;
48
52
  const working = n('working');
49
- return { groups, live: live.length, ready: n('needs'), blocked: n('blocked'), working, warn: working > MANY ? working : 0, rows: live };
53
+ return { groups, live: live.length, ready: n('needs'), blocked: n('blocked'), working, warn: working > MANY ? working : 0, rows: live, idle: live.filter(idleShell) };
50
54
  }
51
55
 
52
56
  export const menuCount = (rows) => (Array.isArray(rows) ? rows : []).filter((s) => s && (s.shown === 'needs' || s.shown === 'blocked')).length;
@@ -69,16 +73,24 @@ const ICON = {
69
73
  clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>', run: '<path d="M4 17l6-6-6-6"/><path d="M12 19h8"/>',
70
74
  };
71
75
  export const icon = (k) => `<svg class="i" viewBox="0 0 24 24" aria-hidden="true">${ICON[k] || ICON.step}</svg>`;
76
+ const XI = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>';
72
77
  const CHEV = '<svg class="i chev" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg>';
73
78
 
74
- export function railHtml(m, { sel = null, shut = [], showAll = false } = {}) {
79
+ /* one row: the session button and, beside it, its End button. `ending` is the row whose End asked first: the row becomes the question. */
80
+ function rowHtml(r, sel, ending) {
81
+ if (ending === r.id) return `<li class="srl-li srl-cf" role="group" aria-label="${esc('End ' + r.name)}"><span>End “${esc(r.name)}”? It is ${esc(WORD[r.state].toLowerCase())}.</span><button type="button" class="srl-yes" data-endyes="${esc(r.id)}">End</button><button type="button" class="srl-no" data-endno="1">Keep</button></li>`;
82
+ return `<li class="srl-li"><button type="button" class="srl-r${r.id === sel ? ' on' : ''}${r.state === 'needs' ? ' rd' : ''}" data-sid="${esc(r.id)}" aria-current="${r.id === sel}" aria-label="${esc(r.name + ', ' + r.hint)}" title="${esc(r.name + ' · ' + r.hint)}"><i class="sdot2 ${DOT[r.state]}" aria-hidden="true"></i><span class="srl-ic">${icon(r.kind)}</span><span class="srl-n">${esc(r.name)}</span><span class="srl-h">${esc(r.hint)}</span></button><button type="button" class="srl-x" data-end="${esc(r.id)}" aria-label="${esc('End ' + r.name)}" title="End this session">${XI}</button></li>`;
83
+ }
84
+
85
+ export function railHtml(m, { sel = null, shut = [], showAll = false, showIdle = false, ending = null } = {}) {
75
86
  if (!m || !m.live) return '<p class="srl-none">No sessions are running. Write in a chat to start one.</p>';
76
87
  let h = m.warn ? `<p class="srl-warn" role="status"><b>${m.warn} agents are working at once.</b> Each one is a program running on this computer, so many at once can slow it. Stop the ones you are not watching.</p>` : '';
77
88
  for (const g of m.groups) {
78
89
  const open = !shut.includes(g.id);
79
90
  h += `<section class="srl-g"><button type="button" class="srl-gh" data-sg="${g.id}" aria-expanded="${open}">${CHEV}<span>${esc(g.title)}</span><em>${g.all}</em></button>`;
80
91
  if (!open) { h += '</section>'; continue; }
81
- h += '<ul>' + g.rows.map((r) => `<li><button type="button" class="srl-r${r.id === sel ? ' on' : ''}${r.state === 'needs' ? ' rd' : ''}" data-sid="${esc(r.id)}" aria-current="${r.id === sel}" aria-label="${esc(r.name + ', ' + r.hint)}" title="${esc(r.name + ' · ' + r.hint)}"><i class="sdot2 ${DOT[r.state]}" aria-hidden="true"></i><span class="srl-ic">${icon(r.kind)}</span><span class="srl-n">${esc(r.name)}</span><span class="srl-h">${esc(r.hint)}</span></button></li>`).join('');
92
+ h += '<ul>' + g.rows.map((r) => rowHtml(r, sel, ending)).join('');
93
+ if (g.id === 'yours' && g.idle) h += `<li class="srl-li"><button type="button" class="srl-more" data-sidle="1">${showIdle ? 'Hide the idle shells' : g.idle + ' more idle · Show'}</button><button type="button" class="srl-endall" data-endidle="1">End all idle</button></li>`;
82
94
  if (g.id === 'pmos' && (g.hidden || showAll)) h += `<li><button type="button" class="srl-more" data-smore="1">${showAll ? 'Hide the ones that need nothing' : g.hidden + ' more working on their own · Show'}</button></li>`;
83
95
  h += '</ul></section>';
84
96
  }
@@ -236,6 +236,7 @@ const LEGACY_STATE = path.join(__dirname, 'state');
236
236
  // must name its own state directory, and finds out by being told rather than by contaminating the
237
237
  // PM's registry and discovering it a day later.
238
238
  const REQUIRED_AS_LIBRARY = require.main !== module;
239
+ const { firstShell } = require('./lib/first-shell.js'); // premium-session-end: the startup shell, asked after the restore
239
240
  if (REQUIRED_AS_LIBRARY && !stateRoot.overrideDir(process.env)) {
240
241
  throw new Error(
241
242
  'server.js was required as a library with no PMOS_STATE_DIR set. Requiring it runs its module ' +
@@ -2985,9 +2986,11 @@ function restorePersisted(opts = {}) {
2985
2986
  const n = Number(String(meta.id).split('-')[1]); if (Number.isFinite(n) && n >= seq) seq = n + 1;
2986
2987
  } catch {}
2987
2988
  };
2989
+ const done = () => { if (typeof opts.onDone === 'function') { try { opts.onDone(); } catch {} } };
2988
2990
  if (!opts.progressive) {
2989
2991
  for (const f of files) restoreOne(f);
2990
2992
  adoptOrphanTmuxSessions();
2993
+ done();
2991
2994
  return;
2992
2995
  }
2993
2996
  // The running server restores in short slices AFTER it is listening, so the page is reachable at once and the sessions
@@ -2998,6 +3001,7 @@ function restorePersisted(opts = {}) {
2998
3001
  while (queue.length && Date.now() - t0 < 15) restoreOne(queue.shift());
2999
3002
  if (queue.length) { setImmediate(slice); return; }
3000
3003
  try { adoptOrphanTmuxSessions(); } catch {}
3004
+ done();
3001
3005
  try { pushSessions(); } catch {}
3002
3006
  };
3003
3007
  setImmediate(slice);
@@ -3350,6 +3354,15 @@ function sweepAutomaticSessions(now = Date.now()) {
3350
3354
  done.ended.push(s.id);
3351
3355
  } else if (act === 'remove' && !s.pty) {
3352
3356
  if (removeSession(s.id)) done.removed.push(s.id);
3357
+ } else if (!act && s.pty && /^chat:/.test(String(s.origin || ''))) {
3358
+ // premium-chat-session L1: an idle chat ends too; its next message resumes the same conversation
3359
+ const goal = (() => { try { return require('./lib/goal-chat.js').goalOf(STATE, String(s.origin).slice(5)); } catch { return null; } })();
3360
+ if (sessionOrigin.decideChat({ ...s, shown: () => sessionShown(s, now) }, policy, now, !!(goal && goal.state === 'started')) === 'end') {
3361
+ s.autoEnded = true; s.note = 'ended: idle too long (chat; it resumes on its next message)';
3362
+ if (s.tmux) tmuxKillSession(s.tmux);
3363
+ try { s.pty.kill(); } catch {}
3364
+ done.ended.push(s.id);
3365
+ }
3353
3366
  }
3354
3367
  }
3355
3368
  return done;
@@ -3787,6 +3800,15 @@ const chatSessions = {
3787
3800
  try { firstInput.deliver(s, t + '\r'); return true; } catch { return false; }
3788
3801
  },
3789
3802
  keys: (id, data) => { const s = sessions.get(String(id || '')); if (!s || !s.pty || s.state === 'exited') return false; try { s.pty.write(String(data)); return true; } catch { return false; } },
3803
+ // slice 4 (PRD L3): the live chat sessions, so a new one can end the longest idle; busy = working or a permission prompt waits
3804
+ list: (now = Date.now()) => [...sessions.values()].filter((s) => /^chat:/.test(String(s.origin || '')) && s.pty && s.state !== 'exited')
3805
+ .map((s) => ({ id: s.id, origin: s.origin, lastOutputAt: s.lastOutputAt, busy: harness.deriveState(s.state, s.lastOutputAt, now).state === 'working' || sessionShown(s, now) === 'blocked' })),
3806
+ end: (id) => { const s = sessions.get(String(id || '')); if (!s || !s.pty || s.state === 'exited') return false; s.autoEnded = true; s.note = 'ended: room for a newer chat (it resumes on its next message)'; if (s.tmux) tmuxKillSession(s.tmux); try { s.pty.kill(); } catch {} return true; },
3807
+ // slice 4 (PRD L2): whether Claude Code still has the conversation file for this id (any project folder)
3808
+ hasConversation: (uuid) => {
3809
+ const dir = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'projects');
3810
+ try { return fs.readdirSync(dir).some((p) => fs.existsSync(path.join(dir, p, String(uuid) + '.jsonl'))); } catch { return false; }
3811
+ },
3790
3812
  };
3791
3813
 
3792
3814
  /* A headless run (workspace-headless-jobs). The row is an ordinary session record, so every caller that checks a
@@ -3903,7 +3925,7 @@ function spawnSession(opts) {
3903
3925
  return s;
3904
3926
  }
3905
3927
  function noteSessionEnd(s) { try { if (refreshRun) refreshRun.ended(s); } catch (e) { warnWriteFail('refresh log (end)', e); } }
3906
- function spawnSessionInner({ name, agent, cwd, ws, origin, initialInput, profile, initiative, modelAsk, planItem, workType, autoDelete, launchFlags, addDirs, onDone, scratch, extraEnv, writePaths }) {
3928
+ function spawnSessionInner({ name, agent, cwd, ws, origin, initialInput, profile, initiative, modelAsk, planItem, workType, autoDelete, launchFlags, addDirs, onDone, scratch, extraEnv, writePaths, chatClaude }) {
3907
3929
  const id = nextSessionId();
3908
3930
  /* pm-os-absorb Run 1 — every AGENT session gets a token, `<id>.<8 hex>`, in its environment as PMOS_SESSION, and
3909
3931
  * PMOS_BIN, this workspace's own bin/pmos.js. `pmos item` run inside it is then attributed `agent:<token>` (the token
@@ -4001,6 +4023,8 @@ function spawnSessionInner({ name, agent, cwd, ws, origin, initialInput, profile
4001
4023
  * hooks post to this workspace (lib/routes-hooks.js, loopback only; the session token travels in the PMOS_SESSION env). */
4002
4024
  // premium-chat-session U1: a chat panel's session gets the /goal Stop hook (lib/goal-chat.js) instead, so a started goal keeps going until done.
4003
4025
  if (agent === 'claude' && /^chat:/.test(String(tag || ''))) argv.push('--settings', JSON.stringify(require('./lib/goal-chat.js').hookSettings(PORT)));
4026
+ // premium-chat-session L2: a chat keeps one Claude Code conversation id, so the session that replaces an ended one resumes it
4027
+ if (agent === 'claude' && /^chat:/.test(String(tag || '')) && chatClaude && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(chatClaude.id || ''))) argv.push(chatClaude.resume ? '--resume' : '--session-id', String(chatClaude.id));
4004
4028
  else if (process.env.PMOS_AGENT_HOOKS === '1' && agent === 'claude') argv.push('--settings', JSON.stringify(require('./lib/routes-hooks.js').settingsFor(PORT)));
4005
4029
  const launchArgs = argv;
4006
4030
  if (mres.tier) {
@@ -9936,14 +9960,13 @@ wss.on('connection', (ws) => {
9936
9960
  loadWorkspaces();
9937
9961
  if (HOME_ENABLED) registerWorkspace(SELF_ROOT); // the home workspace is hosted (PMOS-self, or the repo the launcher named)
9938
9962
  writeTmuxConf(); // must exist before restore may reattach or spawn creates
9939
- restorePersisted({ progressive: !REQUIRED_AS_LIBRARY });
9940
-
9941
9963
  // A first shell so the workspace is never empty on first run (honest real PTY). Only when there
9942
9964
  // is a repo to open it IN: an installed copy with no home and no registered repo yet must wait
9943
9965
  // for the launcher to POST a workspace rather than spawn a shell in the package directory.
9944
- if ((HOME_ENABLED || workspaces.size) && [...sessions.values()].filter((s) => s.pty).length === 0) {
9945
- spawnSession({ name: 'shell', agent: 'shell' });
9946
- }
9966
+ // premium-session-end: asked only once the restore has FINISHED. The running server restores in slices after it listens, so
9967
+ // checking right after the call saw no live pane on every launch and spawned one more `shell`, which tmux then kept: one idle
9968
+ // shell per restart, piling up in the session list.
9969
+ restorePersisted({ progressive: !REQUIRED_AS_LIBRARY, onDone: () => firstShell(sessions.values(), { canHost: HOME_ENABLED || workspaces.size > 0, spawn: () => spawnSession({ name: 'shell', agent: 'shell' }) }) });
9947
9970
 
9948
9971
  if (require.main === module) {
9949
9972
  // pm-os-absorb Run 2 (R25, X11): one nonce per launch, held in memory only. Never in process.env (so no PTY inherits