create-pmos 0.654.0 → 0.656.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.
@@ -11,7 +11,7 @@
11
11
  * No model and no session: the drafts are the PRD's and the KR's own words, each claim cited with path:line and that line's text.
12
12
  *
13
13
  * THE DOOR. Every draft goes through lib/ai-guard.js file(): the kill switch (PMOS_AI, PMOS_AI_OUTCOMES, Settings), the citation check and the
14
- * audit. Its replay gate is per product (version `outcomes-1:<ws>`): before a product's first filing the server replays the drafts on that
14
+ * audit. Its replay gate is per product (version `outcomes-2:<ws>`): before a product's first filing the server replays the drafts on that
15
15
  * product's real records, with the guard's planted fabrications, and files nothing until that passed. The audit and the replay record live in
16
16
  * the per-user runtime folder, never in the repository.
17
17
  *
@@ -23,10 +23,18 @@
23
23
  * that says it did not work, files PMOS's next step under the ✦ (lib/outcomes.js refutedDrafts): stop it when the evidence meets the
24
24
  * kill condition, a new experiment after a second refuted check, else one more round. Class C (lib/autonomy.js): only the PM's ✓ does it.
25
25
  *
26
+ * A DUE CHECK (initiative outcome-checks-run-themselves, bet 1 of the factory line). Every tick in the hours the PM allows, PMOS judges each
27
+ * outcome whose check date passed (duePass, lib/outcome-judge.js): the anchor goal's own reading files a verdict ✦ (class B: recorded by
28
+ * itself with Undo); a goal PMOS failed to read twice the same way files ONE ask (class C); else one short run per initiative and check date
29
+ * reads the records (deps.startRun, <state>/outcome-runs.jsonl). What none of these can tell stays due, and Your move asks the PM once.
30
+ *
26
31
  * deps: { workspaces() → [w], isLead(w), stateDirFor(w), boardOf(w, id) → board id | null, runtime() → the per-user state folder, open(now),
27
- * env, every (ms, its own timer), mayRun(), warn(what, err) }
32
+ * env, every (ms, its own timer), mayRun(), warn(what, err),
33
+ * recordsDir(w)? → the goal records folder, startRun(w, { ini, board, it, why, now })? → { ok, run } | { ok: false, held?, error } }
28
34
  */
29
35
  const crypto = require('crypto');
36
+ const fs = require('fs');
37
+ const path = require('path');
30
38
  const O = require('./outcomes.js');
31
39
  const PR = require('./proposals.js');
32
40
 
@@ -36,12 +44,21 @@ const off = (env) => flagOff((env || process.env).PMOS_OUTCOMES);
36
44
  const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
37
45
  const guardLib = () => { try { return require('./ai-guard.js'); } catch { return null; } };
38
46
  const versionOf = (w) => O.VERSION + ':' + w.id;
39
- const typeOf = (d) => (d.data.kind === 'undated' ? 'date' : d.data.kind === 'refuted' ? 'refuted' : 'new');
47
+ const typeOf = (d) => (d.data.kind === 'undated' ? 'date' : d.data.kind === 'refuted' ? 'refuted' : d.data.kind === 'verdict' ? 'verdict' : d.data.kind === 'source' ? 'source' : 'new');
48
+ const J = require('./outcome-judge.js');
49
+ const RUNS = 'outcome-runs.jsonl'; // <state>/outcome-runs.jsonl: one line per outcome run started { ini, horizon, run, at }
50
+ const RUNS_PER_PASS = 1; // a backlog of due checks starts one run per pass (the machine runs at most 2 at once)
40
51
 
41
52
  /** The proposals line a draft becomes. */
42
53
  function lineOf(d, board, run) {
43
54
  const type = typeOf(d), ini = d.data.initiative;
44
55
  const sources = d.claims.flatMap((c) => c.sources).map((s) => ({ label: s.label, ref: s.ref }));
56
+ if (type === 'verdict' || type === 'source') {
57
+ // PMOS's own verdict (class B, with Undo) or the one ask for a goal it cannot read (class C): one per initiative and check date / goal
58
+ const items = type === 'verdict' ? [{ id: 'verdict', title: J.WORDS[d.data.disposition] || 'Checked' }] : [{ id: 'source', title: 'Connect the source, or pick another number' }];
59
+ const c = PR.clean('outcome', type, { title: d.title, why: d.say, sources, items, data: d.data });
60
+ return c.error ? null : { kind: 'propose', ini, board, run, id: PR.idOf(ini, 'outcome', type, type === 'verdict' ? d.data.horizon : d.data.rid), ...c.prop };
61
+ }
45
62
  if (type === 'refuted') {
46
63
  // one per check: a later refuted check files again (its key is the check's own line)
47
64
  const c = PR.clean('outcome', 'refuted', { title: d.title, why: d.say, sources, items: [{ id: 'next', title: O.NEXT_WORDS[d.data.next], ...(d.data.horizon ? { due: d.data.horizon } : {}) }], data: d.data });
@@ -73,7 +90,7 @@ function create(deps) {
73
90
  // a record that has its outcome now: its open draft goes (zero is silence)
74
91
  const has = new Map(S.subjects.map((it) => [it.id, it]));
75
92
  for (const p of F.props.values()) {
76
- if (p.group !== 'outcome' || p.type === 'refuted' || kept.has(p.id)) continue; // a refuted outcome's next step: refutedPass keeps it
93
+ if (p.group !== 'outcome' || p.type === 'refuted' || p.type === 'verdict' || p.type === 'source' || kept.has(p.id)) continue; // refutedPass and duePass keep theirs
77
94
  const it = has.get(p.ini), sig = PR.sigOf(p);
78
95
  if (F.drops.has(sig)) continue;
79
96
  if (!it || (it.metric && (p.type === 'new' || it.horizon))) PR.append(dir, { by: 'pmos:outcomes' }, { kind: 'drop', ini: p.ini, sig });
@@ -92,11 +109,11 @@ function create(deps) {
92
109
  const AG = guardLib(); if (!AG) return { ws: w.id, filed: 0, why: 'the shared guard is not installed' };
93
110
  const version = versionOf(w), run = 'oc' + now.toString(36) + crypto.randomBytes(3).toString('hex');
94
111
  if (!AG.off(O.JOB, { env: deps.env || process.env, settingsDir: rt }) && !AG.ready(rt, O.JOB, version)) {
95
- const rep = await AG.replay(O.JOB, version, cases(S, fresh.map((x) => x.d)), { root: w.root, stateDir: rt, max: PER_DAY });
112
+ const rep = await AG.replay(O.JOB, version, cases(S, fresh.map((x) => x.d)), { root: w.root, stateDir: rt, refDir: dir, max: PER_DAY });
96
113
  if (!rep.ok) { warn('outcomes replay ' + w.id, new Error(rep.failed.map((f) => f.name + ': ' + f.why).join('; '))); return { ws: w.id, filed: 0, replay: rep }; }
97
114
  }
98
115
  const byId = new Map(fresh.map((x) => [x.d.id, x]));
99
- const r = await AG.file({ job: O.JOB, version, run, root: w.root, stateDir: rt, settingsDir: rt, env: deps.env || process.env, max: PER_DAY }, fresh.map((x) => x.d),
116
+ const r = await AG.file({ job: O.JOB, version, run, root: w.root, stateDir: rt, refDir: dir, settingsDir: rt, env: deps.env || process.env, max: PER_DAY }, fresh.map((x) => x.d),
100
117
  async (acc) => { for (const p of acc) { const x = byId.get(p.id); const l = x && lineOf(x.d, x.board, run); if (l) PR.append(dir, { by: 'agent:outcomes' }, l); } });
101
118
  return { ws: w.id, filed: (r.filed || []).length, held: !!r.held, off: r.off || null };
102
119
  }
@@ -125,15 +142,78 @@ function create(deps) {
125
142
  const AG = guardLib(); if (!AG) return { ws: w.id, filed: 0, why: 'the shared guard is not installed' };
126
143
  const rt = deps.runtime && deps.runtime(), version = versionOf(w), run = 'or' + now.toString(36) + crypto.randomBytes(3).toString('hex');
127
144
  if (!AG.off(O.JOB, { env: deps.env || process.env, settingsDir: rt }) && !AG.ready(rt, O.JOB, version)) {
128
- const rep = await AG.replay(O.JOB, version, cases(S, fresh.map((x) => x.d)), { root: w.root, stateDir: rt, max: PER_DAY });
145
+ const rep = await AG.replay(O.JOB, version, cases(S, fresh.map((x) => x.d)), { root: w.root, stateDir: rt, refDir: dir, max: PER_DAY });
129
146
  if (!rep.ok) { warn('outcomes replay ' + w.id, new Error(rep.failed.map((f) => f.name + ': ' + f.why).join('; '))); return { ws: w.id, filed: 0, replay: rep }; }
130
147
  }
131
148
  const byId = new Map(fresh.map((x) => [x.d.id, x]));
132
- const r = await AG.file({ job: O.JOB, version, run, root: w.root, stateDir: rt, settingsDir: rt, env: deps.env || process.env, max: PER_DAY }, fresh.map((x) => x.d),
149
+ const r = await AG.file({ job: O.JOB, version, run, root: w.root, stateDir: rt, refDir: dir, settingsDir: rt, env: deps.env || process.env, max: PER_DAY }, fresh.map((x) => x.d),
133
150
  async (acc) => { for (const p of acc) { const x = byId.get(p.id); const l = x && lineOf(x.d, x.board, run); if (l) PR.append(dir, { by: 'agent:outcomes' }, l); } });
134
151
  return { ws: w.id, filed: (r.filed || []).length, held: !!r.held, off: r.off || null };
135
152
  }
136
153
 
154
+ /** The due checks (initiative outcome-checks-run-themselves): PMOS judges each one by itself (lib/outcome-judge.js). A goal's own reading
155
+ * that decides it files a verdict ✦ (class B: lib/auto-keep.js records it with Undo); a goal PMOS failed to read twice the same way files
156
+ * ONE ask; anything else starts one short outcome run per initiative and check date (deps.startRun → lib/proposal-runs.js why `outcome`).
157
+ * When neither decides, nothing more is filed: the check stays due and Your move asks the PM (lib/your-move.js verdictsOf). */
158
+ async function duePass(w, { now = Date.now() } = {}) {
159
+ const dir = deps.stateDirFor(w); if (!dir) return { ws: w.id, filed: 0, runs: 0 };
160
+ const S = O.scan(w.root, { today: localDay(now) });
161
+ const F = PR.read(dir), kept = PR.keptIds(F);
162
+ const dueBy = new Map(S.due.map((it) => [it.id, it]));
163
+ // a verdict or ask whose check is no longer due on its date (the PM answered it, or moved the date) goes: zero is silence
164
+ for (const p of F.props.values()) {
165
+ if (p.group !== 'outcome' || (p.type !== 'verdict' && p.type !== 'source') || kept.has(p.id) || F.drops.has(PR.sigOf(p))) continue;
166
+ const it = dueBy.get(p.ini);
167
+ if (!it || (p.data && p.data.horizon && p.data.horizon !== it.horizon)) PR.append(dir, { by: 'pmos:outcomes' }, { kind: 'drop', ini: p.ini, sig: PR.sigOf(p) });
168
+ }
169
+ if (!S.due.length) return { ws: w.id, filed: 0, runs: 0 };
170
+ const AG = guardLib(); if (!AG) return { ws: w.id, filed: 0, runs: 0, why: 'the shared guard is not installed' };
171
+ const rt = deps.runtime && deps.runtime();
172
+ const aiOff = AG.off(O.JOB, { env: deps.env || process.env, settingsDir: rt });
173
+ if (aiOff || off(deps.env)) return { ws: w.id, filed: 0, runs: 0, off: aiOff || 'PMOS_OUTCOMES is off' }; // the switch stops the verdicts and the runs
174
+ const GS = require('./goal-source.js');
175
+ let recordsDir = null; try { recordsDir = (deps.recordsDir && deps.recordsDir(w)) || GS.recordsDirOf(w.root); } catch { recordsDir = GS.recordsDirOf(w.root); }
176
+ let src = null; try { src = GS.source({ root: w.root, recordsDir }); } catch { src = null; }
177
+ const fresh = [], toRun = [];
178
+ const verdictFiled = (ini, horizon) => F.props.has(PR.idOf(ini, 'outcome', 'verdict', horizon));
179
+ for (const x of J.drafts(S, { src, recordsDir, stateDir: dir, refDir: dir })) {
180
+ const board = deps.boardOf(w, x.it.id); if (!board) continue;
181
+ if (x.draft) {
182
+ const l = lineOf(x.draft, board, '');
183
+ if (l && !F.props.has(l.id)) fresh.push({ d: x.draft, board }); // filed once: kept, dropped, undone or waiting, never again
184
+ }
185
+ if (x.judged.kind !== 'verdict' && !verdictFiled(x.it.id, x.it.horizon)) toRun.push({ it: x.it, board, why: x.judged.why });
186
+ }
187
+ let filed = 0, held = false;
188
+ if (fresh.length) {
189
+ const version = versionOf(w), run = 'ov' + now.toString(36) + crypto.randomBytes(3).toString('hex');
190
+ if (!AG.ready(rt, O.JOB, version)) {
191
+ const rep = await AG.replay(O.JOB, version, cases(S, fresh.map((x) => x.d)), { root: w.root, stateDir: rt, refDir: dir, max: PER_DAY });
192
+ if (!rep.ok) { warn('outcomes replay ' + w.id, new Error(rep.failed.map((f) => f.name + ': ' + f.why).join('; '))); return { ws: w.id, filed: 0, runs: 0, replay: rep }; }
193
+ }
194
+ const byId = new Map(fresh.map((x) => [x.d.id, x]));
195
+ const r = await AG.file({ job: O.JOB, version, run, root: w.root, stateDir: rt, refDir: dir, settingsDir: rt, env: deps.env || process.env, max: PER_DAY }, fresh.map((x) => x.d),
196
+ async (acc) => { for (const p of acc) { const x = byId.get(p.id); const l = x && lineOf(x.d, x.board, run); if (l) PR.append(dir, { by: 'agent:outcomes' }, l); } });
197
+ filed = (r.filed || []).length; held = !!r.held;
198
+ if (r.off) return { ws: w.id, filed, runs: 0, off: r.off }; // the AI switch is off: no run either
199
+ }
200
+ let runs = 0;
201
+ if (deps.startRun && toRun.length) {
202
+ const started = runsOf(dir);
203
+ for (const x of toRun) {
204
+ if (runs >= RUNS_PER_PASS) break;
205
+ const key = x.it.id + '|' + x.it.horizon;
206
+ if (started.has(key)) continue; // one run per initiative and check date: what it could not tell, the PM is asked
207
+ let r = null;
208
+ try { r = deps.startRun(w, { ini: x.it.id, board: x.board, it: x.it, why: x.why, now }); } catch (e) { warn('outcome run ' + w.id, e); r = null; }
209
+ if (!r || !r.ok) { if (r && r.held) break; continue; }
210
+ try { fs.mkdirSync(dir, { recursive: true }); fs.appendFileSync(path.join(dir, RUNS), JSON.stringify({ ini: x.it.id, horizon: x.it.horizon, run: r.run || null, at: new Date(now).toISOString() }) + '\n'); } catch (e) { warn('outcome runs ledger', e); }
211
+ runs++;
212
+ }
213
+ }
214
+ return { ws: w.id, filed, held, runs };
215
+ }
216
+
137
217
  async function tick({ now = Date.now() } = {}) {
138
218
  if (off(deps.env) || busy) return { off: off(deps.env), running: busy };
139
219
  busy = true;
@@ -144,8 +224,24 @@ function create(deps) {
144
224
  try { refuted.push(await refutedPass(w, { now })); } catch (e) { warn('outcomes refuted ' + w.id, e); }
145
225
  }
146
226
  } finally { busy = false; }
227
+ const due = await dueTick({ now });
147
228
  const r = await dailyTick({ now });
148
- return { ...r, refuted };
229
+ return { ...r, refuted, due };
230
+ }
231
+ /** Every tick in the hours the PM allows (deps.open): the due checks of each product (duePass). */
232
+ async function dueTick({ now = Date.now() } = {}) {
233
+ let open = true;
234
+ try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
235
+ if (!open || busy) return [];
236
+ busy = true;
237
+ const out = [];
238
+ try {
239
+ for (const w of deps.workspaces()) {
240
+ try { if (deps.isLead && !deps.isLead(w)) continue; } catch { continue; }
241
+ try { out.push(await duePass(w, { now })); } catch (e) { warn('outcomes due ' + w.id, e); }
242
+ }
243
+ } finally { busy = false; }
244
+ return out;
149
245
  }
150
246
  async function dailyTick({ now = Date.now() } = {}) {
151
247
  let open = true;
@@ -168,7 +264,15 @@ function create(deps) {
168
264
  const t = setInterval(() => { try { if (deps.mayRun && !deps.mayRun()) return; } catch { /* no lock: run */ } tick({}).catch((e) => warn('outcomes tick', e)); }, deps.every);
169
265
  if (t.unref) t.unref();
170
266
  }
171
- return { tick, runProduct, refutedPass };
267
+ return { tick, runProduct, refutedPass, duePass };
268
+ }
269
+
270
+ /** The outcome runs started, as `ini|horizon` keys (<state>/outcome-runs.jsonl). */
271
+ function runsOf(dir) {
272
+ const out = new Set();
273
+ let text = ''; try { text = fs.readFileSync(path.join(dir, RUNS), 'utf8'); } catch { return out; }
274
+ for (const l of text.split('\n')) { try { const o = JSON.parse(l); if (o && o.ini && o.horizon) out.add(o.ini + '|' + o.horizon); } catch { /* torn */ } }
275
+ return out;
172
276
  }
173
277
 
174
278
  /** The refuted outcomes whose ✦ next step still waits for the PM (launch simulation W6): every current refuted verdict, less the ones whose
@@ -191,4 +295,4 @@ function waiting(root, stateDir, { today } = {}) {
191
295
  return out;
192
296
  }
193
297
 
194
- module.exports = { create, cases, lineOf, off, waiting, PER_DAY };
298
+ module.exports = { create, cases, lineOf, off, waiting, runsOf, PER_DAY, RUNS };
@@ -26,7 +26,7 @@
26
26
  const fs = require('fs');
27
27
  const path = require('path');
28
28
 
29
- const VERSION = 'outcomes-1';
29
+ const VERSION = 'outcomes-2'; // 2: PMOS's own verdicts and the one ask for an unreadable source (outcome-checks-run-themselves)
30
30
  const JOB = 'outcomes';
31
31
  const DAY = 86400000;
32
32
  const DAYS_AFTER = 30;
@@ -80,6 +80,14 @@ function ledger(root, L, name) {
80
80
 
81
81
  /** The record's check date moved past the one a check answered: the check line's own horizon (written since launch simulation W2), else its
82
82
  * date. Then the outcome is open again. */
83
+ /** The outcome checks that stand: a line `{ initiative_id, undo: <at> }` (the PM's Undo of a verdict PMOS recorded by itself, undoCheck) takes the
84
+ * check with that `at` back, and is no check itself. → [row], ledger order */
85
+ function liveChecks(rows) {
86
+ const gone = new Set();
87
+ for (const r of rows || []) if (r && r.initiative_id && typeof r.undo === 'string' && r.undo) gone.add(r.initiative_id + '|' + r.undo);
88
+ return (rows || []).filter((r) => r && !r.undo && !(r.initiative_id && r.at && gone.has(r.initiative_id + '|' + r.at)));
89
+ }
90
+
83
91
  const reopened = (it, row) => !!(it.horizon && it.horizon > String(row.horizon || row.date || String(row.at || '').slice(0, 10)));
84
92
 
85
93
  const STOPPED = new Set(['paused', 'cancelled', 'canceled', 'stopped', 'dropped', 'archived', 'killed']);
@@ -104,7 +112,7 @@ function scan(root, { today = todayOf() } = {}) {
104
112
  let deleted = new Set();
105
113
  try { const D = require('./ini-deleted.js'); if (typeof D.idsOf === 'function') deleted = new Set(D.idsOf(root)); } catch { /* none */ }
106
114
  const disposedBy = new Map();
107
- for (const c of ledger(root, L, 'outcome_checks.jsonl')) if (c && c.initiative_id && DISPOSITIONS.includes(c.disposition)) disposedBy.set(String(c.initiative_id), c);
115
+ for (const c of liveChecks(ledger(root, L, 'outcome_checks.jsonl'))) if (c && c.initiative_id && DISPOSITIONS.includes(c.disposition)) disposedBy.set(String(c.initiative_id), c);
108
116
 
109
117
  const subjects = [], missing = [], undated = [], due = [], pending = [], disposed = [];
110
118
  let shippedWithout = 0;
@@ -375,9 +383,10 @@ function anyRefuted(root) {
375
383
  /** Every outcome check of the repository with its path:line, oldest first. → [{ row, ref, quote, file, n }] */
376
384
  function checkLines(root, L) {
377
385
  const files = [...new Set([path.join(L.runsDir, 'outcome_checks.jsonl'), path.join(root, 'pmos', 'state', 'outcome_checks.jsonl'), path.join(root, 'planning', 'runs', 'outcome_checks.jsonl')])];
378
- const out = [];
379
- for (const f of files) (linesOf(f) || []).forEach((l, i) => { let o = null; try { o = JSON.parse(l); } catch { return; } if (o && o.initiative_id && DISPOSITIONS.includes(o.disposition)) out.push({ row: o, file: f, n: i + 1, ref: rel(root, f) + ':' + (i + 1), quote: cut(l) }); });
380
- return out.sort((a, b) => String(a.row.at || a.row.date || '').localeCompare(String(b.row.at || b.row.date || '')));
386
+ const out = [], rows = [];
387
+ for (const f of files) (linesOf(f) || []).forEach((l, i) => { let o = null; try { o = JSON.parse(l); } catch { return; } if (o && o.initiative_id) rows.push(o); if (o && o.initiative_id && DISPOSITIONS.includes(o.disposition)) out.push({ row: o, file: f, n: i + 1, ref: rel(root, f) + ':' + (i + 1), quote: cut(l) }); });
388
+ const live = new Set(liveChecks(rows));
389
+ return out.filter((c) => live.has(c.row)).sort((a, b) => String(a.row.at || a.row.date || '').localeCompare(String(b.row.at || b.row.date || '')));
381
390
  }
382
391
 
383
392
  /** The verdict that stands on each initiative: its newest outcome check. A refuted one is CURRENT until the PM chose what next: a check date
@@ -462,7 +471,7 @@ function setLife(root, id, state, reason, actor) {
462
471
  /* ── the outcome ledger: the one writer behind `pmos outcomes record` ───────────────────────────────────────── */
463
472
 
464
473
  /** Append the PM's verdict. Evidence is required for all three (an `inconclusive` with no reason is the cheapest lie). */
465
- function recordCheck(root, { initiative, disposition, evidence, by, via }, { now = Date.now() } = {}) {
474
+ function recordCheck(root, { initiative, disposition, evidence, by, via, sources }, { now = Date.now() } = {}) {
466
475
  root = path.resolve(root);
467
476
  if (typeof initiative !== 'string' || !ID_RE.test(initiative)) return { ok: false, error: 'name the initiative by its id' };
468
477
  if (!DISPOSITIONS.includes(disposition)) return { ok: false, error: `the verdict is one of ${DISPOSITIONS.join(', ')}` };
@@ -479,11 +488,27 @@ function recordCheck(root, { initiative, disposition, evidence, by, via }, { now
479
488
  fs.mkdirSync(dir, { recursive: true });
480
489
  const st = (() => { try { return fs.lstatSync(file); } catch { return null; } })();
481
490
  if (st && !st.isFile()) return { ok: false, error: 'the outcome ledger is not a plain file — nothing was saved' };
482
- const line = { initiative_id: initiative, disposition, evidence: ev, date: todayOf(now), ...(it.horizon ? { horizon: it.horizon } : {}), at: new Date(now).toISOString(), by: by || 'agent:unknown', via: via || 'cli' };
491
+ const src = (Array.isArray(sources) ? sources : []).filter((x) => x && typeof x.ref === 'string' && x.ref).slice(0, 6).map((x) => ({ label: clip(x.label || x.ref, 80), ref: clip(x.ref, 200) }));
492
+ const line = { initiative_id: initiative, disposition, evidence: ev, date: todayOf(now), ...(it.horizon ? { horizon: it.horizon } : {}), ...(src.length ? { sources: src } : {}), at: new Date(now).toISOString(), by: by || 'agent:unknown', via: via || 'cli' };
483
493
  fs.appendFileSync(file, JSON.stringify(line) + '\n');
484
494
  return { ok: true, file: rel(root, file), line };
485
495
  } catch (e) { return { ok: false, error: 'the outcome ledger could not be written: ' + String((e && e.message) || e).slice(0, 160) }; }
486
496
  }
487
497
 
488
- module.exports = { VERSION, JOB, DAYS_AFTER, DEFAULT_DAYS, DISPOSITIONS, scan, drafts, prdMetric, anchorMetric, horizonFor, recordCheck, todayOf, short, frontOf,
498
+ /** Take back one check PMOS recorded by itself (the Undo of its ✦, lib/routes-proposals.js): an `undo` line naming the check's `at`. The check
499
+ * is never rewritten; liveChecks leaves it out, so the outcome is due again. → { ok, file } | { ok: false, error } */
500
+ function undoCheck(root, { initiative, at, by, via }, { now = Date.now() } = {}) {
501
+ root = path.resolve(root);
502
+ if (typeof initiative !== 'string' || !ID_RE.test(initiative)) return { ok: false, error: 'name the initiative by its id' };
503
+ if (typeof at !== 'string' || !at) return { ok: false, error: 'name the check by its time (at)' };
504
+ const L = layoutOf(root), file = path.join(L.runsDir, 'outcome_checks.jsonl');
505
+ try {
506
+ const st = (() => { try { return fs.lstatSync(file); } catch { return null; } })();
507
+ if (!st || !st.isFile()) return { ok: false, error: 'the outcome ledger is not there — nothing to undo' };
508
+ fs.appendFileSync(file, JSON.stringify({ initiative_id: initiative, undo: at, at: new Date(now).toISOString(), by: by || 'pm', via: via || 'ui' }) + '\n');
509
+ return { ok: true, file: rel(root, file) };
510
+ } catch (e) { return { ok: false, error: 'the outcome ledger could not be written: ' + String((e && e.message) || e).slice(0, 160) }; }
511
+ }
512
+
513
+ module.exports = { VERSION, undoCheck, liveChecks, JOB, DAYS_AFTER, DEFAULT_DAYS, DISPOSITIONS, scan, drafts, prdMetric, anchorMetric, horizonFor, recordCheck, todayOf, short, frontOf,
489
514
  experimentField, krMismatch, killMet, anyRefuted, verdictsOf, rowOutcomes, outcomeOfRow, refutedDrafts, setLife, NEXT_WORDS };
@@ -9,6 +9,9 @@
9
9
  * populate an initiative was just added (devPiRules 1): with no extra press, Claude looks for it in every connected source (the name, the
10
10
  * Why, the material and the people in it) and files what it finds as Found elsewhere. The New initiative panel's Create starts it
11
11
  * at once (POST /api/proposals/look); the tick starts it for every other way an initiative is made (a `created` placement line).
12
+ * outcome an outcome's check date passed and its goal's own reading did not decide it (lib/outcome-props.js duePass, once per initiative
13
+ * and check date): PMOS reads the initiative's records and files whether it worked with `pmos propose verdict`, each claim cited
14
+ * path:line with its quote, or nothing when it cannot tell (then Your move asks the PM). The verdict is class B: recorded with Undo.
12
15
  * check each morning inside the day-check window, once a day per initiative that has a late or at-risk task (devTpRules 1): Claude finds
13
16
  * WHY each one slipped (the stored reads, the calendar, meeting notes, chat, Jira status) and files its dates, "looks done" and
14
17
  * tidy names. A date that passes shows at once without a run: lib/proposals.js datesOf proposes from the tasks themselves, with
@@ -16,7 +19,7 @@
16
19
  *
17
20
  * WHAT THE RUN MAY DO (lib/headless.js kind `propose`): read and search the repository, read through the PM's own connectors where the PM's
18
21
  * Claude Code settings allow it, and file with `pmos propose`, pinned by the server to this initiative and run (PMOS_PROPOSE_FILE, _WS,
19
- * _BOARD, _INI, _RUN). It writes no task, no document and no stage: only the PM's ✓ does. Nothing is sent.
22
+ * _BOARD, _INI, _RUN; _ROOT is the repository its verdict's citations are checked in). It writes no task, no document and no stage: only the PM's ✓ does. Nothing is sent.
20
23
  *
21
24
  * At most 2 runs at once for the machine; one per initiative. A run that ends writes the `end` line; ■ Stop ends it at once.
22
25
  *
@@ -42,6 +45,7 @@ const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-'
42
45
  const WHY = {
43
46
  populate: 'The PM just added this initiative. It most likely already lives elsewhere: find it in every connected source and file what you find (Found elsewhere).',
44
47
  check: 'The morning check: some tasks are late or at risk. Find why each one slipped and file new dates, "looks done" and tidy names.',
48
+ outcome: 'Its outcome check date has passed and its goal\'s own reading did not decide it. Read its records and file whether it worked (`pmos propose verdict`), or file nothing when you cannot tell.',
45
49
  };
46
50
 
47
51
  function promptOf(skill, o) {
@@ -49,7 +53,9 @@ function promptOf(skill, o) {
49
53
  return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Why it runs: ${WHY[o.why] || WHY.check} (${o.why})\n- Today: ${o.today}\n`
50
54
  + `- Initiative: ${o.ini} · ${one(o.title, 140)}${o.intent ? '\n- Its Why: ' + one(o.intent, 600) : ''}\n- Its stage now: ${o.stage || 'the first stage'}\n`
51
55
  + `- Its workflow's stages, in order:\n${list((o.stages || []).map((s) => s.key + ' · ' + s.name), 'not known')}\n`
52
- + (o.why === 'check' ? `- Its late and at-risk tasks:\n${list(o.tasks, 'none')}\n` : `- The material the PM gave and the people named are in its record and its first questions (\`pmos initiative export ${o.ini}\`).\n`)
56
+ + (o.why === 'check' ? `- Its late and at-risk tasks:\n${list(o.tasks, 'none')}\n`
57
+ : o.why === 'outcome' && o.outcome ? `- Its expected outcome: ${one(o.outcome.metric, 400)}\n- Its check date: ${o.outcome.horizon}\n- Its anchor: ${one(o.outcome.anchor, 120) || 'none'}\n- Its record: ${one(o.outcome.record, 200)}\n- Why the goal's reading did not decide it: ${one(o.outcome.why, 300)}\n`
58
+ : `- The material the PM gave and the people named are in its record and its first questions (\`pmos initiative export ${o.ini}\`).\n`)
53
59
  + `- Dropped by the PM (do not file these again unless the evidence is new):\n${list(o.dropped, 'none')}\n`
54
60
  + (o.lessons && o.lessons.length ? `- What the PM said about your earlier proposals here, newest first (learn from it: file what they would keep):\n${list(o.lessons, 'none')}\n` : '')
55
61
  + '\nFile with `pmos propose` only (the server pins this initiative and run). Report each source as you read it with `pmos propose look`. Send nothing.';
@@ -94,7 +100,7 @@ function create(deps) {
94
100
  }
95
101
 
96
102
  /** Start one run now. → { ok, run } | { ok: false, error } */
97
- function start({ ws, board, ini, why = 'populate', press = true, now = Date.now() } = {}) {
103
+ function start({ ws, board, ini, why = 'populate', press = true, now = Date.now(), outcome = null } = {}) {
98
104
  if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { ok: false, error: 'PMOS\'s background runs are off (PMOS_PROPOSE or PMOS_HEADLESS)' };
99
105
  const w = (deps.workspaces() || []).find((x) => x.id === ws);
100
106
  if (!w) return { ok: false, error: 'no such workspace' };
@@ -111,13 +117,13 @@ function create(deps) {
111
117
  const lessons = PR.lessonsOf(lines, { ini, match: (p) => ['found', 'dates', 'status', 'names'].includes(p.group), n: 3, wide: true });
112
118
  let tasks = [];
113
119
  if (why === 'check') { try { const c = (deps.checks(w, localDay(now)) || []).find((x) => x.ini === ini); tasks = c ? c.tasks : []; } catch { tasks = []; } }
114
- const prompt = promptOf(skill, { run, why, ini, title: row.title || ini, intent: row.intent || '', stage: row.stage || '', stages: row.stages || [], today: localDay(now), tasks, dropped, lessons });
120
+ const prompt = promptOf(skill, { run, why, ini, title: row.title || ini, intent: row.intent || '', stage: row.stage || '', stages: row.stages || [], today: localDay(now), tasks, dropped, lessons, outcome });
115
121
  const go = press && deps.spawnNow ? deps.spawnNow : deps.spawn;
116
122
  active.set(run, { ws, ini, dir, session: null, why });
117
123
  let session = null;
118
124
  try {
119
- session = go({ name: (why === 'check' ? 'Task check · ' : 'Looking for · ') + one(row.title || ini, 60), ws, origin: `propose:${ws}:${ini}:${run}`, initialInput: prompt + '\r', initiative: ini,
120
- env: { PMOS_PROPOSE_FILE: PR.ledgerFile(dir), PMOS_PROPOSE_WS: ws, PMOS_PROPOSE_BOARD: board || '', PMOS_PROPOSE_INI: ini, PMOS_PROPOSE_RUN: run }, onDone: (r) => ended(run, r) });
125
+ session = go({ name: (why === 'check' ? 'Task check · ' : why === 'outcome' ? 'Outcome check · ' : 'Looking for · ') + one(row.title || ini, 60), ws, origin: `propose:${ws}:${ini}:${run}`, initialInput: prompt + '\r', initiative: ini,
126
+ env: { PMOS_PROPOSE_FILE: PR.ledgerFile(dir), PMOS_PROPOSE_WS: ws, PMOS_PROPOSE_BOARD: board || '', PMOS_PROPOSE_INI: ini, PMOS_PROPOSE_RUN: run, PMOS_PROPOSE_ROOT: w.root }, onDone: (r) => ended(run, r) });
121
127
  } catch (e) { warn('proposal run', e); }
122
128
  if (session && session.held) { active.delete(run); return { ok: false, held: true, error: 'PMOS is busy with other runs; it looks again in a minute' }; }
123
129
  // the look line lands before the run's first `pmos propose look` (the run starts reading after this returns)
@@ -86,7 +86,7 @@ const KINDS = new Set(['epoch', 'look', 'src', 'end', 'propose', 'drop', 'keep',
86
86
  const EXPIRE_DAYS = 14;
87
87
  const EXPIRE_WHY = 'No answer in 14 days, so I left it as it was.';
88
88
  const GROUPS = ['found', 'dates', 'status', 'names', 'outcome', 'description', 'build'];
89
- const TYPES = { found: ['stage', 'docs', 'tasks', 'link', 'maybe', 'unplaced'], dates: ['stage', 'task'], status: ['done'], names: ['tidy'], outcome: ['new', 'date', 'refuted'], description: ['new', 'enrich'], build: ['pr'] };
89
+ const TYPES = { found: ['stage', 'docs', 'tasks', 'link', 'maybe', 'unplaced'], dates: ['stage', 'task'], status: ['done'], names: ['tidy'], outcome: ['new', 'date', 'refuted', 'verdict', 'source'], description: ['new', 'enrich'], build: ['pr'] };
90
90
  const SOURCES = ['drive', 'docs', 'sheets', 'slides', 'jira', 'calendar', 'notes', 'mail', 'slack', 'confluence', 'chat', 'repo'];
91
91
  const SOURCE_NAMES = { drive: 'Drive and Slides', docs: 'Docs', sheets: 'Sheets', slides: 'Slides', jira: 'Jira', calendar: 'Calendar and meeting notes', notes: 'Meeting notes',
92
92
  mail: 'Gmail', slack: 'Slack', confluence: 'Confluence', chat: 'Chat', repo: 'This repository' };
@@ -186,6 +186,20 @@ function clean(group, type, input) {
186
186
  if (d.next === 'iterate' && !DAY_RE.test(str(d.horizon))) return { error: 'data.horizon is the new check date, YYYY-MM-DD' };
187
187
  Object.assign(data, { next: d.next, check: str(d.check), ref: one(d.ref, 200), evidence: one(d.evidence, 300), metric: one(d.metric, 300), anchor: one(d.anchor, 120), title: one(d.title, LIM.title),
188
188
  lane: one(d.lane, 40), work: one(d.work, 20), killMet: d.killMet === true ? true : d.killMet === false ? false : null, ...(d.next === 'iterate' ? { horizon: str(d.horizon) } : {}) });
189
+ } else if (group === 'outcome' && type === 'verdict') {
190
+ // PMOS's own verdict on a due outcome (initiative outcome-checks-run-themselves; lib/outcome-judge.js, or the outcome run's `pmos propose
191
+ // verdict`). Class B: applied by itself with Undo, it records the check in outcome_checks.jsonl (lib/outcomes.js recordCheck)
192
+ const d = isObj(input.data) ? input.data : {};
193
+ if (!['validated', 'refuted'].includes(d.disposition)) return { error: 'data.disposition is validated or refuted (when PMOS cannot tell, it files nothing: the PM is asked)' };
194
+ const evidence = one(d.evidence, 600);
195
+ if (evidence.length < 12) return { error: 'data.evidence says what shows it, at least 12 characters' };
196
+ if (!DAY_RE.test(str(d.horizon))) return { error: 'data.horizon is the check date it answers, YYYY-MM-DD' };
197
+ Object.assign(data, { disposition: d.disposition, evidence, horizon: str(d.horizon) });
198
+ } else if (group === 'outcome' && type === 'source') {
199
+ // the one ask for a goal PMOS cannot read (lib/outcome-judge.js): class C, ✓ adds a task for the PM
200
+ const d = isObj(input.data) ? input.data : {};
201
+ if (!str(d.rid)) return { error: 'data.rid names the goal record PMOS cannot read' };
202
+ Object.assign(data, { rid: one(d.rid, 80), goal: one(d.goal, 120), why: one(d.why, 300), repeats: Number.isInteger(d.repeats) ? d.repeats : 0, ...(DAY_RE.test(str(d.horizon)) ? { horizon: str(d.horizon) } : {}) });
189
203
  } else if (group === 'outcome') {
190
204
  const d = isObj(input.data) ? input.data : {};
191
205
  const metric = one(d.metric, 300), horizon = str(d.horizon);
@@ -19,7 +19,7 @@ const fs = require('fs');
19
19
  const PR = require('./proposals.js');
20
20
  const LP = require('./loose-proposals.js');
21
21
 
22
- const COMMANDS = { propose: ['look', 'found', 'date', 'done', 'name', 'status', 'loose'] };
22
+ const COMMANDS = { propose: ['look', 'found', 'date', 'done', 'name', 'verdict', 'status', 'loose'] };
23
23
  const USAGE = [
24
24
  'usage: pmos propose look|found|date|done|name|status — what PMOS proposes on an initiative, under its ✦',
25
25
  ' pmos propose look <source> --reading | --found <n> --what "<5 documents>" | --none',
@@ -34,6 +34,9 @@ const USAGE = [
34
34
  ' pmos propose done --json <file|-> { "why", "sources", "items": [{ "task" }] }',
35
35
  ' pmos propose name --json <file|-> { "why", "sources", "items": [{ "task", "to", "notes"? }] } verb first, sentence case, about 7 words,',
36
36
  ' the WBS number kept, no "+" and no brackets; the cut detail goes in notes',
37
+ ' pmos propose verdict --json <file|-> only in an outcome run: { "disposition": "worked" | "didnt-work" | "cant-tell", "evidence": "<one line>",',
38
+ ' "claims": [{ "text", "sources": [{ "label", "ref": "<path:line>", "quote": "<the text on that line>" }] }] } each quote is checked',
39
+ ' against its line; a claim that does not match is refused. cant-tell files nothing: the PM is asked.',
37
40
  ' pmos propose status',
38
41
  ' pmos propose loose link --json - { "initiative", "title", "why", "items": [{ "row" }] } rows that belong to one open initiative',
39
42
  ' pmos propose loose merge --json - { "into": "w:<item>", "why", "items": [{ "row": "c:<chat>" }] } a chat that doubles the PM\'s own item',
@@ -82,6 +85,37 @@ function readJson(src, stdin) {
82
85
  }
83
86
  const flag = (args, k) => { const i = args.indexOf('--' + k); return i >= 0 ? (args[i + 1] === undefined || args[i + 1].startsWith('--') ? true : args[i + 1]) : undefined; };
84
87
 
88
+ /** `pmos propose verdict`: the outcome run's verdict on a due check (initiative outcome-checks-run-themselves). Every claim's quote must be
89
+ * on its path:line in the repository (lib/ai-guard.js check) or nothing is filed. It files the class B verdict ✦; the server records it
90
+ * with Undo (lib/routes-proposals.js applyOne). "cant-tell" files nothing: the check stays due and Your move asks the PM. */
91
+ const VERDICT = { worked: 'validated', 'didnt-work': 'refuted', validated: 'validated', refuted: 'refuted' };
92
+ function verdict(args, { say, stdin, env, file, runId, ini, board, F, line }) {
93
+ const root = env.PMOS_PROPOSE_ROOT;
94
+ if (!root) { say('✗ pmos propose verdict is for PMOS\'s outcome run (the server pins PMOS_PROPOSE_ROOT)'); return 1; }
95
+ const jsonAt = args.indexOf('--json'), src = jsonAt >= 0 ? args[jsonAt + 1] : null;
96
+ if (!src) { say('usage: pmos propose verdict --json <file|->'); return 2; }
97
+ const r = readJson(src, stdin); if (r.error) { say('✗ ' + r.error); return 1; }
98
+ const b = r.body && typeof r.body === 'object' && !Array.isArray(r.body) ? r.body : {};
99
+ if (b.disposition === 'cant-tell' || b.disposition === 'inconclusive') { say('filed nothing: the check stays due and Your move asks the PM'); return 0; }
100
+ const disposition = VERDICT[b.disposition];
101
+ if (!disposition) { say('✗ refused: disposition is worked, didnt-work or cant-tell'); return 1; }
102
+ const O = require('./outcomes.js'), AG = require('./ai-guard.js'), J = require('./outcome-judge.js');
103
+ const it = O.scan(root).due.find((x) => x.id === ini);
104
+ if (!it) { say(`✗ refused: ${ini} has no outcome check due now`); return 1; }
105
+ const evidence = String(b.evidence || '').replace(/\s+/g, ' ').trim();
106
+ const c0 = AG.check({ id: 'outcome-verdict:' + ini, title: J.WORDS[disposition], say: evidence || '-', confidence: 'medium', cls: 'B', claims: b.claims }, { root, stateDir: require('path').dirname(file) });
107
+ if (!c0.ok) { say('✗ refused: ' + c0.errors.join('; ')); return 1; }
108
+ const sources = c0.p.claims.flatMap((c) => c.sources).filter((x) => x.verified).map((x) => ({ label: x.label, ref: x.ref }));
109
+ const why = `Its check date was ${O.short(it.horizon)}. ${evidence.replace(/[.\s]+$/, '')}. PMOS recorded "${disposition === 'validated' ? 'worked' : 'didn\'t work'}". Undo takes it back.`;
110
+ const c = PR.clean('outcome', 'verdict', { title: `${J.WORDS[disposition]}: ${it.title}`.slice(0, 120), why, sources, items: [{ id: 'verdict', title: J.WORDS[disposition] }], data: { disposition, evidence, horizon: it.horizon } });
111
+ if (c.error) { say('✗ refused: ' + c.error); return 1; }
112
+ const id = PR.idOf(ini, 'outcome', 'verdict', it.horizon);
113
+ if (F.props.has(id)) { say(`already ${id}: a verdict for this check date was filed before`); return 0; }
114
+ line({ kind: 'propose', ini, board, run: runId, id, ...c.prop });
115
+ say(`filed ${id} · outcome/verdict · ${disposition}`);
116
+ return 0;
117
+ }
118
+
85
119
  async function run(argv, { say = (s) => console.log(s), env = process.env, stdin } = {}) {
86
120
  const args = argv[0] === 'propose' ? argv.slice(1) : argv.slice();
87
121
  const verb = args[0];
@@ -114,6 +148,7 @@ async function run(argv, { say = (s) => console.log(s), env = process.env, stdin
114
148
  }
115
149
  const L = F.looks.get(ini);
116
150
  if (L && L.run === runId && L.stopped) { say('✗ the PM pressed Stop: file nothing more'); return 1; }
151
+ if (verb === 'verdict') return verdict(args, { say, stdin, env, file, runId, ini, board, F, line });
117
152
  const type = verb === 'found' ? args[1] : verb === 'date' ? 'stage' : verb === 'done' ? 'done' : 'tidy';
118
153
  const jsonAt = args.indexOf('--json'), src = jsonAt >= 0 ? args[jsonAt + 1] : null;
119
154
  if (!src) { say(`usage: pmos propose ${verb}${verb === 'found' ? ' <type>' : ''} --json <file|->`); return 2; }
@@ -0,0 +1,91 @@
1
+ 'use strict';
2
+ /* question-batch.js — the day's question list (initiative act-alone-only-with-a-source; A120 + A48 in pmos-ideas/proofs). The changes PMOS
3
+ * holds for want of a source (lib/source-guard.js) come to their owners as one question per owner per initiative, once a day, not one ask
4
+ * per change.
5
+ *
6
+ * questionsOf(held, { pm }) → [question] PURE. held: lib/routes-proposals.js heldOf. One per owner and initiative, the PM's first.
7
+ * today(stateDir, held, { day, pm }) → { day, questions, later } the list fixed for `day`: the first read of a day writes one line to
8
+ * <state>/question-days.jsonl with the proposal ids on it; later reads that day show only those (still held)
9
+ * ones. `later` counts the changes held since, which wait for the next day's list.
10
+ * LEDGER
11
+ *
12
+ * A question: { key, owner, toPm, ini, title, board, text, ids: [proposal id], n }. owner: the owner the plan names on the held work (a task's
13
+ * owner, or the dates proposal's `ask.owner`), else the PM. A question for a teammate is a draft for the PM to pass on: nothing is sent.
14
+ * An answered question leaves the list by itself: the PM's keep or drop closes the proposal, so heldOf no longer returns it. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+
18
+ const LEDGER = 'question-days.jsonl';
19
+ const MAX_IDS = 400;
20
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
21
+ const plural = (n, a, b) => n + ' ' + (n === 1 ? a : b);
22
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
23
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
24
+ const { KIND_NAMES } = require('./source-guard.js');
25
+ const md = (iso) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso || '')); return m ? +m[3] + ' ' + MON[+m[2] - 1] : ''; };
26
+
27
+ /** The owner of a held proposal: the first owner its items name, or the dates proposal's ask. '' when the plan names none. */
28
+ function ownerOf(p) {
29
+ const it = (p.items || []).find((x) => isObj(x) && x.owner);
30
+ return one((it && it.owner) || (isObj(p.ask) && p.ask.owner) || '', 60);
31
+ }
32
+
33
+ /** One line of what a held proposal asks. */
34
+ function partOf(p, hold) {
35
+ const items = (p.items || []).filter(isObj);
36
+ const first = items[0] || {};
37
+ const name = one(first.title || p.title || '', 80);
38
+ const kind = hold && hold.kinds && hold.kinds.length === 1 ? hold.kinds[0] : '';
39
+ const only = kind ? ` Only ${KIND_NAMES[kind] || 'one source'} says so.` : '';
40
+ if (p.group === 'dates' && (p.noReason || !kind)) {
41
+ const n = items.length;
42
+ return `${plural(n, 'task', 'tasks')} passed ${n === 1 ? 'its' : 'their'} date with no news${name ? ' (for example ' + name + ')' : ''}. Re-plan from today, or new dates?`;
43
+ }
44
+ if (p.group === 'dates') { const to = first.to && first.to.due; return `Move ${name || 'the work'}${to ? ' to ' + md(to) : ''}?${only}`; }
45
+ if (p.group === 'status') return `Is ${name || 'it'} done?${only || ' PMOS found no source.'}`;
46
+ if (p.group === 'names') return `Rename "${one(first.from || first.title || '', 60)}" to "${one(first.to || '', 60)}"?${only || ' PMOS found no source.'}`;
47
+ return `${one(p.title || p.why || 'A change', 120)}?${only || ' PMOS found no source.'}`;
48
+ }
49
+
50
+ /** One question per owner and initiative, the PM's first, then by initiative. PURE. */
51
+ function questionsOf(held, { pm = 'PM' } = {}) {
52
+ const by = new Map();
53
+ for (const h of held || []) {
54
+ if (!isObj(h) || !isObj(h.prop) || !h.ini) continue;
55
+ const o0 = ownerOf(h.prop), owner = /^pm:/.test(o0) ? '' : o0, key = (owner || '') + '|' + h.ini; // a task the PM owns (pm:<slug>) is the PM's
56
+ if (!by.has(key)) by.set(key, { key, owner: owner || pm, toPm: !owner, ini: h.ini, title: h.title || h.ini, board: h.board || '', parts: [], ids: [] });
57
+ const q = by.get(key);
58
+ q.ids.push(h.prop.id);
59
+ q.parts.push(partOf(h.prop, h.hold));
60
+ }
61
+ const out = [...by.values()].map((q) => {
62
+ const shown = q.parts.slice(0, 3), more = q.parts.length - shown.length;
63
+ return { key: q.key, owner: q.owner, toPm: q.toPm, ini: q.ini, title: q.title, board: q.board, ids: q.ids, n: q.ids.length,
64
+ text: shown.join(' ') + (more > 0 ? ` And ${plural(more, 'more change', 'more changes')}.` : '') };
65
+ });
66
+ return out.sort((a, b) => (a.toPm === b.toPm ? 0 : a.toPm ? -1 : 1) || a.title.localeCompare(b.title) || a.owner.localeCompare(b.owner));
67
+ }
68
+
69
+ function readDays(stateDir) {
70
+ let text = '';
71
+ try { text = fs.readFileSync(path.join(stateDir, LEDGER), 'utf8'); } catch { return []; }
72
+ const out = [];
73
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && typeof l.day === 'string' && Array.isArray(l.ids)) out.push(l); } catch { /* a torn line is skipped */ } }
74
+ return out;
75
+ }
76
+
77
+ /** The list fixed for `day`. The first read of a day writes its line; later reads that day keep it. */
78
+ function today(stateDir, held, { day, pm, now } = {}) {
79
+ const list = (held || []).filter((h) => isObj(h) && isObj(h.prop) && h.prop.id);
80
+ if (!day) return { day: '', questions: questionsOf(list, { pm }), later: 0 };
81
+ let fixed = stateDir ? readDays(stateDir).filter((l) => l.day === day).pop() : null;
82
+ if (!fixed && stateDir && list.length) {
83
+ fixed = { day, at: new Date(now == null ? Date.now() : now).toISOString(), ids: [...new Set(list.map((h) => h.prop.id))].slice(0, MAX_IDS) };
84
+ try { fs.mkdirSync(stateDir, { recursive: true }); fs.appendFileSync(path.join(stateDir, LEDGER), JSON.stringify(fixed) + '\n'); } catch { /* the list still shows; tomorrow tries again */ }
85
+ }
86
+ const on = new Set(fixed ? fixed.ids : []);
87
+ const mine = fixed ? list.filter((h) => on.has(h.prop.id)) : list;
88
+ return { day, questions: questionsOf(mine, { pm }), later: list.length - mine.length };
89
+ }
90
+
91
+ module.exports = { questionsOf, today, ownerOf, partOf, LEDGER };