create-pmos 0.671.0 → 0.674.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.
@@ -19,7 +19,7 @@
19
19
  * pmos jira moves the status moves the PM asked in PMOS, not answered yet (lib/jira-moves.js)
20
20
  * pmos jira moved <move id> --status "<Jira status>" | --refused "<why>" the agent's answer for one move
21
21
  * pmos jira guesses <initiative> [--from <file|->] a ticket dry run (lib/ticket-dry-run.js), recorded or shown
22
- * pmos jira answer <initiative> <ticket> <n> --text "<answer>" the PM's answer to one dry-run gap
22
+ * pmos jira answer <initiative> <ticket> <n> --text "<answer>" | --keep-default the PM's answer to one dry-run gap, or its default kept
23
23
  * every command: [--json] [--root <dir>]
24
24
  *
25
25
  * This command never talks to Jira. An agent session does, with the PM's own Atlassian connection (D53, D88), and
@@ -44,7 +44,7 @@ const USAGE = [
44
44
  ' pmos jira guesses <initiative> --from <file|-> record a dry run: each ticket\'s guesses, with the PRD lines that answer them',
45
45
  ' Quotes not found word for word in the PRD, done test or record are dropped. Gaps go to the day\'s question list.',
46
46
  ' pmos jira guesses <initiative> the dry run so far: the guesses of each ticket and the open gaps',
47
- ' pmos jira answer <initiative> <ticket> <n> --text "<answer>" the PM\'s answer to gap n: it goes into the ticket',
47
+ ' pmos jira answer <initiative> <ticket> <n> --text "<answer>" | --keep-default the PM\'s answer to gap n, or keep its default: it goes into the ticket',
48
48
  ' pmos jira epic <initiative> new|<KEY or link> [--group <g>] create a new epic at the first push, or use an existing one',
49
49
  ' pmos jira approve <initiative> <ID> … select tickets to push (you, in your own terminal)',
50
50
  ' pmos jira pending <initiative> what the push creates or updates in Jira',
@@ -63,7 +63,7 @@ const USAGE = [
63
63
  ' every command: [--json] [--root <dir>]',
64
64
  'This command never calls Jira. Your agent reads and writes Jira with your own connection.',
65
65
  ];
66
- const BOOL = new Set(['json', 'dry-run', 'help', 'sprints']);
66
+ const BOOL = new Set(['json', 'dry-run', 'help', 'sprints', 'keep-default']);
67
67
  const VALUE = new Set(['from', 'query', 'root', 'epic', 'updated', 'group', 'status', 'refused', 'sprint', 'text']);
68
68
  const FLAG_TEXT = { 'prd-changed': 'PRD changed', removed: 'Removed from PRD', blocked: 'Blocked', incomplete: 'Missing text', pushing: 'Selected, waiting for the push', edited: 'Edited, not in Jira yet' };
69
69
 
@@ -229,7 +229,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
229
229
  if (!v) return fail(`no ticket draft for ${initiative} — press Draft tickets, or run pmos jira draft ${initiative}`);
230
230
  const done = v.filter((t) => t.dryRun);
231
231
  const lines = [`${initiative} · ${done.length} of ${v.length} ${v.length === 1 ? 'ticket' : 'tickets'} dry-run · ${gaps.length} open ${gaps.length === 1 ? 'gap' : 'gaps'}`];
232
- for (const t of done) lines.push(` ${t.id} · ${t.dryRun.guesses} ${t.dryRun.guesses === 1 ? 'guess' : 'guesses'} · ${t.dryRun.answered} answered · ${t.dryRun.partly} partly · ${t.dryRun.gaps} ${t.dryRun.gaps === 1 ? 'gap' : 'gaps'}${t.dryRun.stale ? ' · PRD changed since: run it again' : ''}`);
232
+ for (const t of done) lines.push(` ${t.id} · ${t.dryRun.guesses} ${t.dryRun.guesses === 1 ? 'guess' : 'guesses'} · ${t.dryRun.answered} answered · ${t.dryRun.partly} partly · ${t.dryRun.gaps} ${t.dryRun.gaps === 1 ? 'gap' : 'gaps'}${t.dryRun.gaps ? ` (${t.dryRun.withDefault} with a default)` : ''}${t.dryRun.kept || t.dryRun.changed ? ` · ${t.dryRun.kept} kept, ${t.dryRun.changed} changed` : ''}${t.dryRun.stale ? ' · PRD changed since: run it again' : ''}`);
233
233
  for (const g of gaps) lines.push(` gap ${g.ticket} ${g.n} · ${g.q}`);
234
234
  return out({ ok: true, initiative, tickets: done.map((t) => ({ id: t.id, ...t.dryRun })), gaps }, lines);
235
235
  }
@@ -245,10 +245,10 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), isT
245
245
  }
246
246
  if (verb === 'answer') {
247
247
  const [, ticket, n] = pos;
248
- if (!ticket || !n || !flags.text) return need('<initiative> <ticket> <n> --text "<the answer>"');
249
- const r = jiraTickets.answerDryRun(root, initiative, ticket, n, flags.text, { now });
248
+ if (!ticket || !n || (!flags.text === !flags['keep-default'])) return need('<initiative> <ticket> <n> --text "<the answer>" | --keep-default');
249
+ const r = jiraTickets.answerDryRun(root, initiative, ticket, n, flags.text, { now, keep: !!flags['keep-default'] });
250
250
  if (!r.ok) return fail(r.error);
251
- return out(r, [`${initiative} ${ticket} gap ${r.n} answered${r.written.length ? ' and added to the ticket' : ''}${r.kept.length ? ` · the ticket was not changed: ${r.kept[0].why}` : ''}`]);
251
+ return out(r, [`${initiative} ${ticket} gap ${r.n} answered${r.keptDefault ? ` with its default (${r.answer})` : ''}${r.written.length ? ' and added to the ticket' : ''}${r.kept.length ? ` · the ticket was not changed: ${r.kept[0].why}` : ''}`]);
252
252
  }
253
253
  if (verb === 'show') {
254
254
  const r = jiraTickets.view(root, initiative, { snapshot: jiraStatus.readSnapshot(root, initiative) });
@@ -606,16 +606,16 @@ function dryRun(root, initiative, raw, { now } = {}) {
606
606
  return { ok: true, initiative, tickets: Object.keys(c.tickets), ...sum, unverified: c.unverified, unknown: c.unknown, written: ap.written, kept: ap.kept, file: relOf(root, dryRunPath(root, initiative)) };
607
607
  }
608
608
  /** The PM's answer to a gap: it goes into the ticket and the question leaves the list. */
609
- function answerDryRun(root, initiative, ticket, n, text, { now } = {}) {
609
+ function answerDryRun(root, initiative, ticket, n, text, { now, keep = false } = {}) {
610
610
  const file = DRm().read(dryRunPath(root, initiative));
611
611
  if (!file) return { ok: false, status: 404, error: `no dry run for ${initiative}: run the dry run first` };
612
- const a = DRm().answer(file, ticket, n, text, now);
612
+ const a = DRm().answer(file, ticket, n, text, now, { keep });
613
613
  if (!a.ok) return { ok: false, status: 400, error: a.error };
614
614
  DRm().write(dryRunPath(root, initiative), file);
615
615
  const d = readDraft(root, initiative);
616
616
  let ap = { written: [], kept: [] };
617
617
  if (d) { ap = applyDryRun(d, file, new Set([ticket])); if (ap.written.length) writeDraft(root, initiative, d, { now, prd: prdOf(recordFm(root, initiative)) }); }
618
- return { ok: true, initiative, ticket, n: a.guess.n, q: a.guess.q, answer: a.guess.answer, written: ap.written, kept: ap.kept };
618
+ return { ok: true, initiative, ticket, n: a.guess.n, q: a.guess.q, answer: a.guess.answer, keptDefault: !!a.guess.kept, written: ap.written, kept: ap.kept };
619
619
  }
620
620
  /** The gaps of an initiative's dry run that nobody answered: [{ ticket, n, q }]. Stale and removed tickets are left out. */
621
621
  function dryRunGaps(root, initiative) {
@@ -151,6 +151,9 @@ const VERBS = Object.freeze({
151
151
  // Not a pm-os-absorb verb (run: null): initiative core-documents added it through the same table.
152
152
  coredoc: Object.freeze({ module: 'coredoc-cli.js', run: null, guide: 'cli.md',
153
153
  help: 'pmos coredoc write --scope <scope> --key <key> --file <path|-> — write one draft of a core document; the PM issues it on the page (pmos coredoc help)' }),
154
+ // Not a pm-os-absorb verb (run: null): initiative spec-critic (bet A330) added it through the same table.
155
+ critic: Object.freeze({ module: 'critic-cli.js', run: null, guide: 'cli.md',
156
+ help: 'pmos critic <file>|show|lenses|label|stats — before you share a document, the hardest questions a sceptical reviewer would ask, each quoting the document (pmos critic help)' }),
154
157
  // Not a pm-os-absorb verb (run: null): the Grill and Forecast build (F-A) added it through the same table.
155
158
  forecast: Object.freeze({ module: 'forecast-cli.js', run: null, guide: 'cli.md',
156
159
  help: 'pmos forecast baseline|baseline-off|turned … — a goal forecast\'s kept baseline, and the forecasts that turned (pmos forecast help)' }),
@@ -265,8 +265,12 @@ function fold(lines) {
265
265
  const expired = []; // expire lines, oldest first (History and Your move's "N expired")
266
266
  const removes = []; // remove lines, oldest first: a deleted prototype version (removedOf)
267
267
  let t = '', epoch = '';
268
+ // default-decisions-with-a-deadline: a drop PMOS took as a default carries its batch; the Undo of that batch reads it as never written
269
+ const undoneB = new Set();
270
+ for (const l of lines || []) if (isObj(l) && l.kind === 'undo' && str(l.batch)) undoneB.add(l.batch);
268
271
  for (const l of lines || []) {
269
272
  if (!isObj(l) || !KINDS.has(l.kind)) continue;
273
+ if (l.kind === 'drop' && str(l.batch) && undoneB.has(l.batch)) continue;
270
274
  if (l.at && String(l.at) > t) t = String(l.at);
271
275
  const ini = str(l.ini);
272
276
  if (l.kind === 'epoch') { if (!epoch) epoch = str(l.at); }
@@ -102,4 +102,4 @@ function today(stateDir, held, { day, pm, now, extra = [] } = {}) {
102
102
  return { day, questions: questionsOf(mine, { pm, extra: mineAsks }), later: list.length - mine.length + asks.length - mineAsks.length };
103
103
  }
104
104
 
105
- module.exports = { questionsOf, today, ownerOf, partOf, LEDGER };
105
+ module.exports = { questionsOf, today, ownerOf, partOf, readDays, LEDGER };
@@ -134,6 +134,7 @@ const MODULES = Object.freeze([
134
134
  'routes-next-prompt', // batch 26 item 2: the chat's suggested next prompt and Sharper card (lib/next-prompt.js, through lib/ai-guard.js)
135
135
  'routes-drift', // weekly-drift-check: What would I have missed, Home's weekly ✦ and its ⋯ drop and Undo (runtime drift/drift.jsonl; page-press POST)
136
136
  'routes-moments', // onboarding B3 gradual exposure: the day's ✦ in Home's chat, the menu dots, a quiet place's one line (onboarding-progress record; page-press POST)
137
+ 'routes-spec-critic', // spec-critic: the sceptical reviewer's hardest questions on a document before it is shared (runtime spec-critic.jsonl)
137
138
  ]);
138
139
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
139
140
  const MODULE_NAME = /^[a-z0-9][a-z0-9-]*\.js$/;
@@ -11,7 +11,8 @@
11
11
  * line where the work is.
12
12
  * GET /api/autonomy/ahead?ws&ini&title → { ok, ws, ini, outcome: { date, metric, src } | null, jobs: [{ date, name, src }] }
13
13
  * the initiative's dated things only the server reads, for the Viewer's Coming up list (lib/coming-up.js; batch 29 item 7)
14
- * POST /api/autonomy/undo { ws, ref } → { ok, back, demoted? } Undo of one change: a Driver proposal (p-…), a ✦ batch (pk-…) or a lesson (im-…)
14
+ * POST /api/autonomy/undo { ws, ref } → { ok, back, demoted? } Undo of one change: a Driver proposal (p-…), a ✦ batch (pk-…, also a default PMOS took
15
+ * on a question nobody answered, lib/default-decisions.js) or a lesson (im-…)
15
16
  * POST /api/autonomy/seen { ws, job, product, until } → { ok } Home said the demotion once
16
17
  * GET /api/autonomy/kinds → { ok, kinds: [{ kind, label, made, kept, undone, auto, set, way, until }], showUntil }
17
18
  * How Claude decides (Settings › Claude, boards AwG and AwG2), over every product's state folders: lib/autonomy.js kindsOf. The PM
@@ -57,6 +58,11 @@ async function undoRef(ctx, w, ref, g) {
57
58
  const PR = require('./proposals.js');
58
59
  const dir = ctx.stateDirFor ? ctx.stateDirFor(w) : null;
59
60
  const line = dir ? PR.readLines(PR.ledgerFile(dir)).find((l) => l.kind === 'keep' && l.batch === ref) : null;
61
+ // a default PMOS took on a question nobody answered (lib/default-decisions.js): its Undo brings the question back
62
+ if (!line && dir && require('./default-decisions.js').isDefaultBatch(dir, ref)) {
63
+ const r = require('./default-decisions.js').undo(dir, ref, { product: w.id, actor: g.actor });
64
+ return r.ok ? { status: 200, body: { ok: true, back: true, ...(r.demoted ? { demoted: r.demoted } : {}) } } : bad(r.status || 409, r.error);
65
+ }
60
66
  if (!line) return bad(404, 'no change was applied under that id');
61
67
  const RP = require('./routes-proposals.js');
62
68
  const RB = require('./routes-boards.js');
@@ -98,6 +98,8 @@ function keepCore(ctx, p, g, f, ini, want, choices = {}, extra = {}) {
98
98
  function undoCore(ctx, p, g, id) {
99
99
  const dir = dirOf(ctx, p.w), F = PR.read(dir);
100
100
  const k = F.kept.find((x) => x.batch === id);
101
+ // a default PMOS took on a question nobody answered (lib/default-decisions.js): no keep line, its drops go back
102
+ if (!k && require('./default-decisions.js').isDefaultBatch(dir, id)) { const r = require('./default-decisions.js').undo(dir, id, { product: p.w.id, actor: g.actor }); return r.ok ? { ok: true, back: 1, kept: 0, demoted: r.demoted || null } : { ok: false, status: r.status || 409, error: r.error }; }
101
103
  if (!k || F.undone.has(id)) return { ok: false, status: 409, error: 'Nothing to undo' };
102
104
  const f = TLR.frame(ctx, p.w, p.board);
103
105
  if (!f) return { ok: false, status: 202, error: 'The board is still being read. Try again in a moment.' };
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+ /* routes-spec-critic.js — the sceptical reviewer's routes (initiative spec-critic; lib/spec-critic.js).
3
+ *
4
+ * POST /api/spec-critic { path, ws? } → { ok, run, file, questions, dropped, lenses, added } | { ok: false, error }
5
+ * one critic pass on a markdown, text or HTML document: a path relative to the workspace (it must stay inside it) or a full path.
6
+ * `pmos critic <file>` reaches it with no Origin (D98, like `pmos lab critic`); from a page it needs a page press.
7
+ * GET /api/spec-critic?path=&ws= → { ok, run: <the newest run on that file> | null, changed } a read; changed: the file differs from
8
+ * what the run read
9
+ * The run is read-only (lib/design-critic.js askVia, kind ask) and is recorded in <runtime>/spec-critic.jsonl. Nothing is sent. */
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const guard = require('./pm-guard.js');
13
+ const SC = require('./spec-critic.js');
14
+
15
+ const MAX_BYTES = 2e6;
16
+ const fail = (ctx, res, status, error) => { ctx.json(res, { ok: false, error }, status); return true; };
17
+ function wsOf(ctx, id) { let w = null; try { w = ctx.getWs(id || null); } catch { w = null; } return w && (!id || w.id === id) ? w : null; }
18
+
19
+ /** A document the critic may read → { ok, abs } | { ok: false, status, error }. */
20
+ function docOf(w, p) {
21
+ const given = String(p || '').trim();
22
+ if (!given) return { ok: false, status: 400, error: 'path names the document to read' };
23
+ let abs;
24
+ if (path.isAbsolute(given)) abs = path.resolve(given);
25
+ else {
26
+ if (!w || !w.root) return { ok: false, status: 404, error: 'no such workspace: give the document\'s full path' };
27
+ abs = path.resolve(w.root, given);
28
+ let rootReal = w.root; try { rootReal = fs.realpathSync(w.root); } catch { /* as given */ }
29
+ let real = abs; try { real = fs.realpathSync(abs); } catch { /* checked below */ }
30
+ if (real !== rootReal && !real.startsWith(rootReal + path.sep)) return { ok: false, status: 400, error: `${given}: the document must be inside the workspace` };
31
+ }
32
+ if (!SC.DOC_RE.test(abs)) return { ok: false, status: 400, error: `${given}: give a markdown, text or HTML document (.md, .txt, .html)` };
33
+ let st = null; try { st = fs.statSync(abs); } catch { st = null; }
34
+ if (!st || !st.isFile() || st.size > MAX_BYTES) return { ok: false, status: 400, error: `${given}: no such file, or over 2 MB` };
35
+ try { abs = fs.realpathSync(abs); } catch { /* as resolved */ }
36
+ return { ok: true, abs };
37
+ }
38
+
39
+ async function run(ctx, res, b) {
40
+ const w = wsOf(ctx, typeof b.ws === 'string' && b.ws ? b.ws : null);
41
+ const d = docOf(w, b.path);
42
+ if (!d.ok) return fail(ctx, res, d.status, d.error);
43
+ if (SC.off(process.env)) return fail(ctx, res, 409, 'the critic is off (PMOS_CRITIC=off)');
44
+ let raw = ''; try { raw = fs.readFileSync(d.abs, 'utf8'); } catch { return fail(ctx, res, 400, 'the document could not be read'); }
45
+ const K = SC.lensesFor(w ? w.root : '');
46
+ const text = SC.textOf(raw, d.abs);
47
+ const ask = typeof ctx.specCritic === 'function' ? ctx.specCritic : SC.askVia(ctx.spawnSession);
48
+ const r = await SC.critique(ask, { lenses: K.lenses, text: raw, file: d.abs });
49
+ const id = ctx.runtimeDir ? SC.record(ctx.runtimeDir, { from: String(b.from || 'cli'), ws: w ? w.id : '', file: d.abs, sha: SC.sha(text), chars: text.length,
50
+ lenses: r.lenses || [], ok: r.ok, why: r.why, questions: r.questions, dropped: r.dropped, ms: r.ms }) : null;
51
+ if (!r.ok) return fail(ctx, res, r.off ? 409 : 502, r.why);
52
+ ctx.json(res, { ok: true, run: id, file: d.abs, questions: r.questions, dropped: r.dropped, lenses: r.lenses.length, added: K.added, from: K.from });
53
+ return true;
54
+ }
55
+
56
+ function latest(ctx, res, url) {
57
+ const w = wsOf(ctx, url.searchParams.get('ws') || null);
58
+ const d = docOf(w, url.searchParams.get('path'));
59
+ if (!d.ok) return fail(ctx, res, d.status, d.error);
60
+ const r = ctx.runtimeDir ? SC.latest(ctx.runtimeDir, d.abs) : null;
61
+ let changed = false;
62
+ if (r) { try { changed = SC.sha(SC.textOf(fs.readFileSync(d.abs, 'utf8'), d.abs)) !== r.sha; } catch { changed = false; } }
63
+ ctx.json(res, { ok: true, file: d.abs, run: r, changed });
64
+ return true;
65
+ }
66
+
67
+ module.exports = {
68
+ prefixes: ['/api/spec-critic'],
69
+ docOf,
70
+ handle: async (req, res, url, ctx) => {
71
+ if (url.pathname !== '/api/spec-critic') return fail(ctx, res, 404, 'not found');
72
+ if (req.method === 'GET') return latest(ctx, res, url);
73
+ if (req.method !== 'POST') return fail(ctx, res, 405, 'GET or POST only');
74
+ const got = await ctx.readJson(req);
75
+ if (!got.ok || !got.body || typeof got.body !== 'object' || Array.isArray(got.body)) return fail(ctx, res, 400, 'the body must be a JSON object');
76
+ // `pmos critic` comes with no Origin (D98, like `pmos lab critic`); a page needs a page press
77
+ if (req.headers.origin) { const g = guard.requirePagePress(req, got.body); if (!g.ok) return fail(ctx, res, g.status, g.error); }
78
+ return run(ctx, res, got.body);
79
+ },
80
+ };
@@ -16,7 +16,10 @@
16
16
  * DONE (C2, board CsD): what an agent kept by itself in the last 14 days, one line per batch with its Undo (lib/done-feed.js).
17
17
  * QUESTIONS (act-alone-only-with-a-source): { day, questions: [lib/question-batch.js question], later } — the changes PMOS holds for want
18
18
  * of a source, one question per owner and initiative, the PM's first; the list is fixed for the day (one line in question-days.jsonl).
19
- * On the same card (dry-run-tickets-before-build): the dry-run gaps of drafted tickets and the outside sign-offs with no answer. */
19
+ * On the same card (dry-run-tickets-before-build): the dry-run gaps of drafted tickets and the outside sign-offs with no answer.
20
+ * DEFAULTS (default-decisions-with-a-deadline, lib/default-decisions.js): each question carries `default` ({ choice, due, n, say } | null),
21
+ * `waits` (why it has no default | null), `waiting` (days on the list) and `cost` (A27: what the wait holds up | null). The read takes the
22
+ * defaults due today (one batch each, with Undo in "PMOS did"), and `taken` lists them. A dry-run gap or a sign-off never defaults. */
20
23
  const YM = require('./your-move.js');
21
24
 
22
25
  const localDay = (ms = Date.now()) => { const d = new Date(ms); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
@@ -68,13 +71,25 @@ function expire(ctx, w, now = Date.now()) {
68
71
 
69
72
  /** The day's question list (act-alone-only-with-a-source): the changes PMOS holds for want of a source, one question per owner and
70
73
  * initiative, fixed once a day (lib/question-batch.js). Questions for teammates are drafts: nothing is sent. */
71
- function questions(ctx, w, today) {
74
+ function questions(ctx, w, today, { take = true } = {}) {
72
75
  const dir = ctx.stateDirFor ? ctx.stateDirFor(w) : null;
76
+ const QB = require('./question-batch.js'), DD = require('./default-decisions.js');
73
77
  let held = [];
74
78
  try { held = require('./routes-proposals.js').heldOf(ctx, w); } catch { held = []; }
75
79
  let extra = [];
76
80
  try { extra = asksOf(w.root); } catch { extra = []; }
77
- return require('./question-batch.js').today(dir, held, { day: today, extra });
81
+ let Q = QB.today(dir, held, { day: today, extra });
82
+ if (!dir) return Q;
83
+ // default-decisions-with-a-deadline: a change nobody answered by its due day takes its default (PMOS leaves the plan as it is, with
84
+ // Undo); the question then leaves the list. Every question left says its default or why it waits, and what the wait costs (A27).
85
+ let taken = [];
86
+ if (take) {
87
+ try { taken = DD.take(dir, held, { dayLines: QB.readDays(dir), today, product: w.id, settingsDir: ctx.runtimeDir || null }).taken; } catch { taken = []; }
88
+ if (taken.length) { const gone = new Set(taken.flatMap((t) => t.ids)); held = held.filter((h) => !gone.has(String(h.prop.id))); Q = QB.today(dir, held, { day: today, extra }); }
89
+ }
90
+ const PR = require('./proposals.js');
91
+ const questions2 = DD.annotate(Q.questions, held, { dayLines: QB.readDays(dir), lines: PR.readLines(PR.ledgerFile(dir)), today, extra });
92
+ return { ...Q, questions: questions2, ...(taken.length ? { taken: taken.map((t) => ({ batch: t.batch, ini: t.ini, board: t.board, n: t.ids.length, title: t.title })) } : {}) };
78
93
  }
79
94
 
80
95
  /** The other asks on the same card (dry-run-tickets-before-build): each ticket's dry-run gaps nobody answered (lib/ticket-dry-run.js),
@@ -0,0 +1,241 @@
1
+ 'use strict';
2
+ /* spec-critic.js — before a PM shares a document, PMOS lists the hardest questions a sceptical reviewer would ask (initiative spec-critic;
3
+ * bet A330 of the factory line, proof T10: a sceptical critic on two PRDs gave 8 quote-backed findings, 7 clearly valid, and the same gap
4
+ * in both pointed at the template that made them).
5
+ *
6
+ * EVERY QUESTION NAMES ITS LENS AND QUOTES THE DOCUMENT. lensesFor(root) is the base set below plus the PRODUCT's own reviewer questions,
7
+ * so it works on any product built with PMOS:
8
+ * base the questions every sceptical reader asks (evidence, outcome, trade-off, scope, risk, owner, contradiction, unverified).
9
+ * product review-questions.json under okf/products/<slug>/references/, else pmos/review-questions.json:
10
+ * { questions: [{ id, title, rule, source?, date? }] } (an id that is a base lens replaces that lens).
11
+ * parse() keeps a question only when it names a known lens AND its quote is found in the document (case, whitespace, quote marks and
12
+ * markdown emphasis ignored), so the PM never prepares for a question about words the document does not hold. At most 3 (MAX_QUESTIONS).
13
+ *
14
+ * THE RUN. One read-only session through the design critic's ask path (lib/design-critic.js askVia, origin `briefing-ask:spec-critic:<key>`,
15
+ * kind `ask`). The document's text is in the prompt, so the run needs no file. A run that cannot start, times out or answers nonsense
16
+ * files no questions, and the ledger says it did not run. PMOS_CRITIC=off runs none (the same switch as the design critic).
17
+ *
18
+ * WHERE IT RUNS. `pmos critic <file>` through the running server (POST /api/spec-critic, lib/routes-spec-critic.js); the chat's agent runs
19
+ * it when the PM says they are about to share a document. GET /api/spec-critic gives a page the latest run on a file.
20
+ *
21
+ * THE LEDGER. <runtime>/spec-critic.jsonl, append-only: { kind: 'run', id, at, from, ws?, file, sha, chars, lenses, ok, why?,
22
+ * questions: [{ lens, title, question, quote, why, fix }], dropped, ms } and { kind: 'label', run, n, label: real | noise, by, at } (the PM's
23
+ * word on question n, 1-based; the newest label wins). stats() counts them, and lists a lens flagged in 2 or more documents as a repeat:
24
+ * the same gap in several documents points at the template or generator that made them.
25
+ *
26
+ * BASE · ORIGIN · MAX_QUESTIONS · MAX_CHARS · DOC_RE · off(env)
27
+ * questionsOf(json, rel) PURE → [lens] · lensesFor(root) → { lenses, from, added }
28
+ * textOf(raw, file) PURE → the text the critic reads (HTML without its tags) · norm(s) PURE · sha(text) PURE
29
+ * promptOf({ lenses, text, file, product? }) PURE → string
30
+ * parse(answer, lenses, text) PURE → { questions, dropped } | null (null: the answer could not be read)
31
+ * critique(ask, { root?, lenses?, text, file, product?, env? }) → Promise<{ ok, questions, dropped, lenses, ms } | { ok: false, why, off? }>
32
+ * askVia(spawnSession, { timeoutMs? }) → ask
33
+ * file(rt) · record(rt, run) → id · read(rt) → [run + { labels }] · latest(rt, file) · label(rt, run, n, label, { by }) · stats(rt) */
34
+ const fs = require('fs');
35
+ const path = require('path');
36
+ const crypto = require('crypto');
37
+ const DC = require('./design-critic.js');
38
+
39
+ const FILE = 'spec-critic.jsonl';
40
+ const ORIGIN = 'briefing-ask:spec-critic:';
41
+ const MAX_QUESTIONS = 3, MAX_CHARS = 80000, MAX_RULE = 500, MIN_QUOTE = 6;
42
+ const DOC_RE = /\.(md|markdown|txt|html?)$/i;
43
+ const ID_RE = /^[a-z0-9][a-z0-9-]{0,59}$/;
44
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
45
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
46
+ const off = (env) => DC.off(env);
47
+
48
+ /* ── the base lenses: what a sceptical reviewer asks of any spec, strategy, roadmap or report ── */
49
+ const BASE = Object.freeze([
50
+ { id: 'evidence', title: 'What is the evidence?', rule: 'A claim, number, need or user problem stated with no source, data or example behind it.' },
51
+ { id: 'outcome', title: 'How will we know it worked?', rule: 'Success is measured by output (built, shipped, launched) rather than an outcome; no metric, baseline, target, key result or check date.' },
52
+ { id: 'trade-off', title: 'What will you stop doing?', rule: 'No cost, no trade-off and nothing given up or delayed to make room for this; every option looks free.' },
53
+ { id: 'scope', title: 'What is out?', rule: 'Scope or non-goals are missing or vague, so the ask can grow; no first cut that ships alone.' },
54
+ { id: 'risk', title: 'What if you are wrong?', rule: 'The biggest assumption or risk is not named, or has no test, mitigation or kill line.' },
55
+ { id: 'owner', title: 'Who decides, and by when?', rule: 'No owner, no date, or no clear decision or action asked of the reader.' },
56
+ { id: 'contradiction', title: 'Which part is true?', rule: 'Two parts of the document disagree, or a summary says something its own detail contradicts.' },
57
+ { id: 'unverified', title: 'Is it real yet?', rule: 'A status, delivery or result is claimed but marked unverified, assumed, or never checked.' },
58
+ ].map((c) => Object.freeze({ ...c, source: 'PMOS base lenses' })));
59
+
60
+ /* ── the product's own reviewer questions ── */
61
+ function questionsOf(json, rel = 'review-questions.json') {
62
+ let j = json;
63
+ if (typeof j === 'string') { try { j = JSON.parse(j); } catch { return []; } }
64
+ const list = isObj(j) && Array.isArray(j.questions) ? j.questions : Array.isArray(j) ? j : [];
65
+ const out = [], seen = new Set();
66
+ for (const q of list) {
67
+ if (!isObj(q) || !ID_RE.test(String(q.id || '')) || !one(q.title, 120) || !one(q.rule, MAX_RULE) || seen.has(q.id)) continue;
68
+ seen.add(q.id);
69
+ out.push({ id: q.id, title: one(q.title, 120), rule: one(q.rule, MAX_RULE), source: one([q.source, q.date].filter(Boolean).join(', ') || rel, 160) });
70
+ }
71
+ return out;
72
+ }
73
+ const readOr = (abs) => { try { return fs.readFileSync(abs, 'utf8'); } catch { return null; } };
74
+ /** The base lenses plus the product's own reviewer questions (an id that is a base lens replaces it). */
75
+ function lensesFor(root) {
76
+ const R = String(root || '');
77
+ let lenses = BASE.map((c) => ({ ...c }));
78
+ const from = [];
79
+ let added = 0;
80
+ if (R) {
81
+ let slugs = []; try { slugs = fs.readdirSync(path.join(R, 'okf', 'products')).sort(); } catch { slugs = []; }
82
+ const cands = [...slugs.map((s) => `okf/products/${s}/references/review-questions.json`), 'pmos/review-questions.json'];
83
+ for (const rel of cands) {
84
+ const t = readOr(path.join(R, rel)); if (t == null) continue;
85
+ const qs = questionsOf(t, rel);
86
+ if (!qs.length) continue;
87
+ for (const q of qs) { const i = lenses.findIndex((l) => l.id === q.id); if (i >= 0) lenses[i] = q; else lenses.push(q); added++; }
88
+ from.push(rel);
89
+ break;
90
+ }
91
+ }
92
+ return { lenses, from, added };
93
+ }
94
+
95
+ /* ── the text ── */
96
+ /** What the critic reads: an HTML page without its scripts, styles and tags; any other document as it is. At most MAX_CHARS. */
97
+ function textOf(raw, file = '') {
98
+ let t = String(raw || '');
99
+ if (/\.html?$/i.test(file)) {
100
+ t = t.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, ' ').replace(/<br\s*\/?>|<\/(p|div|li|h\d|tr|section)>/gi, '\n').replace(/<[^>]+>/g, ' ')
101
+ .replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'")
102
+ .replace(/[ \t]+/g, ' ').replace(/\n\s*\n+/g, '\n\n').trim();
103
+ }
104
+ return t.length > MAX_CHARS ? t.slice(0, MAX_CHARS) : t;
105
+ }
106
+ /** For the quote check: lower case, one space, plain quote marks and dashes, no markdown emphasis or table bars. */
107
+ function norm(s) {
108
+ return String(s || '').toLowerCase().replace(/[‘’‛`´]/g, "'").replace(/[“”„]/g, '"').replace(/[–—]/g, '-')
109
+ .replace(/[*_|]+/g, ' ').replace(/\s+/g, ' ').trim();
110
+ }
111
+ const sha = (text) => crypto.createHash('sha1').update(String(text || '')).digest('hex').slice(0, 16);
112
+
113
+ /* ── the run ── */
114
+ function promptOf({ lenses, text, file = '', product = '' }) {
115
+ return [
116
+ `You are PMOS's sceptical reviewer. The user is about to share this document${product ? ' about ' + one(product, 80) : ''}${file ? ' (' + one(path.basename(file), 120) + ')' : ''}. Read it as the most sceptical senior reader in the room would: an executive, an engineering lead, or a finance partner who has to say yes. List the hardest questions that reader would ask, so the user can answer them before sharing. Do not write or change anything.`,
117
+ 'The lenses. Each question must name exactly one of these ids:\n' + lenses.map((l) => `[${l.id}] ${l.title} ${l.rule}`).join('\n'),
118
+ `Rules. At most ${MAX_QUESTIONS} questions, the hardest first. Each question quotes the document's own words it rests on, copied exactly (a few words to one sentence). For something missing, quote the heading or sentence where it should be. A question whose quote is not in the document is thrown away. Give the smallest fix the user can make before sharing, in one line. No praise, no style or grammar notes, no question the document already answers. If a strong reader would ask nothing hard, answer an empty list.`,
119
+ 'The document:\n<<<DOCUMENT\n' + text + '\nDOCUMENT>>>',
120
+ 'Answer with JSON only: {"questions":[{"lens":"<id>","question":"<the question, as the reviewer would ask it>","quote":"<the exact words>","why":"<why it is hard, one line>","fix":"<the smallest fix>"}]}',
121
+ ].join('\n\n');
122
+ }
123
+ /** The critic's answer → questions that name a known lens and quote the document, and how many were dropped; null when unreadable. */
124
+ function parse(answer, lenses, text) {
125
+ const t = String(answer || '').replace(/```(?:json)?/gi, '');
126
+ const at = t.indexOf('{'), end = t.lastIndexOf('}');
127
+ if (at < 0 || end < at) return null;
128
+ let o = null;
129
+ try { o = JSON.parse(t.slice(at, end + 1)); } catch {
130
+ const m = /\{\s*"questions"\s*:\s*\[[\s\S]*?\]\s*\}/.exec(t); if (!m) return null;
131
+ try { o = JSON.parse(m[0]); } catch { return null; }
132
+ }
133
+ if (!isObj(o) || !Array.isArray(o.questions)) return null;
134
+ const byId = new Map(lenses.map((l) => [l.id, l]));
135
+ const doc = norm(text);
136
+ const out = [], seen = new Set();
137
+ let dropped = 0;
138
+ for (const q of o.questions) {
139
+ if (!isObj(q)) continue;
140
+ const l = byId.get(String(q.lens || '').replace(/^\[|\]$/g, '').trim());
141
+ const question = one(q.question, 300), quote = one(q.quote, 400).replace(/^["'“‘]+|["'”’]+$/g, '').replace(/^\.\.\.|\.\.\.$/g, '').trim();
142
+ if (!l || !question) continue;
143
+ const nq = norm(quote);
144
+ if (nq.length < MIN_QUOTE || !doc.includes(nq)) { dropped++; continue; }
145
+ const k = l.id + '|' + nq;
146
+ if (seen.has(k)) continue;
147
+ seen.add(k);
148
+ if (out.length < MAX_QUESTIONS) out.push({ lens: l.id, title: l.title, question, quote, why: one(q.why, 240), fix: one(q.fix, 240) });
149
+ }
150
+ return { questions: out, dropped };
151
+ }
152
+ /** One critic pass. ask(prompt, { key, addDirs }) → Promise<text | null>. */
153
+ async function critique(ask, { root = '', lenses = null, text = '', file = '', product = '', env = process.env } = {}) {
154
+ if (off(env)) return { ok: false, off: true, why: 'the critic is off (PMOS_CRITIC=off)' };
155
+ if (typeof ask !== 'function') return { ok: false, why: 'PMOS could not start a critic session' };
156
+ const T = textOf(text, file);
157
+ if (!T.trim()) return { ok: false, why: 'the document is empty' };
158
+ const L = lenses || lensesFor(root).lenses;
159
+ const started = Date.now();
160
+ const key = crypto.createHash('sha1').update(String(file) + '\n' + sha(T) + '\n' + started).digest('hex').slice(0, 12);
161
+ let answer = null;
162
+ try { answer = await ask(promptOf({ lenses: L, text: T, file, product }), { key, addDirs: [] }); } catch { answer = null; }
163
+ const ms = Date.now() - started;
164
+ if (answer == null) return { ok: false, why: 'the critic session did not answer', ms };
165
+ const p = parse(answer, L, T);
166
+ if (!p) return { ok: false, why: 'the critic\'s answer could not be read', ms };
167
+ return { ok: true, questions: p.questions, dropped: p.dropped, lenses: L.map((l) => l.id), ms };
168
+ }
169
+ /** The design critic's ask path with this critic's origin: a read-only `briefing-ask:` run (kind ask). */
170
+ const askVia = (spawnSession, { timeoutMs } = {}) => DC.askVia(spawnSession, { name: 'spec critic', origin: ORIGIN, ...(timeoutMs ? { timeoutMs } : {}) });
171
+
172
+ /* ── the ledger ── */
173
+ const file = (rt) => path.join(String(rt || ''), FILE);
174
+ function append(rt, line) {
175
+ if (!rt) return false;
176
+ try { fs.mkdirSync(rt, { recursive: true }); fs.appendFileSync(file(rt), JSON.stringify(line) + '\n'); return true; } catch { return false; }
177
+ }
178
+ /** Record one run. → its id */
179
+ function record(rt, run = {}) {
180
+ const id = 'sc-' + Date.now().toString(36) + crypto.randomBytes(3).toString('hex');
181
+ append(rt, { kind: 'run', id, at: new Date().toISOString(), from: one(run.from || 'cli', 40), ...(run.ws ? { ws: one(run.ws, 80) } : {}),
182
+ file: one(run.file, 400), sha: one(run.sha, 16), chars: Number.isFinite(run.chars) ? run.chars : null, lenses: (run.lenses || []).slice(0, 40),
183
+ ok: !!run.ok, ...(run.why ? { why: one(run.why, 200) } : {}),
184
+ questions: (run.questions || []).slice(0, MAX_QUESTIONS).map((q) => ({ lens: q.lens, title: one(q.title, 120), question: one(q.question, 300), quote: one(q.quote, 400), why: one(q.why, 240), fix: one(q.fix, 240) })),
185
+ dropped: Number.isInteger(run.dropped) ? run.dropped : 0, ms: Number.isFinite(run.ms) ? run.ms : null });
186
+ return id;
187
+ }
188
+ function lines(rt) {
189
+ let t = ''; try { t = fs.readFileSync(file(rt), 'utf8'); } catch { return []; }
190
+ const out = [];
191
+ for (const l of t.split('\n')) { if (!l) continue; try { const o = JSON.parse(l); if (isObj(o)) out.push(o); } catch { /* a torn line */ } }
192
+ return out;
193
+ }
194
+ /** Runs, oldest first, each with its labels { n → real | noise } (the newest label wins). */
195
+ function read(rt) {
196
+ const runs = new Map();
197
+ for (const l of lines(rt)) {
198
+ if (l.kind === 'run' && l.id) runs.set(l.id, { ...l, questions: Array.isArray(l.questions) ? l.questions : [], labels: {} });
199
+ else if (l.kind === 'label' && runs.has(l.run)) runs.get(l.run).labels[l.n] = l.label;
200
+ }
201
+ return [...runs.values()];
202
+ }
203
+ /** The newest run on one file (its path as recorded), or null. */
204
+ function latest(rt, f) {
205
+ const R = read(rt).filter((r) => r.file === String(f || ''));
206
+ return R.length ? R[R.length - 1] : null;
207
+ }
208
+ /** The PM's word on question n (1-based) of a run: real or noise. */
209
+ function label(rt, run, n, lab, { by = 'pm:cli' } = {}) {
210
+ const r = read(rt).find((x) => x.id === run);
211
+ if (!r) return { ok: false, error: `there is no critic run ${one(run, 40)}: pmos critic stats lists them` };
212
+ const i = Number(n);
213
+ if (!Number.isInteger(i) || i < 1 || i > r.questions.length) return { ok: false, error: `run ${r.id} has ${r.questions.length} question${r.questions.length === 1 ? '' : 's'}: give a number from 1` };
214
+ if (lab !== 'real' && lab !== 'noise') return { ok: false, error: 'the label is real or noise' };
215
+ append(rt, { kind: 'label', run: r.id, n: i, label: lab, by: one(by, 80), at: new Date().toISOString() });
216
+ return { ok: true, question: r.questions[i - 1] };
217
+ }
218
+ /** The counts the Checker reads, and the lenses that repeat across documents (the newest run per file counts for repeats). */
219
+ function stats(rt) {
220
+ const R = read(rt);
221
+ const s = { runs: R.length, notRun: 0, files: 0, questions: 0, real: 0, noise: 0, unlabelled: 0, dropped: 0, byLens: {}, repeats: [] };
222
+ const newest = new Map();
223
+ for (const r of R) {
224
+ if (!r.ok) { s.notRun++; continue; }
225
+ s.dropped += r.dropped || 0;
226
+ newest.set(r.file, r);
227
+ r.questions.forEach((q, i) => {
228
+ s.questions++;
229
+ s.byLens[q.lens] = (s.byLens[q.lens] || 0) + 1;
230
+ const l = r.labels[i + 1];
231
+ if (l === 'real') s.real++; else if (l === 'noise') s.noise++; else s.unlabelled++;
232
+ });
233
+ }
234
+ s.files = newest.size;
235
+ const docs = {};
236
+ for (const r of newest.values()) for (const lens of new Set(r.questions.map((q) => q.lens))) (docs[lens] = docs[lens] || []).push(r.file);
237
+ s.repeats = Object.entries(docs).filter(([, f]) => f.length >= 2).map(([lens, f]) => ({ lens, files: f })).sort((a, b) => b.files.length - a.files.length);
238
+ return s;
239
+ }
240
+
241
+ module.exports = { FILE, BASE, ORIGIN, MAX_QUESTIONS, MAX_CHARS, DOC_RE, off, questionsOf, lensesFor, textOf, norm, sha, promptOf, parse, critique, askVia, file, record, read, latest, label, stats };
@@ -13,7 +13,12 @@
13
13
  * blockOf(entry) → the text that goes into the ticket's Additional Context, or '' PURE
14
14
  * withBlock(text, block) → the section text with the old block replaced PURE
15
15
  * gapsOf(file, sourceOf) → [{ ticket, n, q }] the guesses no document answers and nobody answered yet PURE
16
- * countsOf(entry) → { guesses, answered, partly, gaps, open } PURE
16
+ * countsOf(entry) → { guesses, answered, partly, gaps, open, withDefault, kept, changed } PURE
17
+ * askOf(guess) → the question with its default offered first (A396, spec-questions-with-defaults) PURE
18
+ *
19
+ * DEFAULTS (initiative spec-questions-with-defaults; A396). A guess may carry `default`: the answer a builder would assume. The ticket
20
+ * says it ("Unless the PM says otherwise: …") until the PM answers, the question list offers it, and the PM can close the gap by keeping it
21
+ * (`kept: true`), so the Checker can count kept against changed.
17
22
  * read(file) · write(file, data)
18
23
  *
19
24
  * A guess is 'answered' (a quote found, and the agent did not say partly), 'partly' (a quote found, the agent said partly) or 'gap'
@@ -30,6 +35,7 @@ const MAX_QUOTES = 3;
30
35
  const MAX_Q = 300;
31
36
  const MAX_QUOTE = 400;
32
37
  const MAX_ANSWER = 1000;
38
+ const MAX_DEFAULT = 300;
33
39
  const MIN_QUOTE = 12;
34
40
 
35
41
  const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -63,7 +69,8 @@ function parse(raw) {
63
69
  const rawQ = isObj(g) ? (g.prd != null ? g.prd : g.quotes != null ? g.quotes : g.quote) : null;
64
70
  const quotes = (Array.isArray(rawQ) ? rawQ : rawQ != null ? [rawQ] : []).map((x) => one(x, MAX_QUOTE)).filter(Boolean).slice(0, MAX_QUOTES);
65
71
  const s = isObj(g) ? String(g.answered != null ? g.answered : g.status || '').toLowerCase() : '';
66
- guesses.push({ q, said: /part/.test(s) ? 'partly' : /^(no|gap|none|false)$/.test(s) ? 'no' : 'yes', quotes });
72
+ const def = isObj(g) ? one(g.default != null ? g.default : g.assume, MAX_DEFAULT) : '';
73
+ guesses.push({ q, said: /part/.test(s) ? 'partly' : /^(no|gap|none|false)$/.test(s) ? 'no' : 'yes', quotes, ...(def ? { default: def } : {}) });
67
74
  if (guesses.length >= MAX_GUESSES) break;
68
75
  }
69
76
  tickets.push({ id: one(t.id, 41), guesses });
@@ -84,7 +91,7 @@ function check(parsed, { ids, sourceOf = () => null, haystack = '', now } = {})
84
91
  const prd = g.quotes.filter((x) => found(x, hay));
85
92
  unverified += g.quotes.length - prd.length;
86
93
  const status = !prd.length ? 'gap' : g.said === 'partly' || g.said === 'no' ? 'partly' : 'answered';
87
- return { n: i + 1, q: g.q, status, prd };
94
+ return { n: i + 1, q: g.q, status, prd, ...(g.default ? { default: g.default } : {}) };
88
95
  });
89
96
  out[t.id] = { source: sourceOf(t.id) || null, at, guesses };
90
97
  }
@@ -97,7 +104,7 @@ function merge(old, checked, { initiative, now } = {}) {
97
104
  const tickets = { ...prev };
98
105
  for (const [id, e] of Object.entries(checked.tickets || {})) {
99
106
  const answers = new Map(((prev[id] && prev[id].guesses) || []).filter((g) => g.answer).map((g) => [qKey(g.q), g]));
100
- tickets[id] = { ...e, guesses: e.guesses.map((g) => { const a = answers.get(qKey(g.q)); return a ? { ...g, answer: a.answer, answeredAt: a.answeredAt } : g; }) };
107
+ tickets[id] = { ...e, guesses: e.guesses.map((g) => { const a = answers.get(qKey(g.q)); return a ? { ...g, answer: a.answer, answeredAt: a.answeredAt, ...(a.kept != null ? { kept: a.kept } : {}) } : g; }) };
101
108
  }
102
109
  return { initiative: initiative || (old && old.initiative) || null, at: new Date(now == null ? Date.now() : now).toISOString(), tickets };
103
110
  }
@@ -108,6 +115,7 @@ function blockOf(entry) {
108
115
  for (const g of (entry && entry.guesses) || []) {
109
116
  if (g.prd && g.prd.length) lines.push(`- ${g.q} PRD: ${g.prd.map((x) => `"${x}"`).join(' · ')}${g.status === 'partly' && !g.answer ? ' (partly)' : ''}`);
110
117
  if (g.answer) lines.push(`- ${g.q} PM: ${g.answer}`);
118
+ else if (g.default && g.status !== 'answered') lines.push(`- ${g.q} Unless the PM says otherwise: ${g.default}`);
111
119
  }
112
120
  return lines.length ? [MARK, '', ...lines].join('\n') : '';
113
121
  }
@@ -124,7 +132,9 @@ function withBlock(text, block) {
124
132
  function countsOf(entry) {
125
133
  const g = (entry && entry.guesses) || [];
126
134
  const n = (s) => g.filter((x) => x.status === s).length;
127
- return { guesses: g.length, answered: n('answered'), partly: n('partly'), gaps: n('gap'), open: g.filter((x) => x.status === 'gap' && !x.answer).length };
135
+ const gaps = g.filter((x) => x.status === 'gap');
136
+ return { guesses: g.length, answered: n('answered'), partly: n('partly'), gaps: gaps.length, open: gaps.filter((x) => !x.answer).length,
137
+ withDefault: gaps.filter((x) => x.default).length, kept: g.filter((x) => x.answer && x.kept === true).length, changed: g.filter((x) => x.answer && x.kept === false).length };
128
138
  }
129
139
 
130
140
  /** The gaps nobody answered, on tickets whose PRD item has not changed since the dry run. */
@@ -134,20 +144,29 @@ function gapsOf(file, sourceOf = () => null) {
134
144
  if (!isObj(e) || !Array.isArray(e.guesses)) continue;
135
145
  const cur = sourceOf(id);
136
146
  if (cur === undefined || (e.source && cur && cur !== e.source)) continue; // the ticket is gone, or its PRD item changed: stale
137
- for (const g of e.guesses) if (g.status === 'gap' && !g.answer) out.push({ ticket: id, n: g.n, q: g.q });
147
+ for (const g of e.guesses) if (g.status === 'gap' && !g.answer) out.push({ ticket: id, n: g.n, q: askOf(g), question: g.q, default: g.default || null });
138
148
  }
139
149
  return out;
140
150
  }
141
151
 
142
152
  /** Set the PM's answer to guess n of a ticket. → { ok, guess } | { ok: false, error } */
143
- function answer(file, ticket, n, text, now) {
153
+ /** The question as the PM reads it: with its default first offered, when it has one (A396). */
154
+ function askOf(g) {
155
+ if (!g.default) return g.q;
156
+ const q = /[?.!]$/.test(g.q) ? g.q : g.q + '?';
157
+ return `${q} Unless you say otherwise: ${/[.!?]$/.test(g.default) ? g.default : g.default + '.'}`;
158
+ }
159
+
160
+ /** Set the PM's answer to guess n of a ticket, or keep its default ({ keep: true }). → { ok, guess } | { ok: false, error } */
161
+ function answer(file, ticket, n, text, now, { keep = false } = {}) {
144
162
  const e = file && file.tickets && file.tickets[ticket];
145
163
  if (!e) return { ok: false, error: `no dry run for ticket ${ticket}` };
146
164
  const g = e.guesses.find((x) => x.n === Number(n));
147
165
  if (!g) return { ok: false, error: `ticket ${ticket} has no guess ${n}` };
148
- const a = one(text, MAX_ANSWER);
166
+ if (keep && !g.default) return { ok: false, error: `guess ${n} of ticket ${ticket} has no default to keep: answer it with --text` };
167
+ const a = keep ? g.default : one(text, MAX_ANSWER);
149
168
  if (!a) return { ok: false, error: 'an answer needs some text' };
150
- g.answer = a; g.answeredAt = new Date(now == null ? Date.now() : now).toISOString();
169
+ g.answer = a; g.kept = !!keep; g.answeredAt = new Date(now == null ? Date.now() : now).toISOString();
151
170
  return { ok: true, guess: g };
152
171
  }
153
172
 
@@ -161,4 +180,4 @@ function write(file, data) {
161
180
  fs.renameSync(tmp, file);
162
181
  }
163
182
 
164
- module.exports = { MARK, parse, check, merge, blockOf, withBlock, gapsOf, countsOf, answer, found, plain, read, write };
183
+ module.exports = { MARK, parse, check, merge, blockOf, withBlock, gapsOf, countsOf, answer, askOf, found, plain, read, write };