create-pmos 0.717.0 → 0.719.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.
Files changed (34) hide show
  1. package/package.json +51 -33
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/changelog.json +50 -0
  8. package/workspace/fixtures/premium-viewer-fixtures.js +10 -5
  9. package/workspace/guide/cli.md +14 -0
  10. package/workspace/guide/home.md +1 -1
  11. package/workspace/guide/layout.md +8 -2
  12. package/workspace/lib/item-why.js +235 -0
  13. package/workspace/lib/needs-providers.js +1 -0
  14. package/workspace/lib/pinned-views.js +26 -0
  15. package/workspace/lib/pmos-verbs.js +5 -0
  16. package/workspace/lib/product-health-cli.js +13 -0
  17. package/workspace/lib/product-health.js +259 -0
  18. package/workspace/lib/routes-search.js +4 -2
  19. package/workspace/lib/search-answer.js +164 -0
  20. package/workspace/lib/why-cli.js +79 -0
  21. package/workspace/package-lock.json +2 -2
  22. package/workspace/package.json +1 -1
  23. package/workspace/public/pm/cozy-nav.js +14 -3
  24. package/workspace/public/pm/cozy-search.js +18 -2
  25. package/workspace/public/pm/palette-all.js +101 -0
  26. package/workspace/public/pm/pinned-views.css +17 -0
  27. package/workspace/public/pm/pinned-views.js +130 -0
  28. package/workspace/public/pm/premium-board.js +53 -3
  29. package/workspace/public/premium-board.html +1 -0
  30. package/workspace/test-lists/item-why.json +9 -0
  31. package/workspace/test-lists/palette-all.json +9 -0
  32. package/workspace/test-lists/pinned-filter-views.json +9 -0
  33. package/workspace/test-lists/product-health.json +9 -0
  34. package/workspace/test-lists/search-answers-first.json +9 -0
@@ -0,0 +1,259 @@
1
+ 'use strict';
2
+ /* product-health.js — one health score per product, with its trend over the month, shown only when it drops
3
+ * (initiative product-health-score, bet A166).
4
+ *
5
+ * partsOf(root, { now }) → { checks, ci, setbacks } each { value 0..100, detail } or null (no data)
6
+ * scoreOf(parts) → 0..100 | null weighted mean of the parts that have data
7
+ * record(root, { now, parts }) → { day, score, parts, written } at most one line per day per score
8
+ * historyOf(root) → [{ day, score, parts }] the last line of each day, oldest first
9
+ * trendOf(history, { now, days }) → [{ day, score }] the month's points
10
+ * dropOf(history, { now }) → { from, to, since, fell: [part] } | null
11
+ * drops(history) → { drops: [{ day, from, to, recovered_day, recovery_days }], median_recovery_days }
12
+ * kinds · rowsFor(w, { lead }) · sig(w) the needs provider (lib/needs-providers.js)
13
+ *
14
+ * node workspace/lib/product-health.js score|trend|drops [<root>] [--json]
15
+ *
16
+ * THE PARTS, read from the product's state folder (lib/driver.js stateDirOf), so the score works on any product:
17
+ * checks factory-checks.jsonl the product's own declared checks (test, lint, audit…) that PMOS ran: the passing share
18
+ * of the newest CHECK_RUNS runs in MONTH_DAYS days
19
+ * ci factory-ci.jsonl 100 less CI_COST per pull request whose newest CI step in MONTH_DAYS days is blocked
20
+ * setbacks improve-signals.jsonl 100 less SETBACK_COST per setback signal in WEEK_DAYS days (see SETBACKS)
21
+ * A part with no data is null and the score is the weighted mean of the others. With no part at all the score is null:
22
+ * "not enough to tell" is the honest state, never 100.
23
+ *
24
+ * THE HISTORY is <state>/product-health.jsonl, one line { v: 1, day, at, score, parts } when the day's score changes.
25
+ * A DROP is a score DROP_POINTS or more under the highest score of the previous WEEK_DAYS days. A low score that has
26
+ * held for longer than that is the product's new level, not a drop. Today shows a drop as one card (kind 8); a score that
27
+ * holds shows nothing (zero is silence). */
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+
31
+ const NAME = 'product-health';
32
+ const KIND = 'health-drop';
33
+ const LEDGER = 'product-health.jsonl';
34
+ const DAY = 86400000;
35
+ const WEEK_DAYS = 7;
36
+ const MONTH_DAYS = 30;
37
+ const CHECK_RUNS = 10;
38
+ const CI_COST = 25;
39
+ const SETBACK_COST = 15;
40
+ const DROP_POINTS = 10;
41
+ const RECOVER_POINTS = 5;
42
+ const WEIGHTS = Object.freeze({ checks: 40, setbacks: 35, ci: 25 });
43
+ const LABEL = Object.freeze({ checks: 'Checks', setbacks: 'Setbacks', ci: 'Pull requests' });
44
+ const SETBACKS = Object.freeze(['revert', 'fix-after-merge', 'ci-fail', 'verifier-fail', 'factory-setback', 'outcome-missed', 'release-check-fail', 'undo']);
45
+ const STUCK = new Set(['blocked', 'block-failed']);
46
+ const TAG = '[product-health]';
47
+
48
+ const dayOf = (t) => new Date(t).toISOString().slice(0, 10);
49
+ const ms = (s) => { const n = Date.parse(s); return Number.isFinite(n) ? n : null; };
50
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
51
+ function stateDir(root) { try { return require('./driver.js').stateDirOf(root); } catch { return null; } }
52
+ function jsonl(file) {
53
+ let t = '';
54
+ try { t = fs.readFileSync(file, 'utf8'); } catch { return []; }
55
+ return t.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
56
+ }
57
+ const within = (rows, now, days) => rows.filter((r) => { const t = ms(r.at); return t !== null && t <= now && now - t <= days * DAY; });
58
+
59
+ // ── the parts ────────────────────────────────────────────────────────────────────────────────────────────
60
+ function checksPart(rows, now) {
61
+ const runs = within(rows, now, MONTH_DAYS).sort((a, b) => ms(b.at) - ms(a.at)).slice(0, CHECK_RUNS);
62
+ if (!runs.length) return null;
63
+ const ok = runs.filter((r) => r.ok === true).length;
64
+ return { value: Math.round((100 * ok) / runs.length), detail: `${ok} of ${plural(runs.length, 'check run', 'check runs')} passed` };
65
+ }
66
+ function ciPart(rows, now) {
67
+ const recent = within(rows, now, MONTH_DAYS);
68
+ if (!recent.length) return null;
69
+ const last = new Map();
70
+ for (const r of recent.sort((a, b) => ms(a.at) - ms(b.at))) if (r.item) last.set(r.item, r);
71
+ const stuck = [...last.values()].filter((r) => STUCK.has(r.step)).length;
72
+ return { value: Math.max(0, 100 - CI_COST * stuck), detail: stuck ? `${plural(stuck, 'pull request', 'pull requests')} stuck on failing checks` : 'no pull request stuck' };
73
+ }
74
+ function setbacksPart(rows, now) {
75
+ if (!rows.length) return null;
76
+ const n = within(rows, now, WEEK_DAYS).filter((r) => SETBACKS.includes(r.kind)).length;
77
+ return { value: Math.max(0, 100 - SETBACK_COST * n), detail: n ? `${plural(n, 'setback', 'setbacks')} this week` : 'no setback this week' };
78
+ }
79
+
80
+ /** → { checks, ci, setbacks }: each { value, detail } or null. `now` defaults to the clock. */
81
+ function partsOf(root, { now = Date.now() } = {}) {
82
+ const sd = stateDir(root);
83
+ if (!sd) return { checks: null, ci: null, setbacks: null };
84
+ return {
85
+ checks: checksPart(jsonl(path.join(sd, 'factory-checks.jsonl')), now),
86
+ ci: ciPart(jsonl(path.join(sd, 'factory-ci.jsonl')), now),
87
+ setbacks: setbacksPart(jsonl(path.join(sd, 'improve-signals.jsonl')), now),
88
+ };
89
+ }
90
+
91
+ function scoreOf(parts) {
92
+ let sum = 0, wsum = 0;
93
+ for (const [k, w] of Object.entries(WEIGHTS)) {
94
+ const p = parts && parts[k];
95
+ if (!p || !Number.isFinite(p.value)) continue;
96
+ sum += w * p.value; wsum += w;
97
+ }
98
+ return wsum ? Math.round(sum / wsum) : null;
99
+ }
100
+
101
+ // ── the history ──────────────────────────────────────────────────────────────────────────────────────────
102
+ function historyOf(root) {
103
+ const sd = stateDir(root);
104
+ if (!sd) return [];
105
+ const byDay = new Map();
106
+ for (const l of jsonl(path.join(sd, LEDGER))) if (/^\d{4}-\d{2}-\d{2}$/.test(l.day) && Number.isFinite(l.score)) byDay.set(l.day, { day: l.day, score: l.score, parts: l.parts || {} });
107
+ return [...byDay.values()].sort((a, b) => (a.day < b.day ? -1 : 1));
108
+ }
109
+
110
+ /** Keep today's score: one line when the day's score changes. A null score writes nothing. */
111
+ function record(root, { now = Date.now(), parts = null, log = (s) => console.log(s) } = {}) {
112
+ const p = parts || partsOf(root, { now });
113
+ const score = scoreOf(p);
114
+ const day = dayOf(now);
115
+ const out = { day, score, parts: p, written: false };
116
+ if (score === null) return out;
117
+ const hist = historyOf(root);
118
+ const last = hist[hist.length - 1];
119
+ if (last && last.day === day && last.score === score) return out;
120
+ const sd = stateDir(root);
121
+ if (!sd) return out;
122
+ const flat = {};
123
+ for (const k of Object.keys(WEIGHTS)) flat[k] = p[k] ? p[k].value : null;
124
+ try { fs.appendFileSync(path.join(sd, LEDGER), JSON.stringify({ v: 1, day, at: new Date(now).toISOString(), score, parts: flat }) + '\n'); }
125
+ catch { return out; }
126
+ out.written = true;
127
+ const prev = last ? ` (was ${last.score} on ${last.day})` : '';
128
+ try { log(`${TAG} ${path.basename(path.resolve(root))} scored ${score} on ${day}${prev}`); } catch { /* a log line never fails the record */ }
129
+ return out;
130
+ }
131
+
132
+ function trendOf(history, { now = Date.now(), days = MONTH_DAYS } = {}) {
133
+ const from = dayOf(now - days * DAY);
134
+ return (history || []).filter((h) => h.day > from && h.day <= dayOf(now)).map((h) => ({ day: h.day, score: h.score }));
135
+ }
136
+
137
+ /** The best score of the WEEK_DAYS days before `day`, from `history`, or null. */
138
+ function baselineBefore(history, day) {
139
+ const t = ms(day + 'T00:00:00Z');
140
+ const from = dayOf(t - WEEK_DAYS * DAY);
141
+ let best = null;
142
+ for (const h of history) if (h.day >= from && h.day < day && (!best || h.score > best.score)) best = h;
143
+ return best;
144
+ }
145
+
146
+ /** Today's drop against the past week, or null. `history` includes today's line when it was recorded. */
147
+ function dropOf(history, { now = Date.now() } = {}) {
148
+ const day = dayOf(now);
149
+ const hist = history || [];
150
+ const today = hist.find((h) => h.day === day);
151
+ if (!today) return null;
152
+ const base = baselineBefore(hist, day);
153
+ if (!base || base.score - today.score < DROP_POINTS) return null;
154
+ const fell = Object.keys(WEIGHTS).filter((k) => {
155
+ const a = base.parts && base.parts[k], b = today.parts && today.parts[k];
156
+ return Number.isFinite(a) && Number.isFinite(b) ? b < a : Number.isFinite(b) && b < 100 && !Number.isFinite(a);
157
+ });
158
+ return { from: base.score, to: today.score, since: base.day, fell };
159
+ }
160
+
161
+ /** Every past drop (the first day of each) and the days it took to come back within RECOVER_POINTS of where it fell from. */
162
+ function drops(history) {
163
+ const hist = history || [];
164
+ const out = [];
165
+ let open = null;
166
+ for (const h of hist) {
167
+ if (open) {
168
+ if (h.score >= open.from - RECOVER_POINTS) {
169
+ open.recovered_day = h.day;
170
+ open.recovery_days = Math.round((ms(h.day + 'T00:00:00Z') - ms(open.day + 'T00:00:00Z')) / DAY);
171
+ open = null;
172
+ }
173
+ continue;
174
+ }
175
+ const base = baselineBefore(hist, h.day);
176
+ if (base && base.score - h.score >= DROP_POINTS) { open = { day: h.day, from: base.score, to: h.score, recovered_day: null, recovery_days: null }; out.push(open); }
177
+ }
178
+ const done = out.filter((d) => d.recovery_days !== null).map((d) => d.recovery_days).sort((a, b) => a - b);
179
+ const median = !done.length ? null : done.length % 2 ? done[(done.length - 1) / 2] : (done[done.length / 2 - 1] + done[done.length / 2]) / 2;
180
+ return { drops: out, median_recovery_days: median };
181
+ }
182
+
183
+ // ── the needs provider ───────────────────────────────────────────────────────────────────────────────────
184
+ const short = (day) => new Date(day + 'T00:00:00Z').toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' });
185
+ function stamp(file) { try { const s = fs.statSync(file); return `${s.mtimeMs}:${s.size}`; } catch { return '-'; } }
186
+ function sig(w) {
187
+ const sd = w && w.root ? stateDir(w.root) : null;
188
+ if (!sd) return '';
189
+ return [dayOf(Date.now()), ...['factory-checks.jsonl', 'factory-ci.jsonl', 'improve-signals.jsonl', LEDGER].map((f) => stamp(path.join(sd, f)))].join('|');
190
+ }
191
+
192
+ function rowsFor(w, { lead, now = Date.now(), log } = {}) {
193
+ if (!lead || !w || !w.root) return [];
194
+ const rec = record(w.root, { now, ...(log ? { log } : {}) });
195
+ if (rec.score === null) return [];
196
+ const d = dropOf(historyOf(w.root), { now });
197
+ if (!d) return [];
198
+ const name = w.name || path.basename(path.resolve(w.root));
199
+ const cause = `Health of ${name} fell from ${d.from} to ${d.to} since ${short(d.since)}`;
200
+ const evidence = (d.fell.length ? d.fell : Object.keys(WEIGHTS)).filter((k) => rec.parts[k]).map((k) => `${LABEL[k]}: ${rec.parts[k].detail}`).join(' · ');
201
+ return [{
202
+ run_id: `${NAME}:${w.id}:${dayOf(now)}`, kind: KIND, initiative_id: null, question: cause, doc: null, ws: w.id,
203
+ today: { kind: 8, source: NAME, cause, evidence, act: { label: 'See the health trend', cli: 'pmos health trend' } },
204
+ }];
205
+ }
206
+
207
+ // ── the command line ─────────────────────────────────────────────────────────────────────────────────────
208
+ const USAGE = [
209
+ 'usage: pmos health [score|trend|drops] [--json] [--root <dir>] — this product\'s health score (0 to 100)',
210
+ ' pmos health score today\'s score and its parts; the score on the last line (-1: not enough to tell)',
211
+ ' pmos health trend the score of each day this month',
212
+ ' pmos health drops each past drop and the days it took to recover, with the median',
213
+ ];
214
+ function cli(argv, { say = (s) => console.log(s), cwd = process.cwd(), now = Date.now() } = {}) {
215
+ const args = argv.slice();
216
+ const json = args.includes('--json');
217
+ const ri = args.indexOf('--root');
218
+ let root = null;
219
+ if (ri >= 0) { root = args[ri + 1]; args.splice(ri, 2); }
220
+ const pos = args.filter((a) => !a.startsWith('--'));
221
+ const verb = pos[0] || 'score';
222
+ if (['help', '-h'].includes(verb) || args.includes('--help')) { for (const l of USAGE) say(l); return 0; }
223
+ if (!['score', 'trend', 'drops'].includes(verb)) { say(`unknown health command "${verb}" — one of score, trend, drops`); return 2; }
224
+ root = path.resolve(cwd, root || pos[1] || '.');
225
+ if (!stateDir(root)) { say(`${TAG} this repository has no PMOS state folder (pmos/state, state or .pmos)`); if (verb === 'score') say('-1'); return 1; }
226
+ const rec = record(root, { now, log: () => {} });
227
+ const hist = historyOf(root);
228
+ if (verb === 'score') {
229
+ if (json) { say(JSON.stringify({ day: rec.day, score: rec.score, parts: rec.parts, drop: dropOf(hist, { now }) })); return 0; }
230
+ if (rec.score === null) say(`${TAG} not enough to tell: no check runs, pull request checks or setbacks recorded yet`);
231
+ else for (const k of Object.keys(WEIGHTS)) if (rec.parts[k]) say(`${TAG} ${LABEL[k]}: ${rec.parts[k].value} (${rec.parts[k].detail})`);
232
+ const d = dropOf(hist, { now });
233
+ if (d) say(`${TAG} fell from ${d.from} to ${d.to} since ${short(d.since)}`);
234
+ say(String(rec.score === null ? -1 : rec.score));
235
+ return 0;
236
+ }
237
+ if (verb === 'trend') {
238
+ const t = trendOf(hist, { now });
239
+ if (json) { say(JSON.stringify({ trend: t })); return 0; }
240
+ if (!t.length) say(`${TAG} no score recorded this month`);
241
+ for (const p of t) say(`${TAG} ${p.day} ${String(p.score).padStart(3)}`);
242
+ say(String(t.length));
243
+ return 0;
244
+ }
245
+ const r = drops(hist);
246
+ if (json) { say(JSON.stringify(r)); return 0; }
247
+ if (!r.drops.length) say(`${TAG} no drop recorded`);
248
+ for (const d of r.drops) say(`${TAG} ${d.day} ${d.from} → ${d.to} ${d.recovery_days === null ? 'not recovered yet' : `recovered in ${plural(d.recovery_days, 'day', 'days')}`}`);
249
+ say(String(r.median_recovery_days === null ? -1 : r.median_recovery_days));
250
+ return 0;
251
+ }
252
+
253
+ module.exports = {
254
+ NAME, KIND, LEDGER, WEIGHTS, SETBACKS, DROP_POINTS, WEEK_DAYS, MONTH_DAYS, USAGE,
255
+ partsOf, scoreOf, record, historyOf, trendOf, dropOf, drops, cli,
256
+ kinds: [KIND], rowsFor, sig,
257
+ };
258
+
259
+ if (require.main === module) process.exitCode = cli(process.argv.slice(2));
@@ -1,11 +1,13 @@
1
1
  'use strict';
2
2
  /* routes-search.js — Search across the repository and every worktree (initiative premium-uncovered-features, E1; lib/search-index.js).
3
3
  *
4
- * GET /api/find?q=<words>&ws=<id>&wt=<id,id> → { ok, q, worktrees, counts, results, more } wt: the worktrees to search (none: all)
4
+ * GET /api/find?q=<words>&ws=<id>&wt=<id,id> → { ok, q, worktrees, counts, results, more, answer? } wt: the worktrees to search (none: all)
5
+ * answer: one sentence from the user's own files with its source (lib/search-answer.js); absent when nothing is clear
5
6
  * GET /api/find/file?ws=<id>&wt=<id>&path=<p> → { ok, wt, branch, main, path, text, mtime } one file of a listed worktree, for the Viewer
6
7
  *
7
8
  * Read-only: nothing here writes or calls anything outside this machine. The repository is the workspace's own (ws, else the home one). */
8
9
  const Search = require('./search-index.js');
10
+ const Answer = require('./search-answer.js'); // the answer first, with its source (search-answers-first)
9
11
 
10
12
  function wsOf(ctx, id) {
11
13
  const w = typeof ctx.getWs === 'function' ? ctx.getWs(id || '') : null;
@@ -29,7 +31,7 @@ module.exports = {
29
31
  try { const l = ctx.runtimeDir ? require('./notes.js').list(ctx.runtimeDir) : null; notes = l && l.ok ? l.notes : []; } catch { notes = []; }
30
32
  const only = (url.searchParams.get('wt') || '').split(',').map((x) => x.trim()).filter(Boolean);
31
33
  try {
32
- ctx.json(res, { ws: w.id, ...Search.search({ root: w.root, q: url.searchParams.get('q') || '', only, notes }) });
34
+ ctx.json(res, { ws: w.id, ...Answer.find({ root: w.root, q: url.searchParams.get('q') || '', only, notes }) });
33
35
  } catch (e) {
34
36
  ctx.json(res, { ok: false, error: 'the search could not run: ' + String((e && e.message) || e).slice(0, 160) }, 500);
35
37
  }
@@ -0,0 +1,164 @@
1
+ 'use strict';
2
+ /* search-answer.js — Search answers first (initiative search-answers-first, bet A388; done test planning/done-tests/search-answers-first.md).
3
+ *
4
+ * keyWords(q) → the query's words without question words ("when is the pilot launch" → ['pilot', 'launch']) PURE
5
+ * searchWords(q) → keyWords joined by spaces: what Search looks for when the whole question finds nothing PURE
6
+ * answerOf({ root, q, results }) → { text, facts, source: { kind, title, path, wt, main, id? } } | null READ-ONLY
7
+ * find({ root, q, only, notes, now }) → lib/search-index.js search() plus `answer` READ-ONLY
8
+ * probe(root) → the health number: the percent of initiatives whose own name gets an answer from their own record
9
+ * CLI: node lib/search-answer.js --probe <root> prints that number on its last line
10
+ *
11
+ * The answer is never written: it is one sentence copied word for word from the user's own files, so it says where it came from and
12
+ * cannot be wrong about it. An initiative whose name holds every key word answers with its Goal's first sentence and its check date. Else
13
+ * the first sentence, in the best matches, that holds every key word ("when" prefers a sentence with a date). A worktree's draft answers
14
+ * only when main has none. Nothing clear (no sentence holds every word, or two initiatives match equally well) gives no answer: zero is
15
+ * silence. No model call, nothing written, nothing sent. Works on any product built with PMOS (planning/initiatives/ or pmos/state/initiatives/). */
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const Search = require('./search-index.js');
19
+
20
+ const STOP = new Set(('a an the is are was were be been am do does did of to in on at for by with from and or what when where who whom whose which why how '
21
+ + 'tell me show find give about any there this that these those it its i my our we you your can could should would will shall has have had').split(' '));
22
+ const INI_DIRS = ['planning/initiatives', 'pmos/state/initiatives'];
23
+ const MAX_DOCS = 12;
24
+ const MONTH = '(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*';
25
+ const DATE = new RegExp(`\\b\\d{4}-\\d{2}-\\d{2}\\b|\\b\\d{1,2}(?:st|nd|rd|th)?\\s+${MONTH}\\b|\\b${MONTH}\\s+\\d{1,2}\\b|\\b(?:mon|tues|wednes|thurs|fri|satur|sun)day\\b|\\b(?:today|tomorrow|next week)\\b`, 'i');
26
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
27
+
28
+ const wordsOf = (s) => String(s || '').toLowerCase().split(/[^a-z0-9%]+/).filter(Boolean);
29
+ /** The query's words without question words. A query of only question words keeps all its words. Pure. */
30
+ function keyWords(q) {
31
+ const all = wordsOf(q);
32
+ const keys = all.filter((w) => !STOP.has(w));
33
+ return keys.length ? keys : all;
34
+ }
35
+ const searchWords = (q) => keyWords(q).join(' ');
36
+ const isWhen = (q) => /^\s*(when|what date|what day|by when|how long)\b/i.test(String(q || ''));
37
+ /** Every key word starts a word of s. */
38
+ const holdsAll = (s, keys) => keys.every((k) => new RegExp('(^|[^a-z0-9])' + esc(k), 'i').test(s));
39
+
40
+ const body = (text) => String(text || '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
41
+ const fm = (text, key) => { const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(String(text || '')); if (!m) return ''; const v = new RegExp('^' + key + ':\\s*["\']?(.+?)["\']?\\s*$', 'm').exec(m[1]); return v ? v[1].trim() : ''; };
42
+
43
+ /** The answerable sentences of a Markdown text, in order: each is word for word in the text. Headings, tables and code are skipped. */
44
+ function sentences(text) {
45
+ const out = [];
46
+ let code = false;
47
+ for (const raw of body(text).split('\n')) {
48
+ const line = raw.trim();
49
+ if (/^(```|~~~)/.test(line)) { code = !code; continue; }
50
+ if (code || !line || /^#/.test(line) || line.includes('|') || /^<[^>]+>/.test(line)) continue;
51
+ const s = line.replace(/^(?:[-*+>]\s+|\d+[.)]\s+)+/, '').replace(/^\[[ xX]\]\s+/, '');
52
+ for (const part of s.split(/(?<=[.!?])\s+(?=[A-Z0-9"“(])/)) {
53
+ const t = part.trim();
54
+ if (t.length >= 12 && t.length <= 240 && t.split(/\s+/).length >= 4) out.push(t);
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+ /** The sentence an initiative record answers with: its Goal's first sentence, else its first body sentence. */
60
+ function goalOf(text) {
61
+ const b = body(text);
62
+ const g = /^##\s+Goal\s*$([\s\S]*?)(?=^#{1,2}\s|(?![\s\S]))/im.exec(b);
63
+ return (g && sentences(g[1])[0]) || sentences(b)[0] || '';
64
+ }
65
+
66
+ /** The initiatives of the main checkout: { id, title, path, text }. A deleted one is left out. */
67
+ function initiativesOf(root) {
68
+ let gone = new Set();
69
+ try { gone = require('./ini-deleted.js').ids(root); } catch { gone = new Set(); }
70
+ const list = [];
71
+ for (const dir of INI_DIRS) {
72
+ let names = [];
73
+ try { names = fs.readdirSync(path.join(root, dir)).filter((f) => f.endsWith('.md') && f !== 'index.md' && f !== 'log.md'); } catch { continue; }
74
+ for (const f of names) {
75
+ const id = f.slice(0, -3);
76
+ if (gone.has(id)) continue;
77
+ let text = '';
78
+ try { text = fs.readFileSync(path.join(root, dir, f), 'utf8'); } catch { continue; }
79
+ list.push({ id, title: Search.titleOf(text, f), path: dir + '/' + f, text });
80
+ }
81
+ }
82
+ return list;
83
+ }
84
+ /** An initiative whose name holds every key word: the one with the fewest other words in its name. A tie gives none. */
85
+ function initiativeAnswer(keys, inis) {
86
+ const hits = inis.filter((x) => holdsAll(x.title + ' ' + x.id.replace(/[-_]/g, ' '), keys))
87
+ .map((x) => ({ x, extra: wordsOf(x.title).filter((w) => !keys.includes(w) && !STOP.has(w)).length }))
88
+ .sort((a, b) => a.extra - b.extra);
89
+ if (!hits.length || (hits[1] && hits[1].extra === hits[0].extra)) return null;
90
+ const { x } = hits[0];
91
+ const text = goalOf(x.text);
92
+ if (!text) return null;
93
+ const when = fm(x.text, 'outcome_horizon');
94
+ return { text, facts: /^\d{4}-\d{2}-\d{2}$/.test(when) ? [{ key: 'check', date: when }] : [], source: { kind: 'initiative', title: x.title, path: x.path, wt: 'main', main: true, id: x.id } };
95
+ }
96
+
97
+ /** One answer for q from the search's results, or null when nothing is clear. Reads files inside the repository's worktrees only. */
98
+ function answerOf({ root, q, results = [], inis = null } = {}) {
99
+ const keys = keyWords(q);
100
+ if (!root || String(q || '').trim().length < 2 || !keys.length) return null;
101
+ const ini = initiativeAnswer(keys, inis || initiativesOf(root));
102
+ if (ini) return ini;
103
+ const wts = new Map(Search.worktrees(root).map((w) => [w.id, w]));
104
+ const docs = (results || []).filter((r) => r && r.path && /\.(md|mdx|txt)$/i.test(r.path) && ['document', 'report', 'initiative'].includes(r.kind));
105
+ const ordered = docs.filter((r) => r.main).concat(docs.filter((r) => !r.main)).slice(0, MAX_DOCS);
106
+ const when = isWhen(q);
107
+ let best = null;
108
+ for (const r of ordered) {
109
+ if (best && r.main === false && best.r.main) break; // a draft answers only when main has none
110
+ const w = wts.get(r.wt || 'main'); if (!w) continue;
111
+ const abs = path.resolve(w.path, r.path);
112
+ if (!abs.startsWith(path.resolve(w.path) + path.sep)) continue;
113
+ let text = '';
114
+ try { const st = fs.statSync(abs); if (!st.isFile() || st.size > 256 * 1024) continue; text = fs.readFileSync(abs, 'utf8'); } catch { continue; }
115
+ for (const s of sentences(text)) {
116
+ if (!holdsAll(s, keys)) continue;
117
+ const score = (when && DATE.test(s) ? 2 : 0) + (r.why === 'name' ? 1 : 0);
118
+ if (!best || score > best.score) best = { r, s, score };
119
+ }
120
+ }
121
+ if (!best) return null;
122
+ const { r, s } = best;
123
+ const source = { kind: r.kind, title: r.title, path: r.path, wt: r.wt || 'main', main: r.main !== false };
124
+ if (r.kind === 'initiative' && r.id) source.id = r.id;
125
+ if (r.branch) source.branch = r.branch;
126
+ return { text: s, facts: [], source };
127
+ }
128
+
129
+ /** Search, then the answer. A question that finds nothing as a whole string is searched again by its key words, then by its longest one. */
130
+ function find({ root, q, only = null, notes = [], now } = {}) {
131
+ let res = Search.search({ root, q, only, notes, now });
132
+ const keys = keyWords(q);
133
+ if (res.ok && !res.results.length && String(q || '').trim().length >= 2) {
134
+ for (const alt of [keys.join(' '), keys.slice().sort((a, b) => b.length - a.length)[0] || '']) {
135
+ if (alt.length < 2 || alt === res.q) continue;
136
+ const r2 = Search.search({ root, q: alt, only, notes, now });
137
+ if (r2.ok && r2.results.length) { res = { ...r2, q: res.q, by: alt }; break; }
138
+ }
139
+ }
140
+ if (!res.ok) return res;
141
+ let answer = null;
142
+ try { answer = answerOf({ root, q, results: res.results }); } catch { answer = null; }
143
+ try { console.log(answer ? '[search-answer] given kind=' + answer.source.kind : '[search-answer] none'); } catch { /* no console */ }
144
+ return answer ? { ...res, answer } : res;
145
+ }
146
+
147
+ /** The health number: of the initiatives, the percent whose own name, typed into Search, is answered from their own record. */
148
+ function probe(root) {
149
+ const inis = initiativesOf(root);
150
+ if (!inis.length) return 0;
151
+ let hit = 0;
152
+ for (const x of inis) { const a = initiativeAnswer(keyWords(x.title), inis); if (a && a.source.id === x.id) hit++; }
153
+ return Math.round((100 * hit) / inis.length);
154
+ }
155
+
156
+ module.exports = { keyWords, searchWords, sentences, goalOf, initiativesOf, answerOf, find, probe };
157
+
158
+ if (require.main === module) {
159
+ const i = process.argv.indexOf('--probe');
160
+ if (i < 0) { console.error('usage: node lib/search-answer.js --probe <root>'); process.exit(2); }
161
+ const root = path.resolve(process.argv[i + 1] || '.');
162
+ const n = probe(root);
163
+ console.log(`initiatives answered from their own record when their name is searched (percent):\n${n}`);
164
+ }
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+ /* why-cli.js — `pmos why …`: why an initiative or a task exists, in three lines anyone can read (initiative three-line-why, bet A86).
3
+ *
4
+ * pmos why <initiative or task> the goal, the problem and the evidence, each with where it was read
5
+ * pmos why show <initiative or task> the same
6
+ * pmos why coverage the share of active initiatives whose why reads all three lines; the last line is the number
7
+ * every command: [--json] [--root <dir>]
8
+ *
9
+ * Reads the record and its PRD from disk through lib/item-why.js. Needs no server, writes nothing, uses no network.
10
+ * Exit codes: 0 done, 1 no such initiative, 2 usage.
11
+ */
12
+ const path = require('path');
13
+ const { execFileSync } = require('child_process');
14
+ const why = require('./item-why.js');
15
+
16
+ const TAG = '[item-why]';
17
+ const COMMANDS = { why: ['show', 'coverage'] };
18
+ const USAGE = [
19
+ 'usage: pmos why <initiative or task> — why the work exists: its goal, problem and evidence in three lines',
20
+ ' pmos why <id> the three lines for an initiative, or for the initiative a task belongs to',
21
+ ' pmos why show <id> the same',
22
+ ' pmos why coverage how many active initiatives have all three lines, and which lines the others miss',
23
+ ' every command: [--json] [--root <dir>]',
24
+ 'A line the records do not hold says "not written". Nothing is guessed.',
25
+ ];
26
+ const LABEL = { goal: 'Goal', problem: 'Problem', evidence: 'Evidence' };
27
+
28
+ function repoRoot(cwd) {
29
+ try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; }
30
+ catch { return cwd; }
31
+ }
32
+
33
+ function parse(argv) {
34
+ const pos = []; const flags = {};
35
+ for (let i = 0; i < argv.length; i++) {
36
+ const a = argv[i];
37
+ if (a === '--root') flags.root = argv[++i];
38
+ else if (a.startsWith('--root=')) flags.root = a.slice(7);
39
+ else if (a.startsWith('--')) flags[a.slice(2)] = true;
40
+ else if (a === '-h') flags.help = true;
41
+ else pos.push(a);
42
+ }
43
+ return { pos, flags };
44
+ }
45
+
46
+ function run(argv, { say = (s) => console.log(s), cwd = process.cwd() } = {}) {
47
+ const { pos, flags } = parse(argv[0] === 'why' ? argv.slice(1) : argv.slice());
48
+ if (flags.help || pos[0] === 'help') { for (const l of USAGE) say(l); return 0; }
49
+ const root = path.resolve(flags.root || repoRoot(cwd));
50
+ const json = !!flags.json;
51
+
52
+ if (pos[0] === 'coverage' || flags.coverage) {
53
+ const c = why.coverage(root);
54
+ if (json) { say(JSON.stringify(c)); return 0; }
55
+ say(`${TAG} ${c.complete} of ${c.active} active initiatives have a three-line why (goal, problem, evidence).`);
56
+ for (const m of c.missing.slice(0, 20)) say(` ${m.id}: no ${m.lines.join(', ')}`);
57
+ if (c.missing.length > 20) say(` … and ${c.missing.length - 20} more (--json lists them all)`);
58
+ say(String(c.percent));
59
+ return 0;
60
+ }
61
+
62
+ const ref = pos[0] === 'show' ? pos[1] : pos[0];
63
+ if (!ref) { for (const l of USAGE) say(l); return 2; }
64
+ const w = why.readWhy(root, ref);
65
+ if (!w) {
66
+ say(json ? JSON.stringify({ ok: false, error: `no initiative "${ref}" in this repository` }) : `✗ no initiative "${ref}" in this repository (pmos initiative list shows them)`);
67
+ return 1;
68
+ }
69
+ if (json) { say(JSON.stringify({ ok: true, ...w })); return 0; }
70
+ say(`${w.title || w.id} (${w.id})`);
71
+ for (const k of ['goal', 'problem', 'evidence']) {
72
+ const l = w[k];
73
+ say(`${LABEL[k]}: ${l ? l.text : 'not written'}`);
74
+ if (l && flags.from) say(` from ${l.from}`);
75
+ }
76
+ return 0;
77
+ }
78
+
79
+ module.exports = { run, COMMANDS, USAGE };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.717.0",
3
+ "version": "0.719.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.717.0",
9
+ "version": "0.719.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/sdk": "^1.3.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.717.0",
3
+ "version": "0.719.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -38,7 +38,7 @@
38
38
  * Routine are not in the phone menu for now (their pages still open from a link). Ask PMOS on a phone is Today's page with ?chats=1 (today.html?chats=1; Home is gone, job #1540), which
39
39
  * lists the chats by work (pm/phone-ask.js). The page's own ⋯ (the phone chat) opens the same menu; its own rows are not added on a phone.
40
40
  */
41
- import { esc, svg, ICON, wsQ } from './cozy-evui.js';
41
+ import { esc, svg, ICON, wsQ, wsParam } from './cozy-evui.js';
42
42
  import { fabLabel, bannerOf } from './cozy-evmodel.js';
43
43
  import { mountToastFaces, loadPrefs } from './cozy-adler.js';
44
44
  import './draft-keep.js'; // forms-keep-drafts: every text box on every page keeps a draft until sent, saved or cleared
@@ -284,7 +284,7 @@ export function mountNav(here, doc = document, opts = {}) {
284
284
  if ('czLive' in b.dataset) { doc.dispatchEvent(new CustomEvent('cz:live-open')); return; }
285
285
  if ('czChat' in b.dataset && N.rail && typeof window.czOpenChat === 'function') { window.czOpenChat(); return; } // the popup with the chat (slice 2)
286
286
  if ('czChat' in b.dataset) { if (opts.chat) opts.chat(); else import('./page-chat.js').then((M) => M.openCos({ here: opts.where ? opts.where() : PLACES.find((p) => p.key === here) ? PLACES.find((p) => p.key === here).label : '' })); }
287
- else if ('czSearch' in b.dataset) import('./cozy-search.js').then((M) => M.openSearch({ ...(opts.search ? { go: opts.search() } : {}), ...(opts.scope ? { scope: opts.scope() } : {}) }));
287
+ else if ('czSearch' in b.dataset) search();
288
288
  // a stale source opens Settings at Connectors, the stale one first (FmA3Settings: open where it matters)
289
289
  else if ('czGuide' in b.dataset) import('./premium-vw-open.js').then((M) => M.openGuide('index'));
290
290
  // a phone opens its one-screen Settings (Ph2_more, pm/cozy-phone-settings.js); a computer the full dialog
@@ -298,8 +298,19 @@ export function mountNav(here, doc = document, opts = {}) {
298
298
  if (!k && !(e.key === '/' && !e.ctrlKey && !e.metaKey && !e.altKey && !typing)) return;
299
299
  if (t && t.closest && t.closest('.xterm')) return; // a terminal keeps its keys
300
300
  e.preventDefault(); e.stopImmediatePropagation();
301
- import('./cozy-search.js').then((M) => M.openSearch({ ...(opts.search ? { go: opts.search() } : {}), ...(opts.scope ? { scope: opts.scope() } : {}) }));
301
+ search();
302
302
  }, true);
303
+ // Search also reaches every page, the actions, and the item last pointed at or focused (bet A315, pm/palette-all.js withEverything)
304
+ let lastAt = null;
305
+ const note = (e) => { if (!e.target || !e.target.closest || !e.target.closest('#czNav, #evSearch')) lastAt = e.target; };
306
+ doc.addEventListener('pointerover', note, { capture: true, passive: true });
307
+ doc.addEventListener('focusin', note, true);
308
+ const chat = () => { if (N.rail && typeof window.czOpenChat === 'function') window.czOpenChat(); else if (opts.chat) opts.chat(); else import('./page-chat.js').then((M) => M.openCos({ here: opts.where ? opts.where() : PLACES.find((p) => p.key === here) ? PLACES.find((p) => p.key === here).label : '' })); };
309
+ function search() {
310
+ const item = lastAt && lastAt.isConnected ? lastAt : null;
311
+ Promise.all([import('./cozy-search.js'), import('./palette-all.js')]).then(([M, P]) => M.openSearch({ ...(opts.search ? { go: opts.search() } : {}),
312
+ scope: P.withEverything(opts.scope ? opts.scope() : null, { places: PLACES, here, item, doc, ws: wsParam(), wsq: wsQ, chat, setTheme: (k) => setTheme(k, doc) }) }));
313
+ }
303
314
  const read = async () => {
304
315
  if (doc.hidden) return;
305
316
  const [n, s, mo] = await Promise.all([getj('/api/news-for-you' + wsQ()), getj('/api/sources' + wsQ()), getj('/api/moments')]);