create-pmos 0.376.0 → 0.378.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.376.0",
3
+ "version": "0.378.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.378.0",
37
+ "at": "2026-10-21T07:48:19.057Z",
38
+ "f": 2,
39
+ "prs": [
40
+ {
41
+ "n": 987,
42
+ "t": "Chips for what an answer worked with, main one opens by itself",
43
+ "s": "Chips for what an answer worked with, main one opens by itself"
44
+ }
45
+ ]
46
+ },
47
+ {
48
+ "v": "0.377.0",
49
+ "at": "2026-10-21T07:27:29.956Z",
50
+ "f": 2,
51
+ "prs": [
52
+ {
53
+ "n": 986,
54
+ "t": "Attach files and photos to a premium chat message",
55
+ "s": "Attach files and photos to a premium chat message"
56
+ }
57
+ ]
58
+ },
35
59
  {
36
60
  "v": "0.376.0",
37
61
  "at": "2026-10-21T07:00:19.034Z",
@@ -297,30 +321,6 @@
297
321
  "s": "When a field loses focus or the keyboard closes, the bar goes back to the bottom of the screen and the dock back to the top."
298
322
  }
299
323
  ]
300
- },
301
- {
302
- "v": "0.358.0",
303
- "at": "2026-10-20T11:00:48.565Z",
304
- "f": 2,
305
- "prs": [
306
- {
307
- "n": 939,
308
- "t": "Chat sessions end when idle, resume, and cap at 4 live",
309
- "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."
310
- }
311
- ]
312
- },
313
- {
314
- "v": "0.357.0",
315
- "at": "2026-10-20T09:57:04.765Z",
316
- "f": 2,
317
- "prs": [
318
- {
319
- "n": 956,
320
- "t": "End sessions from the list; idle shells fold into one line",
321
- "s": "Every row has an End button (×) on hover, on focus and always on touch screens."
322
- }
323
- ]
324
324
  }
325
325
  ]
326
326
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@95b9ef4d
1
+ kernel-source: pmos@54bc44a2
2
2
  assembled: 2026-10-21
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-21T07:00:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T07:48:16Z"}
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-21T07:00:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T07:48:16Z"}
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-21T07:00:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T07:48:16Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -1,4 +1,28 @@
1
1
  [
2
+ {
3
+ "v": "0.378.0",
4
+ "at": "2026-10-21T07:48:19.057Z",
5
+ "f": 2,
6
+ "prs": [
7
+ {
8
+ "n": 987,
9
+ "t": "Chips for what an answer worked with, main one opens by itself",
10
+ "s": "Chips for what an answer worked with, main one opens by itself"
11
+ }
12
+ ]
13
+ },
14
+ {
15
+ "v": "0.377.0",
16
+ "at": "2026-10-21T07:27:29.956Z",
17
+ "f": 2,
18
+ "prs": [
19
+ {
20
+ "n": 986,
21
+ "t": "Attach files and photos to a premium chat message",
22
+ "s": "Attach files and photos to a premium chat message"
23
+ }
24
+ ]
25
+ },
2
26
  {
3
27
  "v": "0.376.0",
4
28
  "at": "2026-10-21T07:00:19.034Z",
@@ -419,6 +419,7 @@ The conversation beside every premium dialog is a real Claude Code session. Anyt
419
419
  - **The conversation** is Claude Code's own record, word for word. Claude's answers are formatted as Claude Code formats them: headings, bold, lists, code, tables, quotes and links (links open in a new tab). Your messages keep their line breaks, and a paste shows without the tags Claude Code wraps around it. A run of tool calls shows as one small grey line, for example "Used Read ×2, slack_read_thread". A connector tool shows its short name.
420
420
  - **While a session runs**, the panel reads it again every 2 seconds and changes only when there is something new. The messages already on screen stay still, so nothing blinks beside the viewer.
421
421
  - **A file Claude names** (a path such as `briefs/drafts/plan.md`, or a link to one) is underlined. Press it to read the file beside the conversation, as a tab in the viewer; on a phone, the Detail side shows it (on the Chat page, the viewer opens over the conversation). Markdown shows as a page, an HTML file shows as the page it draws (press **Source** for its code), and other text files show as code. An HTML page runs its own scripts, so its toggles and charts work, but it cannot reach PMOS or the internet: a web font falls back to the system font. It is read-only. While the tab is open it shows the newest version, so a file Claude is still writing stays current. A file outside the workspaces PMOS serves says "Not in a workspace" and is not read.
422
+ - **What an answer worked with** shows as buttons under it: the files Claude wrote, changed or read, the Jira tickets and Slack channels it used, and the links it named. The first one is the main one: a file Claude wrote comes first, then what it named in its words, then what it only read. When an answer finishes while the chat is open, its main one opens in the viewer by itself, once; answers that were there when you opened the chat open nothing. On a phone a bar over the message box offers it instead (**View**), so the conversation stays in view. A Jira ticket shows what PMOS last read from Jira for a board or initiative it syncs, with **Open in Jira**; a ticket PMOS has not read says so. A Slack channel or message opens with **Open in Slack**, as PMOS keeps no copy of Slack messages.
422
423
  - **A link to a Google Doc or a Confluence page** opens beside the conversation too, as the viewer shows a copy: the text PMOS has read, or **Read it now**. **A Claude artifact link** opens a tab with **Open in Claude**: claude.ai does not let another site show an artifact inside it. Other links open in a new browser tab.
423
424
  - **The session** is also listed in **Sessions** and in the console, where you can open its terminal.
424
425
  - **Ending a session ends only its process.** Whether you press End in the session list, or PMOS ends an idle chat, the conversation stays with the row: the panel and the session's own view still show every turn, read from Claude Code's record (in whichever Claude login ran it, such as `~/.claude-personal`). PMOS also keeps a copy in its own state folder (`chat-history/`), so the conversation stays after Claude Code removes old records. Files the session wrote are never touched. Your next message picks up the same conversation.
@@ -436,6 +437,19 @@ Under the message box, **Scratchpad** opens a pad above the box. It keeps notes
436
437
  - To make the pad taller or shorter, drag the grip on its top edge, or select the grip and press the up arrow or the down arrow. Double-click the grip for the default height.
437
438
  - A dialog with no conversation has no pad.
438
439
 
440
+ ### Attach files and photos
441
+
442
+ Press **+** at the left of the message box. The menu has three items: **Add files or photos**, **Slash commands** and **Scratchpad**.
443
+
444
+ - **Add files or photos** opens the file chooser. You can pick more than one file. On a phone, the phone shows its own choices, such as Take Photo and Photo Library.
445
+ - On a computer, you can also drag a file onto the conversation, or paste a screenshot into the message box.
446
+ - Each file shows as a chip above the message box. A photo shows a small picture. The chip says **Saving** until the file is saved, then it shows the size. Press **×** to remove a file before you send.
447
+ - A message can have 10 files at most. Each file can be 20 MB at most. You can send files without words.
448
+ - The files are saved on this machine, in the PMOS state folder (`chat-files/`). They never go into a repository.
449
+ - When you send, the message tells Claude the full path of each file. Claude reads the files itself: photos, screenshots, PDFs and text files. The chat session can read that folder without asking you first.
450
+ - In the conversation, your message shows its files as chips above your words. Press a chip to open the file in the viewer. A photo shows as the picture and a PDF shows as the document. For other files, the viewer gives **Download**.
451
+ - A dialog with no conversation has no **+**.
452
+
439
453
  ### Give Claude a goal with `/goal`
440
454
 
441
455
  Type `/` in the box to see the commands: `/goal`, `/compact` and `/clear`. Use the arrow keys and Enter, or press one.
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+ /* chat-files.js — files and photos the PM attaches to a premium chat message (initiative premium-chat-attach).
3
+ *
4
+ * dirOf(runtimeDir, key) → <runtimeDir>/chat-files/<hash of key> one folder for each conversation
5
+ * save({ runtimeDir, key, name, buf, now }) → { ok, name, path, size, kind } | { ok: false, status, error }
6
+ * remove({ runtimeDir, key, name }) → { ok } | { ok: false, … } a file not sent yet, from its chip's ×
7
+ * pathsOf({ runtimeDir, key, names }) → { ok, paths } | { ok: false, … } the saved files a message names
8
+ * withFiles(text, paths) → the message with the closing line that names each file for Claude
9
+ * splitFiles(text) → { text, files: [path] } the same line read back, for the PM's bubble
10
+ * servable(runtimeDir, p) → { ok, file, size, type, inline } | { ok: false, … } GET /api/chat-file?path=
11
+ *
12
+ * The files live in the workspace state folder, never in a repository, so nothing reaches git. The chat sessions start with
13
+ * the chat-files folder as an added directory, so Claude reads an attachment without a permission question. Nothing here
14
+ * sends anything anywhere. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const crypto = require('crypto');
18
+
19
+ const MAX_BYTES = 20 * 1024 * 1024, MAX_FILES = 10;
20
+ const DIR = 'chat-files';
21
+ const LEAD = '[Attached files, read each one: ';
22
+ const KINDS = Object.freeze({
23
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.heic': 'image/heic',
24
+ '.pdf': 'application/pdf',
25
+ });
26
+ const INLINE = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'application/pdf']);
27
+
28
+ const fail = (status, error) => ({ ok: false, status, error });
29
+ const rootOf = (runtimeDir) => path.join(runtimeDir, DIR);
30
+ const dirOf = (runtimeDir, key) => path.join(rootOf(runtimeDir), crypto.createHash('sha256').update(String(key)).digest('hex').slice(0, 20));
31
+
32
+ /** A file name safe on every disk and in the message line: letters, digits, dot, dash and underscore; spaces become dashes. Pure. */
33
+ function cleanName(name) {
34
+ const b = String(name == null ? '' : name).split(/[\\/]/).pop().normalize('NFKD').replace(/[^\w.\- ]+/g, '').replace(/\s+/g, '-').replace(/^[.-]+/, '');
35
+ const m = /^(.*?)(\.[A-Za-z0-9]{1,8})?$/.exec(b) || [];
36
+ const stem = (m[1] || '').slice(0, 80) || 'file', ext = (m[2] || '').toLowerCase();
37
+ return stem + ext;
38
+ }
39
+ /** The stored name: a time prefix keeps two files of the same name apart and orders the folder. */
40
+ const storedName = (name, now = new Date()) => now.toISOString().replace(/[-:]/g, '').replace(/\..*$/, '') + '-' + cleanName(name);
41
+ const NAME_RE = /^\d{8}T\d{6}-[\w.-]{1,96}$/;
42
+
43
+ function save({ runtimeDir, key, name, buf, now = new Date() }) {
44
+ if (!runtimeDir) return fail(409, 'this workspace has no state folder to keep the file in');
45
+ if (!key) return fail(400, 'key must name a conversation');
46
+ if (!Buffer.isBuffer(buf) || !buf.length) return fail(400, 'The file is empty.');
47
+ if (buf.length > MAX_BYTES) return fail(413, 'The file is larger than 20 MB.');
48
+ const dir = dirOf(runtimeDir, key), n = storedName(name, now);
49
+ fs.mkdirSync(dir, { recursive: true });
50
+ let f = path.join(dir, n), i = 1;
51
+ while (fs.existsSync(f)) f = path.join(dir, n.replace(/(\.[a-z0-9]+)?$/, (e) => '-' + (i++) + (e || '')));
52
+ fs.writeFileSync(f, buf);
53
+ const base = path.basename(f);
54
+ return { ok: true, name: base, path: f, size: buf.length, kind: KINDS[path.extname(base)] || 'file' };
55
+ }
56
+ function remove({ runtimeDir, key, name }) {
57
+ if (!runtimeDir || !key) return fail(400, 'key must name a conversation');
58
+ if (!NAME_RE.test(String(name || ''))) return fail(400, 'no such file');
59
+ try { fs.unlinkSync(path.join(dirOf(runtimeDir, key), String(name))); } catch { return fail(404, 'no such file'); }
60
+ return { ok: true };
61
+ }
62
+ function pathsOf({ runtimeDir, key, names }) {
63
+ if (names == null) return { ok: true, paths: [] };
64
+ if (!Array.isArray(names)) return fail(400, 'files must be a list of names');
65
+ if (names.length > MAX_FILES) return fail(400, 'At most ' + MAX_FILES + ' files on one message.');
66
+ const dir = runtimeDir && key ? dirOf(runtimeDir, key) : null;
67
+ const paths = [];
68
+ for (const n of names) {
69
+ const f = dir && NAME_RE.test(String(n || '')) ? path.join(dir, String(n)) : null;
70
+ if (!f || !fs.existsSync(f)) return fail(400, 'A file on this message was not saved: ' + String(n || '').slice(0, 80));
71
+ paths.push(f);
72
+ }
73
+ return { ok: true, paths };
74
+ }
75
+ /** The message with one closing line that names each file. Files only: a short ask stands in for the words. Pure. */
76
+ function withFiles(text, paths) {
77
+ const t = String(text == null ? '' : text).trim();
78
+ if (!paths || !paths.length) return t;
79
+ return (t || 'Look at the attached files.') + '\n\n' + LEAD + paths.join(' | ') + ']';
80
+ }
81
+ /** The PM's words and the files the closing line names. Pure; a message with no line comes back as it is. */
82
+ function splitFiles(text) {
83
+ const t = String(text == null ? '' : text);
84
+ const i = t.lastIndexOf(LEAD);
85
+ if (i < 0 || !/\]\s*$/.test(t)) return { text: t, files: [] };
86
+ const files = t.slice(i + LEAD.length).replace(/\]\s*$/, '').split(' | ').map((s) => s.trim()).filter(Boolean);
87
+ return { text: t.slice(0, i).trim(), files };
88
+ }
89
+ function servable(runtimeDir, p) {
90
+ if (!runtimeDir) return fail(404, 'no such file');
91
+ const root = path.resolve(rootOf(runtimeDir)), f = path.resolve(String(p || ''));
92
+ if (path.dirname(path.dirname(f)) !== root || !NAME_RE.test(path.basename(f))) return fail(404, 'no such file');
93
+ let st; try { st = fs.lstatSync(f); } catch { return fail(404, 'no such file'); }
94
+ if (!st.isFile()) return fail(404, 'no such file');
95
+ const type = KINDS[path.extname(f).toLowerCase()] || 'application/octet-stream';
96
+ return { ok: true, file: f, size: st.size, type, inline: INLINE.has(type) };
97
+ }
98
+
99
+ module.exports = { MAX_BYTES, MAX_FILES, DIR, LEAD, rootOf, dirOf, cleanName, storedName, save, remove, pathsOf, withFiles, splitFiles, servable };
@@ -244,6 +244,25 @@ function readSnapshot(root, initiative) {
244
244
  return { fetchedAt: isStr(data.fetched_at) ? data.fetched_at : null, query: isStr(data.query) ? data.query : null, tickets };
245
245
  }
246
246
 
247
+ /**
248
+ * One ticket by its key from every stored Jira reading (the initiatives' and the boards' snapshots), newest reading first, or null.
249
+ * The Chat page's viewer shows a ticket Claude worked with from this; it never reads Jira itself (premium-chat-viewer slice 2).
250
+ */
251
+ function findTicket(root, key) {
252
+ const k = String(key || '').toUpperCase();
253
+ if (!KEY_RE.test(k)) return null;
254
+ let names;
255
+ try { names = fs.readdirSync(jiraTickets.jiraDir(root)); } catch { return null; }
256
+ let best = null;
257
+ for (const n of names) {
258
+ if (!n.endsWith('.md') || n.endsWith('-tickets.md')) continue;
259
+ const snap = readSnapshot(root, n.slice(0, -3));
260
+ const r = snap && snap.tickets.get(k);
261
+ if (r && (!best || String(snap.fetchedAt || '') > String(best.fetchedAt || ''))) best = { ...r, fetchedAt: snap.fetchedAt, from: n.slice(0, -3) };
262
+ }
263
+ return best;
264
+ }
265
+
247
266
  /**
248
267
  * Write the snapshot from a saved search result. Only the tickets this initiative pushed are kept; any other issue in
249
268
  * the result is counted and ignored. A pushed ticket missing from the result keeps its last reading, marked stale.
@@ -509,5 +528,5 @@ function which(root, key) {
509
528
  return { ok: true, key: k, initiatives: hits };
510
529
  }
511
530
 
512
- module.exports = { queryFor, linkedInitiatives, normalize, sync, readSnapshot, which, sprintLabel, snapshotPath, snapshotRel, sprintQuery, syncSprints, readSprints, SPRINTS_FILE,
531
+ module.exports = { queryFor, linkedInitiatives, normalize, sync, readSnapshot, findTicket, which, sprintLabel, snapshotPath, snapshotRel, sprintQuery, syncSprints, readSprints, SPRINTS_FILE,
513
532
  sprintsToSummarise, saveSprintNotes, readSprintNotes, sameSprint, noteOne, NOTES_FILE };
@@ -14,6 +14,7 @@ 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
16
  const Goal = require('./goal-chat.js');
17
+ const Files = require('./chat-files.js');
17
18
  const Inbox = require('./agent-inbox.js');
18
19
  const actor = require('./actor.js');
19
20
  const WP = require('./my-work-premium.js');
@@ -90,7 +91,10 @@ async function post(req, res, url, ctx) {
90
91
  if (act === 'ask') {
91
92
  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; }
92
93
  // 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.
93
- const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: b.text, sessions: ctx.chatSessions, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
94
+ // premium-chat-attach A5: the files a message names must be saved files of its conversation; one closing line names each for Claude
95
+ const att = Files.pathsOf({ runtimeDir, key: b.key, names: b.files });
96
+ if (!att.ok) { ctx.json(res, { ok: false, error: att.error }, att.status); return true; }
97
+ const a = (ctx.chatSessions ? Ag.chat : Ag.ask)({ runtimeDir, key: b.key, text: Files.withFiles(b.text, att.paths), sessions: ctx.chatSessions, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || (/^src:/.test(String(b.key || '')) && !(b.key === 'src:this-page' && url.searchParams.get('ws'))) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
94
98
  ctx.json(res, a.body, a.status);
95
99
  return true;
96
100
  }
@@ -106,10 +110,56 @@ async function post(req, res, url, ctx) {
106
110
  return true;
107
111
  }
108
112
 
113
+ /* premium-chat-attach A4, A7: a file or photo the PM attaches to a chat message. POST takes the raw bytes as a page press and saves them in the
114
+ * conversation's folder; /remove deletes one not sent yet; GET serves a saved one to the PM's bubble and the viewer, an image or PDF inline,
115
+ * anything else as a download, so no attached page ever runs as this app. */
116
+ function readRaw(req, max) {
117
+ return new Promise((resolve) => {
118
+ const parts = []; let n = 0, over = false;
119
+ req.on('data', (c) => { if (over) return; n += c.length; if (n > max) { over = true; parts.length = 0; return; } parts.push(c); });
120
+ req.on('end', () => resolve(over ? { over: true } : { buf: Buffer.concat(parts) }));
121
+ req.on('error', () => resolve({ over: false, buf: null }));
122
+ });
123
+ }
124
+ async function chatFile(req, res, url, ctx) {
125
+ if (url.pathname === '/api/chat-file' && req.method === 'GET') {
126
+ const f = Files.servable(ctx.runtimeDir, url.searchParams.get('path'));
127
+ if (!f.ok) { ctx.json(res, { ok: false, error: f.error }, f.status); return true; }
128
+ const name = path.basename(f.file).replace(/^\d{8}T\d{6}-/, '');
129
+ res.writeHead(200, { 'Content-Type': f.type, 'Content-Length': f.size, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=3600',
130
+ 'Content-Disposition': (f.inline ? 'inline' : 'attachment') + '; filename="' + name + '"', ...(f.inline ? {} : { 'Content-Security-Policy': 'sandbox' }) });
131
+ fs.createReadStream(f.file).pipe(res);
132
+ return true;
133
+ }
134
+ if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
135
+ if (req.headers && req.headers['x-pmos-session']) { ctx.json(res, { ok: false, error: 'an agent session cannot attach a file to the PM\'s message' }, 403); return true; }
136
+ const g = guard.requirePagePress(req, {});
137
+ if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
138
+ if (url.pathname === '/api/chat-file/remove') {
139
+ const got = await ctx.readJson(req);
140
+ if (!got.ok) { ctx.json(res, { ok: false, error: 'body must be JSON' }, 400); return true; }
141
+ const key = String((got.body && got.body.key) || '');
142
+ if (!Ag.KEY_RE.test(key)) { ctx.json(res, { ok: false, error: 'key must name a row' }, 400); return true; }
143
+ const r = Files.remove({ runtimeDir: ctx.runtimeDir, key, name: got.body.name });
144
+ ctx.json(res, r.ok ? { ok: true } : { ok: false, error: r.error }, r.ok ? 200 : r.status);
145
+ return true;
146
+ }
147
+ if (url.pathname !== '/api/chat-file') return false;
148
+ const key = url.searchParams.get('key') || '';
149
+ if (!Ag.KEY_RE.test(key)) { ctx.json(res, { ok: false, error: 'key must name a row' }, 400); return true; }
150
+ const raw = await readRaw(req, Files.MAX_BYTES);
151
+ if (raw.over) { ctx.json(res, { ok: false, error: 'The file is larger than 20 MB.' }, 413); return true; }
152
+ let r;
153
+ try { r = Files.save({ runtimeDir: ctx.runtimeDir, key, name: url.searchParams.get('name') || 'file', buf: raw.buf }); } catch (e) { r = { ok: false, status: 500, error: 'The file could not be saved: ' + String((e && e.message) || e).slice(0, 120) }; }
154
+ ctx.json(res, r.ok ? { ok: true, name: r.name, path: r.path, size: r.size, kind: r.kind } : { ok: false, error: r.error }, r.ok ? 200 : r.status);
155
+ return true;
156
+ }
157
+
109
158
  module.exports = {
110
159
  products,
111
- prefixes: ['/api/briefing-premium'],
160
+ prefixes: ['/api/briefing-premium', '/api/chat-file'],
112
161
  handle: async (req, res, url, ctx) => {
162
+ if (url.pathname === '/api/chat-file' || url.pathname.startsWith('/api/chat-file/')) return chatFile(req, res, url, ctx);
113
163
  if (url.pathname === '/api/briefing-premium/goal-stop') {
114
164
  // 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.
115
165
  if (req.method !== 'POST') { ctx.json(res, { ok: false, error: 'POST only' }, 405); return true; }
@@ -429,6 +429,8 @@ function callTarget(input, root) {
429
429
  else if (str(input.command)) t = str(input.command).split('\n')[0];
430
430
  else if (str(input.pattern)) t = str(input.pattern) + (str(input.path) ? ' in ' + rel(str(input.path)) : '');
431
431
  else if (str(input.url)) t = str(input.url);
432
+ else if (str(input.issueIdOrKey) || str(input.issueKey) || str(input.issue_key)) t = str(input.issueIdOrKey) || str(input.issueKey) || str(input.issue_key); // a Jira call: the ticket (premium-chat-viewer slice 2)
433
+ else if (str(input.channel_id) || str(input.channel)) t = (str(input.channel_id) || str(input.channel)) + (str(input.message_ts) || str(input.thread_ts) ? ' ' + (str(input.message_ts) || str(input.thread_ts)) : ''); // a Slack call: the channel and the message
432
434
  else if (str(input.query)) t = str(input.query);
433
435
  else if (str(input.description)) t = str(input.description);
434
436
  else if (str(input.path)) t = rel(str(input.path));
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.376.0",
3
+ "version": "0.378.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.376.0",
9
+ "version": "0.378.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.376.0",
3
+ "version": "0.378.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,147 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-chat-attach-test.js — files and photos on a premium chat message (initiative premium-chat-attach).
4
+ * Serves the real My work page from the real server with a fixture model; files save through the real /api/chat-file in a scratch state folder.
5
+ * B1 the + and its menu · B2 Slash commands · B3 pick two files, chips, saved · B4 remove one · B5 paste and drop · B6 send names the files
6
+ * B7 the PM's bubble shows the files and a chip opens the photo in the viewer · B8 no key, no + · B9 phone */
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { spawn } = require('child_process');
10
+ const { findBrowser } = require('./lib/find-browser');
11
+ const T = require('./test-run').configure({ name: 'premium-chat-attach' });
12
+ const WP = require('./lib/my-work-premium.js');
13
+ const F = require('./fixtures/my-work-premium-facts.js');
14
+
15
+ const BASE = T.BASE;
16
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
17
+ const until = async (fn, ms = 6000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
18
+ const results = [];
19
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + extra : ''}`); };
20
+ let srv = null; let browser = null;
21
+ const finish = async (code) => {
22
+ if (browser) await browser.close().catch(() => {});
23
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
24
+ T.killTmux();
25
+ const bad = results.filter((x) => !x.cond).length;
26
+ console.log(`\n${results.length - bad}/${results.length} premium-chat-attach assertions passed`);
27
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
28
+ };
29
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
30
+ const SHOTS = process.env.ATTACH_SHOTS || ''; // a folder: the suite also saves screenshots there for review
31
+ const shot = async (page, n) => { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, n + '.png') }); };
32
+ const KEY = 'work:attach-1';
33
+ // a 2x2 PNG, so the chip and the viewer have a real picture to draw
34
+ const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVR4nGP4z8DwnwEIGP4zMDAwAAA+xAP9TfeQ1AAAAABJRU5ErkJggg==', 'base64');
35
+ const filesIn = () => { const d = path.join(T.STATE_DIR, 'chat-files'); const out = []; try { for (const s of fs.readdirSync(d)) for (const f of fs.readdirSync(path.join(d, s))) out.push(f); } catch { /* none yet */ } return out; };
36
+
37
+ (async () => {
38
+ const exe = findBrowser();
39
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
40
+ let chromium;
41
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
42
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT) }) });
43
+ await T.waitForServer(BASE);
44
+ browser = await chromium.launch({ executablePath: exe });
45
+ const model = WP.build({ v: F.view(), now: F.NOW });
46
+
47
+ const open = async ({ w = 1280, h = 900, scheme = 'light' } = {}) => {
48
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: scheme });
49
+ const page = await ctx.newPage();
50
+ const errors = [], asks = [];
51
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
52
+ await page.route('**/api/my-work-premium', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model, as_of: Date.now() }) }));
53
+ await page.route('**/api/briefing-premium/**', (r) => { const rq = r.request(); if (rq.method() !== 'GET') asks.push({ path: new URL(rq.url()).pathname, body: JSON.parse(rq.postData() || '{}') }); r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, turns: [], working: false }) }); });
54
+ await page.goto(BASE + '/premium-work.html', { waitUntil: 'domcontentloaded' });
55
+ await page.waitForFunction(() => document.querySelector('#dBody') !== null);
56
+ return { page, ctx, errors, asks };
57
+ };
58
+ const dlg = (page, key) => page.evaluate(async (key) => { const m = await import('/pm/premium-shell.js'); m.openDlg({ eye: 'Test', title: 'Attach test', say: 'Hello.', noteKey: key, html: '<p>detail</p>' }); m.setTab('chat'); }, key);
59
+ const close = (page) => page.evaluate(async () => { const m = await import('/pm/premium-shell.js'); m.closeDlg(); });
60
+ const chips = (page) => page.$$eval('#attRow .atc', (xs) => xs.map((x) => ({ name: x.querySelector('b').textContent, meta: (x.querySelector('em') || {}).textContent || '' })));
61
+
62
+ let { page, ctx, errors, asks } = await open();
63
+ await dlg(page, KEY);
64
+ /* B1 */
65
+ ok('B1 the + is at the left inside the message box', await page.isVisible('#askPlus') && await page.evaluate(() => { const p = document.querySelector('#askPlus').getBoundingClientRect(), t = document.querySelector('#askIn').getBoundingClientRect(); return p.left >= t.left && p.right < t.left + 60 && p.bottom <= t.bottom + 1 && p.top >= t.top - 1; }));
66
+ ok('B1 the menu starts closed and no chip row shows', await page.isHidden('#plusM') && await page.isHidden('#attRow'));
67
+ await page.click('#askPlus');
68
+ ok('B1 the + opens a menu of three above the box', await page.isVisible('#plusM') && (await page.$$('#plusM [data-plus]')).length === 3 && await page.evaluate(() => document.querySelector('#plusM').getBoundingClientRect().bottom <= document.querySelector('#askIn').getBoundingClientRect().top + 8));
69
+ ok('B1 the menu names Add files or photos, Slash commands and Scratchpad', /Add files or photos[\s\S]*Slash commands[\s\S]*Scratchpad/.test(await page.textContent('#plusM')));
70
+ await shot(page, 'menu-1280-light');
71
+ await page.keyboard.press('Escape');
72
+ ok('B1 Escape closes the menu and leaves the dialog open', await page.isHidden('#plusM') && await page.evaluate(() => document.querySelector('#dlg').classList.contains('on')));
73
+ /* B2 */
74
+ await page.click('#askPlus'); await page.click('[data-plus="slash"]');
75
+ ok('B2 Slash commands puts / in the box and shows the commands', (await page.inputValue('#askIn')) === '/' && await page.isVisible('#slashM'));
76
+ await page.fill('#askIn', ''); await page.evaluate(() => document.querySelector('#askIn').dispatchEvent(new Event('input', { bubbles: true })));
77
+ await page.click('#askPlus'); await page.click('[data-plus="pad"]');
78
+ ok('B2 Scratchpad opens the pad', await page.isVisible('#sPad'));
79
+ await page.click('#sPadT');
80
+ /* B3 */
81
+ await page.setInputFiles('#askFile', [{ name: 'Screenshot 1.41.39 PM.png', mimeType: 'image/png', buffer: PNG }, { name: 'Q4 roadmap.pdf', mimeType: 'application/pdf', buffer: Buffer.from('%PDF-1.4 test') }]);
82
+ ok('B3 two picked files show as two chips with their sizes once saved', !!(await until(async () => { const c = await chips(page); return c.length === 2 && c.every((x) => /KB/.test(x.meta)); })), JSON.stringify(await chips(page)));
83
+ ok('B3 a photo chip shows the picture', await page.evaluate(() => { const i = document.querySelector('#attRow img.ath'); return !!i && i.complete && i.naturalWidth === 2; }));
84
+ ok('B3 both files are saved in the state folder, never under the key', filesIn().length === 2 && filesIn().some((f) => /-Screenshot-1.41.39-PM\.png$/.test(f)));
85
+ await shot(page, 'chips-1280-light');
86
+ /* B4 */
87
+ await page.click('#attRow .atc:nth-child(2) [data-att-rm]');
88
+ ok('B4 × removes the chip and deletes the file not sent', (await chips(page)).length === 1 && !!(await until(async () => filesIn().length === 1)));
89
+ /* B5 */
90
+ await page.evaluate(() => { const dt = new DataTransfer(); dt.items.add(new File(['note text'], 'notes.txt', { type: 'text/plain' })); const e = new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }); document.querySelector('#askIn').dispatchEvent(e); });
91
+ ok('B5 a pasted file is attached', !!(await until(async () => { const c = await chips(page); return c.length === 2 && c[1].name === 'notes.txt' && /KB/.test(c[1].meta); })));
92
+ ok('B5 the paste put no text in the box', (await page.inputValue('#askIn')) === '');
93
+ await page.evaluate(() => { const dt = new DataTransfer(); dt.items.add(new File(['x'], 'dropped.csv', { type: 'text/csv' })); const b = document.querySelector('#dBody'); b.dispatchEvent(new DragEvent('dragover', { dataTransfer: dt, bubbles: true, cancelable: true })); b.dispatchEvent(new DragEvent('drop', { dataTransfer: dt, bubbles: true, cancelable: true })); });
94
+ ok('B5 a file dropped on the conversation is attached', !!(await until(async () => (await chips(page)).length === 3)));
95
+ ok('B5 the drop outline goes away after the drop', !(await page.evaluate(() => document.querySelector('#dBody').classList.contains('atdrop'))));
96
+ /* B6 */
97
+ await page.fill('#askIn', 'Where is this on PMOS?');
98
+ await page.click('#askGo');
99
+ const ask = await until(async () => asks.find((a) => a.path.endsWith('/ask')));
100
+ ok('B6 send passes the words and the three saved names', !!ask && ask.body.text === 'Where is this on PMOS?' && Array.isArray(ask.body.files) && ask.body.files.length === 3 && ask.body.files.every((n) => filesIn().includes(n)), JSON.stringify(ask && ask.body));
101
+ ok('B6 after the send the chips go', !!(await until(async () => await page.isHidden('#attRow'))));
102
+ // the real ask route turns the names into the closing line (no session here: the route answers, the line is checked through the store)
103
+ const lib = require('./lib/chat-files.js');
104
+ const paths = lib.pathsOf({ runtimeDir: T.STATE_DIR, key: KEY, names: ask.body.files });
105
+ ok('B6 the names resolve to the files of this conversation', paths.ok && paths.paths.length === 3);
106
+ /* B7 */
107
+ const line = lib.withFiles('Where is this on PMOS?', paths.paths).replace(/\n/g, ' ');
108
+ await page.evaluate(async (text) => { const m = await import('/pm/premium-shell.js'); document.querySelector('#dBody .stream').innerHTML = m.sessionHtml({ state: 'conv', messages: [{ role: 'user', text }] }); }, line);
109
+ ok('B7 the PM\'s bubble shows the files as chips and the words, not the line', await page.evaluate(() => { const u = document.querySelector('#dBody .turn.u .ub'); return !!u && u.querySelectorAll('.atc[data-att]').length === 3 && /Where is this on PMOS\?/.test(u.textContent) && !/Attached files/.test(u.textContent); }));
110
+ await shot(page, 'bubble-1280-light');
111
+ await page.click('#dBody .turn.u .atc[data-att$=".png"]');
112
+ ok('B7 a photo chip opens the picture in the viewer', !!(await until(async () => page.evaluate(() => { const i = document.querySelector('#dOut .obody.vw:not([hidden]) img.atview'); return !!i && i.complete && i.naturalWidth === 2; }))));
113
+ await shot(page, 'viewer-1280-light');
114
+ const png = paths.paths.find((p) => p.endsWith('.png')), txt = paths.paths.find((p) => p.endsWith('.txt'));
115
+ const r1 = await fetch(BASE + '/api/chat-file?path=' + encodeURIComponent(png));
116
+ ok('B7 a photo is served inline as an image', r1.status === 200 && r1.headers.get('content-type') === 'image/png' && /^inline/.test(r1.headers.get('content-disposition')));
117
+ const r2 = await fetch(BASE + '/api/chat-file?path=' + encodeURIComponent(txt));
118
+ ok('B7 any other file is a sandboxed download', r2.status === 200 && /^attachment/.test(r2.headers.get('content-disposition')) && r2.headers.get('content-security-policy') === 'sandbox');
119
+ const r3 = await fetch(BASE + '/api/chat-file?path=' + encodeURIComponent(path.join(T.STATE_DIR, 'settings.json')));
120
+ ok('B7 a path outside the attachments is refused', r3.status === 404);
121
+ const r4 = await fetch(BASE + '/api/chat-file?key=' + encodeURIComponent(KEY) + '&name=x.png', { method: 'POST', body: PNG });
122
+ ok('B7 a save that does not come from the page is refused', r4.status === 403);
123
+ await close(page);
124
+ /* B8 */
125
+ await dlg(page, null);
126
+ ok('B8 a dialog with no conversation has no +', await page.isHidden('#askPlus'));
127
+ await close(page);
128
+ ok('B1-B8 no page errors', errors.length === 0, errors.join(' | '));
129
+ await ctx.close();
130
+
131
+ /* B9 phone, both themes */
132
+ for (const scheme of ['light', 'dark']) {
133
+ ({ page, ctx, errors } = await open({ w: 390, h: 844, scheme }));
134
+ await dlg(page, KEY);
135
+ const h0 = await page.evaluate(() => document.querySelector('#askF').getBoundingClientRect().height);
136
+ await page.setInputFiles('#askFile', [{ name: 'IMG_2041.png', mimeType: 'image/png', buffer: PNG }, { name: 'a-rather-long-file-name-for-a-phone.pdf', mimeType: 'application/pdf', buffer: Buffer.from('%PDF') }, { name: 'third.png', mimeType: 'image/png', buffer: PNG }]);
137
+ await until(async () => (await chips(page)).length === 3 && (await chips(page)).every((x) => /KB/.test(x.meta)));
138
+ await shot(page, 'chips-390-' + scheme);
139
+ ok(`B9 ${scheme}: on a phone the +, the box and the chips stay inside the width`, await page.evaluate(() => { const w = innerWidth; return ['#askPlus', '#askIn', '#attRow'].every((s) => { const r = document.querySelector(s).getBoundingClientRect(); return r.width > 0 && r.left >= 0 && r.right <= w + 1; }) && document.documentElement.scrollWidth <= w; }));
140
+ ok(`B9 ${scheme}: the chips sit in one row, so the box grows by one row only`, await page.evaluate((h0) => { const r = [...document.querySelectorAll('#attRow .atc')].map((x) => Math.round(x.getBoundingClientRect().top)); return new Set(r).size === 1 && document.querySelector('#askF').getBoundingClientRect().height < h0 + 70; }, h0));
141
+ ok(`B9 ${scheme}: the + and × are 44px targets`, await page.evaluate(() => document.querySelector('#askPlus').getBoundingClientRect().height >= 44 && document.querySelector('[data-att-rm]').getBoundingClientRect().height >= 44));
142
+ await page.click('#askPlus'); await shot(page, 'menu-390-' + scheme);
143
+ ok(`B9 ${scheme}: no page errors`, errors.length === 0, errors.join(' | '));
144
+ await ctx.close();
145
+ }
146
+ finish();
147
+ })();