create-pmos 0.255.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 +1 -1
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/state/discoveries.md +1 -1
- package/workspace/briefing-premium-doc-edit-test.js +176 -0
- package/workspace/briefing-premium-initiative-test.js +2 -2
- package/workspace/briefing-premium-metrics-test.js +186 -0
- package/workspace/guide/briefing-premium.md +3 -2
- package/workspace/lib/board-metrics-premium.js +129 -0
- package/workspace/lib/routes-board-premium.js +25 -1
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/premium-board.js +87 -2
- package/workspace/public/pm/premium-doc-edit.js +70 -0
- package/workspace/public/pm/premium-initiative.js +115 -13
- package/workspace/public/pm/premium.css +63 -0
- package/workspace/public/premium-board.html +6 -0
- package/workspace/test-files.json +4 -0
- package/workspace/test-lists/briefing-premium.json +4 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* lib/board-metrics-premium.js — the Metrics card of a tenant's premium Board (initiative briefing-premium-metrics).
|
|
3
|
+
*
|
|
4
|
+
* build(facts) → model PURE. facts = { now, repo, runs[]|null, commits[]|null (ms), inits[]|null, initsPending, missing[] }
|
|
5
|
+
* read({ root, engine, now }) → model the card of one workspace's repository: its run log, its trunk's history, its workflow state.
|
|
6
|
+
* weeksTo(now, n) → [{ from, to, label }] PURE. The n weeks (Monday to Sunday, UTC) that end with the week of `now`.
|
|
7
|
+
*
|
|
8
|
+
* THE RULE THE FILE FOLLOWS: a number is made only from a record of the repository it names. A source that cannot be read is "Not read", a
|
|
9
|
+
* week with too few runs is blank, and no target exists, so no tile is "on target" or "off target". Blocked and Idle keep no history and have no chart. */
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const { execFile } = require('child_process');
|
|
13
|
+
const BP = require('./briefing-premium.js');
|
|
14
|
+
|
|
15
|
+
const WEEKS = 8, MIN_RUNS = 10, DAY = 86400000, IDLE_DAYS = 30;
|
|
16
|
+
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
17
|
+
const day = (t) => { const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()]; };
|
|
18
|
+
const plural = (n, one, many) => (n === 1 ? one : many);
|
|
19
|
+
const startOfWeek = (t) => { const d = new Date(t); const dow = (d.getUTCDay() + 6) % 7; return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - dow); };
|
|
20
|
+
|
|
21
|
+
function weeksTo(now, n = WEEKS) {
|
|
22
|
+
const last = startOfWeek(now), out = [];
|
|
23
|
+
for (let k = n - 1; k >= 0; k--) { const from = last - k * 7 * DAY, to = from + 7 * DAY; out.push({ from, to, label: day(Math.min(to - 1, now)) }); }
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const DEFS = {
|
|
28
|
+
corrections: 'Human corrections per 100 agent runs in the week: the corrections logged on the week\'s runs, divided by those runs. Lower is better. A week with fewer than ' + MIN_RUNS + ' runs is left blank.',
|
|
29
|
+
merges: 'Commits on the first-parent line of the trunk in the week. A merged pull request is one commit there.',
|
|
30
|
+
blocked: 'Open initiatives that the workflow engine reports with a blocked step. It keeps no history.',
|
|
31
|
+
idle: 'Open initiatives with no activity in the last ' + IDLE_DAYS + ' days, or none on record. It keeps no history.',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** 'Down 12.4 pts vs last week' for two values, the mockup's wording; null when either is missing. */
|
|
35
|
+
function change(prev, cur, dec) {
|
|
36
|
+
if (prev == null || cur == null) return null;
|
|
37
|
+
const d = cur - prev, a = Math.abs(d), txt = a.toFixed(dec);
|
|
38
|
+
return { d, good: d < 0, txt: (+txt === 0 ? 'No change' : (d > 0 ? 'Up ' : 'Down ') + txt) + ' vs last week' };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function build(f) {
|
|
42
|
+
const now = f.now || Date.now(), W = weeksTo(now), missing = (f.missing || []).slice();
|
|
43
|
+
const repo = f.repo || '';
|
|
44
|
+
const tiles = [];
|
|
45
|
+
|
|
46
|
+
// corrections per 100 runs
|
|
47
|
+
if (f.runs == null) tiles.push({ key: 'corrections', label: 'Corrections per 100 runs', absent: 'Not read', why: 'planning/runs/agent-runs.jsonl could not be read in ' + repo + '.', def: DEFS.corrections });
|
|
48
|
+
else {
|
|
49
|
+
const per = W.map((w) => {
|
|
50
|
+
const rs = f.runs.filter((r) => { const t = Date.parse(r.created_at); return Number.isFinite(t) && t >= w.from && t < w.to && Number.isFinite(Number(r.human_corrections)); });
|
|
51
|
+
return { n: rs.length, v: rs.length >= MIN_RUNS ? Math.round(rs.reduce((a, r) => a + Number(r.human_corrections), 0) / rs.length * 1000) / 10 : null };
|
|
52
|
+
});
|
|
53
|
+
const ser = per.map((p) => p.v), li = ser.map((v, i) => (v != null ? i : -1)).filter((i) => i >= 0).pop();
|
|
54
|
+
if (li == null) tiles.push({ key: 'corrections', label: 'Corrections per 100 runs', absent: 'No weeks yet', why: 'No week of the last ' + WEEKS + ' has ' + MIN_RUNS + ' runs with a logged correction count. ' + f.runs.length + ' ' + plural(f.runs.length, 'run is', 'runs are') + ' on record in all.', def: DEFS.corrections });
|
|
55
|
+
else {
|
|
56
|
+
const ch = li > 0 ? change(ser[li - 1], ser[li], 1) : null;
|
|
57
|
+
tiles.push({ key: 'corrections', label: 'Corrections per 100 runs', value: ser[li].toFixed(1), text: 'week to ' + W[li].label + ', ' + per[li].n + ' runs', kind: ch ? (ch.d === 0 ? '' : ch.good ? 'ok' : 'warn') : '', ser, wk: W.map((w) => w.label), nt: per.map((p) => (p.n ? p.n + ' ' + plural(p.n, 'run', 'runs') : '')), dec: 1, suf: '', change: ch, def: DEFS.corrections, lowBetter: true });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// merges a week
|
|
62
|
+
if (f.commits == null) tiles.push({ key: 'merges', label: 'Merged a week', absent: 'Not read', why: 'The history of the trunk could not be read in ' + repo + '.', def: DEFS.merges });
|
|
63
|
+
else {
|
|
64
|
+
const ser = W.map((w) => f.commits.filter((t) => t >= w.from && t < w.to).length), li = ser.length - 1;
|
|
65
|
+
tiles.push({ key: 'merges', label: 'Merged a week', value: String(ser[li]), text: 'to the trunk, week to ' + W[li].label, kind: '', ser, wk: W.map((w) => w.label), nt: ser.map(() => ''), dec: 0, suf: '', change: li > 0 ? (() => { const d = ser[li] - ser[li - 1]; return { d, good: d > 0, txt: (d === 0 ? 'No change' : (d > 0 ? 'Up ' : 'Down ') + Math.abs(d)) + ' vs last week' }; })() : null, def: DEFS.merges, lowBetter: false });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// blocked, idle
|
|
69
|
+
const waiting = (key, label, def) => ({ key, label, absent: f.initsPending ? 'Reading' : 'Not read', why: f.initsPending ? 'The workflow engine is deriving the initiatives of ' + repo + '. This tile fills in when it ends.' : 'The workflow engine could not be run in ' + repo + '.', def, pending: !!f.initsPending });
|
|
70
|
+
if (!f.inits) { tiles.push(waiting('blocked', 'Blocked', DEFS.blocked), waiting('idle', 'Idle for a month', DEFS.idle)); }
|
|
71
|
+
else {
|
|
72
|
+
const open = f.inits.filter((i) => !i.accepted && !i.stopped);
|
|
73
|
+
const blocked = open.filter((i) => (i.steps || []).some((s) => s.status === 'blocked')).length;
|
|
74
|
+
const idle = open.filter((i) => { const t = Date.parse(i.last_activity); return !Number.isFinite(t) || now - t > IDLE_DAYS * DAY; }).length;
|
|
75
|
+
tiles.push(
|
|
76
|
+
{ key: 'blocked', label: 'Blocked', value: String(blocked), text: 'of ' + open.length + ' open. No history is kept', kind: blocked ? 'bad' : '', def: DEFS.blocked, lowBetter: true },
|
|
77
|
+
{ key: 'idle', label: 'Idle for a month', value: String(idle), text: 'of ' + open.length + ' open. No history is kept', kind: idle ? 'warn' : '', def: DEFS.idle, lowBetter: true },
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// one row per tile for the read-only agent (key board:metric-<tile>), in the shape the Board's own rows have
|
|
82
|
+
const rows = tiles.map((t) => {
|
|
83
|
+
const say = t.absent ? t.label + ' is not shown: ' + t.why : t.label + ' is ' + t.value + ', ' + t.text + '.' + (t.change ? ' ' + t.change.txt + '.' : '');
|
|
84
|
+
const facts = [['Measure', t.label], ['Now', t.absent ? t.absent : t.value], ['Counted from', repo], ['Better when', t.lowBetter ? 'Lower' : t.lowBetter === false ? 'Higher' : '']]
|
|
85
|
+
.concat(t.ser ? t.ser.map((v, j) => [t.wk[j], v == null ? 'No runs' : String(v)]) : []).filter((x) => x[1] !== '');
|
|
86
|
+
t.rowKey = 'board:metric-' + t.key;
|
|
87
|
+
return { key: t.rowKey, id: null, title: t.label, sub: 'Metric · ' + repo, dialog: { say, facts, files: [] } };
|
|
88
|
+
});
|
|
89
|
+
const look = tiles.filter((t) => t.kind === 'warn' || t.kind === 'bad').length;
|
|
90
|
+
return {
|
|
91
|
+
state: 'ready', pending: !!f.initsPending, repo,
|
|
92
|
+
header: missing.length ? 'not read: ' + missing.join(', ') : 'counted from ' + repo,
|
|
93
|
+
hint: (look ? look + ' of ' + tiles.length + ' need a look. ' : '') + 'Each chart is one measure over the last ' + WEEKS + ' weeks. Press a measure for its definition and values. A week with fewer than ' + MIN_RUNS + ' runs is left blank.',
|
|
94
|
+
note: 'Counted from ' + repo + ': corrections from planning/runs/agent-runs.jsonl, merges from the history of its trunk, blocked and idle from its workflow state, in weeks to ' + W[W.length - 1].label + '. A week with fewer than ' + MIN_RUNS + ' runs is blank. Blocked and idle keep no history.',
|
|
95
|
+
tiles, rows,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/* ── the reader ────────────────────────────────────────────────────────────────────────────────────────────── */
|
|
100
|
+
const git = (args) => new Promise((res) => execFile('git', args, { maxBuffer: 64 * 1024 * 1024, timeout: 60000 }, (e, out) => res(e ? null : String(out))));
|
|
101
|
+
const kept = new Map(); // root → { key, inits, inflight }
|
|
102
|
+
|
|
103
|
+
async function readCommits(root, now) {
|
|
104
|
+
const since = new Date(weeksTo(now)[0].from).toISOString();
|
|
105
|
+
const ref = (await git(['-C', root, 'rev-parse', '--verify', '-q', 'origin/main'])) ? 'origin/main' : 'HEAD';
|
|
106
|
+
const out = await git(['-C', root, 'log', '--first-parent', '--since=' + since, '--format=%ct', ref]);
|
|
107
|
+
return out === null ? null : out.split('\n').filter(Boolean).map((x) => Number(x) * 1000);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function readRuns(root) {
|
|
111
|
+
try { return fs.readFileSync(path.join(root, 'planning', 'runs', 'agent-runs.jsonl'), 'utf8').split('\n').map((l) => l.trim()).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { return null; }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The card of one repository. Runs and history are read at once; the workflow state is slow, so it is derived in the background and kept until the repository changes. */
|
|
115
|
+
async function read({ root, engine, now = Date.now() }) {
|
|
116
|
+
const k = kept.get(root) || { key: null, inits: null, inflight: false }; kept.set(root, k);
|
|
117
|
+
const key = await BP.repoKey(root);
|
|
118
|
+
if (!k.inflight && engine && (!k.inits || k.key !== key)) {
|
|
119
|
+
k.inflight = true;
|
|
120
|
+
BP.readInitiatives({ root, engine }).then((inits) => { if (inits) { k.inits = inits; k.key = key; } }).catch(() => { }).finally(() => { k.inflight = false; });
|
|
121
|
+
}
|
|
122
|
+
const repo = path.basename(root);
|
|
123
|
+
const model = build({ now, repo, runs: readRuns(root), commits: await readCommits(root, now), inits: k.inits, initsPending: !!engine && !k.inits && k.inflight });
|
|
124
|
+
return model;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const forget = () => kept.clear();
|
|
128
|
+
|
|
129
|
+
module.exports = { build, read, weeksTo, forget, MIN_RUNS };
|
|
@@ -7,8 +7,13 @@
|
|
|
7
7
|
* this route answers 202 too and the page asks again: no request waits for the read. Read-only: the one press of the page (Draft it) goes to
|
|
8
8
|
* POST /api/core-docs/draft from the page. */
|
|
9
9
|
const BoardPremium = require('./board-premium.js');
|
|
10
|
+
const BoardP = BoardPremium;
|
|
10
11
|
const boards = require('./routes-boards.js');
|
|
11
12
|
const coreDocs = require('./routes-core-docs.js');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const Metrics = require('./board-metrics-premium.js');
|
|
16
|
+
const { ENGINE_PATHS } = require('./console-state.js');
|
|
12
17
|
|
|
13
18
|
/** GET `pathAndQuery` from a route module's own handler, as the Work page's route does, and return { status, body }. */
|
|
14
19
|
async function via(mod, pathAndQuery, req, ctx) {
|
|
@@ -20,9 +25,28 @@ async function via(mod, pathAndQuery, req, ctx) {
|
|
|
20
25
|
}
|
|
21
26
|
const qs = (o) => '?' + Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
|
|
22
27
|
|
|
28
|
+
/** GET /api/board-metrics-premium?ws=<id> — the Metrics card of a tenant's Board (initiative briefing-premium-metrics). Read-only, and apart from the Board's own
|
|
29
|
+
* route so the Board never waits for it. The home workspace has no card: { ok, state: 'none' }. */
|
|
30
|
+
async function metrics(req, res, url, ctx) {
|
|
31
|
+
if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
|
|
32
|
+
try {
|
|
33
|
+
const w = ctx.getWs && ctx.getWs(url.searchParams.get('ws') || null);
|
|
34
|
+
if (!w || !w.root) { ctx.json(res, { ok: false, state: 'error', error: 'that workspace is not registered' }, 404); return true; }
|
|
35
|
+
const home = ctx.homeRoot || ctx.selfRoot || null;
|
|
36
|
+
if (home && path.resolve(w.root) === path.resolve(home)) { ctx.json(res, { ok: true, state: 'none', why: 'The board of this repository has no Metrics card.' }); return true; }
|
|
37
|
+
const engine = ENGINE_PATHS.find((p) => fs.existsSync(p)) || null;
|
|
38
|
+
const model = await Metrics.read({ root: w.root, engine, now: Date.now() });
|
|
39
|
+
// the read-only agent finds a tile's row in the Board's model
|
|
40
|
+
const bm = BoardP.peekModel(); if (bm && Array.isArray(bm.rows)) bm.rows = bm.rows.filter((r) => !/^board:metric-/.test(r.key)).concat(model.rows);
|
|
41
|
+
ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
|
|
42
|
+
} catch (e) { ctx.json(res, { ok: false, state: 'error', error: String((e && e.message) || e).slice(0, 240) }, 500); }
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
|
|
23
46
|
module.exports = {
|
|
24
|
-
prefixes: ['/api/board-premium'],
|
|
47
|
+
prefixes: ['/api/board-premium', '/api/board-metrics-premium'],
|
|
25
48
|
handle: async (req, res, url, ctx) => {
|
|
49
|
+
if (url.pathname === '/api/board-metrics-premium') return metrics(req, res, url, ctx);
|
|
26
50
|
if (url.pathname !== '/api/board-premium') return false;
|
|
27
51
|
if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
|
|
28
52
|
const fail = (error) => { ctx.json(res, { ok: false, state: 'error', error: String(error).slice(0, 240) }, 500); return true; };
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pmos-workspace",
|
|
3
|
-
"version": "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.
|
|
9
|
+
"version": "0.257.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/workspace/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Coming up cards, Core documents, the dock and the standard dialog. The one press is Draft it on a core document, through POST /api/core-docs/draft.
|
|
4
4
|
* Nothing here moves an initiative or issues a document. */
|
|
5
5
|
import { pmPost } from './http.js';
|
|
6
|
-
import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, store, crumbHtml, wireCrumb } from './premium-shell.js';
|
|
6
|
+
import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, store, crumbHtml, wireCrumb, kv, H } from './premium-shell.js';
|
|
7
7
|
|
|
8
8
|
const MODE_KEY = 'pmos.premium.openAs';
|
|
9
9
|
let M = null; // the model
|
|
@@ -173,8 +173,93 @@ async function load() {
|
|
|
173
173
|
return;
|
|
174
174
|
}
|
|
175
175
|
$('#brief').textContent = '';
|
|
176
|
-
M = r.model; draw();
|
|
176
|
+
const first = !M; M = r.model; draw();
|
|
177
|
+
if (first && M.board.ws) startMetrics(M.board.ws); // the Metrics card of a tenant's board reads apart from the board
|
|
177
178
|
if (M.docs.rows.some((d) => d.running)) setTimeout(load, 5000); // a core-document run is going: ask again until it ends
|
|
178
179
|
}
|
|
179
180
|
$('#brief').textContent = 'Reading the board.';
|
|
180
181
|
load();
|
|
182
|
+
|
|
183
|
+
/* ── the Metrics card of a tenant's board (initiative briefing-premium-metrics) ─────────────────────────────────
|
|
184
|
+
* Reads GET /api/board-metrics-premium?ws= apart from the board's own answer and draws lib/board-metrics-premium.js's tiles: a number and a chart only
|
|
185
|
+
* where a record counted one, "Not read" where it could not be. A tile opens the standard dialog. Nothing here writes. */
|
|
186
|
+
let MM = null, metTimer = null; // the Metrics card's model and its re-read timer
|
|
187
|
+
const MET_GEO = { W: 220, H: 60, P: 5 };
|
|
188
|
+
const metGeo = (m) => { const n = m.ser.length, { W, H: Ht, P } = MET_GEO, vs = m.ser.filter((v) => v != null), lo = Math.min(...vs), hi = Math.max(...vs), sp = hi - lo || 1; return { n, W, H: Ht, P, X: (j) => P + j * (W - 2 * P) / (n - 1), Y: (v) => P + (1 - (v - lo) / sp) * (Ht - 2 * P) }; };
|
|
189
|
+
const metFmt = (m, v) => (+v).toFixed(m.dec) + (m.suf || '');
|
|
190
|
+
|
|
191
|
+
function metTileHtml(t, i) {
|
|
192
|
+
if (t.absent) return `<div class="mt1" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)}: ${esc(t.absent)}. ${esc(t.why)}"><span>${esc(t.label)}</span><b class="mval">${esc(t.absent)}</b><em class="mwk">${esc(t.why)}</em></div>`;
|
|
193
|
+
const chg = t.change ? `<span class="mchg ${t.change.d === 0 ? '' : t.change.good ? 'good' : 'bad'}">${t.change.d === 0 ? '' : t.change.d > 0 ? '▲ ' : '▼ '}${esc(t.change.txt)}</span>` : '';
|
|
194
|
+
if (!t.ser) return `<div class="mt1 ${t.kind}" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)}, ${esc(t.value)}, ${esc(t.text)}"><span>${esc(t.label)}</span><b class="mval">${esc(t.value)}</b><em class="mwk">${esc(t.text)}</em></div>`;
|
|
195
|
+
const g = metGeo(t); let ln = '', op = false;
|
|
196
|
+
t.ser.forEach((v, j) => { if (v == null) { op = false; return; } ln += (op ? 'L' : 'M') + g.X(j).toFixed(1) + ',' + g.Y(v).toFixed(1); op = true; });
|
|
197
|
+
const f = Math.max(0, t.ser.findIndex((v) => v != null)), gap = t.ser.slice(f).some((v) => v == null), n1 = g.n - 1, lastJ = t.ser.reduce((a, v, j) => (v != null ? j : a), f);
|
|
198
|
+
return `<div class="mt1 mch ${t.kind}" data-m="${i}" data-op="m:${i}" tabindex="0" role="button" aria-label="${esc(t.label)} over eight weeks, now ${esc(t.value)}. Use the arrow keys to read each week."><span>${esc(t.label)}</span><b class="mval">${esc(t.value)}</b><em class="mwk">${esc(t.text)}</em>${chg}`
|
|
199
|
+
+ `<svg viewBox="0 0 ${g.W} ${g.H}">${f > 0 ? `<line class="gp" x1="${g.X(0)}" x2="${g.X(f)}" y1="${g.H - g.P}" y2="${g.H - g.P}"/>` : ''}${gap ? '' : `<path class="ar" d="${ln}L${g.X(n1)},${g.H}L${g.X(f)},${g.H}Z"/>`}<path class="ln2" d="${ln}"/><line class="cx" x1="0" x2="0" y1="0" y2="${g.H}"/><circle class="dt" cx="${g.X(lastJ)}" cy="${g.Y(t.ser[lastJ])}" r="3.5"/></svg>`
|
|
200
|
+
+ `<span class="mfoot"><i>${esc(t.wk[0])}</i><i>${esc(t.wk[t.wk.length - 1])}</i></span></div>`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Read one week of a chart tile: the guide line and dot move, the value and caption change. */
|
|
204
|
+
function metChartAt(el, j) {
|
|
205
|
+
const t = MM.tiles[+el.dataset.m]; if (!t || !t.ser) return;
|
|
206
|
+
const g = metGeo(t); j = j == null ? t.ser.reduce((a, v, k) => (v != null ? k : a), 0) : Math.max(0, Math.min(g.n - 1, j));
|
|
207
|
+
const v = t.ser[j], has = v != null, x = g.X(j), y = has ? g.Y(v) : 0, now = j === t.ser.reduce((a, w, k) => (w != null ? k : a), 0);
|
|
208
|
+
const cx = $('.cx', el), dt = $('.dt', el);
|
|
209
|
+
cx.setAttribute('x1', x); cx.setAttribute('x2', x); dt.setAttribute('cx', x); dt.setAttribute('cy', y); dt.style.opacity = has ? '' : '0';
|
|
210
|
+
el.classList.toggle('hv', !now); el.dataset.j = j;
|
|
211
|
+
const val = now ? t.value : has ? metFmt(t, v) : 'No runs', cap = now ? t.text : 'Week to ' + t.wk[j] + (t.nt[j] ? ' · ' + t.nt[j] : '');
|
|
212
|
+
$('.mval', el).textContent = val; $('.mwk', el).textContent = cap;
|
|
213
|
+
el.setAttribute('aria-label', t.label + ', ' + (now ? 'now ' : '') + val + ', ' + cap + '. Use the arrow keys to read each week.');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function metDraw() {
|
|
217
|
+
const card = $('#cMet'); if (!MM) { card.hidden = true; return; }
|
|
218
|
+
card.hidden = false;
|
|
219
|
+
$('#metCap').textContent = MM.header;
|
|
220
|
+
$('#metHint').textContent = MM.hint;
|
|
221
|
+
$('#metBody').style.gridTemplateColumns = 'repeat(' + Math.min(4, MM.tiles.length) + ',minmax(0,1fr))';
|
|
222
|
+
$('#metBody').innerHTML = MM.tiles.map(metTileHtml).join('');
|
|
223
|
+
$('#metNote').textContent = MM.note;
|
|
224
|
+
pillOf($('#perTabs'));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function metOpenTile(i) {
|
|
228
|
+
const t = MM.tiles[i], r = MM.rows[i]; if (!t || !r) return;
|
|
229
|
+
const d = r.dialog;
|
|
230
|
+
const rows = t.absent ? [['Now', t.absent], ['Why', t.why], ['Counted from', MM.repo]]
|
|
231
|
+
: [['Now', t.value], ['Counted', t.text], ['Change', t.change ? t.change.txt : ''], ['Better when', t.lowBetter ? 'Lower' : t.lowBetter === false ? 'Higher' : ''], ['Period', t.ser ? 'Week · last 8 weeks' : 'Now'], ['Source', MM.repo]];
|
|
232
|
+
const vals = t.ser ? H('Values') + `<div class="vtb">${t.ser.map((v, j) => `<div><span>${esc(t.wk[j])}</span><b>${v == null ? 'No runs' : esc(metFmt(t, v))}</b></div>`).join('')}</div>` : '';
|
|
233
|
+
const pane = `<article class="paper doc"><p class="lede" style="margin:0 0 10px">${esc(t.def)}</p>${kv(rows)}${vals}<p class="note" style="margin-top:12px">${esc(MM.note)}</p></article>`;
|
|
234
|
+
openDlg({ eye: 'Measure · real data', title: t.label, sub: MM.repo, say: d.say, stream: turnA(logHtml({ logTitle: 'Read from the repository', log: ['Read the repository\'s own records', 'Counted them by week', 'Changed nothing'] })) + turnA(ptx(d.say)), noteKey: r.key, pane, label: 'Measure' });
|
|
235
|
+
loadThread(r.key);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const metIdx = (e) => { const t = e.target.closest('[data-m]'); return t ? t : null; };
|
|
239
|
+
const metBody = () => $('#metBody');
|
|
240
|
+
function metWire() {
|
|
241
|
+
metBody().addEventListener('click', (e) => { const t = metIdx(e); if (t) metOpenTile(+t.dataset.m); });
|
|
242
|
+
metBody().addEventListener('keydown', (e) => {
|
|
243
|
+
const t = metIdx(e); if (!t) return;
|
|
244
|
+
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); metOpenTile(+t.dataset.m); return; }
|
|
245
|
+
if (!t.classList.contains('mch') || !/^Arrow(Left|Right)$/.test(e.key)) return;
|
|
246
|
+
e.preventDefault(); const m = MM.tiles[+t.dataset.m], now = t.dataset.j == null ? m.ser.length - 1 : +t.dataset.j; metChartAt(t, now + (e.key === 'ArrowLeft' ? -1 : 1));
|
|
247
|
+
});
|
|
248
|
+
metBody().addEventListener('pointermove', (e) => { const t = metIdx(e); if (!t || !t.classList.contains('mch')) return; const s = $('svg', t).getBoundingClientRect(), m = MM.tiles[+t.dataset.m], g = metGeo(m); metChartAt(t, Math.round(((e.clientX - s.left) / s.width * g.W - g.P) / (g.W - 2 * g.P) * (g.n - 1))); });
|
|
249
|
+
metBody().addEventListener('pointerout', (e) => { const t = metIdx(e); if (t && t.classList.contains('mch') && !t.contains(e.relatedTarget)) metChartAt(t, null); });
|
|
250
|
+
$('#perTabs').addEventListener('click', (e) => { const b = e.target.closest('[aria-disabled="true"]'); if (b) toast('PMOS counts runs and merges by week only.'); });
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function startMetrics(ws) {
|
|
254
|
+
clearTimeout(metTimer);
|
|
255
|
+
let r = null;
|
|
256
|
+
try { const res = await fetch('/api/board-metrics-premium?ws=' + encodeURIComponent(ws || ''), { credentials: 'same-origin' }); r = await res.json(); } catch { r = null; }
|
|
257
|
+
if (r && r.ok && r.state === 'none') { MM = null; metDraw(); return; } // the home workspace's board has no card
|
|
258
|
+
if (!r || !r.ok || r.state !== 'ready') {
|
|
259
|
+
MM = null; metDraw(); $('#cMet').hidden = false; $('#metCap').textContent = 'not read'; $('#metHint').textContent = 'The metrics could not be read, so none is shown.' + (r && r.error ? ' The reason: ' + r.error : ''); $('#metBody').innerHTML = ''; $('#metNote').textContent = '';
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
MM = r.model; metDraw();
|
|
263
|
+
if (MM.pending) metTimer = setTimeout(() => startMetrics(ws), 4000); // the workflow engine is still deriving the Blocked and Idle tiles
|
|
264
|
+
}
|
|
265
|
+
metWire();
|
|
@@ -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
|
|
4
|
-
* standard dialog beside the read-only agent. The
|
|
5
|
-
*
|
|
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.
|
|
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">
|
|
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
|
|
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" ────────── */
|