create-pmos 0.337.0 → 0.339.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.337.0",
3
+ "version": "0.339.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.339.0",
37
+ "at": "2026-10-20T03:01:53.405Z",
38
+ "f": 2,
39
+ "prs": [
40
+ {
41
+ "n": 934,
42
+ "t": "A started /goal keeps working until it is done",
43
+ "s": "Every chat panel session starts with a Claude Code Stop hook."
44
+ }
45
+ ]
46
+ },
47
+ {
48
+ "v": "0.338.0",
49
+ "at": "2026-10-20T02:42:22.826Z",
50
+ "f": 2,
51
+ "prs": [
52
+ {
53
+ "n": 933,
54
+ "t": "/goal in the premium chat panel grills the goal into a SMART goal",
55
+ "s": "Typing / opens a short menu with /goal, /compact and /clear."
56
+ }
57
+ ]
58
+ },
35
59
  {
36
60
  "v": "0.337.0",
37
61
  "at": "2026-10-20T02:07:25.408Z",
@@ -282,30 +306,6 @@
282
306
  "s": "The right pane can open other items as tabs beside its own detail, with at most 4 extra tabs."
283
307
  }
284
308
  ]
285
- },
286
- {
287
- "v": "0.319.0",
288
- "at": "2026-10-19T14:50:54.311Z",
289
- "f": 2,
290
- "prs": [
291
- {
292
- "n": 897,
293
- "t": "My work has no Calendar card; the Briefing holds the calendar",
294
- "s": "My work has no calendar."
295
- }
296
- ]
297
- },
298
- {
299
- "v": "0.318.0",
300
- "at": "2026-10-19T14:41:50.138Z",
301
- "f": 2,
302
- "prs": [
303
- {
304
- "n": 896,
305
- "t": "One calm top bar on every premium page",
306
- "s": "Every page has the same bar."
307
- }
308
- ]
309
309
  }
310
310
  ]
311
311
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@6989d666
1
+ kernel-source: pmos@85ad48db
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-20T02:07:22Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-20T03:01:50Z"}
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-20T02:07:22Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-20T03:01:50Z"}
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-20T02:07:22Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-20T03:01:50Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -1,4 +1,28 @@
1
1
  [
2
+ {
3
+ "v": "0.339.0",
4
+ "at": "2026-10-20T03:01:53.405Z",
5
+ "f": 2,
6
+ "prs": [
7
+ {
8
+ "n": 934,
9
+ "t": "A started /goal keeps working until it is done",
10
+ "s": "Every chat panel session starts with a Claude Code Stop hook."
11
+ }
12
+ ]
13
+ },
14
+ {
15
+ "v": "0.338.0",
16
+ "at": "2026-10-20T02:42:22.826Z",
17
+ "f": 2,
18
+ "prs": [
19
+ {
20
+ "n": 933,
21
+ "t": "/goal in the premium chat panel grills the goal into a SMART goal",
22
+ "s": "Typing / opens a short menu with /goal, /compact and /clear."
23
+ }
24
+ ]
25
+ },
2
26
  {
3
27
  "v": "0.337.0",
4
28
  "at": "2026-10-20T02:07:25.408Z",
@@ -379,3 +379,18 @@ The conversation beside every premium dialog is a real Claude Code session. Anyt
379
379
  - Answers from the older read-only agent stay above the session, marked "Earlier read-only answer".
380
380
 
381
381
  Sending and the option presses need the page's launch nonce, so an agent session cannot type into your chat.
382
+
383
+ ### Give Claude a goal with `/goal`
384
+
385
+ Type `/` in the box to see the commands: `/goal`, `/compact` and `/clear`. Use the arrow keys and Enter, or press one.
386
+
387
+ - **`/goal <what you want>`** asks Claude to make the goal SMART before any work. Claude reads the records first, then asks only what it could not find out: at most 5 questions, one at a time, about how you will know it is done, by when, whether it can be done here, and what it serves.
388
+ - **Each question** shows its answers as buttons, with the recommended one marked. Press one, or answer in your own words. **Start with defaults** stops the questions; a value you did not give is marked "assumed".
389
+ - **The goal card** shows the goal, its done points, what Claude may do, what it serves, the deadline and the round limit. Nothing runs until you press **Start**. **Change something** lets you say what to change; **Cancel** drops the goal.
390
+ - **Start** tells Claude to work on the goal until every done point is met. Merging follows your standing rule (merge once required CI is green). Claude asks before anything that is sent to other people.
391
+
392
+ - **While it works**, a goal card under the conversation shows the round, each done point met or open, and the deadline. The points are Claude's own report, so the card says "unverified". Each time Claude would stop with a point still open, it is told to keep going.
393
+ - **It stops by itself** when Claude reports every point met (Done), when it needs you (Needs you: answer it in the box and it goes on), at the deadline, after the round limit (12 unless the goal says fewer), or after 3 rounds that met no new point. The card says which.
394
+ - **Stop the goal** presses Esc in the session and ends the goal.
395
+
396
+ Start, Cancel and Stop need the page's launch nonce too. The goal and each round are kept in `goal-runs.jsonl` in the state folder.
@@ -14,6 +14,7 @@ const fs = require('fs');
14
14
  const path = require('path');
15
15
  const crypto = require('crypto');
16
16
  const headless = require('./headless.js');
17
+ const Goal = require('./goal-chat.js');
17
18
 
18
19
  const THREADS = 'briefing-premium-threads.jsonl';
19
20
  const KEY_RE = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/;
@@ -170,18 +171,25 @@ function chat({ runtimeDir, key, text, model, sessions, wsId, now = new Date() }
170
171
  if (q.length > MAX_Q * 4) return fail(400, 'The message is too long (' + MAX_Q * 4 + ' characters at most).');
171
172
  if (!sessions || typeof sessions.spawn !== 'function') return fail(409, 'this workspace cannot start sessions');
172
173
  const live = chatSessionOf(runtimeDir, key);
173
- if (live && sessions.alive(live)) {
174
- if (!sessions.type(live, q)) return fail(409, 'The message did not reach the session. Open it in Agent sessions.');
175
- return { status: 200, body: { ok: true, session: live, started: false } };
174
+ const alive = !!(live && sessions.alive(live));
175
+ 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');
177
+ // slice 2 (PRD G2): `/goal <text>` becomes the PMOS grilling prompt, on record before it reaches the session
178
+ let msg = q, goal = null;
179
+ const cmd = Goal.parseCommand(q);
180
+ if (cmd) { const b = Goal.begin({ runtimeDir, key, text: cmd.text, now }); if (b.error) return fail(400, b.error); msg = b.prompt; goal = b.id; }
181
+ const extra = goal ? { goal } : {};
182
+ if (alive) {
183
+ if (!sessions.type(live, msg)) return fail(409, 'The message did not reach the session. Open it in Agent sessions.');
184
+ if (!goal) Goal.resume({ runtimeDir, key, now }); // slice 3: the PM's answer to a goal that needs them sets it going again
185
+ return { status: 200, body: { ok: true, session: live, started: false, ...extra } };
176
186
  }
177
- const row = rowFor(model, key);
178
- if (!row) return fail(404, model ? 'that row is not on the page' : 'the page has not read the repository yet');
179
187
  let s;
180
- try { s = sessions.spawn({ name: 'chat: ' + clip(row.title, 60), agent: 'claude', ws: wsId, origin: 'chat:' + key, initialInput: openingFor(row, q) + '\r' }); } catch (e) { s = { state: 'exited', note: String((e && e.message) || e).slice(0, 120) }; }
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) }; }
181
189
  if (!s || s.state === 'exited' || !s.id) return fail(409, 'Claude could not start: ' + ((s && s.note) || 'no session'));
182
190
  fs.mkdirSync(runtimeDir, { recursive: true });
183
191
  fs.appendFileSync(path.join(runtimeDir, CHATS), JSON.stringify({ key, session: s.id, at: now.toISOString() }) + '\n');
184
- return { status: 200, body: { ok: true, session: s.id, started: true } };
192
+ return { status: 200, body: { ok: true, session: s.id, started: true, ...extra } };
185
193
  }
186
194
  /** A permission option ('1'…'9') or Stop ('esc'), typed into the key's live session with no Enter. */
187
195
  function press({ runtimeDir, key, what, sessions }) {
@@ -0,0 +1,173 @@
1
+ 'use strict';
2
+ /* goal-chat — `/goal` in the premium chat panel (initiative premium-chat-session, slice 2; PRD G2–G7).
3
+ * `/goal <text>` turns into a PMOS grilling prompt typed into the panel's own Claude Code session: Claude reads the records, asks at most
4
+ * five questions to make the goal SMART, and ends each message with a fenced `pmos-goal` JSON block the panel draws as chips or a goal card.
5
+ * Start and Cancel are the PM's presses. The record is append-only: goal-runs.jsonl in the state folder (grilling, started, cancelled). */
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const crypto = require('crypto');
9
+
10
+ const RUNS = 'goal-runs.jsonl';
11
+ const LIMIT = 12;
12
+ const MAX_TEXT = 1000;
13
+ // The first line of every message PMOS types for a goal. The panel reads it to show the PM's turn as typed (public/pm/goal-chat.js).
14
+ const MARK = { grill: '[PMOS /goal]', start: '[PMOS /goal start]', cancel: '[PMOS /goal cancel]' };
15
+
16
+ /** '/goal Ship X' → { text: 'Ship X' }; '/goal' → { text: '' }; anything else → null. */
17
+ function parseCommand(s) {
18
+ const m = /^\/goal(?:\s+([\s\S]*))?$/.exec(String(s == null ? '' : s).trim());
19
+ return m ? { text: (m[1] || '').trim() } : null;
20
+ }
21
+
22
+ function grillPrompt(text) {
23
+ return [
24
+ MARK.grill + ' The PM set a goal: ' + text,
25
+ '',
26
+ 'Make it a SMART goal with the PM before any work. Do not start the work: nothing runs until the PM presses Start on the page.',
27
+ '1. Read the records first (this repository\'s planning/ folder, its initiatives and OKRs, open pull requests where you can) and fill what you can of S (what exactly), M (how we know it is done, as checkable points), A (achievable with what you can do in this session; if it is too big, propose the first part), R (which initiative or KR it serves) and T (by when).',
28
+ '2. Ask the PM only about the points you could not fill. At most 5 questions in all, one per message, in this order: M, T, A, R, S. Each question offers 2 or 3 short answers; mark one as recommended.',
29
+ '3. Stop asking when all five are filled, after 5 questions, or when the PM says "start with defaults". A point the PM did not give takes a sensible default and is listed in "assumed".',
30
+ '4. If the goal needs something you cannot do here (for example sending mail that is not set up), say so and propose what you can do instead.',
31
+ '',
32
+ 'End every message of this exchange with one fenced code block with the language tag pmos-goal, holding one JSON object. The page draws it; keep the words before it short.',
33
+ '- While asking: {"step":"question","n":2,"question":"How will we know it is done?","options":[{"label":"PR green and checklist ticked","recommended":true},{"label":"PR merged"}],"draft":{...what is known so far}}',
34
+ '- When ready: {"step":"ready","draft":{...}}',
35
+ 'The draft: {"goal":"one sentence","done":["checkable point", "..."],"may":"what you may do","serves":"initiative or KR","by":"deadline, ISO 8601 date and time","limit":' + LIMIT + ',"assumed":["by"]}. Leave out the keys you do not know yet.',
36
+ ].join('\n');
37
+ }
38
+
39
+ function startMessage(draft) {
40
+ return [
41
+ MARK.start + ' The PM pressed Start. Work on this goal now, as you would in a terminal under the PM\'s Claude Code settings, until every done point is met:',
42
+ JSON.stringify(draft),
43
+ 'Merging follows the PM\'s standing rule (merge once required CI is green). Ask before anything that is sent to other people. Stop and ask when you need the PM.',
44
+ 'At the end of each message about this goal, add a fenced pmos-goal block: {"step":"progress","state":"working|done|needs-you","met":["done points met"],"open":["done points still open"]}.',
45
+ ].join('\n');
46
+ }
47
+ const cancelMessage = () => MARK.cancel + ' The PM cancelled this goal. Do no more work for it and say in one line what you stopped.';
48
+
49
+ const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1) + '…' : t; };
50
+ /** The confirmed draft as the server keeps it, or null when it has no goal or no done point. Unknown keys are dropped. */
51
+ function cleanDraft(d) {
52
+ if (!d || typeof d !== 'object') return null;
53
+ const goal = clip(d.goal, 300);
54
+ const done = (Array.isArray(d.done) ? d.done : []).map((x) => clip(x, 200)).filter(Boolean).slice(0, 8);
55
+ if (!goal || !done.length) return null;
56
+ const limit = Number.isInteger(d.limit) && d.limit >= 1 && d.limit <= LIMIT ? d.limit : LIMIT;
57
+ const out = { goal, done, limit };
58
+ for (const k of ['may', 'serves', 'by']) { const v = clip(d[k], 300); if (v) out[k] = v; }
59
+ const assumed = (Array.isArray(d.assumed) ? d.assumed : []).filter((k) => ['goal', 'done', 'may', 'serves', 'by', 'limit'].includes(k));
60
+ if (assumed.length) out.assumed = assumed;
61
+ return out;
62
+ }
63
+
64
+ function append(runtimeDir, row) { fs.mkdirSync(runtimeDir, { recursive: true }); fs.appendFileSync(path.join(runtimeDir, RUNS), JSON.stringify(row) + '\n'); }
65
+ /** The key's latest goal: { id, state: grilling|started|cancelled, text, draft?, at } or null. */
66
+ function goalOf(runtimeDir, key) {
67
+ let t; try { t = fs.readFileSync(path.join(runtimeDir, RUNS), 'utf8'); } catch { return null; }
68
+ let g = null;
69
+ for (const l of t.split('\n')) {
70
+ if (!l.trim()) continue; let e; try { e = JSON.parse(l); } catch { continue; }
71
+ if (!e || e.key !== key) continue;
72
+ if (e.event === 'grilling') g = { id: e.id, state: 'grilling', text: e.text, at: e.at };
73
+ else if (!g || e.id !== g.id) continue;
74
+ else if (e.event === 'started') g = { ...g, state: 'started', draft: e.draft, startedAt: e.at, rounds: 0, met: [], open: (e.draft && e.draft.done) || [], at: e.at };
75
+ else if (e.event === 'cancelled') g = { ...g, state: 'cancelled', at: e.at };
76
+ else if (e.event === 'round') g = { ...g, rounds: e.n, met: e.met || [], open: e.open || [], at: e.at };
77
+ else if (e.event === 'resumed') g = { ...g, state: 'started', reason: undefined, at: e.at };
78
+ else if (['done', 'stopped', 'waiting'].includes(e.event)) g = { ...g, state: e.event, ...(e.reason ? { reason: e.reason } : {}), met: e.met || g.met, open: e.open || g.open, at: e.at };
79
+ }
80
+ return g;
81
+ }
82
+
83
+ /* ── slice 3: until achieved (PRD U1–U7) ───────────────────────────────────────────────────────────────────────────────
84
+ * Claude Code's Stop hook posts here each time Claude would end its turn in a chat session. While the key's goal is started
85
+ * and not done, the answer blocks the stop and tells Claude what is still open; it lets Claude stop when Claude reports the
86
+ * goal done or needs the PM, at the deadline, after the round limit, or after NO_PROGRESS rounds that met no new point.
87
+ * The done check is Claude's own report (a pmos-goal progress block), so the page calls it unverified. */
88
+ const NO_PROGRESS = 3;
89
+ const REASON = { deadline: 'The deadline has passed.', limit: 'It used all its rounds.', 'no-progress': 'Three rounds in a row met no new done point.', pm: 'You stopped it.' };
90
+ /** The last fenced pmos-goal block in a message, parsed, or null. */
91
+ function blockOf(text) {
92
+ const re = /```pmos-goal[^\n]*\n([\s\S]*?)```/g;
93
+ let m, last = null; while ((m = re.exec(String(text || '')))) last = m;
94
+ if (!last) return null;
95
+ try { const b = JSON.parse(last[1]); return b && typeof b === 'object' ? b : null; } catch { return null; }
96
+ }
97
+ const strs = (a) => (Array.isArray(a) ? a.map((x) => clip(x, 200)).filter(Boolean).slice(0, 8) : null);
98
+ /** The chat key a session belongs to (premium-chat-sessions.jsonl, the last line that names it), or null. */
99
+ function keyOfSession(runtimeDir, session, chatsFile) {
100
+ let t; try { t = fs.readFileSync(path.join(runtimeDir, chatsFile), 'utf8'); } catch { return null; }
101
+ let key = null;
102
+ for (const l of t.split('\n')) { if (!l.trim()) continue; let e; try { e = JSON.parse(l); } catch { continue; } if (e && e.session === session && typeof e.key === 'string') key = e.key; }
103
+ return key;
104
+ }
105
+ const roundsOf = (runtimeDir, id) => {
106
+ let t; try { t = fs.readFileSync(path.join(runtimeDir, RUNS), 'utf8'); } catch { return []; }
107
+ return t.split('\n').filter((l) => l.trim()).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter((e) => e && e.id === id && e.event === 'round');
108
+ };
109
+ /** The Stop hook's answer for one chat session: {} lets Claude stop; { decision: 'block', reason } keeps it working. */
110
+ function onStop({ runtimeDir, key, message, now = new Date() }) {
111
+ const g = key && goalOf(runtimeDir, key);
112
+ if (!g || g.state !== 'started' || !g.draft) return {};
113
+ const d = g.draft, b = blockOf(message), all = d.done || [];
114
+ const met = (b && b.step === 'progress' && strs(b.met)) || g.met || [];
115
+ const open = (b && b.step === 'progress' && strs(b.open)) || all.filter((x) => !met.includes(x));
116
+ const base = { id: g.id, key, met, open, at: now.toISOString() };
117
+ if (b && b.step === 'progress' && (b.state === 'done' || (open.length === 0 && met.length > 0))) { append(runtimeDir, { event: 'done', ...base }); return {}; }
118
+ if (b && b.step === 'progress' && b.state === 'needs-you') { append(runtimeDir, { event: 'waiting', ...base }); return {}; }
119
+ const due = Date.parse(d.by || '');
120
+ const stop = (reason) => { append(runtimeDir, { event: 'stopped', reason, ...base }); return {}; };
121
+ if (Number.isFinite(due) && now.getTime() > due) return stop('deadline');
122
+ const n = (g.rounds || 0) + 1;
123
+ if (n > (d.limit || LIMIT)) return stop('limit');
124
+ const prev = roundsOf(runtimeDir, g.id);
125
+ if (prev.length >= NO_PROGRESS && prev.slice(-NO_PROGRESS).every((r) => (r.met || []).length >= met.length)) return stop('no-progress');
126
+ append(runtimeDir, { event: 'round', n, ...base });
127
+ return { decision: 'block', reason: '[PMOS /goal round ' + n + '] The goal is not done yet: ' + met.length + ' of ' + all.length + ' done points met. Keep working on: ' + (open.length ? open.join('; ') : 'the open points') + '. This is round ' + n + ' of ' + (d.limit || LIMIT) + '. If you need the PM, ask and end with a pmos-goal progress block whose state is needs-you. End each message with the progress block.' };
128
+ }
129
+ /** The PM answered a goal that waits on them (U3): it is working again. A goal in any other state is left as it is. */
130
+ function resume({ runtimeDir, key, now = new Date() }) {
131
+ const g = goalOf(runtimeDir, key);
132
+ if (!g || g.state !== 'waiting') return false;
133
+ append(runtimeDir, { event: 'resumed', id: g.id, key, at: now.toISOString() });
134
+ return true;
135
+ }
136
+ /** The Claude Code --settings for a chat session: one Stop hook that posts to this workspace with the session's token. */
137
+ function hookSettings(port, host = '127.0.0.1') {
138
+ return { hooks: { Stop: [{ hooks: [{ type: 'http', url: 'http://' + host + ':' + port + '/api/briefing-premium/goal-stop', headers: { 'x-pmos-session': '$PMOS_SESSION' }, allowedEnvVars: ['PMOS_SESSION'], timeout: 10 }] }] } };
139
+ }
140
+
141
+ /** chat() hands a `/goal` message here: { error } or { id, prompt } with the grilling line already on record. */
142
+ function begin({ runtimeDir, key, text, now = new Date() }) {
143
+ const t = String(text || '').trim();
144
+ if (!t) return { error: 'Write the goal after /goal, for example: /goal Ship the Board metrics card.' };
145
+ if (t.length > MAX_TEXT) return { error: 'The goal is too long (' + MAX_TEXT + ' characters at most).' };
146
+ const id = 'goal-' + crypto.randomBytes(6).toString('hex');
147
+ append(runtimeDir, { event: 'grilling', id, key, text: t, at: now.toISOString() });
148
+ return { id, prompt: grillPrompt(t) };
149
+ }
150
+
151
+ const fail = (status, error) => ({ status, body: { ok: false, error } });
152
+ /** The PM's Start or Cancel on the goal card. sessions: { alive(id), type(id, text) }; session: the key's chat session id. */
153
+ function decide({ runtimeDir, key, id, act, draft, session, sessions, now = new Date() }) {
154
+ if (!runtimeDir) return fail(409, 'this workspace has no state folder to keep the goal in');
155
+ if (!['start', 'cancel', 'stop'].includes(act)) return fail(400, 'act must be start, cancel or stop');
156
+ const g = goalOf(runtimeDir, key);
157
+ if (!g || g.id !== id) return fail(404, 'That goal is not the one this conversation is on.');
158
+ if (act === 'stop') { // U5: the PM's Stop on a working goal: Esc in the session, and the goal ends
159
+ if (g.state !== 'started') return fail(409, 'This goal is not working.');
160
+ if (session && sessions && sessions.alive(session) && sessions.keys) sessions.keys(session, '\x1b');
161
+ append(runtimeDir, { event: 'stopped', reason: 'pm', id, key, at: now.toISOString() });
162
+ return { status: 200, body: { ok: true, id, state: 'stopped' } };
163
+ }
164
+ if (g.state !== 'grilling') return fail(409, g.state === 'cancelled' ? 'This goal was cancelled.' : 'This goal has already started.');
165
+ if (!session || !sessions || !sessions.alive(session)) return fail(409, 'No session is running for this conversation. Send /goal again to start one.');
166
+ let d = null;
167
+ if (act === 'start') { d = cleanDraft(draft); if (!d) return fail(400, 'The goal needs a sentence and at least one done point before it can start.'); }
168
+ if (!sessions.type(session, act === 'start' ? startMessage(d) : cancelMessage())) return fail(409, 'The message did not reach the session. Open it in Agent sessions.');
169
+ append(runtimeDir, { event: act === 'start' ? 'started' : 'cancelled', id, key, ...(d ? { draft: d } : {}), at: now.toISOString() });
170
+ return { status: 200, body: { ok: true, id, state: act === 'start' ? 'started' : 'cancelled' } };
171
+ }
172
+
173
+ module.exports = { parseCommand, grillPrompt, startMessage, cancelMessage, cleanDraft, goalOf, begin, decide, onStop, resume, blockOf, keyOfSession, hookSettings, MARK, RUNS, LIMIT, NO_PROGRESS, REASON };
@@ -13,6 +13,8 @@ const fs = require('fs');
13
13
  const guard = require('./pm-guard.js');
14
14
  const Wr = require('./briefing-premium-writes.js');
15
15
  const Ag = require('./briefing-premium-agent.js');
16
+ const Goal = require('./goal-chat.js');
17
+ const actor = require('./actor.js');
16
18
  const WP = require('./my-work-premium.js');
17
19
  const BoardP = require('./board-premium.js');
18
20
  const InitP = require('./initiative-premium.js');
@@ -42,7 +44,7 @@ function ownerOf(ctx, ws) {
42
44
 
43
45
  const enginePath = () => ENGINE_PATHS.find((p) => fs.existsSync(p)) || null;
44
46
 
45
- const POSTS = ['decide', 'put-off', 'return', 'ask', 'press', 'refresh'];
47
+ const POSTS = ['decide', 'put-off', 'return', 'ask', 'press', 'goal', 'refresh'];
46
48
  const rootOf = (url, ctx) => {
47
49
  let root; try { const w = ctx.getWs && ctx.getWs(url.searchParams.get('ws') || null); root = w && w.root; } catch { root = null; }
48
50
  return root || path.resolve(__dirname, '..', '..');
@@ -78,6 +80,12 @@ async function post(req, res, url, ctx) {
78
80
  ctx.json(res, a.body, a.status);
79
81
  return true;
80
82
  }
83
+ if (act === 'goal') { // premium-chat-session G6: the PM's Start or Cancel on the goal card
84
+ if (!Ag.KEY_RE.test(String(b.key || ''))) { ctx.json(res, { ok: false, error: 'key must name a row' }, 400); return true; }
85
+ const a = Goal.decide({ runtimeDir, key: b.key, id: b.id, act: b.act, draft: b.draft, session: runtimeDir && Ag.chatSessionOf(runtimeDir, b.key), sessions: ctx.chatSessions });
86
+ ctx.json(res, a.body, a.status);
87
+ return true;
88
+ }
81
89
  if (act === 'ask') {
82
90
  let wsId; try { const w = merged && sk ? { id: sk.ws } : ctx.getWs && ctx.getWs(url.searchParams.get('ws') || null); wsId = w && w.id; } catch { wsId = undefined; }
83
91
  // premium-chat-session: the panel IS a Claude Code session (one per key). Without the server's session hooks it falls back to the read-only run.
@@ -100,6 +108,18 @@ async function post(req, res, url, ctx) {
100
108
  module.exports = {
101
109
  prefixes: ['/api/briefing-premium'],
102
110
  handle: async (req, res, url, ctx) => {
111
+ if (url.pathname === '/api/briefing-premium/goal-stop') {
112
+ // premium-chat-session U1: Claude Code's Stop hook for a chat session. The session's own token names it; the answer keeps a started goal going.
113
+ if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
114
+ const got = await ctx.readJson(req);
115
+ const tok = req.headers && req.headers['x-pmos-session'];
116
+ const who = actor.sessionForToken(Array.isArray(tok) ? tok[0] : tok, { sessDir: ctx.sessDir || path.join(ctx.runtimeDir || '', 'sessions') });
117
+ if (!who || !ctx.runtimeDir) { ctx.json(res, { ok: false, error: 'no valid session token' }, 401); return true; }
118
+ const key = Goal.keyOfSession(ctx.runtimeDir, who.session, Ag.CHATS);
119
+ const body = got.ok && got.body && typeof got.body === 'object' ? got.body : {};
120
+ ctx.json(res, key ? Goal.onStop({ runtimeDir: ctx.runtimeDir, key, message: body.last_assistant_message }) : {});
121
+ return true;
122
+ }
103
123
  if (url.pathname.startsWith('/api/briefing-premium/') && POSTS.includes(url.pathname.slice('/api/briefing-premium/'.length))) {
104
124
  if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
105
125
  return post(req, res, url, ctx);
@@ -109,7 +129,7 @@ module.exports = {
109
129
  const key = url.searchParams.get('key') || '';
110
130
  if (!Ag.KEY_RE.test(key)) { ctx.json(res, { ok: false, error: 'key must name a row' }, 400); return true; }
111
131
  const sid = ctx.runtimeDir ? Ag.chatSessionOf(ctx.runtimeDir, key) : null;
112
- ctx.json(res, { ok: true, ...Ag.threadOf(ctx.runtimeDir, key), session: sid && ctx.chatSessions && ctx.chatSessions.alive(sid) ? sid : null });
132
+ ctx.json(res, { ok: true, ...Ag.threadOf(ctx.runtimeDir, key), session: sid && ctx.chatSessions && ctx.chatSessions.alive(sid) ? sid : null, goal: ctx.runtimeDir ? Goal.goalOf(ctx.runtimeDir, key) : null });
113
133
  return true;
114
134
  }
115
135
  if (url.pathname !== '/api/briefing-premium') return false;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.337.0",
3
+ "version": "0.339.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.337.0",
9
+ "version": "0.339.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.337.0",
3
+ "version": "0.339.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",
@@ -0,0 +1,92 @@
1
+ /* goal-chat — the panel's half of `/goal` (initiative premium-chat-session, slice 2; PRD G1, G4, G5, G7). Pure: no DOM, so Node tests it.
2
+ * Claude ends each grilling message with a fenced `pmos-goal` JSON block (lib/goal-chat.js writes the rule into the prompt). This module
3
+ * splits that block off the words, draws a question as chips and a ready goal as one card, and shows the PM's PMOS-typed turns as typed. */
4
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
5
+
6
+ /** The `/` menu (G1): PMOS's /goal, then Claude Code's own commands. */
7
+ export const SLASH = [
8
+ { cmd: '/goal', name: 'Give Claude a goal', say: 'It asks a few questions to make the goal SMART, then works on it after you press Start.' },
9
+ { cmd: '/compact', name: 'Compact the conversation', say: 'Claude Code summarises the conversation so far to free room.' },
10
+ { cmd: '/clear', name: 'Clear the conversation', say: 'Claude Code starts again with an empty context in the same session.' },
11
+ ];
12
+ /** The menu items for what is in the box, or [] when the menu stays shut (no leading `/`, or a space typed). */
13
+ export const slashMatches = (v) => (/^\/[a-z]*$/i.test(String(v || '')) ? SLASH.filter((x) => x.cmd.startsWith(String(v).toLowerCase())) : []);
14
+
15
+ /** { text, block }: the words with the last `pmos-goal` block taken out, and that block parsed (null when there is none or it does not parse). */
16
+ export function splitGoal(text) {
17
+ const t = String(text == null ? '' : text);
18
+ const re = /```pmos-goal[^\n]*\n([\s\S]*?)```/g;
19
+ let m, last = null;
20
+ while ((m = re.exec(t))) last = m;
21
+ if (!last) return { text: t, block: null };
22
+ let block = null; try { block = JSON.parse(last[1]); } catch { block = null; }
23
+ return { text: (t.slice(0, last.index) + t.slice(last.index + last[0].length)).trim(), block: block && typeof block === 'object' ? block : null };
24
+ }
25
+
26
+ const MARK = { grill: '[PMOS /goal]', start: '[PMOS /goal start]', cancel: '[PMOS /goal cancel]' };
27
+ const OPENING = 'The PM is talking to you from the chat panel';
28
+ /** The PM's turn as the PM typed it (G7): `/goal Ship X` for the grilling prompt, a short line for Start and Cancel, and only the PM's
29
+ * words for the opening message that carries the row's context. Anything else is shown unchanged. */
30
+ export function shownUser(text) {
31
+ const t = String(text == null ? '' : text);
32
+ if (t.includes(MARK.start)) return 'Start the goal';
33
+ const r = /\[PMOS \/goal round (\d+)\]/.exec(t); if (r) return 'Keep going: round ' + r[1];
34
+ if (t.includes(MARK.cancel)) return 'Cancel the goal';
35
+ const g = t.indexOf(MARK.grill + ' The PM set a goal: ');
36
+ if (g >= 0) return '/goal ' + t.slice(g + (MARK.grill + ' The PM set a goal: ').length).split('\n')[0];
37
+ if (t.startsWith(OPENING)) { const i = t.lastIndexOf('\nThe PM says: '); if (i >= 0) return t.slice(i + '\nThe PM says: '.length); }
38
+ return t;
39
+ }
40
+
41
+ const LETTERS = [['S', 'goal'], ['M', 'done'], ['A', 'may'], ['R', 'serves'], ['T', 'by']];
42
+ const has = (d, k) => d && (k === 'done' ? Array.isArray(d.done) && d.done.length > 0 : !!d[k]);
43
+ /** S M A R T, filled for the points the draft holds. */
44
+ export const smartHtml = (d) => `<div class="smart" aria-label="SMART points filled">${LETTERS.map(([l, k]) => `<b class="${has(d, k) ? 'y' : ''}" title="${esc(k)}">${l}</b>`).join('')}</div>`;
45
+
46
+ /** The goal as a card (G5): every value, "assumed" on the defaulted ones. */
47
+ export function goalCard(d, state) {
48
+ const a = new Set(Array.isArray(d.assumed) ? d.assumed : []);
49
+ const row = (k, label, v) => (v ? `<dt>${label}</dt><dd${a.has(k) ? ' class="assumed"' : ''}>${v}</dd>` : '');
50
+ const pill = state === 'cancelled' ? 'Cancelled' : state && state !== 'grilling' ? 'Started' : 'Not started';
51
+ const done = Array.isArray(d.done) && d.done.length ? `<ul>${d.done.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : '';
52
+ return `<div class="gcard"><div class="grow"><b>${esc(d.goal || 'Goal')}</b><span class="gpill">${pill}</span></div><dl class="gkv">${row('done', 'Done when', done)}${row('may', 'It may', esc(d.may))}${row('serves', 'Serves', esc(d.serves))}${row('by', 'By', esc(d.by))}${row('limit', 'Limit', esc((Number.isInteger(d.limit) ? d.limit : 12) + ' rounds of work at most'))}</dl></div>`;
53
+ }
54
+
55
+ /** The block under Claude's words. live: this is the newest message, Claude is waiting and the goal is still being grilled, so it can be pressed. */
56
+ export function goalBlockHtml(block, { live = false, state = 'grilling' } = {}) {
57
+ if (!block) return '';
58
+ const d = block.draft && typeof block.draft === 'object' ? block.draft : {};
59
+ if (block.step === 'question') {
60
+ const opts = (Array.isArray(block.options) ? block.options : []).filter((o) => o && o.label).slice(0, 4);
61
+ const chips = live ? `<div class="chips">${opts.map((o) => `<button type="button" class="chip${o.recommended ? ' rec' : ''}" data-chat-say="${esc(o.label)}">${esc(o.label)}${o.recommended ? '<small>recommended</small>' : ''}</button>`).join('')}<button type="button" class="chip" data-chat-say="Start with defaults">Start with defaults</button></div>` : '';
62
+ return `${smartHtml(d)}<p class="tt"><b>${esc(block.question || '')}</b></p>${chips}`;
63
+ }
64
+ if (block.step === 'ready') {
65
+ const ok = !!(d.goal && Array.isArray(d.done) && d.done.length);
66
+ const btns = live && ok ? '<div class="chatopts"><button type="button" class="cta" data-goal="start">Start</button><button type="button" class="cta alt" data-goal="change">Change something</button><button type="button" class="cta alt" data-goal="cancel">Cancel</button></div>' : '';
67
+ return `${smartHtml(d)}${goalCard(d, state)}${btns}`;
68
+ }
69
+ if (block.step === 'progress') {
70
+ const met = Array.isArray(block.met) ? block.met.length : 0, open = Array.isArray(block.open) ? block.open.length : 0;
71
+ const word = block.state === 'done' ? 'Done, as Claude sees it' : block.state === 'needs-you' ? 'Needs you' : 'Working';
72
+ return `<p class="gprog">${esc(word)} · ${met} of ${met + open} done points met · unverified</p>`;
73
+ }
74
+ return '';
75
+ }
76
+
77
+ const WHY = { deadline: 'The deadline has passed.', limit: 'It used all its rounds.', 'no-progress': 'Three rounds in a row met no new done point.', pm: 'You stopped it.' };
78
+ /** The working goal's card (slice 3, PRD U4, U5): its state, the round, each done point met or open, and Stop while it works.
79
+ * goal: the GET /thread goal record. The done check is Claude's own report, so it says "unverified". */
80
+ export function goalProgressHtml(goal) {
81
+ if (!goal || !goal.draft || !['started', 'done', 'stopped', 'waiting'].includes(goal.state)) return '';
82
+ const d = goal.draft, all = Array.isArray(d.done) ? d.done : [], met = new Set(goal.met || []);
83
+ const limit = Number.isInteger(d.limit) ? d.limit : 12;
84
+ const pill = goal.state === 'started' ? 'Working · round ' + Math.max(1, (goal.rounds || 0) + 1) + ' of ' + limit
85
+ : goal.state === 'done' ? 'Done, as Claude reports it' : goal.state === 'waiting' ? 'Needs you' : 'Stopped';
86
+ const note = goal.state === 'stopped' ? (WHY[goal.reason] || 'It stopped.') + ' Send a message to go on, or /goal to set a new goal.'
87
+ : goal.state === 'waiting' ? 'Claude needs your answer above. Your reply lets it go on.'
88
+ : goal.state === 'done' ? 'Check the work before you rely on it. Claude checked its own points.' : 'Claude keeps working until every point is met, the deadline, or ' + limit + ' rounds.';
89
+ const pts = all.map((x) => `<li class="${met.has(x) ? 'm' : ''}"><i aria-hidden="true"></i><span>${esc(x)}</span><em>${met.has(x) ? 'met' : 'open'}</em></li>`).join('');
90
+ const stop = goal.state === 'started' ? '<div class="chatopts"><button type="button" class="cta alt" data-goal="stop">Stop the goal</button></div>' : '';
91
+ return `<div class="gcard gprog2" role="status"><div class="grow"><b>${esc(d.goal)}</b><span class="gpill">${esc(pill)}</span></div><p class="gprog">${met.size} of ${all.length} done points met · unverified${d.by ? ' · due ' + esc(d.by) : ''}</p><ul class="gpts">${pts}</ul><p class="gprog">${esc(note)}</p>${stop}</div>`;
92
+ }
@@ -4,6 +4,7 @@ import { recChipView, STOP_LINE } from './premium-meeting.js';
4
4
  import { vwReset } from './premium-viewer.js';
5
5
  import { chipActs, openLive, openFocus, mountRecord, HL_LINE } from './premium-vw-rec.js';
6
6
  import { lineItems, behindOf, refreshTargets, whenRead } from './freshness-words.js';
7
+ import { splitGoal, shownUser, goalBlockHtml, goalProgressHtml, slashMatches } from './goal-chat.js';
7
8
  export const $ = (s, r = document) => r.querySelector(s);
8
9
  export const $$ = (s, r = document) => [...r.querySelectorAll(s)];
9
10
  export const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
@@ -173,7 +174,7 @@ export function openDlg(o) {
173
174
  $('#dlg').inert = false; document.documentElement.style.overflow = 'hidden';
174
175
  $('#dEye').textContent = o.eye; $('#dTitle').textContent = o.title; $('#dSub').textContent = o.sub || ''; $('#dSub').hidden = !o.sub;
175
176
  $('#oMain').innerHTML = o.pane || `<article class="paper doc">${o.html}</article>`; $('#oLab').textContent = o.label || 'Detail'; vwReset(); // extra viewer tabs belong to the dialog that opened them
176
- $('#dBody').innerHTML = `<div class="stream" role="log">${o.stream || turnA(ptx(o.say))}</div><form class="askbar" id="askF"><input id="askIn" placeholder="Message Claude" maxlength="8000" autocomplete="off" aria-label="A message for Claude"><button type="submit" data-act="ask" id="askGo" aria-label="Send to Claude" title="Send to Claude"><svg class="i" viewBox="0 0 24 24"><path d="M5 12h14M13 6l6 6-6 6"/></svg></button></form><p class="fine2" id="askNote">${CHAT_NOTE}</p>`;
177
+ $('#dBody').innerHTML = `<div class="stream" role="log">${o.stream || turnA(ptx(o.say))}</div><form class="askbar" id="askF"><div class="slashm" id="slashM" role="listbox" aria-label="Commands" hidden></div><input id="askIn" placeholder="Message Claude, or type /" maxlength="8000" autocomplete="off" aria-label="A message for Claude" aria-controls="slashM"><button type="submit" data-act="ask" id="askGo" aria-label="Send to Claude" title="Send to Claude"><svg class="i" viewBox="0 0 24 24"><path d="M5 12h14M13 6l6 6-6 6"/></svg></button></form><p class="fine2" id="askNote">${CHAT_NOTE}</p>`;
177
178
  $('#dlg').classList.remove('full'); setMode('split'); setTab('out'); // on a phone the dialog opens on the Detail tab and the Detail / Conversation switch brings the conversation, as the mockup draws it
178
179
  $('#veil').classList.add('on'); $('#dlg').classList.add('on');
179
180
  $$('#dGrid .pane').forEach((p) => { p.scrollTop = 0; });
@@ -242,13 +243,21 @@ export function threadHtml(th) {
242
243
  /** "Used Read ×2, Edit" for a run of tool calls, as the console's conversation says it. */
243
244
  export const toolLine = (tools) => 'Used ' + Object.entries(tools || {}).map(([n, k]) => (k > 1 ? n + ' ×' + k : n)).join(', ');
244
245
  /** The session's part of the panel: its turns, the permission question with its options, and Stop while Claude works. Pure, for Node. */
245
- export function sessionHtml(c) {
246
+ /** goal: the key's /goal record (GET /thread), so the newest grilling message can be pressed (slice 2, PRD G4, G5). */
247
+ export function sessionHtml(c, goal = null) {
246
248
  if (!c) return '';
247
249
  if (c.state === 'ended') return turnAgent('<p class="tt" role="status">This session has ended. Your next message starts a new one.</p>');
248
250
  if (c.state !== 'conv') return turnAgent(`<p class="tt" role="status">${esc(c.missing || 'Claude is starting.')}</p>`);
249
- const out = (c.messages || []).map((m) => m.role === 'user' ? turnU(m.text)
250
- : m.role === 'assistant' ? turnAgent(`<p class="agtag">Claude</p>${paras(m.text)}`)
251
- : `<p class="toolline" title="${esc((m.calls || []).map((x) => x.tool + (x.target ? ' ' + x.target : '')).join('\n'))}">${esc(toolLine(m.tools))}</p>`);
251
+ const msgs = c.messages || [], last = msgs.length - 1;
252
+ const waiting = !c.ask && c.turn !== 'agent' && c.turn !== 'tool';
253
+ const out = msgs.map((m, i) => {
254
+ if (m.role === 'user') return turnU(shownUser(m.text));
255
+ if (m.role !== 'assistant') return `<p class="toolline" title="${esc((m.calls || []).map((x) => x.tool + (x.target ? ' ' + x.target : '')).join('\n'))}">${esc(toolLine(m.tools))}</p>`;
256
+ const g = splitGoal(m.text);
257
+ const live = i === last && waiting && !!goal && goal.state === 'grilling';
258
+ return turnAgent(`<p class="agtag">Claude</p>${g.text ? paras(g.text) : ''}${goalBlockHtml(g.block, { live, state: goal && goal.state })}`);
259
+ });
260
+ const gp = goalProgressHtml(goal); if (gp) out.push(gp);
252
261
  if (c.ask) out.push(turnAgent(`<p class="agtag">Claude asks before it goes on</p><p class="tt">${esc(c.ask.question)}</p><div class="chatopts">${(c.ask.options || []).map((o) => `<button type="button" class="cta alt" data-chat-press="${esc(o.n)}">${esc(o.label)}</button>`).join('')}</div>`));
253
262
  else if (c.turn === 'agent' || c.turn === 'tool') out.push(turnAgent(`<p class="tt" role="status">${c.turn === 'tool' && c.openCall ? 'Running ' + esc(c.openCall) + '.' : 'Claude is working.'} <button type="button" class="cta alt" data-chat-press="esc">Stop</button></p>`));
254
263
  return out.join('');
@@ -259,7 +268,8 @@ export function drawThread(th, key, conv) {
259
268
  const box = $('#dBody .stream'); if (!box) return;
260
269
  let t = $('#thr', box); if (!t) { box.insertAdjacentHTML('beforeend', '<div id="thr"></div>'); t = $('#thr', box); }
261
270
  const b = $('#dBody'), atEnd = b.scrollHeight - b.scrollTop - b.clientHeight < 80;
262
- t.innerHTML = threadHtml(th) + sessionHtml(conv);
271
+ t.innerHTML = threadHtml(th) + sessionHtml(conv, th.goal);
272
+ S.goal = th.goal || null; S.draft = readyDraft(conv);
263
273
  const go = $('#askGo'); if (go) go.disabled = !!th.working; // an earlier read-only run still answering
264
274
  const n = $('#askNote'); if (n) n.textContent = th.working ? 'The agent is answering. You can write again when it has.' : conv && conv.ask ? 'Claude is waiting for your answer above.' : CHAT_NOTE;
265
275
  if (atEnd) b.scrollTop = b.scrollHeight;
@@ -275,6 +285,12 @@ export async function loadThread(key) {
275
285
  drawThread(th, key, conv && conv.ok ? conv : null);
276
286
  if ((th.working || th.session) && S.key === key && $('#dlg').classList.contains('on')) threadTimer = setTimeout(() => loadThread(key), 2000);
277
287
  }
288
+ /** The draft of the newest ready goal block in the conversation, which Start sends as the confirmed goal. */
289
+ function readyDraft(conv) {
290
+ const ms = (conv && conv.messages) || [];
291
+ for (let i = ms.length - 1; i >= 0; i--) { if (ms[i].role !== 'assistant') continue; const b = splitGoal(ms[i].text).block; if (b && b.step === 'ready') return b.draft || null; }
292
+ return null;
293
+ }
278
294
  const chatPost = (act, body) => { const ws = new URLSearchParams(location.search).get('ws'); return pmPost('/api/briefing-premium/' + act + (ws ? '?ws=' + encodeURIComponent(ws) : ''), body).catch(() => null); };
279
295
  $('#dBody').addEventListener('click', async (e) => {
280
296
  const p = e.target.closest('[data-chat-press]'); if (!p || !S.key) return;
@@ -283,18 +299,55 @@ $('#dBody').addEventListener('click', async (e) => {
283
299
  if (!r || !r.ok) $('#askNote').textContent = (r && r.error) || 'The key did not reach the session.';
284
300
  setTimeout(() => loadThread(S.key), 500);
285
301
  });
302
+ /* /goal (slice 2): a chip sends its answer; Start and Cancel are the PM's presses on the goal card; Change something hands the box back. */
303
+ async function sendText(key, text) {
304
+ const go = $('#askGo'); if (go) go.disabled = true; $('#askNote').textContent = 'Sending.';
305
+ const res = await chatPost('ask', { key, text });
306
+ if (go) go.disabled = false;
307
+ if (!res || res.ok !== true) { $('#askNote').textContent = (res && res.error) || 'The message was not sent.'; return false; }
308
+ $('#askNote').textContent = res.started ? 'Claude is starting a session for this.' : 'Sent.';
309
+ const b = $('#dBody'); b.scrollTop = b.scrollHeight;
310
+ loadThread(key);
311
+ return true;
312
+ }
313
+ $('#dBody').addEventListener('click', async (e) => {
314
+ const say = e.target.closest('[data-chat-say]'), gb = e.target.closest('[data-goal]'), mi = e.target.closest('[data-slash]');
315
+ if (mi) { pickSlash(mi.dataset.slash); return; }
316
+ if (!S.key || (!say && !gb)) return;
317
+ if (say) { say.disabled = true; await sendText(S.key, say.dataset.chatSay); return; }
318
+ const act = gb.dataset.goal;
319
+ if (act === 'change') { const inp = $('#askIn'); inp.placeholder = 'Tell Claude what to change'; inp.focus(); return; }
320
+ if (!S.goal) return;
321
+ gb.disabled = true;
322
+ const r = await chatPost('goal', { key: S.key, id: S.goal.id, act, draft: S.draft });
323
+ $('#askNote').textContent = r && r.ok ? ({ start: 'Claude is starting on the goal.', cancel: 'The goal is cancelled.', stop: 'The goal is stopped.' }[act]) : (r && r.error) || 'The press did not reach the session.';
324
+ loadThread(S.key);
325
+ });
326
+ /* the `/` menu (G1): opens on a leading `/`, arrows move, Enter or Tab picks, Esc shuts it */
327
+ let slashAt = 0;
328
+ function drawSlash() {
329
+ const m = $('#slashM'), inp = $('#askIn'); if (!m || !inp) return;
330
+ const list = slashMatches(inp.value);
331
+ if (!list.length) { m.hidden = true; m.removeAttribute('data-esc-layer'); inp.removeAttribute('aria-activedescendant'); return; }
332
+ slashAt = Math.min(slashAt, list.length - 1);
333
+ m.innerHTML = list.map((x, i) => `<button type="button" role="option" id="slash-${i}" aria-selected="${i === slashAt}" class="${i === slashAt ? 'sel' : ''}" data-slash="${esc(x.cmd)}"><code>${esc(x.cmd)}</code><b>${esc(x.name)}</b><em>${esc(x.say)}</em></button>`).join('');
334
+ m.hidden = false; m.setAttribute('data-esc-layer', ''); inp.setAttribute('aria-activedescendant', 'slash-' + slashAt);
335
+ }
336
+ function pickSlash(cmd) { const inp = $('#askIn'); inp.value = cmd + ' '; slashAt = 0; drawSlash(); inp.focus(); }
337
+ $('#dBody').addEventListener('input', (e) => { if (e.target.id === 'askIn') { slashAt = 0; drawSlash(); } });
338
+ $('#dBody').addEventListener('keydown', (e) => {
339
+ if (e.target.id !== 'askIn') return;
340
+ const list = slashMatches(e.target.value); if (!list.length || $('#slashM').hidden) return;
341
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); slashAt = (slashAt + (e.key === 'ArrowDown' ? 1 : list.length - 1)) % list.length; drawSlash(); }
342
+ else if (e.key === 'Tab' || (e.key === 'Enter' && e.target.value !== list[slashAt].cmd)) { e.preventDefault(); pickSlash(list[slashAt].cmd); }
343
+ else if (e.key === 'Escape') { e.preventDefault(); e.target.value = ''; drawSlash(); }
344
+ });
286
345
  $('#dBody').addEventListener('submit', async (e) => {
287
346
  e.preventDefault();
288
347
  const inp = $('#askIn'), text = inp.value.trim(), key = S.key;
289
348
  if (!key) { $('#askNote').textContent = 'This row has no conversation, so the message was not sent.'; return; }
290
349
  if (!text) { $('#askNote').textContent = 'Write a message for Claude.'; return; }
291
- const go = $('#askGo'); go.disabled = true; $('#askNote').textContent = 'Sending.';
292
- const res = await chatPost('ask', { key, text });
293
- go.disabled = false;
294
- if (!res || res.ok !== true) { $('#askNote').textContent = (res && res.error) || 'The message was not sent.'; return; }
295
- inp.value = ''; $('#askNote').textContent = res.started ? 'Claude is starting a session for this.' : 'Sent.';
296
- const b = $('#dBody'); b.scrollTop = b.scrollHeight;
297
- loadThread(key);
350
+ if (await sendText(key, text)) { inp.value = ''; inp.placeholder = 'Message Claude, or type /'; drawSlash(); }
298
351
  });
299
352
 
300
353
  /* ── the hero folds into the dock on scroll ─────────────────────────────────────────────────────────────── */
@@ -2131,3 +2131,35 @@ button.wl-row[aria-pressed="true"] .wl-tog{background:var(--solid);color:var(--o
2131
2131
  --acc:var(--ink);--accw:var(--well);--sh1:var(--card-shadow);--sh2:var(--card-shadow);--sh3:var(--card-shadow);--hi:none}
2132
2132
  /* the console sheet's body is .brief, which is the premium hero sentence here: give it back the console's plain text */
2133
2133
  :root .c3 .brief{margin-top:0;max-width:none;font-size:inherit;line-height:inherit;font-weight:inherit;letter-spacing:normal;color:inherit;text-wrap:wrap;transform:none;will-change:auto}
2134
+
2135
+ /* ── /goal in the chat panel (initiative premium-chat-session, slice 2): the `/` menu, answer chips, the SMART letters and the goal card ── */
2136
+ .slashm{position:absolute;left:0;right:0;bottom:calc(100% - 6px);z-index:3;background:var(--card-solid);border-radius:var(--r-in);box-shadow:var(--card-shadow);padding:6px;display:grid;gap:2px}
2137
+ .slashm[hidden]{display:none}
2138
+ .askbar .slashm>button{display:grid;grid-template-columns:84px 1fr;align-items:baseline;gap:2px 12px;width:auto;height:auto;min-height:44px;text-align:left;padding:10px 12px;border-radius:14px;background:transparent;color:var(--ink);place-items:initial}
2139
+ .askbar .slashm>button.sel,.askbar .slashm>button:hover{background:var(--well)}
2140
+ .slashm code{font:600 var(--fs-3) var(--mono);color:var(--ember-ink);grid-row:span 2}
2141
+ .slashm b{font-weight:600}
2142
+ .slashm em{font-style:normal;color:var(--ink-2);font-size:var(--t-small)}
2143
+ .chips{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}
2144
+ .chip{min-height:44px;border:1px solid var(--hair);background:var(--card-solid);color:var(--ink);border-radius:999px;padding:7px 14px;font-size:var(--t-small)}
2145
+ .chip.rec{border-color:var(--ember);box-shadow:0 0 0 3px var(--spot)}
2146
+ .chip small{color:var(--ink-3);margin-left:6px}
2147
+ .chip:disabled{opacity:.55;cursor:not-allowed}
2148
+ .smart{display:flex;gap:6px;margin-bottom:8px}
2149
+ .smart b{font:600 var(--fs-1) var(--mono);width:24px;height:24px;border-radius:8px;display:grid;place-items:center;background:var(--well);color:var(--ink-3)}
2150
+ .smart b.y{background:var(--solid);color:var(--on-solid)}
2151
+ .gcard{background:var(--card-solid);border:1px solid var(--hair);border-radius:var(--r-in);padding:14px 16px;margin-top:6px}
2152
+ .gcard .grow{display:flex;justify-content:space-between;align-items:flex-start;gap:10px}
2153
+ .gcard .gpill{flex:none;font-size:var(--t-micro);padding:3px 10px;border-radius:999px;background:var(--well);color:var(--ink-2)}
2154
+ .gkv{display:grid;grid-template-columns:96px 1fr;gap:8px 14px;margin:12px 0 0}
2155
+ .gkv dt{color:var(--ink-2);font-size:var(--t-small)}
2156
+ .gkv dd{margin:0;font-size:var(--t-small);overflow-wrap:anywhere}
2157
+ .gkv dd ul{margin:0;padding-left:18px}
2158
+ .gkv dd.assumed::after{content:" · assumed";color:var(--ember-ink);font-size:var(--t-micro)}
2159
+ .gprog{margin:8px 0 0;font-size:var(--t-small);color:var(--ink-2)}
2160
+ @media (max-width:520px){.gkv{grid-template-columns:1fr;gap:2px}.gkv dd{margin-bottom:6px}}
2161
+ .gpts{list-style:none;margin:10px 0 0;padding:0;display:grid;gap:6px}
2162
+ .gpts li{display:grid;grid-template-columns:14px 1fr auto;gap:10px;align-items:baseline;font-size:var(--t-small)}
2163
+ .gpts i{width:10px;height:10px;border-radius:50%;box-shadow:inset 0 0 0 1.5px var(--ink-3)}
2164
+ .gpts li.m i{background:var(--ok);box-shadow:none}
2165
+ .gpts em{font-style:normal;color:var(--ink-3);font-size:var(--t-micro)}
@@ -3991,7 +3991,9 @@ function spawnSessionInner({ name, agent, cwd, ws, origin, initialInput, profile
3991
3991
  const argv = [...(mres.state === 'applied' ? mres.args : []), ...fres.args];
3992
3992
  /* PER-SESSION HOOKS (console3 wave D). Off unless PMOS_AGENT_HOOKS=1: then an agent session starts with --settings whose
3993
3993
  * hooks post to this workspace (lib/routes-hooks.js, loopback only; the session token travels in the PMOS_SESSION env). */
3994
- if (process.env.PMOS_AGENT_HOOKS === '1' && agent === 'claude') argv.push('--settings', JSON.stringify(require('./lib/routes-hooks.js').settingsFor(PORT)));
3994
+ // 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.
3995
+ if (agent === 'claude' && /^chat:/.test(String(tag || ''))) argv.push('--settings', JSON.stringify(require('./lib/goal-chat.js').hookSettings(PORT)));
3996
+ else if (process.env.PMOS_AGENT_HOOKS === '1' && agent === 'claude') argv.push('--settings', JSON.stringify(require('./lib/routes-hooks.js').settingsFor(PORT)));
3995
3997
  const launchArgs = argv;
3996
3998
  if (mres.tier) {
3997
3999
  const mc = modelLib.core();
@@ -38,6 +38,7 @@
38
38
  "briefing-premium.test.js",
39
39
  "briefing-premium-writes.test.js",
40
40
  "briefing-premium-agent.test.js",
41
+ "goal-chat.test.js",
41
42
  "briefing-premium-work.test.js",
42
43
  "briefing-premium-board.test.js",
43
44
  "briefing-premium-insights.test.js",
@@ -210,6 +211,7 @@
210
211
  "briefing-premium.test.js": 1,
211
212
  "briefing-premium-writes.test.js": 1,
212
213
  "briefing-premium-agent.test.js": 1,
214
+ "goal-chat.test.js": 1,
213
215
  "briefing-premium-work.test.js": 1,
214
216
  "briefing-premium-board.test.js": 1,
215
217
  "briefing-premium-insights.test.js": 1,