create-pmos 0.256.0 → 0.257.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.256.0",
3
+ "version": "0.257.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@f4eae68
1
+ kernel-source: pmos@97ec1d5
2
2
  assembled: 2026-10-18
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-18T01:25:47Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T01:44: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-18T01:25:47Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T01:44: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-18T01:25:47Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T01:44:16Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* briefing-premium-doc-edit-test.js — the premium sheet's Edit and Proposals tabs (initiative briefing-premium-doc-edit; planning/prd/briefing-premium-doc-edit-prd.md E1 to E8).
4
+ * Serves the real page from the real server. The initiative model and the /api/doc-sheet routes are answered by a small stateful stand-in, so each press can be
5
+ * read off the request the page sent. The routes' own behaviour (the file, the log, stale, 403) is in briefing-premium-doc-edit.test.js, on a scratch repository.
6
+ * E1 tabs · E2 edit · E3 ask · E4 proposals · E5 after a write · E6 held · E7 honesty · E8 fidelity and floors */
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: 'briefing-premium-doc-edit' });
12
+ const IP = require('./lib/initiative-premium.js');
13
+ const F = require('./fixtures/initiative-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 = 10000, 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} briefing-premium-doc-edit assertions passed`);
27
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
28
+ };
29
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
30
+
31
+ const MOCKUP = fs.readFileSync(path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'briefing-artifact.html'), 'utf8');
32
+ const CSS = fs.readFileSync(path.join(__dirname, 'public', 'pm', 'premium.css'), 'utf8');
33
+ const PATH = 'planning/prd/self-serve-v2-prd.md';
34
+ const TEXT = '---\ntype: PRD\ntitle: "Self-serve onboarding v2"\n---\n\n# PRD: Self-serve onboarding v2\n\n## Problem\n\nA partner waits for a person.\n\n## Goal\n\n- a first call without help\n\n## Requirements\n\nR1 a first call\n';
35
+ const prop = (o) => Object.assign({ id: 'prop-a', state: 'proposed', prompt: 'add a one-paragraph summary', at: '2026-10-18T01:00:00Z', hash: 'ha', by: 'agent', why: null, sections: [
36
+ { name: 'Summary', kind: 'added', before: '', after: 'Partners reach a first call without help.', current: null, stale: false },
37
+ { name: 'Goal', kind: 'changed', before: 'x', after: 'y', current: 'z', stale: true }] }, o || {});
38
+
39
+ (async () => {
40
+ const exe = findBrowser();
41
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
42
+ let chromium;
43
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
44
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PMOS_SELF_ROOT: path.resolve(__dirname, '..') }) });
45
+ await T.waitForServer(BASE);
46
+ browser = await chromium.launch({ executablePath: exe });
47
+
48
+ const open = async ({ w = 1280, h = 900, theme = 'light', props = [prop()], post = null } = {}) => {
49
+ const ctx = await browser.newContext({ viewport: { width: w, height: h } });
50
+ const page = await ctx.newPage();
51
+ const S = { text: TEXT, revs: [{ rev: 1, why: '', by: 'baseline', at: '2026-10-16T08:00:00Z' }], props, ask: null, errors: [], posts: [], gets: [] };
52
+ page.on('pageerror', (e) => S.errors.push(String((e && e.message) || e)));
53
+ await page.route('**/api/initiative-premium*', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model: IP.build(F.facts()), as_of: F.NOW }) }));
54
+ await page.route('**/api/doc-health/check', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, health: { passed: 1, total: 1, checks: [{ id: 'fresh', pass: true, reason: 'ok' }] } }) }));
55
+ await page.route('**/api/briefing-premium/**', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, turns: [], working: false }) }));
56
+ await page.route('**/api/doc-sheet/**', (r) => {
57
+ const rq = r.request(), u = new URL(rq.url()), route = u.pathname.replace('/api/doc-sheet/', ''), send = (b, status = 200) => r.fulfill({ status, contentType: 'application/json', body: JSON.stringify(b) });
58
+ if (rq.method() === 'GET') {
59
+ S.gets.push({ route, query: u.search });
60
+ if (route === 'log') return send({ ok: true, path: PATH, revisions: S.revs, events: [] });
61
+ if (route === 'at') return send({ ok: true, path: PATH, rev: S.revs.length, text: S.text });
62
+ if (route === 'proposals') return send({ ok: true, path: PATH, proposals: S.props });
63
+ if (route === 'ask') return send(S.ask || { ok: true, id: 'ask-1', state: 'working' });
64
+ return send({ ok: false, error: 'not in this test' }, 404);
65
+ }
66
+ const body = JSON.parse(rq.postData() || '{}'); S.posts.push({ route, query: u.search, body, headers: rq.headers() });
67
+ if (post) { const a = post(route, body, S); if (a) return send(a.body, a.status || 200); }
68
+ if (route === 'edit') { S.text = body.text; S.revs.push({ rev: S.revs.length + 1, why: body.why, by: 'pm', at: '2026-10-18T02:00:00Z' }); return send({ ok: true }); }
69
+ if (route === 'accept') { S.props = S.props.map((p) => (p.id === body.id ? Object.assign({}, p, { state: 'accepted' }) : p)); S.revs.push({ rev: S.revs.length + 1, why: 'add a one-paragraph summary', by: 'pm', at: '2026-10-18T02:00:00Z' }); return send({ ok: true }); }
70
+ if (route === 'reject') { S.props = S.props.map((p) => (p.id === body.id ? Object.assign({}, p, { state: 'rejected', why: body.why }) : p)); return send({ ok: true }); }
71
+ if (route === 'ask') { S.ask = { ok: true, id: 'ask-1', state: 'working' }; return send({ ok: true, id: 'ask-1', state: 'working' }); }
72
+ return send({ ok: false, error: 'not in this test' }, 404);
73
+ });
74
+ await page.goto(BASE + '/premium-initiative.html?id=self-serve-v2&ws=w1&board=w1&theme=' + theme);
75
+ await until(() => page.evaluate(() => document.querySelector('#cIniDoc')));
76
+ await page.locator('#dmList .dmo[data-doc="prd"]').click();
77
+ await until(() => page.evaluate(() => document.querySelector('#oMain .dsbody')));
78
+ return { ctx, page, S };
79
+ };
80
+ const txt = (p, q) => p.evaluate((s) => (document.querySelector(s) || {}).textContent || '', q);
81
+ const tab = async (p, k) => { await p.click(`#shT [data-sh="${k}"]`); await sleep(150); };
82
+
83
+ const A = await open(); const p = A.page;
84
+ ok('0 the sheet opens', !!(await p.evaluate(() => document.querySelector('#shT'))));
85
+ /* E1 tabs */
86
+ ok('E1 the sheet has Read, Edit, Proposals, Edit log and Health, with the open count on Proposals', await p.evaluate(() => [...document.querySelectorAll('#shT button')].map((b) => b.textContent.replace(/\s+/g, ' ').trim()).join('|') === 'Read|Edit|Proposals 1|Edit log|Health'));
87
+ ok('E1 the Read outline marks only a heading an open proposal names', await p.evaluate(() => { const b = [...document.querySelectorAll('.dso button')]; return b.length === 0 || b.every((x) => !x.querySelector('i') === !/Goal|Summary/.test(x.textContent)); }));
88
+ ok('E7 the footnote no longer says read-only', !/Read-only/.test(await txt(p, '#oMain .xn')) && /only when you press Save or Accept/.test(await txt(p, '#oMain .xn')));
89
+
90
+ /* E2 edit */
91
+ await tab(p, 'edit');
92
+ ok('E2 the Edit tab holds the file as text, Save is off, and the note says no changes', await p.evaluate((t) => document.querySelector('#dsEd').value === t && document.querySelector('#dsSave').disabled && /No changes yet/.test(document.querySelector('#dsNote').textContent), TEXT));
93
+ await p.fill('#dsEd', TEXT + '\nMore.\n');
94
+ ok('E2 a change turns Save on and the note says changed', await p.evaluate(() => !document.querySelector('#dsSave').disabled && /Changed/.test(document.querySelector('#dsNote').textContent)));
95
+ await p.click('#dsSave');
96
+ ok('E2 Save with no reason posts nothing and says why', await p.evaluate(() => /Say why the document changes/.test(document.querySelector('#dsErr').textContent)) && A.S.posts.length === 0);
97
+ ok('E2 the text typed is still there after the refusal', (await p.inputValue('#dsEd')) === TEXT + '\nMore.\n');
98
+ await tab(p, 'read'); await tab(p, 'edit');
99
+ ok('E2 the draft survives a tab switch', (await p.inputValue('#dsEd')) === TEXT + '\nMore.\n');
100
+ await p.fill('#dsWhy', 'add the missing line'); await p.click('#dsSave');
101
+ await until(() => A.S.posts.length);
102
+ const e1 = A.S.posts[0];
103
+ ok('E2 Save posts path, text and why to /api/doc-sheet/edit with the launch headers and the workspace', e1 && e1.route === 'edit' && Object.keys(e1.body).sort().join() === 'path,text,why' && e1.body.path === PATH && e1.body.why === 'add the missing line' && e1.body.text.endsWith('More.\n') && /ws=w1/.test(e1.query) && e1.headers.origin === BASE, JSON.stringify(e1 && { r: e1.route, q: e1.query }));
104
+ /* E5 after a write */
105
+ await until(() => p.evaluate(() => /No changes yet/.test((document.querySelector('#dsNote') || {}).textContent || '')));
106
+ ok('E5 after Save the text is read again from the route and the note says no changes', (await p.inputValue('#dsEd')).endsWith('More.\n') && await p.evaluate(() => document.querySelector('#dsSave').disabled));
107
+ await tab(p, 'log');
108
+ ok('E5 the Edit log shows the new revision with its reason', await until(() => p.evaluate(() => /v2 add the missing line/.test((document.querySelector('#oMain .evl') || {}).textContent || ''))));
109
+
110
+ /* E3 + E4 proposals */
111
+ await tab(p, 'props');
112
+ const pv = await until(() => p.evaluate(() => document.querySelector('.dsp') && { n: document.querySelectorAll('.dsp').length, t: document.querySelector('.dsp').textContent.replace(/\s+/g, ' '), acc: !!document.querySelector('[data-ds^="acc:"]'), rej: !!document.querySelector('[data-ds^="rej:"]'), stale: /Changed since this was proposed/.test(document.querySelector('.dsp').textContent), head: document.querySelector('#oMain .label:nth-of-type(2)') ? '' : '' }));
113
+ ok('E4 an open proposal names who, the request, the added text, and a stale section says so', pv && /The agent/.test(pv.t) && /add a one-paragraph summary/.test(pv.t) && /\+ Partners reach a first call/.test(pv.t) && pv.stale && pv.acc && pv.rej, JSON.stringify(pv));
114
+ ok('E4 the lists say how many are open and closed', await p.evaluate(() => /Open proposals · 1/.test(document.querySelector('#oMain').textContent) && !/Closed ·/.test(document.querySelector('#oMain').textContent)));
115
+ const nAcc = A.S.posts.length;
116
+ await p.click('[data-ds^="acc:"]');
117
+ await until(() => A.S.posts.length > nAcc);
118
+ const ac = A.S.posts[A.S.posts.length - 1];
119
+ ok('E4 Accept posts path, id, hash and only the sections still current', ac.route === 'accept' && Object.keys(ac.body).sort().join() === 'hash,id,path,sections' && ac.body.hash === 'ha' && ac.body.sections.join() === 'Summary', JSON.stringify(ac.body));
120
+ await until(() => p.evaluate(() => /Closed · 1/.test(document.querySelector('#oMain').textContent)));
121
+ ok('E5 after Accept the proposal is listed as closed and accepted, and none is open', await p.evaluate(() => /Open proposals · 0/.test(document.querySelector('#oMain').textContent) && /Accepted/.test(document.querySelector('.dsp.accepted').textContent) && /No open proposals/.test(document.querySelector('#oMain').textContent)));
122
+ ok('E5 the Proposals count is gone from the tab once none is open', await p.evaluate(() => document.querySelector('#shT [data-sh="props"]').textContent.trim() === 'Proposals'));
123
+ await A.ctx.close();
124
+
125
+ /* E4 stale-all, reject, ask */
126
+ {
127
+ const B = await open({ props: [prop({ sections: [{ name: 'Goal', kind: 'changed', before: 'x', after: 'y', current: 'z', stale: true }] }), prop({ id: 'prop-b', hash: 'hb', prompt: 'drop the code block', sections: [{ name: 'Requirements', kind: 'removed', before: 'R1', after: '', current: 'R1', stale: false }] })] });
128
+ const q = B.page; await tab(q, 'props');
129
+ ok('E4 a proposal whose every section is stale has no Accept and says so', await q.evaluate(() => { const d = [...document.querySelectorAll('.dsp')].find((x) => /add a one-paragraph summary/.test(x.textContent)); return d && !d.querySelector('[data-ds^="acc:"]') && !!d.querySelector('[data-ds^="rej:"]') && /cannot be accepted/.test(d.textContent); }));
130
+ ok('E4 a removed section says it removes', await q.evaluate(() => /Removes this section/.test(document.querySelector('#oMain').textContent)));
131
+ await q.click('[data-ds="rej:prop-b"]');
132
+ ok('E4 Reject asks for a reason first and posts nothing yet', await q.evaluate(() => !!document.querySelector('#dsRj')) && B.S.posts.length === 0);
133
+ await q.click('[data-ds="rejgo:prop-b"]');
134
+ ok('E4 Reject with no reason is refused with no post', await q.evaluate(() => /Say why you are rejecting it/.test(document.querySelector('#dsErr').textContent)) && B.S.posts.length === 0);
135
+ await q.fill('#dsRj', 'not needed'); await q.click('[data-ds="rejgo:prop-b"]'); await until(() => B.S.posts.length);
136
+ ok('E4 Reject posts path, id and why only', B.S.posts[0].route === 'reject' && Object.keys(B.S.posts[0].body).sort().join() === 'id,path,why' && B.S.posts[0].body.why === 'not needed');
137
+ await until(() => q.evaluate(() => /Closed · 1/.test(document.querySelector('#oMain').textContent)));
138
+ ok('E5 the rejected proposal is closed with its reason', await q.evaluate(() => /Rejected/.test(document.querySelector('.dsp.rejected').textContent) && /not needed/.test(document.querySelector('.dsp.rejected').textContent)));
139
+ /* ask */
140
+ await q.fill('#dsAsk', 'tighten the goal'); await q.click('[data-ds="ask"]'); await until(() => B.S.posts.length > 1);
141
+ const ak = B.S.posts[1];
142
+ ok('E3 Ask posts path and prompt to /api/doc-sheet/ask', ak.route === 'ask' && Object.keys(ak.body).sort().join() === 'path,prompt' && ak.body.prompt === 'tighten the goal' && /ws=w1/.test(ak.query));
143
+ ok('E3 while it works the tab says the agent can only read, and the button is off', await until(() => q.evaluate(() => /The agent is reading the document/.test(document.querySelector('#oMain').textContent) && document.querySelector('[data-ds="ask"]').disabled)));
144
+ ok('E3 the page polls the ask by id', await until(() => B.S.gets.some((g) => g.route === 'ask' && /id=ask-1/.test(g.query)), 8000));
145
+ B.S.ask = { ok: true, id: 'ask-1', state: 'failed', error: 'The run ended without an answer. Ask again.' };
146
+ ok('E3 a failed ask shows the route\'s own error', await until(() => q.evaluate(() => /The run ended without an answer/.test(document.querySelector('#oMain').textContent)), 8000));
147
+ ok('0 no page error', B.S.errors.length === 0, B.S.errors.join(' | '));
148
+ await B.ctx.close();
149
+ }
150
+ /* E5/E4 a refused accept shows the route's reason and reads again */
151
+ {
152
+ const C = await open({ post: (route) => (route === 'accept' ? { status: 409, body: { ok: false, error: 'stale: Summary changed since this proposal was made', reason: 'stale' } } : null) });
153
+ await tab(C.page, 'props'); await C.page.click('[data-ds^="acc:"]');
154
+ ok('E4 a refused Accept shows the route\'s reason and the proposal stays open', await until(() => C.page.evaluate(() => /stale: Summary changed since this proposal was made/.test((document.querySelector('#dsErr') || {}).textContent || '') && /Open proposals · 1/.test(document.querySelector('#oMain').textContent))));
155
+ await C.ctx.close();
156
+ }
157
+ /* the mockup's .dsed carries a toolbar above it (radius 0 0 14px 14px); this build leaves the toolbar out, so the box keeps the full 14px radius */
158
+ /* E8 fidelity: the page's rules for the new elements equal the mockup's last rule for each class */
159
+ const rule = (src, sel) => { const m = [...src.matchAll(new RegExp('(?:^|[}\\n])\\s*' + sel.replace(/[.#]/g, (c) => '\\' + c) + '\\{([^}]*)\\}', 'g'))].filter((x) => sel !== '.dsfoot' || /justify-content/.test(x[1])); return m.length ? m[m.length - 1][1].replace('border-radius:0 0 14px 14px', 'border-radius:14px').replace(/#6d3fd1/g, 'rgb(109,63,209)').replace(/\s+/g, '') : null; };
160
+ for (const sel of ['.dsed', '.dsy', '.dsfoot', '.dsdf', '#dsAsk']) {
161
+ const a = rule(MOCKUP, sel), b = rule(CSS, sel);
162
+ ok(`E8 ${sel} has the mockup's declarations`, a && b && b.replace(/;$/, '') === a.replace(/;$/, ''), JSON.stringify({ a, b }));
163
+ }
164
+ for (const [w, h, theme] of [[1280, 900, 'light'], [1280, 900, 'dark'], [390, 844, 'light'], [390, 844, 'dark']]) {
165
+ const R = await open({ w, h, theme });
166
+ for (const t of ['edit', 'props']) {
167
+ await tab(R.page, t);
168
+ const f = await R.page.evaluate(() => { const bad = []; for (const e of document.querySelectorAll('#oMain button,#oMain input:not([type=checkbox]),#oMain textarea')) { const r = e.getBoundingClientRect(); if (r.width && r.height && r.height < 32) bad.push(e.textContent.trim() || e.id); } return { sx: document.documentElement.scrollWidth - innerWidth, bad, out: [...document.querySelectorAll('#oMain textarea,#oMain .dsp,#oMain .dsask2')].filter((e) => e.getBoundingClientRect().right > innerWidth + 1).length }; });
169
+ ok(`E8 ${t} tab at ${w} px ${theme}: no sideways scroll, no tiny target, nothing past the edge`, f.sx <= 0 && f.bad.length === 0 && f.out === 0, JSON.stringify(f));
170
+ }
171
+ const cs = await R.page.evaluate(() => { const e = document.querySelector('#dsAsk'); const c = getComputedStyle(e); return { r: c.borderRadius, fs: c.fontSize }; });
172
+ ok(`E8 the ask box is 14px rounded, 15px type at ${w} px ${theme}`, cs.r === '14px' && cs.fs === '15px', JSON.stringify(cs));
173
+ await R.ctx.close();
174
+ }
175
+ finish();
176
+ })();
@@ -181,7 +181,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
181
181
  const nPost0 = A.posts.length;
182
182
  await p.locator('#dmList .dmo[data-doc="prd"]').click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && /Self-serve onboarding v2/.test(document.querySelector('#oMain').textContent) && document.querySelector('#oMain .dsbody'))); await sleep(500);
183
183
  const sh = await p.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, path: document.querySelector('#oMain .dpath').textContent, tabs: [...document.querySelectorAll('#shT button')].map((b) => b.textContent).join(','), fm: [...document.querySelectorAll('#oMain .kv2 span')].map((s) => s.textContent).join('|'), heads: [...document.querySelectorAll('#oMain h3.d2')].map((h) => h.textContent).join('|'), outline: [...document.querySelectorAll('#oMain .dso button')].map((b) => b.textContent).join('|'), pre: [...document.querySelectorAll('#oMain pre')].map((e) => e.textContent).join('|'), li: document.querySelectorAll('#oMain li').length }));
184
- ok('I8 Read shows the file\'s path, its front matter as a grid, its headings, list and code', sh.title === 'PRD' && sh.path === 'planning/prd/self-serve-v2-prd.md' && sh.tabs === 'Read,Edit log,Health' && /type\|PRD\|title\|Self-serve onboarding v2/.test(sh.fm) && sh.heads === 'PRD: Self-serve onboarding v2|Problem|Goal|Requirements' && sh.li === 2 && /R1 a first call/.test(sh.pre), JSON.stringify(sh));
184
+ ok('I8 Read shows the file\'s path, its front matter as a grid, its headings, list and code', sh.title === 'PRD' && sh.path === 'planning/prd/self-serve-v2-prd.md' && sh.tabs === 'Read,Edit,Proposals,Edit log,Health' && /type\|PRD\|title\|Self-serve onboarding v2/.test(sh.fm) && sh.heads === 'PRD: Self-serve onboarding v2|Problem|Goal|Requirements' && sh.li === 2 && /R1 a first call/.test(sh.pre), JSON.stringify(sh));
185
185
  ok('I8 Read asked for the log and the last revision, by GET, for this path', A.gets.some((g) => g.path === '/api/doc-sheet/log' && /path=planning%2Fprd%2Fself-serve-v2-prd.md/.test(g.query)) && A.gets.some((g) => g.path === '/api/doc-sheet/at' && /rev=2/.test(g.query)));
186
186
  await p.click('#shT [data-sh="log"]');
187
187
  const lg = await until(() => p.evaluate(() => document.querySelector('#oMain .hsr') && [...document.querySelectorAll('#oMain .hsr')].map((r) => r.textContent.replace(/\s+/g, ' ').trim())));
@@ -191,7 +191,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
191
191
  ok('I8 Health shows each check as passed, not passed or no input, and says no input is not counted', hl && /1 of 2 checks/.test(hl.note) && hl.rows.join() === 'ckr done:Passed,ckr blocked:Not passed,ckr skipped:No input', JSON.stringify(hl));
192
192
  ok('I8 the health check posts the path and the workspace only', A.posts.some((x) => x.path === '/api/doc-health/check' && Object.keys(x.body).sort().join() === 'path,ws' && x.body.ws === 'w1'));
193
193
  ok('I8 the sheet wrote nothing: no edit, propose, accept, reject, why, mark or ask post went out', !A.posts.slice(nPost0).some((x) => /doc-sheet/.test(x.path)) && !A.posts.some((x) => /^\/api\/doc-sheet\/(edit|propose|accept|reject|why|mark-current|ask)/.test(x.path)));
194
- ok('I8 the sheet says it is read-only', /Read-only/.test(await txt('#oMain .xn')));
194
+ ok('I8 the sheet says the file changes only on Save or Accept', /only when you press Save or Accept/.test(await txt('#oMain .xn')));
195
195
  A.setThread({ ok: true, working: false, turns: [] });
196
196
  await p.fill('#askIn', 'What is missing?'); const nA = A.posts.length; await p.press('#askIn', 'Enter');
197
197
  ok('I8 a question posts the document key and the text', await until(() => A.posts.length > nA && A.posts[A.posts.length - 1].path === '/api/briefing-premium/ask' && A.posts[A.posts.length - 1].body.key === 'doc:self-serve-v2:prd' && A.posts[A.posts.length - 1].body.text === 'What is missing?'));
@@ -160,6 +160,6 @@ The initiative page is at `/premium-initiative.html?id=<initiative>`. A click on
160
160
  - **Checks** lists the engine's six steps (spec, contract, build, quality, review, accept) with their state and the evidence each states, and marks the next one. "All N workflow steps" lists every step.
161
161
  - **Tasks** lists the PRD requirements and the board's tracker items for this initiative. The repository records no result for each requirement, so a requirement says "No result" and is never drawn as done or open. **By stage** groups them by state. **Timeline** draws a bar for each task that has both a start and a due date, and lists the rest. Press a task to read its record; for a PMOS task you can change its status. **Add a task** writes a PMOS task to the board's own record; with no dates the board plans it from tomorrow for a week. Jira tickets stay read-only. There is no Add a document: nothing stores a document you add.
162
162
  - **Core documents** has the same counts, filter and search as the Board's card, for this initiative. **Draft it** starts the existing read-only run that writes a draft and sends nothing. Technical documents (the record, the rubric, the stories, the review and the explainer) are grouped and not counted.
163
- - **The document sheet.** A document that has a file opens in a dialog with **Read** (the file's text, its front matter as a grid and an outline), **Edit log** (the revisions and other entries of the document sheet) and **Health** (the document-health checks; a check with no input is not counted). The read-only agent sits beside it and starts from the file. The sheet writes nothing: editing, accepting a proposal, Issue and Drop are not built on this page.
163
+ - **The document sheet.** A document that has a file opens in a dialog with **Read** (the file's text, its front matter as a grid and an outline), **Edit** (the file as plain Markdown, a reason, and **Save**), **Proposals** (**Ask the agent**, the open proposals with **Accept** and **Reject**, and the closed ones), **Edit log** (the revisions and other entries of the document sheet) and **Health** (the document-health checks; a check with no input is not counted). The file changes only when you press Save or Accept, and every change is kept in the Edit log with its reason. Save and Reject need a reason. A proposal made on text that has since changed shows which sections are out of date and cannot take them. The agent beside the sheet still only reads. Bold and undo buttons, Issue and Drop are not built on this page.
164
164
 
165
165
  Not drawn, because PMOS holds no record for them: the mockup's demo tasks, its Jira data, and the owner "Agents" on a requirement.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.256.0",
3
+ "version": "0.257.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.256.0",
9
+ "version": "0.257.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.256.0",
3
+ "version": "0.257.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,70 @@
1
+ /* premium-doc-edit.js — the pure half of the premium document sheet's Edit and Proposals tabs (initiative briefing-premium-doc-edit).
2
+ * No DOM and no fetch: it turns the answers of /api/doc-sheet/* into what the tabs draw, and builds the bodies of the presses. Every figure here is a
3
+ * field of a route's answer; a proposal's section is stale only because the route says it is. */
4
+ const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
5
+
6
+ /** One proposal as the tab draws it. `p` is a row of GET /api/doc-sheet/proposals. */
7
+ export function proposalView(p) {
8
+ const secs = (p.sections || []).map((s) => ({
9
+ name: s.name, kind: s.kind, stale: !!s.stale,
10
+ add: s.kind === 'removed' ? 'Removes this section' : clip(s.after, 320),
11
+ }));
12
+ const open = p.state === 'proposed';
13
+ const live = secs.filter((s) => !s.stale);
14
+ return {
15
+ id: p.id, hash: p.hash, open, state: p.state,
16
+ who: p.by === 'pm' ? 'You' : 'The agent',
17
+ request: clip(p.prompt, 240),
18
+ sections: secs,
19
+ canAccept: open && live.length > 0,
20
+ staleAll: open && secs.length > 0 && live.length === 0,
21
+ why: p.why ? clip(p.why, 240) : '',
22
+ label: p.state === 'accepted' ? 'Accepted' : p.state === 'rejected' ? 'Rejected' : p.state === 'proposed' ? 'Open' : String(p.state || ''),
23
+ };
24
+ }
25
+
26
+ /** The Proposals tab's lists and the names the Read outline marks. Only open proposals count. */
27
+ export function proposalsModel(rows) {
28
+ const all = (rows || []).map(proposalView);
29
+ const open = all.filter((p) => p.open), closed = all.filter((p) => !p.open);
30
+ const marked = new Set();
31
+ for (const p of open) for (const s of p.sections) marked.add(s.name);
32
+ return { open, closed, count: open.length, marked };
33
+ }
34
+
35
+ /** Save press. Refuses an empty reason or an unchanged text before any post; the route refuses an empty reason too. */
36
+ export function editBody(path, before, text, why) {
37
+ if (typeof text !== 'string') return { error: 'There is no text to save.' };
38
+ if (!String(why || '').trim()) return { error: 'Say why the document changes. The reason is kept in the Edit log.' };
39
+ if (text === before) return { error: 'Nothing has changed yet.' };
40
+ return { body: { path, text, why: String(why).trim() } };
41
+ }
42
+
43
+ /** Accept press. `picked` is the names of the sections to take; a stale section is never sent. With none picked nothing is sent. */
44
+ export function acceptBody(path, p, picked) {
45
+ const live = new Set(p.sections.filter((s) => !s.stale).map((s) => s.name));
46
+ const names = (picked || []).filter((n) => live.has(n));
47
+ if (!names.length) return { error: 'Pick at least one section that is still current.' };
48
+ return { body: { path, id: p.id, hash: p.hash, sections: names } };
49
+ }
50
+
51
+ /** Reject press. A reason is required (the route requires it too). */
52
+ export function rejectBody(path, p, why) {
53
+ if (!String(why || '').trim()) return { error: 'Say why you are rejecting it. The reason is kept in the Edit log.' };
54
+ return { body: { path, id: p.id, why: String(why).trim() } };
55
+ }
56
+
57
+ /** Ask press. */
58
+ export function askBody(path, prompt) {
59
+ if (!String(prompt || '').trim()) return { error: 'Tell the agent what to change.' };
60
+ return { body: { path, prompt: String(prompt).trim() } };
61
+ }
62
+
63
+ /** The ask's state as the tab says it. `a` is GET /api/doc-sheet/ask. */
64
+ export function askLine(a) {
65
+ if (!a) return '';
66
+ if (a.state === 'working') return 'The agent is reading the document. It can read and propose; nothing changes until you accept.';
67
+ if (a.state === 'proposed') return 'The agent proposed a change. It is listed below.';
68
+ if (a.state === 'failed') return a.error || 'The agent could not answer.';
69
+ return '';
70
+ }
@@ -1,9 +1,10 @@
1
1
  /* pm/premium-initiative.js — the premium initiative page (initiative briefing-premium-initiative, slice 6). Reads GET /api/initiative-premium?id= and draws the
2
2
  * model lib/initiative-premium.js builds from the routes the production Initiatives sheet reads: the overview and checks, the Tasks card (PRD requirements and
3
- * the board's tracker items) and the Core documents card. A document row with a file opens the read-only document sheet (Read, Edit log, Health) in the
4
- * standard dialog beside the read-only agent. The one press is Draft it, through POST /api/core-docs/draft. Nothing here edits a document, issues one,
5
- * moves an initiative or adds a task. */
3
+ * the board's tracker items) and the Core documents card. A document row with a file opens the document sheet (Read, Edit, Proposals, Edit log, Health) in the
4
+ * standard dialog beside the read-only agent. The presses are Draft it (POST /api/core-docs/draft), the sheet's Save, Ask the agent, Accept and Reject (the
5
+ * existing /api/doc-sheet routes, initiative briefing-premium-doc-edit), Add a task and a task's status. Nothing here issues a document or moves an initiative. */
6
6
  import { pmPost } from './http.js';
7
+ import { proposalsModel, editBody, acceptBody, rejectBody, askBody, askLine } from './premium-doc-edit.js';
7
8
  import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, crumbHtml, wireCrumb, AI } from './premium-shell.js';
8
9
 
9
10
  let M = null; // the model
@@ -210,9 +211,11 @@ function openAsk(q) {
210
211
  setMode('chat');
211
212
  }
212
213
 
213
- /* ── the document sheet: Read, Edit log, Health. Read-only. ─────────────────────────────────────────────── */
214
- let sheet = null; // { d, tab, text, log, health, err }
215
- const TABS = [['read', 'Read'], ['log', 'Edit log'], ['health', 'Health']];
214
+ /* ── the document sheet: Read, Edit, Proposals, Edit log, Health. ─────────────────────────────────────────────── */
215
+ let sheet = null; // { d, tab, text, log, health, props, draft, why, ask, askText, picked, busy, msg, err }
216
+ const TABS = [['read', 'Read'], ['edit', 'Edit'], ['props', 'Proposals'], ['log', 'Edit log'], ['health', 'Health']];
217
+ const wsq = () => (M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '');
218
+ const propsM = (s) => proposalsModel(s.props || []);
216
219
  function mdHtml(text) {
217
220
  const lines = String(text || '').replace(/\r/g, '').split('\n'), out = [], outline = [];
218
221
  let i = 0, fm = [];
@@ -235,13 +238,33 @@ function mdHtml(text) {
235
238
  }
236
239
  function sheetPane() {
237
240
  const s = sheet, d = s.d;
238
- const menu = `<div class="seg" id="shT" role="group" aria-label="Document views"><i class="pill"></i>${TABS.map(([k, n]) => `<button data-sh="${k}" aria-pressed="${s.tab === k}">${n}</button>`).join('')}</div>`;
241
+ const menu = `<div class="seg" id="shT" role="group" aria-label="Document views"><i class="pill"></i>${TABS.map(([k, n]) => `<button data-sh="${k}" aria-pressed="${s.tab === k}">${n}${k === 'props' && s.props && propsM(s).count ? ` <em>${propsM(s).count}</em>` : ''}</button>`).join('')}</div>`;
239
242
  const head = `<p class="dpath">${esc(d.path)}</p><div class="dsm"><span class="${d.st === 'ok' ? 'ok' : d.st === 'draft' ? 'warn' : 'mut'}">${esc(d.state)}</span>${d.when ? `<span>updated ${esc(d.when)}</span>` : ''}${d.by ? `<span>${esc(d.by)}</span>` : ''}</div>`;
240
243
  let body = '';
241
244
  if (s.err) body = `<p class="empty3 plain">${esc(s.err)}</p>`;
242
245
  else if (s.tab === 'read') {
243
246
  if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
244
- else { const m = s.md || (s.md = mdHtml(s.text)); body = (m.fm.length ? kv(m.fm) : '') + `<div class="dsrd${m.outline.length > 2 ? '' : ' no'}">${m.outline.length > 2 ? `<nav class="dso" aria-label="Outline"><p class="label">Outline <em>${m.outline.length} headings</em></p>${m.outline.map((t, n) => `<button data-go="${n}">${esc(t)}</button>`).join('')}</nav>` : ''}<div class="dsbody">${m.html}</div></div>`; }
247
+ else { const m = s.md || (s.md = mdHtml(s.text)); body = (m.fm.length ? kv(m.fm) : '') + `<div class="dsrd${m.outline.length > 2 ? '' : ' no'}">${m.outline.length > 2 ? `<nav class="dso" aria-label="Outline"><p class="label">Outline <em>${m.outline.length} headings</em></p>${m.outline.map((t, n) => `<button data-go="${n}">${esc(t)}${s.props && propsM(s).marked.has(t) ? '<i></i>' : ''}</button>`).join('')}</nav>` : ''}<div class="dsbody">${m.html}</div></div>`; }
248
+ } else if (s.tab === 'edit') {
249
+ if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
250
+ else {
251
+ const cur = s.draft == null ? s.text : s.draft, nv = ((s.log && s.log.revisions) || []).length + 1;
252
+ body = `<textarea id="dsEd" class="dsed" spellcheck="true" aria-label="Edit the document">${esc(cur)}</textarea>`
253
+ + `<p class="note" id="dsNote" style="margin:8px 0">${cur === s.text ? 'No changes yet.' : 'Changed. Health checks the document again after you save.'}</p>`
254
+ + `<input id="dsWhy" class="dsy" placeholder="Why are you changing it? Kept in the edit log." aria-label="Why are you changing it" value="${esc(s.why || '')}">`
255
+ + `<p class="note" id="dsErr" role="alert" style="margin:6px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`
256
+ + `<div class="dsfoot"><span class="note">Saved by you as v${nv}</span><span><button class="dmcta alt" data-ds="discard">Cancel</button><button class="dmcta dark" id="dsSave" data-ds="save"${s.busy || cur === s.text ? ' disabled' : ''}>Save as v${nv}</button></span></div>`;
257
+ }
258
+ } else if (s.tab === 'props') {
259
+ if (!s.props) body = '<p class="empty3 plain">Reading the proposals.</p>';
260
+ else {
261
+ const m = propsM(s), line = askLine(s.ask);
262
+ body = `<div class="dsask2"><p class="label">${AI}Ask the agent</p><textarea id="dsAsk" rows="3" placeholder="Tell the agent what to change, for example: add a one-paragraph summary at the top" aria-label="Tell the agent what to change">${esc(s.askText || '')}</textarea><div class="dsrow"><button class="dmcta alt" data-ds="ask"${s.busy || (s.ask && s.ask.state === 'working') ? ' disabled' : ''}>${AI}Ask the agent</button></div><p class="note" style="margin:8px 0 0">The agent drafts a proposal and can only read. Nothing in the document changes until you accept it, and your request is kept in the edit log.</p>${line ? `<p class="note" role="status" style="margin:6px 0 0">${esc(line)}</p>` : ''}</div>`
263
+ + `<p class="label" style="margin:18px 0 8px">Open proposals · ${m.count}</p>`
264
+ + (m.count ? m.open.map((p) => propHtml(s, p)).join('') : `<div class="dsnone">${CHECK}No open proposals.</div>`)
265
+ + (m.closed.length ? `<p class="label" style="margin:18px 0 8px">Closed · ${m.closed.length}</p>${m.closed.map((p) => `<div class="dsp ${esc(p.state)}"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${p.why ? `<q>${esc(p.why)}</q>` : ''}</div><span class="dst2">${esc(p.label)}</span></div>`).join('')}` : '')
266
+ + `<p class="note" id="dsErr" role="alert" style="margin:10px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`;
267
+ }
245
268
  } else if (s.tab === 'log') {
246
269
  if (!s.log) body = '<p class="empty3 plain">Reading the log.</p>';
247
270
  else {
@@ -253,19 +276,33 @@ function sheetPane() {
253
276
  if (!s.health) body = '<p class="empty3 plain">Checking the document.</p>';
254
277
  else body = `<p class="note" style="margin:0 0 10px">${s.health.passed} of ${s.health.total} checks that had the input they need passed. A check with no input is not counted.</p><div class="ckl">${s.health.checks.map((c) => `<div class="ckr ${c.pass === true ? 'done' : c.pass === false ? 'blocked' : 'skipped'}"><i></i><b>${esc(c.id)}</b><span>${c.pass === true ? 'Passed' : c.pass === false ? 'Not passed' : 'No input'}</span><small>${esc(c.reason || '')}</small></div>`).join('')}</div>`;
255
278
  }
256
- return `<article class="paper doc">${head}${menu}<div id="shBody">${body}</div><p class="xn">Read-only. Editing a document and accepting an agent’s proposal are not built on this page.</p></article>`;
279
+ return `<article class="paper doc">${head}${menu}<div id="shBody">${body}</div><p class="xn">Every change is kept in the Edit log with its reason. The file changes only when you press Save or Accept.</p></article>`;
280
+ }
281
+ function propHtml(s, p) {
282
+ const picked = s.picked && s.picked[p.id], on = (n) => (picked ? picked.includes(n) : true);
283
+ const secs = p.sections.map((x) => `<div class="dsdf">${p.sections.length > 1 && !x.stale ? `<label><input type="checkbox" data-pk="${esc(p.id)}" value="${esc(x.name)}"${on(x.name) ? ' checked' : ''}> ` : ''}<b>${esc(x.name)}</b>${p.sections.length > 1 && !x.stale ? '</label>' : ''} ${x.stale ? '<span class="dst2">Changed since this was proposed</span>' : `<ins>+ ${esc(x.add)}</ins>`}</div>`).join('');
284
+ return `<div class="dsp"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${secs}${p.staleAll ? '<q>The document changed since this was proposed, so it cannot be accepted. Ask again.</q>' : ''}</div><div class="dsa">${p.canAccept ? `<button class="dmcta dark" data-ds="acc:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Accept</button>` : ''}<button class="dmcta alt" data-ds="rej:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject</button></div>${s.rejecting === p.id ? `<div class="dsrow" style="grid-column:1/-1"><input id="dsRj" class="dsy" placeholder="Why are you rejecting it? Kept in the edit log." aria-label="Why are you rejecting it" value="${esc(s.rejWhy || '')}"><button class="dmcta dark" data-ds="rejgo:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject it</button><button class="dmcta alt" data-ds="rejno">Cancel</button></div>` : ''}</div>`;
257
285
  }
258
286
  function drawSheet() { $('#oMain').innerHTML = sheetPane(); pillOf($('#shT')); }
259
287
  async function getJson(url, init) { try { const r = await fetch(url, Object.assign({ credentials: 'same-origin' }, init || {})); return await r.json(); } catch { return null; } }
260
288
  async function loadTab(tab) {
261
289
  const s = sheet, p = encodeURIComponent(s.d.path), ws = M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '';
262
- if (tab === 'read' && s.text == null) {
290
+ if (tab !== 'props' && tab !== 'log' && tab !== 'health' && !s.props) {
291
+ const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
292
+ if (sheet !== s) return;
293
+ if (pr && pr.ok) s.props = pr.proposals || [];
294
+ }
295
+ if ((tab === 'read' || tab === 'edit') && s.text == null) {
263
296
  const lg = s.log || (s.log = await getJson('/api/doc-sheet/log?path=' + p + ws));
264
297
  if (sheet !== s) return;
265
298
  const revs = lg && lg.ok ? lg.revisions || [] : [];
266
299
  const at = revs.length ? await getJson('/api/doc-sheet/at?path=' + p + '&rev=' + revs[revs.length - 1].rev + ws) : null;
267
300
  if (sheet !== s) return;
268
301
  if (at && at.ok) s.text = at.text; else s.err = (at && at.error) || (lg && lg.error) || 'The file could not be read.';
302
+ } else if (tab === 'props' && !s.props) {
303
+ const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
304
+ if (sheet !== s) return;
305
+ if (!pr || pr.ok === false) s.err = (pr && pr.error) || 'The proposals could not be read.'; else s.props = pr.proposals || [];
269
306
  } else if (tab === 'log' && !s.log) {
270
307
  s.log = await getJson('/api/doc-sheet/log?path=' + p + ws);
271
308
  if (sheet !== s) return;
@@ -279,16 +316,81 @@ async function loadTab(tab) {
279
316
  }
280
317
  function openSheet(d) {
281
318
  if (!d || !d.path) return;
282
- sheet = { d, tab: 'read', text: null, log: null, health: null, err: null };
283
- const key = 'doc:' + M.id + ':' + d.key, say = d.title + ' is ' + d.state.toLowerCase() + (d.by ? '. ' + d.by + '.' : '.') + ' I can read the file with you and answer questions. I change nothing.';
319
+ sheet = { d, tab: 'read', text: null, log: null, health: null, props: null, draft: null, why: '', ask: null, askText: '', picked: {}, busy: false, msg: '', err: null };
320
+ const key = 'doc:' + M.id + ':' + d.key, say = d.title + ' is ' + d.state.toLowerCase() + (d.by ? '. ' + d.by + '.' : '.') + ' I can read the file with you and answer questions. I change nothing; only you change the file, with Save or Accept.';
284
321
  openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(logHtml({ logTitle: 'Read from the repository', log: ['Found the file ' + d.path, 'Read its revisions from the document sheet', 'Left the file as it is'] })) + turnA(ptx(say)), noteKey: key, pane: '', label: 'Document' });
285
322
  drawSheet(); loadThread(key); loadTab('read');
286
323
  }
287
324
  $('#oMain').addEventListener('click', (e) => {
288
325
  const t = e.target.closest('[data-sh]');
289
- if (t && sheet) { sheet.tab = t.dataset.sh; sheet.err = null; drawSheet(); loadTab(sheet.tab); return; }
326
+ if (t && sheet) { keepDraft(); sheet.tab = t.dataset.sh; sheet.err = null; sheet.msg = ''; drawSheet(); loadTab(sheet.tab); return; }
327
+ const b = e.target.closest('[data-ds]'); if (b && sheet) { sheetPress(b.dataset.ds); return; }
290
328
  const g = e.target.closest('[data-go]'); if (g) { const h = $('#ds-h' + g.dataset.go); if (h) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); }
291
329
  });
330
+ $('#oMain').addEventListener('change', (e) => { const c = e.target.closest('[data-pk]'); if (c && sheet) sheet.picked[c.dataset.pk] = $$('[data-pk]', $('#oMain')).filter((x) => x.dataset.pk === c.dataset.pk && x.checked).map((x) => x.value); });
331
+ $('#oMain').addEventListener('input', (e) => {
332
+ if (!sheet) return;
333
+ if (e.target.id === 'dsEd') { sheet.draft = e.target.value; const ch = sheet.draft !== sheet.text; $('#dsSave').disabled = !ch || sheet.busy; $('#dsNote').textContent = ch ? 'Changed. Health checks the document again after you save.' : 'No changes yet.'; }
334
+ else if (e.target.id === 'dsWhy') sheet.why = e.target.value;
335
+ else if (e.target.id === 'dsAsk') sheet.askText = e.target.value;
336
+ else if (e.target.id === 'dsRj') sheet.rejWhy = e.target.value;
337
+ });
338
+ function keepDraft() { if (!sheet) return; const ed = $('#dsEd'), w = $('#dsWhy'), a = $('#dsAsk'), rj = $('#dsRj'); if (rj) sheet.rejWhy = rj.value; if (ed) sheet.draft = ed.value; if (w) sheet.why = w.value; if (a) sheet.askText = a.value; }
339
+ /* the sheet's presses: each posts to one existing /api/doc-sheet route (ws in the query, as the routes read it) and then reads the routes again */
340
+ const dsPost = (route, body) => pmPost('/api/doc-sheet/' + route + (M.board.ws ? '?ws=' + encodeURIComponent(M.board.ws) : ''), body);
341
+ async function reloadSheet(s) {
342
+ s.text = null; s.md = null; s.log = null; s.health = null; s.props = null; s.draft = null; s.why = ''; s.rejecting = null;
343
+ await loadTab(s.tab);
344
+ if (sheet === s) { s.busy = false; drawSheet(); }
345
+ }
346
+ async function sheetPress(act) {
347
+ const s = sheet; keepDraft();
348
+ const fail = (m) => { s.busy = false; s.msg = m; drawSheet(); };
349
+ if (act === 'rejno') { s.rejecting = null; s.msg = ''; drawSheet(); return; }
350
+ if (act === 'discard') { s.draft = null; s.why = ''; s.msg = ''; drawSheet(); return; }
351
+ if (act === 'save') {
352
+ const r = editBody(s.d.path, s.text, s.draft == null ? s.text : s.draft, s.why); if (r.error) return fail(r.error);
353
+ s.busy = true; s.msg = ''; drawSheet();
354
+ const res = await dsPost('edit', r.body); if (sheet !== s) return;
355
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be saved.');
356
+ toast('Saved. The reason is in the Edit log.'); return reloadSheet(s);
357
+ }
358
+ if (act === 'ask') {
359
+ const r = askBody(s.d.path, s.askText); if (r.error) return fail(r.error);
360
+ s.busy = true; s.msg = ''; drawSheet();
361
+ const res = await dsPost('ask', r.body); if (sheet !== s) return;
362
+ s.busy = false;
363
+ if (!res || res.ok !== true || !res.id) return fail((res && res.error) || 'The agent could not be asked.');
364
+ s.askText = ''; s.ask = { state: 'working', id: res.id }; drawSheet(); return pollAsk(s, res.id);
365
+ }
366
+ const [kind, id] = [act.split(':')[0], act.slice(act.indexOf(':') + 1)];
367
+ const p = propsM(s).open.find((x) => x.id === id); if (!p) return;
368
+ if (kind === 'acc') {
369
+ const r = acceptBody(s.d.path, p, s.picked[id] || p.sections.filter((x) => !x.stale).map((x) => x.name)); if (r.error) return fail(r.error);
370
+ s.busy = true; s.msg = ''; drawSheet();
371
+ const res = await dsPost('accept', r.body); if (sheet !== s) return;
372
+ if (!res || res.ok !== true) { await reloadSheet(s); return fail((res && res.error) || 'The proposal could not be accepted.'); }
373
+ toast('Accepted. The file changed and the request is in the Edit log.'); return reloadSheet(s);
374
+ }
375
+ if (kind === 'rej') { s.rejecting = id; s.rejWhy = ''; s.msg = ''; drawSheet(); const f = $('#dsRj'); if (f) f.focus(); return; }
376
+ if (kind === 'rejgo') {
377
+ const r = rejectBody(s.d.path, p, s.rejWhy); if (r.error) return fail(r.error);
378
+ s.busy = true; s.msg = ''; drawSheet();
379
+ const res = await dsPost('reject', r.body); if (sheet !== s) return;
380
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The proposal could not be rejected.');
381
+ toast('Rejected. The file is as it was.'); return reloadSheet(s);
382
+ }
383
+ }
384
+ async function pollAsk(s, id) {
385
+ for (let i = 0; i < 400 && sheet === s; i++) {
386
+ await new Promise((r) => setTimeout(r, 2000));
387
+ const a = await getJson('/api/doc-sheet/ask?id=' + encodeURIComponent(id) + wsq()); if (sheet !== s) return;
388
+ if (!a || a.ok === false) { s.ask = { state: 'failed', error: (a && a.error) || 'The answer could not be read.' }; drawSheet(); return; }
389
+ s.ask = a;
390
+ if (a.state !== 'working') { s.props = null; await loadTab('props'); if (sheet === s) drawSheet(); return; }
391
+ if (s.tab === 'props') drawSheet();
392
+ }
393
+ }
292
394
  $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
293
395
 
294
396
  /* ── load: the routes derive the initiatives in the background, so the first answers are "reading" ────────── */
@@ -1211,6 +1211,14 @@ button.dsn:hover{box-shadow:inset 0 0 0 1.5px rgb(79,109,245)}
1211
1211
  .pkempty{padding:10px 14px}
1212
1212
  .top{position:relative;z-index:6}
1213
1213
  .pkw{z-index:40}
1214
+ /* the document sheet's Edit and Proposals tabs (initiative briefing-premium-doc-edit); the mockup's rules, cut by class */
1215
+ .dsed{width:100%;min-height:280px;border-radius:14px;border:1px solid var(--hair);background:var(--card-solid);padding:16px;font:500 15px/1.65 var(--mono);color:var(--ink);resize:vertical}
1216
+ .dsy{width:100%;height:42px;border-radius:14px;border:1px solid var(--hair);background:var(--card-solid);padding:0 14px;font:inherit;font-size:15px;color:var(--ink)}.dsed:focus-visible,.dsy:focus-visible,#dsAsk:focus-visible{outline:2px solid var(--ember);outline-offset:1px}
1217
+ .dsfoot{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-top:12px}.dsfoot>span{display:flex;gap:8px;align-items:center}
1218
+ #dsAsk{width:100%;border-radius:14px;border:1px solid var(--hair);background:var(--card-solid);padding:12px 14px;font:inherit;font-size:15px;color:var(--ink);resize:vertical;margin-bottom:10px}
1219
+ .dsp{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px 16px;align-items:center;padding:14px 16px;border-radius:14px;background:var(--well);margin-bottom:10px}.dsp>div:first-child{display:grid;gap:4px;min-width:0}.dsp b{font-size:12.5px}.dsp span{font-size:15px}.dsp q{font-size:12.5px;color:var(--ink-3);quotes:none}.dsp.accepted,.dsp.rejected{opacity:.6}.dst2{font:600 12.5px var(--mono);color:var(--ink-3)}
1220
+ .dsdf{margin-top:4px;padding:8px 12px;border-radius:8px;background:var(--card-solid);font-size:12.5px;line-height:1.5}.dsdf ins{text-decoration:none;color:var(--ok)}
1221
+
1214
1222
  .bt2{display:grid;gap:10px;margin:16px 0 6px}
1215
1223
  .mt1{background:var(--well);border-radius:18px;padding:14px 16px 12px;display:grid;gap:2px;align-content:start;outline:0}
1216
1224
  .mt1 span{font-size:12.5px;color:var(--ink-3)}
@@ -41,6 +41,7 @@
41
41
  "briefing-premium-work.test.js",
42
42
  "briefing-premium-board.test.js",
43
43
  "briefing-premium-initiative.test.js",
44
+ "briefing-premium-doc-edit.test.js",
44
45
  "briefing-premium-products.test.js",
45
46
  "briefing-premium-sources.test.js",
46
47
  "briefing-premium-metrics.test.js",
@@ -203,6 +204,7 @@
203
204
  "briefing-premium-work.test.js": 1,
204
205
  "briefing-premium-board.test.js": 1,
205
206
  "briefing-premium-initiative.test.js": 1,
207
+ "briefing-premium-doc-edit.test.js": 1,
206
208
  "briefing-premium-products.test.js": 1,
207
209
  "briefing-premium-sources.test.js": 1,
208
210
  "briefing-premium-metrics.test.js": 1,
@@ -5,6 +5,7 @@
5
5
  "briefing-premium-work-test.js",
6
6
  "briefing-premium-board-test.js",
7
7
  "briefing-premium-initiative-test.js",
8
+ "briefing-premium-doc-edit-test.js",
8
9
  "briefing-premium-products-test.js",
9
10
  "briefing-premium-sources-test.js",
10
11
  "briefing-premium-metrics-test.js",
@@ -15,6 +16,7 @@
15
16
  "briefing-premium-work-test.js": 80,
16
17
  "briefing-premium-board-test.js": 120,
17
18
  "briefing-premium-initiative-test.js": 120,
19
+ "briefing-premium-doc-edit-test.js": 90,
18
20
  "briefing-premium-products-test.js": 90,
19
21
  "briefing-premium-sources-test.js": 90,
20
22
  "briefing-premium-metrics-test.js": 120,