create-pmos 0.848.0 → 0.850.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 +68 -139
- 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/changelog.json +67 -2
- package/workspace/guide/cli.md +31 -0
- package/workspace/guide/settings-and-switches.md +2 -0
- package/workspace/lib/balance-cli.js +58 -5
- package/workspace/lib/balance-target.js +228 -0
- package/workspace/lib/compare-cli.js +140 -0
- package/workspace/lib/drift-cli.js +4 -1
- package/workspace/lib/features.json +2 -1
- package/workspace/lib/needs-providers.js +1 -0
- package/workspace/lib/pmos-verbs.js +4 -1
- package/workspace/lib/routes-drift.js +4 -1
- package/workspace/lib/routes-spec-drift.js +130 -0
- package/workspace/lib/spec-code-drift.js +334 -0
- package/workspace/lib/spec-drift-cli.js +89 -0
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/bd-backlog.css +1 -0
- package/workspace/public/pm/bd-backlog.js +3 -0
- package/workspace/public/pm/compare-items.css +29 -0
- package/workspace/public/pm/compare-items.js +181 -0
- package/workspace/public/pm/spec-code-drift.js +61 -0
- package/workspace/public/premium-library.html +2 -0
- package/workspace/test-lists/balance-rebalance.json +9 -0
- package/workspace/test-lists/compare-items.json +9 -0
- package/workspace/test-lists/spec-code-drift.json +9 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* balance-target.js — a target mix for the roadmap, and the rank move that closes the most gap (initiative balance-rebalance, bet A65,
|
|
3
|
+
* job #2051). `pmos balance target|gap` (lib/balance-cli.js) is its CLI; lib/list-balance.js gives the kind of each initiative.
|
|
4
|
+
*
|
|
5
|
+
* parseTarget('feature:50,fix:30,debt:20') → { ok, target: { feature: 50, fix: 30, debt: 20 } } | { ok: false, error }
|
|
6
|
+
* known kinds only (list-balance KINDS), whole percents, adding up to 100.
|
|
7
|
+
* setTarget(runtime, root, target, { front, by }) · clearTarget(runtime, root, { by }) · undoTarget(runtime, root, { by })
|
|
8
|
+
* append-only `<runtime>/balance-targets.jsonl`; one line per write. Undo takes the last set or clear back.
|
|
9
|
+
* targetOf(runtime, root) → { target, front, at, by } | null
|
|
10
|
+
* ranked(root) → [{ id, title, kind }] the live initiatives in Roadmap order (D105), finished ones left out
|
|
11
|
+
* gapOf(list, target, front) → { front: [...], mix: { kind: pct }, gap } gap = half the sum of |actual − target|, in points
|
|
12
|
+
* movesOf(list, target, front, { max }) → the best rank moves, at most `max` (2): an under-target initiative from below the front
|
|
13
|
+
* moved just above an over-target one in it. Each: { id, above, kind, pushes, gapAfter, closes, cli, undo }. Only moves that close gap.
|
|
14
|
+
* count(runtime, { days }) → target and gap uses recorded in the last N days (the health number)
|
|
15
|
+
* needs provider (lib/needs-providers.js): kinds ['balance-gap'] · rowsFor(w, { lead }) · sig(w)
|
|
16
|
+
* one Today row (kind 7) when a target is saved, the front is ROW_GAP points or more off it, and a move closes some of the gap.
|
|
17
|
+
* Its ✦ is the rank move (`pmos initiative after|top`), with Undo.
|
|
18
|
+
* With no target saved: one row (kind 7) that proposes a target drawn from the roadmap (proposeTarget), when the front is
|
|
19
|
+
* ROW_GAP points or more off that proposal and a move would close some of it. Its ✦ saves the proposal (`pmos balance target …`),
|
|
20
|
+
* with Undo (`pmos balance target --undo`). Otherwise no row.
|
|
21
|
+
* proposeTarget(list, front) → { feature: 60, fix: 30, … } | null the mix of the whole live roadmap, the largest kind
|
|
22
|
+
* capped at the balance line (60%) and the rest given to the other kinds it holds, in steps of 10. null when it holds one kind.
|
|
23
|
+
*
|
|
24
|
+
* Reading writes nothing in the repository. Nothing here moves a rank by itself or sends anything: a move is a command the PM presses.
|
|
25
|
+
*/
|
|
26
|
+
const fs = require('fs');
|
|
27
|
+
const path = require('path');
|
|
28
|
+
const B = require('./list-balance.js');
|
|
29
|
+
|
|
30
|
+
const FILE = 'balance-targets.jsonl';
|
|
31
|
+
const DEFAULT_FRONT = 6;
|
|
32
|
+
const ROW_GAP = 15;
|
|
33
|
+
const KIND = 'balance-gap';
|
|
34
|
+
const fileOf = (runtime) => path.join(runtime, FILE);
|
|
35
|
+
const log = (s) => { try { process.stderr.write('[balance] ' + s + '\n'); } catch { /* a closed stream */ } };
|
|
36
|
+
|
|
37
|
+
function lines(runtime) {
|
|
38
|
+
let raw = '';
|
|
39
|
+
try { raw = fs.readFileSync(fileOf(runtime), 'utf8'); } catch { return []; }
|
|
40
|
+
const out = [];
|
|
41
|
+
for (const l of raw.split('\n')) { if (!l.trim()) continue; try { out.push(JSON.parse(l)); } catch { /* a torn line */ } }
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
function append(runtime, line) {
|
|
45
|
+
fs.mkdirSync(runtime, { recursive: true });
|
|
46
|
+
fs.appendFileSync(fileOf(runtime), JSON.stringify({ at: new Date().toISOString(), ...line }) + '\n');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseTarget(text) {
|
|
50
|
+
const s = String(text == null ? '' : text).trim();
|
|
51
|
+
if (!s) return { ok: false, error: 'say the mix, e.g. feature:50,fix:30,debt:20' };
|
|
52
|
+
const target = {};
|
|
53
|
+
for (const part of s.split(/[,\s]+/).filter(Boolean)) {
|
|
54
|
+
const m = /^([a-z-]+)[:=](\d{1,3})%?$/i.exec(part);
|
|
55
|
+
if (!m) return { ok: false, error: `"${part}" is not kind:percent, e.g. feature:50` };
|
|
56
|
+
const k = m[1].toLowerCase();
|
|
57
|
+
if (!B.KINDS.includes(k)) return { ok: false, error: `${k} is not a kind. Use ${B.KINDS.join(', ')}` };
|
|
58
|
+
if (k in target) return { ok: false, error: `${k} is named twice` };
|
|
59
|
+
target[k] = Number(m[2]);
|
|
60
|
+
}
|
|
61
|
+
const sum = Object.values(target).reduce((a, b) => a + b, 0);
|
|
62
|
+
if (sum !== 100) return { ok: false, error: `the parts add up to ${sum}, not 100` };
|
|
63
|
+
return { ok: true, target };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const keyOf = (root) => path.resolve(root);
|
|
67
|
+
/** The saved target of a repository, folded from its lines: each set or clear is a state; undo takes the last one back. */
|
|
68
|
+
function targetOf(runtime, root) {
|
|
69
|
+
const at = keyOf(root), stack = [];
|
|
70
|
+
for (const l of lines(runtime)) {
|
|
71
|
+
if (l.root !== at) continue;
|
|
72
|
+
if (l.ev === 'set') stack.push({ target: l.target, front: l.front || DEFAULT_FRONT, at: l.at, by: l.by });
|
|
73
|
+
else if (l.ev === 'clear') stack.push(null);
|
|
74
|
+
else if (l.ev === 'undo') stack.pop();
|
|
75
|
+
}
|
|
76
|
+
return stack.length ? stack[stack.length - 1] : null;
|
|
77
|
+
}
|
|
78
|
+
function writes(runtime, root) { return lines(runtime).filter((l) => l.root === keyOf(root) && ['set', 'clear'].includes(l.ev)).length - lines(runtime).filter((l) => l.root === keyOf(root) && l.ev === 'undo').length; }
|
|
79
|
+
|
|
80
|
+
function setTarget(runtime, root, target, { front, by } = {}) {
|
|
81
|
+
const f = front == null ? DEFAULT_FRONT : Number(front);
|
|
82
|
+
if (!Number.isInteger(f) || f < 2 || f > 50) return { ok: false, error: '--front is a whole number from 2 to 50' };
|
|
83
|
+
append(runtime, { ev: 'set', root: keyOf(root), target, front: f, by: by || 'agent:unknown' });
|
|
84
|
+
log(`target set ${Object.entries(target).map(([k, v]) => k + ':' + v).join(',')} front ${f}`);
|
|
85
|
+
return { ok: true, saved: targetOf(runtime, root) };
|
|
86
|
+
}
|
|
87
|
+
function clearTarget(runtime, root, { by } = {}) {
|
|
88
|
+
if (!targetOf(runtime, root)) return { ok: false, error: 'no target is saved for this repository' };
|
|
89
|
+
append(runtime, { ev: 'clear', root: keyOf(root), by: by || 'agent:unknown' });
|
|
90
|
+
log('target clear');
|
|
91
|
+
return { ok: true, saved: null };
|
|
92
|
+
}
|
|
93
|
+
function undoTarget(runtime, root, { by } = {}) {
|
|
94
|
+
if (writes(runtime, root) <= 0) return { ok: false, error: 'no target change to take back' };
|
|
95
|
+
append(runtime, { ev: 'undo', root: keyOf(root), by: by || 'agent:unknown' });
|
|
96
|
+
log('target undo');
|
|
97
|
+
return { ok: true, saved: targetOf(runtime, root) };
|
|
98
|
+
}
|
|
99
|
+
/** One use of `gap` (target writes count by themselves). */
|
|
100
|
+
function used(runtime, root, what) { try { append(runtime, { ev: 'use', root: keyOf(root), what }); } catch { /* a read-only runtime */ } }
|
|
101
|
+
function count(runtime, { days = 7, now = Date.now() } = {}) {
|
|
102
|
+
const since = now - days * 86400000;
|
|
103
|
+
return lines(runtime).filter((l) => ['set', 'clear', 'undo', 'use'].includes(l.ev) && Date.parse(l.at) >= since).length;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The live initiatives of a repository in Roadmap order (one ranked list, D105). Finished ones are left out. */
|
|
107
|
+
function ranked(root) {
|
|
108
|
+
const rowsLib = require('./initiative-rows.js'), P = require('./placements.js'), PR = require('./plan-rules.js');
|
|
109
|
+
const d = rowsLib.deriveSync(root);
|
|
110
|
+
if (!d.ok) return [];
|
|
111
|
+
const rows = new Map(d.rows.map((r) => [r.id, r]));
|
|
112
|
+
const placed = P.readPlacements(root, { now: Date.now(), rules: PR.readRules(root), records: d.rows });
|
|
113
|
+
return placed.ranked.map((id) => rows.get(id)).filter((r) => r && !r.accepted && !r.stopped)
|
|
114
|
+
.map((r) => ({ id: r.id, title: r.title || r.id, kind: B.kindOf(r) }));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function gapOf(list, target, front = DEFAULT_FRONT) {
|
|
118
|
+
const f = (list || []).slice(0, front), n = f.length;
|
|
119
|
+
const mix = Object.fromEntries(B.KINDS.map((k) => [k, n ? Math.round((f.filter((x) => x.kind === k).length / n) * 100) : 0]));
|
|
120
|
+
const exact = (k) => (n ? (f.filter((x) => x.kind === k).length / n) * 100 : 0);
|
|
121
|
+
const gap = n ? Math.round(B.KINDS.reduce((s, k) => s + Math.abs(exact(k) - (target[k] || 0)), 0) / 2) : 0;
|
|
122
|
+
return { front: f, mix, gap };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function movesOf(list, target, front = DEFAULT_FRONT, { max = 2 } = {}) {
|
|
126
|
+
const L = list || [];
|
|
127
|
+
if (L.length <= front) return [];
|
|
128
|
+
const now = gapOf(L, target, front), n = now.front.length;
|
|
129
|
+
const share = (k) => (now.front.filter((x) => x.kind === k).length / n) * 100;
|
|
130
|
+
const under = (k) => share(k) < (target[k] || 0), over = (k) => share(k) > (target[k] || 0);
|
|
131
|
+
const best = new Map();
|
|
132
|
+
for (let ui = front; ui < L.length; ui++) {
|
|
133
|
+
const u = L[ui];
|
|
134
|
+
if (!under(u.kind)) continue;
|
|
135
|
+
for (let oi = 0; oi < front; oi++) {
|
|
136
|
+
const o = L[oi];
|
|
137
|
+
if (!over(o.kind) || o.kind === u.kind) continue;
|
|
138
|
+
const moved = L.filter((x) => x.id !== u.id);
|
|
139
|
+
moved.splice(oi, 0, u);
|
|
140
|
+
const after = gapOf(moved, target, front).gap;
|
|
141
|
+
if (after >= now.gap) continue;
|
|
142
|
+
const m = { id: u.id, title: u.title, kind: u.kind, above: o.id, pushes: L[front - 1].id, gapAfter: after, closes: now.gap - after,
|
|
143
|
+
cli: oi === 0 ? `pmos initiative top ${u.id}` : `pmos initiative after ${u.id} ${L[oi - 1].id}`,
|
|
144
|
+
undo: `pmos initiative after ${u.id} ${L[ui - 1].id}` };
|
|
145
|
+
const was = best.get(u.id);
|
|
146
|
+
// the move that closes the most; on a tie, the one that lifts it least far (the lowest over-target one in the front)
|
|
147
|
+
if (!was || m.closes > was.closes || (m.closes === was.closes && oi > L.findIndex((x) => x.id === was.above))) best.set(u.id, m);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return [...best.values()].sort((a, b) => b.closes - a.closes || L.findIndex((x) => x.id === a.id) - L.findIndex((x) => x.id === b.id)).slice(0, max);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const label = (k) => B.KIND_LABEL[k] || k;
|
|
154
|
+
const mixWords = (o) => B.KINDS.filter((k) => o[k]).map((k) => `${label(k)} ${o[k]}%`).join(' · ') || 'nothing';
|
|
155
|
+
|
|
156
|
+
/* ── the needs provider: an off-target roadmap is a Today row by itself ─────────────────────────────────────────────── */
|
|
157
|
+
/** The Today row for workspace `ws` (pure): [] unless a target is saved, the gap is ROW_GAP or more and a move closes some of it. */
|
|
158
|
+
function rowsOf(ws, saved, list) {
|
|
159
|
+
if (!saved || !saved.target) return [];
|
|
160
|
+
const g = gapOf(list, saved.target, saved.front);
|
|
161
|
+
if (g.gap < ROW_GAP) return [];
|
|
162
|
+
const m = movesOf(list, saved.target, saved.front, { max: 1 })[0];
|
|
163
|
+
if (!m) return [];
|
|
164
|
+
const cause = `The top ${g.front.length} of your roadmap is ${g.gap} points off your target mix (${mixWords(g.mix)}; target ${mixWords(saved.target)}). Moving ${m.id} (${label(m.kind)}) above ${m.above} closes ${m.closes}.`;
|
|
165
|
+
return [{
|
|
166
|
+
run_id: `${KIND}:${ws}:${m.id}:${m.above}`, kind: KIND, initiative_id: m.id, question: cause, doc: null, ws,
|
|
167
|
+
today: { kind: 7, source: 'balance-target', cause, evidence: `pmos balance gap · target saved ${String(saved.at || '').slice(0, 10)}`,
|
|
168
|
+
act: { label: `Move ${m.id} up`, cli: m.cli, undo: m.undo } },
|
|
169
|
+
}];
|
|
170
|
+
}
|
|
171
|
+
/** A target drawn from the roadmap: its whole mix, the largest kind capped at the balance line, in steps of 10. Pure. */
|
|
172
|
+
function proposeTarget(list, front = DEFAULT_FRONT) {
|
|
173
|
+
const L = list || [];
|
|
174
|
+
if (L.length <= front) return null;
|
|
175
|
+
const n = Object.fromEntries(B.KINDS.map((k) => [k, L.filter((x) => x.kind === k).length]));
|
|
176
|
+
const present = B.KINDS.filter((k) => n[k] > 0);
|
|
177
|
+
if (present.length < 2) return null;
|
|
178
|
+
const share = Object.fromEntries(present.map((k) => [k, (n[k] / L.length) * 100]));
|
|
179
|
+
const top = present.reduce((a, b) => (share[b] > share[a] ? b : a));
|
|
180
|
+
if (share[top] > B.DEFAULT_MAX) {
|
|
181
|
+
const rest = 100 - share[top], spare = share[top] - B.DEFAULT_MAX;
|
|
182
|
+
share[top] = B.DEFAULT_MAX;
|
|
183
|
+
for (const k of present) if (k !== top) share[k] += spare * (share[k] / rest);
|
|
184
|
+
}
|
|
185
|
+
// whole steps of 10 that add up to 100: round down, then give the leftover steps to the largest remainders
|
|
186
|
+
const t = Object.fromEntries(present.map((k) => [k, Math.floor(share[k] / 10) * 10]));
|
|
187
|
+
let left = 100 - Object.values(t).reduce((a, b) => a + b, 0);
|
|
188
|
+
for (const k of [...present].sort((a, b) => (share[b] % 10) - (share[a] % 10) || B.KINDS.indexOf(a) - B.KINDS.indexOf(b))) { if (left <= 0) break; t[k] += 10; left -= 10; }
|
|
189
|
+
for (const k of present) if (!t[k]) delete t[k];
|
|
190
|
+
return Object.keys(t).length >= 2 ? t : null;
|
|
191
|
+
}
|
|
192
|
+
const targetText = (t) => B.KINDS.filter((k) => t[k]).map((k) => `${k}:${t[k]}`).join(',');
|
|
193
|
+
/** The proposal row (pure): [] unless the front is ROW_GAP or more off the proposed target and a move would close some of it. */
|
|
194
|
+
function proposalRowsOf(ws, list, front = DEFAULT_FRONT) {
|
|
195
|
+
const t = proposeTarget(list, front);
|
|
196
|
+
if (!t) return [];
|
|
197
|
+
const g = gapOf(list, t, front);
|
|
198
|
+
if (g.gap < ROW_GAP || !movesOf(list, t, front, { max: 1 }).length) return [];
|
|
199
|
+
const cause = `The top ${g.front.length} of your roadmap is ${mixWords(g.mix)}. Save a target mix of ${mixWords(t)}, drawn from your whole roadmap, and PMOS names the rank move that closes the ${g.gap}-point gap.`;
|
|
200
|
+
return [{
|
|
201
|
+
run_id: `${KIND}:${ws}:propose:${targetText(t)}`, kind: KIND, initiative_id: null, question: cause, doc: null, ws,
|
|
202
|
+
today: { kind: 7, source: 'balance-target', cause, evidence: `pmos balance show · ${list.length} live initiatives`,
|
|
203
|
+
act: { label: 'Save this target', cli: `pmos balance target ${targetText(t)}`, undo: 'pmos balance target --undo' } },
|
|
204
|
+
}];
|
|
205
|
+
}
|
|
206
|
+
const runtimeNow = () => require('./state-root.js').defaultRoot({ env: process.env });
|
|
207
|
+
function rowsFor(w, { lead } = {}) {
|
|
208
|
+
if (!lead || !w || !w.root) return [];
|
|
209
|
+
const saved = targetOf(runtimeNow(), w.root);
|
|
210
|
+
return saved ? rowsOf(w.id, saved, ranked(w.root)) : proposalRowsOf(w.id, ranked(w.root));
|
|
211
|
+
}
|
|
212
|
+
function sig(w) {
|
|
213
|
+
let t = '-';
|
|
214
|
+
try { const st = fs.statSync(fileOf(runtimeNow())); t = st.size + ':' + st.mtimeMs; } catch { /* no target yet */ }
|
|
215
|
+
let p = '-';
|
|
216
|
+
try { p = String(require('./plan-ledgers.js').ledgerSig(w.root, 'placements')); } catch { /* no ledger */ }
|
|
217
|
+
return t + '|' + p + '|' + new Date().toISOString().slice(0, 10);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
module.exports = { FILE, DEFAULT_FRONT, ROW_GAP, KIND, kinds: [KIND], fileOf, parseTarget, targetOf, setTarget, clearTarget, undoTarget, used, count,
|
|
221
|
+
ranked, gapOf, movesOf, mixWords, proposeTarget, proposalRowsOf, rowsOf, rowsFor, sig };
|
|
222
|
+
|
|
223
|
+
if (require.main === module) {
|
|
224
|
+
const a = process.argv.slice(2);
|
|
225
|
+
if (a[0] !== 'count') { console.log('usage: node lib/balance-target.js count [--days N]'); process.exit(2); }
|
|
226
|
+
const i = a.indexOf('--days'), days = i >= 0 ? Math.max(1, Number(a[i + 1]) || 7) : 7;
|
|
227
|
+
console.log(String(count(runtimeNow(), { days })));
|
|
228
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* compare-cli.js — `pmos compare <a> <b>`: two items side by side, the differences marked (idea A421, initiative compare-items; done test
|
|
3
|
+
* planning/done-tests/compare-items.md). The chat's way to the compare panel Work opens (public/pm/compare-items.js).
|
|
4
|
+
*
|
|
5
|
+
* pmos compare <a> <b> [--json] [--root <dir>] (pmos compare show <a> <b> is the same)
|
|
6
|
+
* <a>, <b>: an initiative id (its record, kit or PMOS-self layout) or a file path, each with an optional @<git revision>:
|
|
7
|
+
* pmos compare checkout-redesign wechat-login two initiatives: their fields and their `## ` sections
|
|
8
|
+
* pmos compare planning/prd/otp.md@HEAD~1 planning/prd/otp.md two versions of one brief
|
|
9
|
+
* Prints the rows that differ (removed words in [-…-], added words in {+…+}) and the rows that are the same in one line.
|
|
10
|
+
*
|
|
11
|
+
* sideOf(root, ref) → { ok: true, side } | { ok: false, error } side: { title, sub, fields: [[name, value]], parts: [[name, text]] }
|
|
12
|
+
* splitOf(text) → { front: [[key, value]], parts: [[heading, text]] } PURE
|
|
13
|
+
*
|
|
14
|
+
* The rows come from the page's own pure model (public/pm/compare-items.js compareOf), so the chat and the panel never disagree.
|
|
15
|
+
* READ ONLY: it reads files and `git show`, writes nothing to the product and sends nothing. Each run counts the use-log control
|
|
16
|
+
* compareOpen (this computer's runtime folder, the health number) and prints one [compare-items] line on stderr.
|
|
17
|
+
* Exit codes: 0 done, 1 an item was not found, 2 usage. */
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const { execFileSync } = require('child_process');
|
|
21
|
+
const why = require('./item-why.js');
|
|
22
|
+
|
|
23
|
+
const TAG = '[compare-items]';
|
|
24
|
+
const COMMANDS = { compare: ['show'] };
|
|
25
|
+
const USAGE = [
|
|
26
|
+
'usage: pmos compare <a> <b> — two items side by side, the differences marked',
|
|
27
|
+
' <a>, <b> an initiative id or a file path, each with an optional @<git revision> (a version: brief.md@HEAD~1)',
|
|
28
|
+
' pmos compare show <a> <b> the same',
|
|
29
|
+
' every command: [--json] [--root <dir>]',
|
|
30
|
+
'Removed words show in [-…-], added words in {+…+}. Nothing is written or sent.',
|
|
31
|
+
];
|
|
32
|
+
const FIELD_WORD = { parent_kr: 'Goal it moves', status: 'Status', lane: 'Lane', kind: 'Kind', owner: 'Owner', stage: 'Stage', state: 'State',
|
|
33
|
+
expected_outcome: 'Expected outcome', outcome_horizon: 'Check date', kill: 'Kill if', start: 'Start', due: 'Due', target_date: 'Due' };
|
|
34
|
+
const SKIP = new Set(['title', 'type', 'timestamp', 'id', 'done_test_path', 'health_read', 'health_log', 'try_open']);
|
|
35
|
+
const nameOf = (k) => FIELD_WORD[k] || (k.charAt(0).toUpperCase() + k.slice(1)).replace(/_/g, ' ');
|
|
36
|
+
|
|
37
|
+
function repoRoot(cwd) {
|
|
38
|
+
try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; }
|
|
39
|
+
catch { return cwd; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The frontmatter as named fields and the body as its `## ` parts (the text before the first heading is "Opening"). PURE. */
|
|
43
|
+
function splitOf(text) {
|
|
44
|
+
const t = String(text || '').replace(/\r\n?/g, '\n');
|
|
45
|
+
const fm = why.frontOf(t);
|
|
46
|
+
const front = Object.entries(fm).filter(([k, v]) => !SKIP.has(k) && String(v == null ? '' : v).trim() !== '').map(([k, v]) => [nameOf(k), String(v)]);
|
|
47
|
+
const body = t.replace(/^---\n[\s\S]*?\n---\n?/, '');
|
|
48
|
+
const parts = []; let cur = 'Opening', buf = [];
|
|
49
|
+
const flush = () => { const x = buf.join('\n').trim(); if (x) parts.push([cur, x]); buf = []; };
|
|
50
|
+
for (const line of body.split('\n')) {
|
|
51
|
+
const m = /^##\s+(.+?)\s*#*\s*$/.exec(line);
|
|
52
|
+
if (m) { flush(); cur = m[1]; } else if (!/^#\s/.test(line)) buf.push(line);
|
|
53
|
+
}
|
|
54
|
+
flush();
|
|
55
|
+
// a heading used twice keeps both, numbered, so no part hides another
|
|
56
|
+
const seen = new Map();
|
|
57
|
+
return { front, parts: parts.map(([k, v]) => { const n = (seen.get(k) || 0) + 1; seen.set(k, n); return [n > 1 ? `${k} (${n})` : k, v]; }) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const inside = (root, f) => { const a = path.resolve(f); return a === root || a.startsWith(root + path.sep); };
|
|
61
|
+
/** One item read from disk or from git. */
|
|
62
|
+
function sideOf(root, ref) {
|
|
63
|
+
const raw = String(ref || '').trim();
|
|
64
|
+
if (!raw) return { ok: false, error: 'an item is missing' };
|
|
65
|
+
const at = raw.lastIndexOf('@');
|
|
66
|
+
const base = at > 0 ? raw.slice(0, at) : raw, rev = at > 0 ? raw.slice(at + 1) : '';
|
|
67
|
+
if (rev && !/^[A-Za-z0-9._~^/-]{1,80}$/.test(rev)) return { ok: false, error: `"${rev}" is not a git revision` };
|
|
68
|
+
let file = null;
|
|
69
|
+
const asPath = path.resolve(root, base);
|
|
70
|
+
if (inside(root, asPath) && (fs.existsSync(asPath) || rev) && /[./\\]/.test(base)) file = asPath;
|
|
71
|
+
else { const rec = why.recordPathOf(root, base); if (rec) file = rec; }
|
|
72
|
+
if (!file || !inside(root, file)) return { ok: false, error: `no initiative or file "${base}" here` };
|
|
73
|
+
const relp = path.relative(root, file).split(path.sep).join('/');
|
|
74
|
+
let text = null, when = '';
|
|
75
|
+
if (rev) {
|
|
76
|
+
try {
|
|
77
|
+
text = execFileSync('git', ['show', `${rev}:${relp}`], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 8 << 20 });
|
|
78
|
+
when = execFileSync('git', ['log', '-1', '--format=%cs', rev, '--', relp], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
79
|
+
} catch { return { ok: false, error: `${relp} has no version at ${rev}` }; }
|
|
80
|
+
} else {
|
|
81
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return { ok: false, error: `${relp} cannot be read` }; }
|
|
82
|
+
}
|
|
83
|
+
const fm = why.frontOf(text), s = splitOf(text);
|
|
84
|
+
const title = String(fm.title || path.basename(relp, path.extname(relp))) + (rev ? ` @ ${rev}` : '');
|
|
85
|
+
return { ok: true, side: { title, sub: [relp, when].filter(Boolean).join(' · '), fields: s.front, parts: s.parts } };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parse(argv) {
|
|
89
|
+
const pos = [], flags = {};
|
|
90
|
+
for (let i = 0; i < argv.length; i++) {
|
|
91
|
+
const a = argv[i];
|
|
92
|
+
if (a === '--root') flags.root = argv[++i];
|
|
93
|
+
else if (a.startsWith('--root=')) flags.root = a.slice(7);
|
|
94
|
+
else if (a === '-h' || a === '--help') flags.help = true;
|
|
95
|
+
else if (a.startsWith('--')) flags[a.slice(2)] = true;
|
|
96
|
+
else pos.push(a);
|
|
97
|
+
}
|
|
98
|
+
return { pos, flags };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const pieceText = (p) => (p.op === 'del' ? `[-${p.t.trim()}-]${/\s$/.test(p.t) ? ' ' : ''}` : p.op === 'add' ? `{+${p.t.trim()}+}${/\s$/.test(p.t) ? ' ' : ''}` : p.t);
|
|
102
|
+
const oneLine = (s, n = 160) => { const t = String(s || '').replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1) + '…' : t; };
|
|
103
|
+
function used(o) {
|
|
104
|
+
try {
|
|
105
|
+
const dir = o.stateDir || require('./state-root.js').defaultRoot({ env: o.env || process.env });
|
|
106
|
+
require('./use-log.js').record(dir, [{ kind: 'use', page: 'today', control: 'compareOpen', device: 'desk' }], o.now || Date.now());
|
|
107
|
+
} catch { /* a count, never a reason to fail */ }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function run(argv, o = {}) {
|
|
111
|
+
const say = o.say || ((s) => console.log(s));
|
|
112
|
+
const args = argv[0] === 'compare' ? argv.slice(1) : argv.slice();
|
|
113
|
+
const { pos, flags } = parse(args);
|
|
114
|
+
if (pos[0] === 'show') pos.shift();
|
|
115
|
+
if (flags.help || pos[0] === 'help') { for (const l of USAGE) say(l); return 0; }
|
|
116
|
+
if (pos.length !== 2) { for (const l of USAGE) say(l); return 2; }
|
|
117
|
+
const root = path.resolve(flags.root || repoRoot(o.cwd || process.cwd()));
|
|
118
|
+
const A = sideOf(root, pos[0]), B = sideOf(root, pos[1]);
|
|
119
|
+
for (const x of [A, B]) if (!x.ok) { if (flags.json) say(JSON.stringify({ ok: false, error: x.error })); else say(`✗ ${x.error}`); return 1; }
|
|
120
|
+
const C = await import(require('url').pathToFileURL(path.join(__dirname, '..', 'public', 'pm', 'compare-items.js')).href);
|
|
121
|
+
const m = C.compareOf(A.side, B.side);
|
|
122
|
+
used(o);
|
|
123
|
+
try { console.error(TAG, 'compare', m.differ, 'of', m.total); } catch { /* no stderr */ }
|
|
124
|
+
if (flags.json) {
|
|
125
|
+
say(JSON.stringify({ ok: true, left: { title: m.left.title, sub: m.left.sub }, right: { title: m.right.title, sub: m.right.sub }, unit: m.unit, differ: m.differ, same: m.same, total: m.total, rows: m.rows }));
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
say(`${m.left.title} and ${m.right.title}: ${C.sumText(m) || 'nothing to compare'}.`);
|
|
129
|
+
for (const r of m.rows.filter((x) => !x.same)) {
|
|
130
|
+
say(`• ${r.name}`);
|
|
131
|
+
if (r.diff) { say(` - ${oneLine(r.diff.a.map(pieceText).join(''), 400) || 'None'}`); say(` + ${oneLine(r.diff.b.map(pieceText).join(''), 400) || 'None'}`); }
|
|
132
|
+
else { say(` - ${oneLine(r.a) || 'None'}`); say(` + ${oneLine(r.b) || 'None'}`); }
|
|
133
|
+
}
|
|
134
|
+
const same = m.rows.filter((x) => x.same);
|
|
135
|
+
if (same.length) say(`${same.length} the same: ${oneLine(same.map((x) => x.name).join(', '), 300)}.`);
|
|
136
|
+
say('Nothing was changed or sent.');
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { TAG, COMMANDS, USAGE, splitOf, sideOf, run };
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* replay (lib/ai-guard.js), and writes one replay line to your own ledger. This product's items show
|
|
9
9
|
* on Home only after a replay that passed.
|
|
10
10
|
* pmos drift status [--json] the last weekly result and the replays on record.
|
|
11
|
+
* pmos drift spec … Library › Drift: specs and code that no longer match (lib/spec-drift-cli.js).
|
|
11
12
|
*
|
|
12
13
|
* Run it in the product's repository. The weekly run itself needs no command: the server runs it each Monday. Nothing here changes a task,
|
|
13
14
|
* an initiative or a ticket, and nothing is sent. Exit codes: 0 done, 1 refused or the replay failed, 2 usage. */
|
|
@@ -17,12 +18,13 @@ const D = require('./drift.js');
|
|
|
17
18
|
const R = require('./drift-runs.js');
|
|
18
19
|
const Facts = require('./drift-facts.js');
|
|
19
20
|
|
|
20
|
-
const COMMANDS = { drift: ['show', 'replay', 'status'] };
|
|
21
|
+
const COMMANDS = { drift: ['show', 'replay', 'status', 'spec'] };
|
|
21
22
|
const USAGE = [
|
|
22
23
|
'usage: pmos drift show|replay|status — the weekly check for quiet drift (What would I have missed)',
|
|
23
24
|
' pmos drift show [--weeks <n>] [--json] what each of the last n weeks (default 4) would have shown for this repository; writes nothing',
|
|
24
25
|
' pmos drift replay [--json] replay the last 4 weeks of this repository on its real records; its items show on Today only after this passes',
|
|
25
26
|
' pmos drift status [--json] the last weekly result and the replays on record',
|
|
27
|
+
' pmos drift spec [fix|update|undo <row>] specs and code that no longer match (Library › Drift; pmos drift spec help)',
|
|
26
28
|
'The weekly run starts by itself each Monday. Nothing is changed in a task, an initiative or Jira, and nothing is sent.',
|
|
27
29
|
];
|
|
28
30
|
|
|
@@ -47,6 +49,7 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, cwd =
|
|
|
47
49
|
const sub = args[0];
|
|
48
50
|
if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 1; }
|
|
49
51
|
if (!COMMANDS.drift.includes(sub)) { say(`unknown drift command "${sub}". Use one of: ${COMMANDS.drift.join(', ')}`); return 2; }
|
|
52
|
+
if (sub === 'spec') return require('./spec-drift-cli.js').run(args.slice(1), { say, env, cwd, now, runtime });
|
|
50
53
|
const { pos, flags } = parse(args.slice(1));
|
|
51
54
|
if (pos.length) { say(`✗ pmos drift ${sub} takes no argument`); return 2; }
|
|
52
55
|
for (const k of Object.keys(flags)) if (k !== 'json' && !(k === 'weeks' && sub === 'show')) { say(`✗ --${k} is not an option of pmos drift ${sub}`); return 2; }
|
|
@@ -62,6 +62,7 @@
|
|
|
62
62
|
{"id": "rules", "audience": "user", "status": "ga", "group": "What PMOS did", "name": "Rules PMOS learned", "say": "The standing rules PMOS learned from your corrections, and edit or retire one.", "cmd": "/rules", "verb": "rules"},
|
|
63
63
|
{"id": "line", "audience": "user", "status": "ga", "group": "Catch up", "name": "Where each initiative stands", "say": "Days in its stage, what is missing, the next move, and whether it is stuck.", "cmd": "/line", "verb": "line", "hint": "<initiative>", "ask": ["initiative"]},
|
|
64
64
|
{"id": "hire", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "The next hire", "say": "The role your open work most needs, and a one-page role brief to edit.", "cmd": "/hire", "verb": "hire"},
|
|
65
|
+
{"id": "compare", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Compare two items", "say": "Two items or two versions of one file side by side, with the differences marked.", "cmd": "/compare", "verb": "compare", "hint": "<item> <item>", "place": "board"},
|
|
65
66
|
{"id": "experiment", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Copy and layout tests", "say": "Try new words or a new layout on an initiative: PMOS drafts the test, you start it, one line says how sure the winner is.", "cmd": "/experiment", "verb": "experiment", "hint": "draft <initiative> \"<what to try>\""},
|
|
66
67
|
{"id": "review", "audience": "user", "status": "ga", "group": "Before you ship", "name": "Built beside its design", "say": "The built screen beside its design, each difference circled and numbered. Accept it, or send a difference back as a fix.", "cmd": "/built-vs-design", "verb": "review", "sub": "list", "hint": "<initiative>", "place": "board"},
|
|
67
68
|
{"id": "story-map", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Story map", "say": "A new bet's user journey left to right, with the Release 1 line to move tasks across.", "cmd": "/story-map", "verb": "story-map", "hint": "<initiative>"},
|
|
@@ -69,7 +70,7 @@
|
|
|
69
70
|
{"id": "prototype", "audience": "user", "status": "ga", "group": "Before you ship", "name": "Simulated users try the prototype", "say": "Where simulated users, one per persona, got stuck on a prototype, and the personas that walk it.", "cmd": "/prototype", "verb": "prototype", "hint": "findings <initiative>"},
|
|
70
71
|
{"id": "goals", "audience": "user", "status": "ga", "group": "Your product", "name": "Starter goals", "say": "Up to three goals drafted from your own product, each with its source; keep one and it becomes a goal.", "cmd": "/goals", "verb": "goals"},
|
|
71
72
|
{"id": "approver", "audience": "user", "status": "ga", "group": "Before you ship", "name": "What an approver asks", "say": "What each approver asked or objected to before, ahead of the next sign-off.", "cmd": "/approver", "verb": "approver", "hint": "<name>"},
|
|
72
|
-
{"id": "balance", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "The mix of a list", "say": "Feature, fix, debt or discovery in one line,
|
|
73
|
+
{"id": "balance", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "The mix of a list", "say": "Feature, fix, debt or discovery in one line, a target mix for the roadmap, and the rank move that closes the gap.", "cmd": "/balance", "verb": "balance"},
|
|
73
74
|
{"id": "layouts", "audience": "user", "status": "ga", "group": "Before you ship", "name": "Three layouts for a new screen", "say": "Three layouts of a new screen side by side, the one that fits your picks, and the one you keep to build.", "cmd": "/layouts", "verb": "layouts"},
|
|
74
75
|
{"id": "declined", "audience": "user", "status": "ga", "group": "Plan and decide", "name": "Asks you declined", "say": "Asks closed without being done, each with a kind reply draft PMOS never sends.", "cmd": "/declined", "verb": "declined"},
|
|
75
76
|
{"id": "sprint", "audience": "user", "status": "ga", "group": "Catch up", "name": "Sprint retro", "say": "A closed sprint's retro from its close numbers, and its one tracked change.", "cmd": "/sprint", "verb": "sprint"},
|
|
@@ -45,6 +45,7 @@ const PROVIDERS = Object.freeze([
|
|
|
45
45
|
'setup-station', // setup-station: a product that has not passed Setup (tracker read, agreed goal, owner), with the next ✦ (kind 7)
|
|
46
46
|
'critical-needs', // critical-moved (bet A103): a task on an initiative's critical path moved its start or due date, with go-live (kind 7)
|
|
47
47
|
'change-requests', // change-requests (bet A105): a stakeholder's open change request, with what it would break; ✦ approves with Undo (kind 1)
|
|
48
|
+
'balance-target', // balance-rebalance (bet A65): the top of the roadmap is 15 points or more off the target mix, with the one ✦ rank move (kind 7)
|
|
48
49
|
]);
|
|
49
50
|
/** Kinds that already mean something in the needs queue. A provider may not reuse one. */
|
|
50
51
|
const RESERVED_KINDS = Object.freeze(['question', 'accept', 'outcome', 'keep', 'evidence', 'plan-flag', 'provider-error']);
|
|
@@ -159,6 +159,9 @@ const VERBS = Object.freeze({
|
|
|
159
159
|
// Not a pm-os-absorb verb (run: null): initiative three-line-why (bet A86) added it through the same table.
|
|
160
160
|
why: Object.freeze({ module: 'why-cli.js', run: null, guide: 'cli.md',
|
|
161
161
|
help: 'pmos why <initiative or task> | coverage — why the work exists in three lines: goal, problem, evidence, read from its records (pmos why help)' }),
|
|
162
|
+
// Not a pm-os-absorb verb (run: null): initiative compare-items (job #1919, A421) added it through the same table.
|
|
163
|
+
compare: Object.freeze({ module: 'compare-cli.js', run: null, guide: 'cli.md',
|
|
164
|
+
help: 'pmos compare <a> <b> — two initiatives, or two versions of a document (<file>@<revision>), side by side with the differences marked (pmos compare help)' }),
|
|
162
165
|
// Not a pm-os-absorb verb (run: null): initiative copy-tests (job #1905, A351) added it through the same table.
|
|
163
166
|
experiment: Object.freeze({ module: 'copy-tests.js', run: null, guide: 'cli.md',
|
|
164
167
|
help: 'pmos experiment draft|list|show|flag|start|result|keep|undo|count — copy and layout tests on an initiative: drafted from plain words, started by you, one table and one ✦ line with how sure (pmos experiment help)' }),
|
|
@@ -204,7 +207,7 @@ const VERBS = Object.freeze({
|
|
|
204
207
|
help: 'pmos approver list|show|brief — what each approver asked or objected to before, from the sign-offs and the decision journal, before the next sign-off (pmos approver help)' }),
|
|
205
208
|
// Not a pm-os-absorb verb (run: null): initiative balance-meter (bet A448) added it through the same table.
|
|
206
209
|
balance: Object.freeze({ module: 'balance-cli.js', run: null, guide: 'cli.md',
|
|
207
|
-
help: 'pmos balance show — the mix of a list in one line
|
|
210
|
+
help: 'pmos balance show|target|gap — the mix of a list in one line, a target mix for the roadmap, and the rank move that closes the gap (pmos balance help)' }),
|
|
208
211
|
// Not a pm-os-absorb verb (run: null): initiative product-principles-draft (bet A352) added it through the same table.
|
|
209
212
|
principles: Object.freeze({ module: 'principles-cli.js', run: null, guide: 'cli.md',
|
|
210
213
|
help: 'pmos principles list|sources|draft|keep|drop|undo|add — the product\'s principles, drafted from its decisions, each citing them; keep or drop each (pmos principles help)' }),
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* GET /api/drift/slip?ws=<id> → { ok, ws, name, notRead, today, initiatives, tasks, days, unsourced_days } open tasks behind
|
|
14
14
|
* their first plan (initiative slip-baseline-contradictions, lib/plan-baseline.js); read-only
|
|
15
15
|
* GET /api/drift/contradictions?ws=<id> → { ok, ws, name, notRead, items, total } records that disagree (lib/contradictions.js); read-only
|
|
16
|
+
* /api/spec-drift[/act|/undo] Library › Drift: specs and code that no longer match (lib/routes-spec-drift.js, which says what each does)
|
|
16
17
|
*
|
|
17
18
|
* THE SWITCH. PMOS_DRIFT=off, or the shared guard's switch (lib/ai-guard.js off: PMOS_AI, the ai settings): every GET answers { ok, on: false }
|
|
18
19
|
* and every POST 409. WHO WRITES: a POST that carries an agent session header is refused (403); pm-guard requirePagePress checks the page. */
|
|
@@ -30,6 +31,8 @@ function isOn(ctx) {
|
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
async function handle(req, res, url, ctx) {
|
|
34
|
+
// Library › Drift, spec and code (initiative spec-code-drift): its own module, under this module's place in the route table
|
|
35
|
+
if (url.pathname === '/api/spec-drift' || url.pathname.startsWith('/api/spec-drift/')) return require('./routes-spec-drift.js').handle(req, res, url, ctx);
|
|
33
36
|
const send = (r) => { ctx.json(res, r.body, r.status); return true; };
|
|
34
37
|
const what = url.pathname.replace(/^\/api\/drift\/?/, '');
|
|
35
38
|
const dir = D.dirOf(ctx.runtimeDir);
|
|
@@ -115,4 +118,4 @@ async function handle(req, res, url, ctx) {
|
|
|
115
118
|
return send({ status: 200, body: { ok: true } });
|
|
116
119
|
}
|
|
117
120
|
|
|
118
|
-
module.exports = { prefixes: ['/api/drift'], handle };
|
|
121
|
+
module.exports = { prefixes: ['/api/drift', '/api/spec-drift'], handle };
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* routes-spec-drift.js — Library › Drift: "Spec and code no longer match" over HTTP (initiative spec-code-drift, idea A495; lib/spec-code-drift.js).
|
|
3
|
+
* lib/routes-drift.js hands it every /api/spec-drift request, so the route table does not change.
|
|
4
|
+
*
|
|
5
|
+
* GET /api/spec-drift → { ok, on, specs, compared, drifted, rows, running } this week's mismatches of every open
|
|
6
|
+
* product. rows is [] when nothing differs (zero is silence). A product with no result for
|
|
7
|
+
* this week starts its check in the background (a worker thread: the page never waits on git)
|
|
8
|
+
* and `running` names how many are being read; the next open shows them.
|
|
9
|
+
* POST /api/spec-drift/act { ws, id, what } → { ok, task } what: 'code' (fix the code) or 'spec' (update the spec). A work item is added
|
|
10
|
+
* to the spec's initiative by the boards' own Add a task, and the row says so.
|
|
11
|
+
* POST /api/spec-drift/undo { ws, id } → { ok } the work item is removed again (the boards' own delete) and the row is open again.
|
|
12
|
+
*
|
|
13
|
+
* ONCE A WEEK. The check of a product runs at most once in a week (the Monday that starts it, local time): a second open in the same week
|
|
14
|
+
* reads the ledger. `pmos drift spec --now` runs it again by hand. THE SWITCH: PMOS_SPEC_DRIFT=off answers { ok, on: false } and every POST
|
|
15
|
+
* 409. WHO WRITES: a POST with an agent session header is refused (403; the chat uses `pmos drift spec fix|update|undo`); pm-guard
|
|
16
|
+
* requirePagePress checks the page. Nothing is sent outside. */
|
|
17
|
+
const path = require('path');
|
|
18
|
+
const { Worker } = require('worker_threads');
|
|
19
|
+
const guard = require('./pm-guard.js');
|
|
20
|
+
const S = require('./spec-code-drift.js');
|
|
21
|
+
|
|
22
|
+
const prefixes = ['/api/spec-drift'];
|
|
23
|
+
const running = new Set();
|
|
24
|
+
const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
|
|
25
|
+
const bad = (status, error) => ({ status, body: { ok: false, error } });
|
|
26
|
+
const nowMs = (ctx) => { const t = Date.parse((ctx.env || process.env).PMOS_SPEC_DRIFT_NOW || ''); return Number.isFinite(t) ? t : Date.now(); };
|
|
27
|
+
const wsKey = (root) => require('./driver.js').wsIdOf(root);
|
|
28
|
+
|
|
29
|
+
/** The check of one repository in a worker thread of this process, so the server never blocks on git. It calls the same
|
|
30
|
+
* check() export in-process; no new program is started. Tests replace runner.run. */
|
|
31
|
+
const WORKER_SRC = `
|
|
32
|
+
const { parentPort, workerData } = require('worker_threads');
|
|
33
|
+
let out;
|
|
34
|
+
try { out = require(workerData.mod).check(workerData.root); } catch (e) { out = { ok: false, error: String((e && e.message) || e).slice(0, 200) }; }
|
|
35
|
+
parentPort.postMessage(out);
|
|
36
|
+
`;
|
|
37
|
+
const runner = {
|
|
38
|
+
run: (root) => new Promise((resolve) => {
|
|
39
|
+
let done = false;
|
|
40
|
+
const end = (r) => { if (!done) { done = true; clearTimeout(timer); resolve(r); } };
|
|
41
|
+
let w;
|
|
42
|
+
try { w = new Worker(WORKER_SRC, { eval: true, workerData: { mod: path.join(__dirname, 'spec-code-drift.js'), root } }); } catch (e) { end({ ok: false, error: 'the check could not start' }); return; }
|
|
43
|
+
const timer = setTimeout(() => { end({ ok: false, error: 'the check took too long' }); w.terminate(); }, 10 * 60 * 1000);
|
|
44
|
+
if (timer.unref) timer.unref();
|
|
45
|
+
w.once('message', (r) => end(r && typeof r === 'object' ? r : { ok: false, error: 'the check did not answer' }));
|
|
46
|
+
w.once('error', (e) => end({ ok: false, error: String((e && e.message) || e).slice(0, 200) }));
|
|
47
|
+
w.once('exit', () => end({ ok: false, error: 'the check did not answer' }));
|
|
48
|
+
}),
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
function products(ctx) {
|
|
52
|
+
const out = [], seen = new Set();
|
|
53
|
+
for (const w of (ctx.workspaceList ? ctx.workspaceList() : []) || []) {
|
|
54
|
+
if (!w || !w.root || seen.has(path.resolve(w.root))) continue;
|
|
55
|
+
seen.add(path.resolve(w.root));
|
|
56
|
+
out.push({ w, key: wsKey(w.root) });
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Start this week's check of a product unless it has one or one is running. Its only write is the week line. */
|
|
62
|
+
function startWeek(ctx, dir, p, week) {
|
|
63
|
+
if (running.has(p.key)) return null;
|
|
64
|
+
running.add(p.key);
|
|
65
|
+
const t0 = Date.now();
|
|
66
|
+
return Promise.resolve(runner.run(p.w.root)).then((r) => {
|
|
67
|
+
if (r && r.ok) {
|
|
68
|
+
S.append(dir, { kind: 'week', ws: p.key, week, specs: r.specs, compared: r.compared, items: r.items }, new Date(nowMs(ctx)).toISOString());
|
|
69
|
+
console.log(`${S.TAG} week ws=${p.key} specs=${r.specs} compared=${r.compared} items=${r.items.length} ms=${Date.now() - t0}`);
|
|
70
|
+
} else console.warn(`${S.TAG} check failed ws=${p.key}: ${(r && r.error) || 'no answer'}`);
|
|
71
|
+
}).catch((e) => console.warn(`${S.TAG} check failed ws=${p.key}: ${(e && e.message) || e}`)).finally(() => running.delete(p.key));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function handle(req, res, url, ctx) {
|
|
75
|
+
const send = (r) => { ctx.json(res, r.body, r.status); return true; };
|
|
76
|
+
const what = url.pathname.replace(/^\/api\/spec-drift\/?/, '');
|
|
77
|
+
const env = ctx.env || process.env;
|
|
78
|
+
const dir = S.dirOf(ctx.runtimeDir);
|
|
79
|
+
const on = !flagOff(env.PMOS_SPEC_DRIFT);
|
|
80
|
+
if (what === '') {
|
|
81
|
+
if (req.method !== 'GET') return send(bad(405, 'GET only'));
|
|
82
|
+
if (!on || !dir) return send({ status: 200, body: { ok: true, on: false } });
|
|
83
|
+
const F = S.read(dir), week = S.weekOf(nowMs(ctx));
|
|
84
|
+
const out = { ok: true, on: true, week, specs: 0, compared: 0, drifted: 0, rows: [], running: 0 };
|
|
85
|
+
for (const p of products(ctx)) {
|
|
86
|
+
const v = S.view(F, p.key);
|
|
87
|
+
if (v.week !== week) startWeek(ctx, dir, p, week);
|
|
88
|
+
if (!v.week) continue;
|
|
89
|
+
out.specs += v.specs; out.compared += v.compared; out.drifted += v.drifted;
|
|
90
|
+
for (const r of v.rows) out.rows.push({ ...r, ws: p.w.id, product: p.w.name || p.w.id });
|
|
91
|
+
}
|
|
92
|
+
out.running = products(ctx).filter((p) => running.has(p.key)).length;
|
|
93
|
+
return send({ status: 200, body: out });
|
|
94
|
+
}
|
|
95
|
+
if (what !== 'act' && what !== 'undo') return send(bad(404, 'no such spec-drift route'));
|
|
96
|
+
if (req.method !== 'POST') return send(bad(405, 'POST only'));
|
|
97
|
+
if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'The chat uses pmos drift spec fix, update or undo.'));
|
|
98
|
+
const rd = await ctx.readJson(req);
|
|
99
|
+
if (!rd.ok) return send(bad(400, 'the body is not JSON'));
|
|
100
|
+
const body = rd.body || {};
|
|
101
|
+
const g = guard.requirePagePress(req, body);
|
|
102
|
+
if (!g.ok) return send(bad(g.status, g.error));
|
|
103
|
+
if (!on || !dir) return send(bad(409, 'The weekly spec check is off.'));
|
|
104
|
+
const p = products(ctx).find((x) => x.w.id === body.ws);
|
|
105
|
+
if (!p) return send(bad(404, 'no such product'));
|
|
106
|
+
const F = S.read(dir), v = S.view(F, p.key);
|
|
107
|
+
const row = v.rows.find((r) => r.id === body.id);
|
|
108
|
+
const item = row && (F.weeks.get(p.key).items || []).find((it) => it.id === body.id);
|
|
109
|
+
if (!item) return send(bad(404, 'There is no such row this week.'));
|
|
110
|
+
const at = new Date(nowMs(ctx)).toISOString();
|
|
111
|
+
const CF = require('./capture-file.js');
|
|
112
|
+
if (what === 'act') {
|
|
113
|
+
if (body.what !== 'code' && body.what !== 'spec') return send(bad(400, "what is 'code' (fix the code) or 'spec' (update the spec)"));
|
|
114
|
+
if (row.act) return send(bad(409, 'This row already has a work item.'));
|
|
115
|
+
const work = S.workOf(item, body.what);
|
|
116
|
+
const r = CF.file(ctx, { ws: p.w.id, ini: item.ini, title: work.title, bullet: 'task' }, g);
|
|
117
|
+
if (!r.ok || !r.filed.task) return send(bad(r.status || 409, r.error || 'The initiative has no board to add the task to.'));
|
|
118
|
+
S.append(dir, { kind: 'act', ws: p.key, id: item.id, what: body.what, task: { ws: r.filed.ws, board: r.filed.board, ini: r.filed.ini, task: r.filed.task, title: work.title } }, at);
|
|
119
|
+
console.log(`${S.TAG} act ws=${p.key} id=${item.id} what=${body.what} task=${r.filed.task}`);
|
|
120
|
+
return send({ status: 200, body: { ok: true, task: { id: r.filed.task, title: work.title, initiative: item.ini } } });
|
|
121
|
+
}
|
|
122
|
+
const a = F.acts.get(p.key + '|' + item.id);
|
|
123
|
+
if (!a) return send(bad(409, 'This row has no work item to take back.'));
|
|
124
|
+
if (a.task) CF.unfile(ctx, a.task, g);
|
|
125
|
+
S.append(dir, { kind: 'undo', ws: p.key, id: item.id }, at);
|
|
126
|
+
console.log(`${S.TAG} undo ws=${p.key} id=${item.id}`);
|
|
127
|
+
return send({ status: 200, body: { ok: true } });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
module.exports = { prefixes, handle, runner, running };
|