create-pmos 0.751.0 → 0.752.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +32 -33
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/changelog.json +31 -0
  8. package/workspace/guide/cli.md +11 -0
  9. package/workspace/guide/home.md +3 -1
  10. package/workspace/guide/settings-and-switches.md +2 -2
  11. package/workspace/lib/autonomy.js +2 -1
  12. package/workspace/lib/driver-decide.js +8 -0
  13. package/workspace/lib/driver-needs.js +3 -20
  14. package/workspace/lib/driver-run.js +16 -1
  15. package/workspace/lib/driver.js +23 -11
  16. package/workspace/lib/line-cli.js +99 -0
  17. package/workspace/lib/line.js +231 -0
  18. package/workspace/lib/never-wait.js +144 -0
  19. package/workspace/lib/pmos-verbs.js +3 -0
  20. package/workspace/lib/routes-today-log.js +6 -3
  21. package/workspace/lib/today-log.js +21 -3
  22. package/workspace/package-lock.json +2 -2
  23. package/workspace/package.json +1 -1
  24. package/workspace/public/pm/cozy-today-app.js +17 -2
  25. package/workspace/public/pm/cozy-today-model.js +21 -3
  26. package/workspace/public/pm/cozy-today-view.js +4 -2
  27. package/workspace/public/pm/quiet-batch.js +111 -0
  28. package/workspace/public/pm/quiet-rows.js +130 -0
  29. package/workspace/public/pm/wf-page.css +2 -0
  30. package/workspace/public/pm/wf-page.js +38 -8
  31. package/workspace/test-lists/line.json +9 -0
  32. package/workspace/test-lists/never-wait-on-drafts.json +9 -0
  33. package/workspace/test-lists/quiet-rows.json +9 -0
@@ -0,0 +1,231 @@
1
+ 'use strict';
2
+ /* line.js — where each initiative of a product stands on its own workflow, and what moves it next (product line plan, slice 2;
3
+ * initiative pmos-line). Read-only: it never seeds a To finish task, moves an initiative or sends anything.
4
+ *
5
+ * place(input, now?) PURE → one initiative's place on the line:
6
+ * { id, title, workflow, station: { key, name, n, of } | null, live, ended, daysThere, since, quietDays, clock,
7
+ * missing: [text], next, flag: 'stuck' | 'moving' | 'waiting' | 'cant-tell', why, limit }
8
+ * input = { row, the Board's row (lib/routes-boards.js boardRow): wf, wfStage, wfStages, wfMap, oneStage, ended, end
9
+ * tasks: [{ state, from? }], the initiative's tasks (lib/stage-read.js tasksOf)
10
+ * moves: [{ at, to, via }], the Board moves and workflow switches of it (scripts/boards.js fold), oldest first
11
+ * jira: { fetchedAt, epics: [key], tickets: [{ key, category, updated? }] } | null
12
+ * activity: [ISO time] } dated lines that name it: ledger lines, ticket changes, its record's commits
13
+ * lineOf(root, { only?, now? }) → { ok, product, rows: [place answer], live, placed, ended } | { ok: false, error }
14
+ * summary(line) → { live, placed, percent }
15
+ *
16
+ * THE STATION IS THE INITIATIVE'S OWN WORKFLOW STAGE (D99), the one the Board and `pmos workflow of` show. Its exit items are the stage's
17
+ * To finish lines; a line is missing until its task is Done or Won't do. A stage with no To finish list has one exit item, its output;
18
+ * a stage whose output is Jira work lists its open tickets.
19
+ *
20
+ * RULE 1 OF THE PLAN: "can't tell" beats a guess. A station set by a Jira read older than STALE_DAYS, or an initiative with no dated
21
+ * record at all, is can't tell: never stuck. Waiting for capacity is never stuck either. Stuck limits are defaults (LIMITS), by the
22
+ * stage's key or name, else its category; a product's own limits are a later slice. */
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+ const { execFileSync } = require('child_process');
26
+
27
+ const DAY = 86400000;
28
+ const STALE_DAYS = 7;
29
+ const TICKET_QUIET_WORKDAYS = 3;
30
+ // Days a station may hold an initiative with no activity. 'tickets' = quiet Jira tickets decide; null = never stuck (waiting); 0 = closed.
31
+ const LIMITS = {
32
+ triage: 3, initiate: 3, 'done test': 3, discover: 15, discovery: 15, plan: 5, prioritize: null, prioritise: null,
33
+ build: 'tickets', implementation: 'tickets', execute: 'tickets', pulls: 'tickets', 'pull requests': 'tickets', ci: 'tickets', merge: 'tickets',
34
+ deliver: 3, release: 3, monitor: 14, evaluate: 7, evaluation: 7, close: 7, closed: 0,
35
+ };
36
+ const CAT_LIMIT = { todo: 3, doing: 15, done: 7 };
37
+ const DONE_STATES = new Set(['done', "won't do", 'wont do', 'archived']);
38
+ const CAPACITY = /\b(prioriti[sz]\w*|capacity|slot)\b/i;
39
+ const CLOSED_NAME = /^(closed|complete[d]?)$/i;
40
+
41
+ const lc = (s) => String(s || '').trim().toLowerCase();
42
+ const ms = (t) => { const v = Date.parse(t || ''); return Number.isFinite(v) ? v : null; };
43
+ const days = (from, to) => Math.max(0, Math.floor((to - from) / DAY));
44
+ function workdays(from, to) {
45
+ let n = 0;
46
+ for (let t = from + DAY; t <= to; t += DAY) { const d = new Date(t).getUTCDay(); if (d !== 0 && d !== 6) n++; }
47
+ return n;
48
+ }
49
+ function limitOf(st) {
50
+ if (!st) return 15;
51
+ for (const k of [lc(st.key), lc(st.name)]) if (Object.prototype.hasOwnProperty.call(LIMITS, k)) return LIMITS[k];
52
+ return CAT_LIMIT[st.cat] != null ? CAT_LIMIT[st.cat] : 15;
53
+ }
54
+
55
+ /** The exit items still missing on the current stage. → [text] */
56
+ function missingOf(st, row, tasks, jira) {
57
+ const finish = Array.isArray(st.finish) ? st.finish.filter((f) => typeof f === 'string' && f.trim()) : [];
58
+ if (finish.length) {
59
+ const map = row.wfMap || {};
60
+ const mine = (k) => k === st.key || map[k] === st.key;
61
+ return finish.filter((f) => !(tasks || []).some((t) => t && t.from && mine(t.from.stage) && t.from.finish === f && DONE_STATES.has(lc(t.state))));
62
+ }
63
+ const out = st.output || {};
64
+ if (out.kind === 'jira' && jira && Array.isArray(jira.tickets) && jira.tickets.length) {
65
+ const epics = new Set((jira.epics || []).map((k) => String(k).toUpperCase()));
66
+ const tk = jira.tickets.filter((t) => !epics.has(String(t.key).toUpperCase()));
67
+ const open = tk.filter((t) => t.category !== 'done');
68
+ if (!open.length) return [];
69
+ return [`${open.length} of ${tk.length} tickets open (${open.slice(0, 5).map((t) => t.key).join(', ')}${open.length > 5 ? ', …' : ''})`];
70
+ }
71
+ return [out.name ? String(out.name).trim() : `what finishes ${st.name}`];
72
+ }
73
+
74
+ function place(input, now = Date.now()) {
75
+ const { row, tasks = [], moves = [], jira = null, activity = [] } = input || {};
76
+ const one = row.oneStage || {};
77
+ const base = { id: row.id, title: row.title || row.id, workflow: row.wf ? row.wf.name : null };
78
+ const endWord = row.ended ? (row.ended.as === 'wontdo' ? "Won't do" : 'Archived') : row.archived ? 'Archived'
79
+ : one.stage === 'shipped' ? 'Shipped' : one.stage === 'cancelled' ? 'Cancelled' : null;
80
+ const st0 = row.wfStage || null;
81
+ const st = st0 ? { ...((row.wfStages || []).find((s) => s.key === st0.key) || {}), ...st0 } : null;
82
+ const station = st ? { key: st.key, name: st.name, n: st.n, of: st.of } : null;
83
+ if (endWord || (st && CLOSED_NAME.test(String(st.name || '')))) {
84
+ return { ...base, station, live: false, ended: endWord || st.name, daysThere: null, since: null, quietDays: null, clock: null, missing: [], next: null, flag: null, why: 'ended', limit: null };
85
+ }
86
+ if (!st) return { ...base, station: null, live: true, ended: null, daysThere: null, since: null, quietDays: null, clock: null, missing: [], next: null, flag: 'cant-tell', why: 'no workflow stage', limit: null };
87
+
88
+ // the clock: what put it on this station, else the last dated activity
89
+ const here = (to) => { const t = lc(to); return t === lc(st.key) || t === lc(st.name); };
90
+ const lastMove = [...moves].reverse().find((m) => m && here(m.to) && ms(m.at));
91
+ let since = null, setBy = null;
92
+ if (one.setBy === 'pm' && ms(one.readAt) && one.stage !== 'on-hold') { since = ms(one.readAt); setBy = one.source || 'your word'; }
93
+ if (lastMove && (!since || ms(lastMove.at) > since)) { since = ms(lastMove.at); setBy = lastMove.via === 'move' ? 'a Board move' : 'a workflow change'; }
94
+ const acts = activity.map(ms).filter((x) => x != null && x <= now + DAY);
95
+ const tickets = jira && Array.isArray(jira.tickets) ? jira.tickets : [];
96
+ for (const t of tickets) { const u = ms(t.updated); if (u != null) acts.push(u); }
97
+ const last = acts.length ? Math.max(...acts) : null;
98
+ const daysThere = since != null ? days(since, now) : null;
99
+ const quietDays = last != null ? days(last, now) : null;
100
+ const clock = daysThere != null ? daysThere : quietDays;
101
+
102
+ const missing = missingOf(st, row, tasks, jira);
103
+ const stages = row.wfStages || [];
104
+ const idx = stages.findIndex((s) => s.key === st.key);
105
+ const nextStage = stages.slice(idx + 1).find((s) => s.status !== 'skipped');
106
+ const limit = limitOf(st);
107
+ const capacityOnly = limit === null || (missing.length > 0 && missing.every((m) => CAPACITY.test(m)));
108
+ let next;
109
+ if (one.stage === 'on-hold') next = 'resume when the PM takes it off hold';
110
+ else if (capacityOnly && missing.length) next = `wait for a capacity slot: ${missing[0]}`;
111
+ else if (missing.length) next = `finish: ${missing[0]}`;
112
+ else next = nextStage ? `move to ${nextStage.name}` : 'close it';
113
+
114
+ const out = { ...base, station, live: true, ended: null, daysThere, since: since != null ? new Date(since).toISOString() : null, setBy,
115
+ quietDays, clock, missing, next, limit: limit === 'tickets' ? `${TICKET_QUIET_WORKDAYS} working days with no ticket change` : limit };
116
+ const flag = (f, why) => ({ ...out, flag: f, why });
117
+
118
+ if (one.stage === 'on-hold') return flag('waiting', 'on hold: the clock is stopped');
119
+ if (capacityOnly) return flag('waiting', 'waiting for capacity is never stuck');
120
+ if (one.setBy === 'jira' && jira && ms(jira.fetchedAt) != null && days(ms(jira.fetchedAt), now) > STALE_DAYS)
121
+ return flag('cant-tell', `the Jira read is ${days(ms(jira.fetchedAt), now)} days old`);
122
+ if (limit === 'tickets' && tickets.length) {
123
+ const epics = new Set((jira.epics || []).map((k) => String(k).toUpperCase()));
124
+ const open = tickets.filter((t) => !epics.has(String(t.key).toUpperCase()) && t.category !== 'done');
125
+ const upd = tickets.map((t) => ms(t.updated)).filter((x) => x != null);
126
+ const end = ms(row.end);
127
+ if (open.length && end != null && end + DAY < now) return flag('stuck', `the planned end ${row.end} passed with ${open.length} tickets open`);
128
+ if (upd.length) {
129
+ const q = workdays(Math.max(...upd), now);
130
+ if (open.length && q > TICKET_QUIET_WORKDAYS) return flag('stuck', `no ticket changed in ${q} working days`);
131
+ return flag('moving', open.length ? `a ticket changed ${q} working days ago` : 'every ticket is done');
132
+ }
133
+ }
134
+ const lim = limit === 'tickets' ? 15 : limit;
135
+ if (clock == null) return flag('cant-tell', 'no dated record says when it got here or last moved');
136
+ if (clock <= lim) return flag('moving', daysThere != null ? `${daysThere} of ${lim} days on this station` : `last activity ${quietDays} days ago`);
137
+ if (quietDays != null && quietDays <= lim) return flag('moving', `${daysThere} days here, but activity ${quietDays} days ago`);
138
+ return flag('stuck', daysThere != null ? `${daysThere} days on this station, past ${lim}, with no activity since` : `quiet ${quietDays} days, past ${lim}`);
139
+ }
140
+
141
+ /* ── reading a repository ─────────────────────────────────────────────────────────────────────────────────────────────── */
142
+ const ID_FIELDS = ['initiative', 'initiative_id', 'init', 'ini', 'id'];
143
+ // Ledgers whose lines are not progress on the work: PMOS's own proposals wait for the PM (a draft nobody kept moves nothing), the
144
+ // Driver's run log and the folder scan record that a run looked. A task, a Board move, a plan item, a run or a ticket change counts.
145
+ const NOT_PROGRESS = new Set(['proposals.jsonl', 'driver.jsonl', 'scan.jsonl', 'claims.jsonl', 'use-log.jsonl', 'initiative-layout.jsonl', 'forecast.jsonl']);
146
+ // lines that only record a read or a view are not activity on the work
147
+ const READ_KINDS = /(^|[-_])(read|reads|seen|view|views|snapshot|scan|lead|digest|open|opened|stage-judge)($|[-_])/i;
148
+ /** id → [ISO time]: every dated ledger line that names an initiative, in the state folder and planning/runs. */
149
+ function activityIndex(dirs, ids) {
150
+ const out = new Map([...ids].map((id) => [id, []]));
151
+ for (const dir of dirs) {
152
+ let files = [];
153
+ try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl') && !NOT_PROGRESS.has(f)); } catch { continue; }
154
+ for (const f of files) {
155
+ let txt = '';
156
+ try { txt = fs.readFileSync(path.join(dir, f), 'utf8'); } catch { continue; }
157
+ for (const line of txt.split('\n')) {
158
+ if (!line || line[0] !== '{') continue;
159
+ let e; try { e = JSON.parse(line); } catch { continue; }
160
+ const at = e.at || e.ts || e.time || e.created_at;
161
+ if (typeof at !== 'string' || READ_KINDS.test(String(e.kind || e.type || ''))) continue;
162
+ for (const k of ID_FIELDS) { const v = e[k]; if (typeof v === 'string' && out.has(v)) { out.get(v).push(at); break; } }
163
+ }
164
+ }
165
+ }
166
+ return out;
167
+ }
168
+ /** The commit times of a file, or [] when the repository has no real history (one import commit is not history). */
169
+ function gitTimes(root, rel, real) {
170
+ if (!real || !rel) return [];
171
+ try { return execFileSync('git', ['log', '--format=%cI', '-n', '20', '--', rel], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).split('\n').filter(Boolean); }
172
+ catch { return []; }
173
+ }
174
+ function realHistory(root) {
175
+ try { return Number(execFileSync('git', ['rev-list', '--count', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()) > 1; }
176
+ catch { return false; }
177
+ }
178
+
179
+ function lineOf(root, { only = null, now = Date.now() } = {}) {
180
+ const SR = require('./stage-read.js');
181
+ const boards = require('./routes-boards.js');
182
+ const rowsLib = require('./initiative-rows.js');
183
+ const { w, ctx } = SR.cliCtx(root);
184
+ const stateDir = ctx.stateDirFor();
185
+ if (!stateDir) return { ok: false, error: 'this repository has no PMOS state folder (pmos/state, state or .pmos)' };
186
+ const was = rowsLib.setBackground(false);
187
+ try {
188
+ try { rowsLib.deriveNow(root); } catch { /* baseRows says what could not be read */ }
189
+ const pass = { ...ctx, boardsPass: new Map() };
190
+ const base = boards.baseRows(w, pass);
191
+ if (!base.ok) return { ok: false, error: base.error || 'the initiative records could not be read' };
192
+ let ids = base.rows.map((r) => r.id);
193
+ if (only) { if (!ids.includes(only)) return { ok: false, error: `no initiative ${only} on a board of this workspace` }; ids = [only]; }
194
+ const folded = boards.foldOf(pass, w);
195
+ const acts = activityIndex([stateDir, path.join(root, 'planning', 'runs')], new Set(ids));
196
+ const real = realHistory(root);
197
+ let JS = null; try { JS = require('./jira-status.js'); } catch { JS = null; }
198
+ let JT = null; try { JT = require('./jira-tickets.js'); } catch { JT = null; }
199
+ const rows = [];
200
+ for (const id of ids) {
201
+ const r = boards.initiativeWorkflow(pass, w, id);
202
+ if (!r.ok) continue;
203
+ const b0 = base.rows.find((x) => x.id === id) || {};
204
+ let tasks = []; try { tasks = SR.tasksOf(pass, w, id); } catch { tasks = []; }
205
+ const moves = (folded.moves || []).filter((m) => m.id === id && m.board === r.board.id)
206
+ .map((m) => ({ ...m, at: require('./status-when.js').realAt(m) }));
207
+ let jira = null;
208
+ if (JS) {
209
+ try {
210
+ const snap = JS.readSnapshot(root, id);
211
+ if (snap && snap.tickets && snap.tickets.size) {
212
+ jira = { fetchedAt: snap.fetchedAt || null, epics: JT ? JT.epicKeysOf(root, id) : (r.row.epics || []),
213
+ tickets: [...snap.tickets.values()].map((t) => ({ key: t.key, category: t.category || 'todo', updated: t.updated || null })) };
214
+ }
215
+ } catch { jira = null; }
216
+ }
217
+ const recRel = typeof b0.record === 'string' ? path.relative(root, path.resolve(root, b0.record)) : null;
218
+ const activity = (acts.get(id) || []).concat(gitTimes(root, recRel, real));
219
+ rows.push(place({ row: r.row, tasks, moves, jira, activity }, now));
220
+ }
221
+ const live = rows.filter((x) => x.live);
222
+ return { ok: true, product: path.basename(root), rows, live: live.length, placed: live.filter((x) => x.station && x.next).length, ended: rows.length - live.length };
223
+ } finally { rowsLib.setBackground(was); }
224
+ }
225
+
226
+ function summary(line) {
227
+ const live = line.live || 0, placed = line.placed || 0;
228
+ return { live, placed, percent: live ? Math.round((placed / live) * 1000) / 10 : 0 };
229
+ }
230
+
231
+ module.exports = { place, lineOf, summary, missingOf, limitOf, activityIndex, LIMITS, STALE_DAYS };
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+ /* never-wait.js — PMOS never waits on its own drafts (initiative never-wait-on-drafts; rule 3 of the product line plan, slice 1).
3
+ *
4
+ * An open Driver draft (lib/driver.js proposal) used to hold its target: the sweep started no new run on it until the PM decided, and the
5
+ * D106 auto apply ran only once, when the draft was filed. Now every open draft goes one of four ways, each with Undo:
6
+ *
7
+ * apply class A or B (lib/autonomy.js DRIVER_CLASS), cites a source, has an Undo writer (lib/driver-decide.js UNDOABLE): applied by
8
+ * itself through lib/driver-decide.js autoApply, also when it was filed earlier. The kill switch, the mode, a demotion, "Ask
9
+ * first" and no-source-no-auto still hold there; a draft they hold is a question (below).
10
+ * default a question: a draft PMOS may not apply by itself and that only changes PMOS's own records (no source, no Undo writer, or held
11
+ * by a rule above). After DEFAULT_DAYS PMOS takes the safe answer, "leave the record as it is": one `default` line closes the
12
+ * draft, nothing is written, and one `applied` line for `driver:default` puts it in PMOS did with Undo. Undo reopens the draft
13
+ * and it never defaults again.
14
+ * lapse class C (a stage move others read, a message to a person): it waits for the PM in the daily batch. After LAPSE_DAYS one
15
+ * `lapse` line closes it as "not sent": nothing is written or sent. Undo reopens it for another LAPSE_DAYS.
16
+ * wait younger than its deadline.
17
+ * A board in mode off or shadow is left alone. `pmos ai off` and PMOS_AUTONOMY=off stop defaults and lapses too.
18
+ *
19
+ * DEFAULT_DAYS · LAPSE_DAYS · DEFAULT_JOB · LAPSE_JOB
20
+ * classify(state, { now }) PURE → [{ id, way: apply|default|lapse|wait, cls, due }]
21
+ * heldTargets(state) PURE → [target key] targets whose agent blocker of the latest sweep day woke nothing while a
22
+ * draft was open on them (the health number; 0 is the goal)
23
+ * step({ file, stateDir, product, ctx, now, env, settingsDir, log }) → Promise of { applied, defaulted, lapsed } one ledger, once per sweep
24
+ * CLI: node lib/never-wait.js held <state folder> prints the held targets, the count on the last line
25
+ */
26
+ const D = require('./driver.js');
27
+
28
+ const DEFAULT_DAYS = 2;
29
+ const LAPSE_DAYS = 7;
30
+ const DEFAULT_JOB = 'driver:default';
31
+ const LAPSE_JOB = 'driver:lapse';
32
+ const DEFAULT_BY = 'pmos:default';
33
+ const LAPSE_BY = 'pmos:lapse';
34
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
35
+ const md = (ms) => { const d = new Date(ms); return `${d.getUTCDate()} ${MON[d.getUTCMonth()]}`; };
36
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
37
+
38
+ const A = () => require('./autonomy.js');
39
+ const UNDOABLE = () => require('./driver-decide.js').UNDOABLE;
40
+ const sinceOf = (p) => Date.parse(p.reopened_at || p.at);
41
+
42
+ /** How each open draft goes now. PURE. */
43
+ function classify(state, { now = Date.now() } = {}) {
44
+ const out = [];
45
+ for (const p of D.openProposals(state)) {
46
+ const since = sinceOf(p);
47
+ const cls = A().classOfDriver(p.what);
48
+ if (cls === 'C') {
49
+ const due = Number.isFinite(since) ? since + LAPSE_DAYS * D.DAY : null;
50
+ out.push({ id: p.id, cls, way: due != null && now >= due ? 'lapse' : 'wait', due });
51
+ continue;
52
+ }
53
+ const sourced = require('./source-guard.js').citedOf(p).length > 0;
54
+ if (sourced && UNDOABLE().has(p.what)) { out.push({ id: p.id, cls, way: 'apply', due: null }); continue; }
55
+ const due = Number.isFinite(since) ? since + DEFAULT_DAYS * D.DAY : null;
56
+ out.push({ id: p.id, cls, way: !p.no_default && due != null && now >= due ? 'default' : 'wait', due });
57
+ }
58
+ return out;
59
+ }
60
+
61
+ /** The targets the old rule still holds: an agent blocker of the latest sweep day with no wake, on a target with an open draft. PURE. */
62
+ function heldTargets(state) {
63
+ const days = state.blockers.map((b) => b.day).filter(Boolean).sort();
64
+ const day = days[days.length - 1];
65
+ if (!day) return [];
66
+ const open = new Set(D.openProposals(state).map((p) => D.targetKey(p.target)));
67
+ const out = new Set();
68
+ for (const b of state.blockers) {
69
+ if (b.day !== day || b.owner !== 'agent' || !b.target) continue;
70
+ const k = D.targetKey(b.target);
71
+ if (open.has(k) && !state.wakeKeys.has(`stuck:${b.key}:${day}`)) out.add(k);
72
+ }
73
+ return [...out];
74
+ }
75
+
76
+ /** The board a draft's target is on, for its mode: Work is `work`; an initiative takes the board of its latest run. */
77
+ function boardOf(state, target) {
78
+ if (target.kind === 'work') return 'work';
79
+ const runs = [...state.runs.values()].filter((r) => D.targetKey(r.target) === D.targetKey(target) && r.board);
80
+ return runs.length ? runs[runs.length - 1].board : null;
81
+ }
82
+
83
+ const actorOf = (p) => {
84
+ const actor = require('./actor.js');
85
+ const a = { by: typeof p.by === 'string' ? p.by : 'agent:unknown', via: 'cli' };
86
+ return actor.isAgent(a) ? a : { by: 'agent:unknown', via: 'cli' };
87
+ };
88
+ const nameOf = (p) => `${String(p.what || 'draft').replace(/-/g, ' ')} on ${p.target.id}`;
89
+
90
+ /** One ledger, once per sweep. Never throws; each refusal leaves the draft as it is. */
91
+ async function step({ file, stateDir, product = null, ctx = {}, now = Date.now(), env = process.env, settingsDir = null, log = console.error } = {}) {
92
+ const out = { applied: 0, defaulted: 0, lapsed: 0 };
93
+ if (!file || !stateDir) return out;
94
+ const say = (s) => { try { log(`[never-wait] ${s}`); } catch { /* a log never stops the step */ } };
95
+ let state = D.fold(D.readLines(file));
96
+ const plan = classify(state, { now });
97
+ if (!plan.length) return out;
98
+ const killed = A().killed({ env, settingsDir });
99
+ const decideLib = require('./driver-decide.js');
100
+ for (const x of plan) {
101
+ if (x.way === 'wait') continue;
102
+ state = D.fold(D.readLines(file));
103
+ const p = state.proposals.get(x.id);
104
+ if (!p || p.state !== 'open') continue;
105
+ const mode = D.modeOf(state, boardOf(state, p.target));
106
+ if (mode === 'off' || mode === 'shadow') continue;
107
+ const ini = p.target.kind === 'initiative' ? p.target.id : null;
108
+ if (x.way === 'apply') {
109
+ const r = await decideLib.autoApply({ file, proposal: p.id, actor: actorOf(p), ctx: { ...ctx, settingsDir }, now, stateDir, product, mode });
110
+ if (r.applied) { out.applied++; say(`applied ${p.id} (${nameOf(p)}) on ${product || '*'}: class ${r.cls}, with Undo`); continue; }
111
+ // held by a rule (mode, demotion, Ask first, a PM edit): it is a question now, with the same 2-day default
112
+ const due = sinceOf(p) + DEFAULT_DAYS * D.DAY;
113
+ if (p.no_default || !(now >= due)) continue;
114
+ x.way = 'default'; x.due = due;
115
+ }
116
+ if (killed) continue;
117
+ if (x.way === 'default') {
118
+ const dec = A().decide({ stateDir, job: DEFAULT_JOB, product, cls: 'B', mode: 'auto', undoable: true, now, env, settingsDir });
119
+ if (!dec.apply) continue;
120
+ const why = `No answer by ${md(x.due)}, so PMOS left it as it was.`;
121
+ D.append(file, { ev: 'default', proposal: p.id, why, by: DEFAULT_BY }, { now });
122
+ A().recordApplied(stateDir, { job: DEFAULT_JOB, product, ref: p.id, title: `Left ${nameOf(p)} as it was: nobody answered by ${md(x.due)}`, cls: 'B', ini, why,
123
+ src: [`Unanswered draft, due ${new Date(x.due).toISOString().slice(0, 10)}`] }, { now, settingsDir });
124
+ out.defaulted++; say(`defaulted ${p.id} (${nameOf(p)}) on ${product || '*'}: left as it was`);
125
+ } else if (x.way === 'lapse') {
126
+ const why = `Nobody sent it within ${LAPSE_DAYS} days, so PMOS did not send it.`;
127
+ D.append(file, { ev: 'lapse', proposal: p.id, why, by: LAPSE_BY }, { now });
128
+ A().recordApplied(stateDir, { job: LAPSE_JOB, product, ref: p.id, title: `Not sent: ${nameOf(p)}, waited ${LAPSE_DAYS} days`, cls: 'B', ini, why,
129
+ src: [`Waited ${LAPSE_DAYS} days in the daily batch`] }, { now, settingsDir });
130
+ out.lapsed++; say(`lapsed ${p.id} (${nameOf(p)}) on ${product || '*'}: not sent`);
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+
136
+ module.exports = { DEFAULT_DAYS, LAPSE_DAYS, DEFAULT_JOB, LAPSE_JOB, DEFAULT_BY, LAPSE_BY, classify, heldTargets, step };
137
+
138
+ if (require.main === module) {
139
+ const [verb, dir] = process.argv.slice(2);
140
+ if (verb !== 'held' || !dir) { console.log('usage: node lib/never-wait.js held <state folder>'); process.exit(2); }
141
+ const held = heldTargets(D.fold(D.readLines(D.ledgerFile(dir))));
142
+ for (const k of held) console.log(k);
143
+ console.log(held.length);
144
+ }
@@ -145,6 +145,9 @@ const VERBS = Object.freeze({
145
145
  // Not a pm-os-absorb verb (run: null): initiative standing-rules-list (bet A470) added it through the same table.
146
146
  rules: Object.freeze({ module: 'rules-cli.js', run: null, guide: 'cli.md',
147
147
  help: 'pmos rules [edit|retire|restore|count] — the standing rules PMOS learned from your corrections: where each came from, times fired, last fired (pmos rules help)' }),
148
+ // Not a pm-os-absorb verb (run: null): initiative pmos-line (product line plan, slice 2) added it through the same table.
149
+ line: Object.freeze({ module: 'line-cli.js', run: null, guide: 'cli.md',
150
+ help: 'pmos line [<initiative>|count] — where each initiative stands on its own workflow: days there, what is missing, the next move, stuck or not (pmos line help)' }),
148
151
  // Not a pm-os-absorb verb (run: null): initiative three-line-why (bet A86) added it through the same table.
149
152
  why: Object.freeze({ module: 'why-cli.js', run: null, guide: 'cli.md',
150
153
  help: 'pmos why <initiative or task> | coverage — why the work exists in three lines: goal, problem, evidence, read from its records (pmos why help)' }),
@@ -4,6 +4,8 @@
4
4
  * GET /api/today-log?day=YYYY-MM-DD → { ok, day, entries, marks } the PM's own entries and the marks on the rows of that day
5
5
  * POST /api/today-log/add { text, day, bullet?, first? } → { ok, entry } a task, an event or a note typed in the first line
6
6
  * POST /api/today-log/mark { key, act, day, until?, snap? } → { ok } done, undone, later (until a later day), now (back to today), drop, undrop, keep
7
+ * POST /api/today-log/fix { day, ws, keys } → { ok } quiet-rows: the line rows Your move shows that day for one product
8
+ * (at most 3); GET returns them as `fixed: { [ws]: keys }`
7
9
  *
8
10
  * The day is the PM's local day, sent by the page. Every POST passes pm-guard requirePagePress: the page only. A mark changes only the
9
11
  * log: done on a task or an item of the PM is sent to that record's own route by the page, and the mark is the log's line beside it.
@@ -26,19 +28,20 @@ module.exports = {
26
28
  const day = url.searchParams.get('day') || localDay();
27
29
  if (!TL.DAY_RE.test(day)) { ctx.json(res, { ok: false, error: 'day is YYYY-MM-DD' }, 400); return true; }
28
30
  const f = TL.fold(TL.readLines(fileOf(ctx)), day);
29
- ctx.json(res, { ok: true, day, entries: f.entries, marks: f.marks });
31
+ ctx.json(res, { ok: true, day, entries: f.entries, marks: f.marks, fixed: f.fixed });
30
32
  return true;
31
33
  }
32
- if (req.method !== 'POST' || (p !== '/api/today-log/add' && p !== '/api/today-log/mark')) return false;
34
+ if (req.method !== 'POST' || (p !== '/api/today-log/add' && p !== '/api/today-log/mark' && p !== '/api/today-log/fix')) return false;
33
35
  const got = await ctx.readJson(req);
34
36
  if (!got.ok) { ctx.json(res, { ok: false, error: 'invalid JSON body' }, 400); return true; }
35
37
  const body = got.body || {};
36
38
  const g = guard.requirePagePress(req, body);
37
39
  if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
38
40
  const day = String(body.day || '');
39
- const r = p === '/api/today-log/add' ? TL.addEvent(body, day, 'tl-' + crypto.randomBytes(6).toString('hex')) : TL.markEvent(body, day);
41
+ const r = p === '/api/today-log/add' ? TL.addEvent(body, day, 'tl-' + crypto.randomBytes(6).toString('hex')) : p === '/api/today-log/fix' ? TL.fixEvent(body, day) : TL.markEvent(body, day);
40
42
  if (r.error) { ctx.json(res, { ok: false, error: r.error }, 400); return true; }
41
43
  TL.appendLine(fileOf(ctx), r.event);
44
+ if (p === '/api/today-log/fix') console.info('[quiet-rows] fixed day=' + day + ' rows=' + r.event.keys.length);
42
45
  if (p === '/api/today-log/add') {
43
46
  const e = r.event;
44
47
  ctx.json(res, { ok: true, entry: { id: e.id, key: 'own:' + e.id, bullet: e.bullet, text: e.text, first: e.first, time: e.time, day: e.day, done: false } });
@@ -16,6 +16,8 @@
16
16
  * (carried), and the ones done on `day`; marks: { [key]: { done?, until?, dropped?, kept? } }
17
17
  * addEvent(body, day, id) → { event } | { error } PURE: the line POST /api/today-log/add appends
18
18
  * markEvent(body, day) → { event } | { error } PURE: the line POST /api/today-log/mark appends
19
+ * fixEvent(body, day) → { event } | { error } PURE: the line POST /api/today-log/fix appends (quiet-rows: the day
20
+ * ledger of Your move's line rows, one product's at most FIX_MAX keys; fold returns them as `fixed`)
19
21
  * readLines(file) · appendLine(file, line, now) the one file, append-only, <runtime>/today-log/log.jsonl
20
22
  *
21
23
  * SINGLE WRITER: appendLine() is the only function that writes the file. `at` is set there. The day is the PM's local day, sent by
@@ -31,6 +33,8 @@ const BULLETS = ['task', 'event', 'note'];
31
33
  const ACTS = ['done', 'undone', 'later', 'now', 'drop', 'undrop', 'keep'];
32
34
  const MAX_TEXT = 240;
33
35
  const SNAP = ['title', 'work', 'job'];
36
+ const FIX_MAX = 3; // quiet-rows: at most 3 line rows a day per product
37
+ const WS_RE = /^[A-Za-z0-9._:@/+-]{0,120}$/;
34
38
 
35
39
  /** One line the PM typed. A leading "!" marks it first; "o " or "○ " makes it an event, "- " or "– " a note, "• " or nothing a task.
36
40
  * An event's time ("10:30", "9.15", "14:00") is read from its words and kept apart. */
@@ -83,15 +87,29 @@ function markEvent(body, day) {
83
87
  return { event: ev };
84
88
  }
85
89
 
90
+ /** The line POST /api/today-log/fix appends (quiet-rows, the day ledger). body: { ws (the product, '' for the one workspace), keys: the
91
+ * line rows Your move shows that day, at most FIX_MAX }. The latest line of a product and a day wins: a new ship-date blocker that takes the
92
+ * lowest row's place writes the product's keys again. */
93
+ function fixEvent(body, day) {
94
+ const b = body || {};
95
+ if (!DAY_RE.test(String(day || ''))) return { error: 'day is YYYY-MM-DD' };
96
+ const ws = b.ws == null ? '' : String(b.ws);
97
+ if (!WS_RE.test(ws)) return { error: 'ws names the product' };
98
+ if (!Array.isArray(b.keys) || b.keys.length > FIX_MAX || !b.keys.every((k) => KEY_RE.test(String(k || '')))) return { error: 'keys is a list of at most ' + FIX_MAX + ' row keys' };
99
+ return { event: { event: 'fix', day, ws, keys: [...new Set(b.keys.map(String))] } };
100
+ }
101
+
86
102
  /** Fold the lines for one day. An own entry shows on its day and every day after until it is done or dropped (carried); a done
87
103
  * entry shows only on the day it was done. A mark holds by key: the last done/undone wins, a later day hides the row until then,
88
104
  * a drop hides it until an undrop, a keep is remembered with its day (PMOS suggests a drop again only a while after it). */
89
105
  function fold(lines, day) {
90
106
  const d = DAY_RE.test(String(day || '')) ? day : '9999-12-31';
91
- const own = new Map(), marks = {};
107
+ const own = new Map(), marks = {}, fixed = {};
92
108
  const M = (k) => (marks[k] = marks[k] || {});
93
109
  for (const ev of lines || []) {
94
110
  if (!ev || typeof ev !== 'object' || !DAY_RE.test(String(ev.day || '')) || ev.day > d) continue;
111
+ // quiet-rows: the day's line rows per product; only the day asked for, the latest line of a product wins
112
+ if (ev.event === 'fix') { if (ev.day === d && Array.isArray(ev.keys) && WS_RE.test(String(ev.ws == null ? '' : ev.ws))) fixed[String(ev.ws || '')] = ev.keys.filter((k) => KEY_RE.test(String(k))).slice(0, FIX_MAX); continue; }
95
113
  if (ev.event === 'added' && ID_RE.test(String(ev.id || '')) && BULLETS.includes(ev.bullet)) {
96
114
  own.set(ev.id, { id: ev.id, key: 'own:' + ev.id, bullet: ev.bullet, text: String(ev.text || ''), first: !!ev.first, time: ev.time || null, day: ev.day, at: ev.at || null });
97
115
  continue;
@@ -115,7 +133,7 @@ function fold(lines, day) {
115
133
  if (m.doneBefore && !m.done) continue;
116
134
  entries.push({ ...e, done: !!m.done });
117
135
  }
118
- return { entries, marks };
136
+ return { entries, marks, fixed };
119
137
  }
120
138
 
121
139
  function readLines(file) {
@@ -128,4 +146,4 @@ function appendLine(file, line, now = new Date()) {
128
146
  fs.appendFileSync(file, JSON.stringify({ ...line, at: now.toISOString() }) + '\n');
129
147
  }
130
148
 
131
- module.exports = { DAY_RE, KEY_RE, BULLETS, ACTS, parseEntry, addEvent, markEvent, fold, readLines, appendLine };
149
+ module.exports = { DAY_RE, KEY_RE, BULLETS, ACTS, FIX_MAX, parseEntry, addEvent, markEvent, fixEvent, fold, readLines, appendLine };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.751.0",
3
+ "version": "0.752.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.751.0",
9
+ "version": "0.752.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/sdk": "^1.3.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.751.0",
3
+ "version": "0.752.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -20,6 +20,7 @@ import * as TP from './cozy-today-view.js';
20
20
  import * as OM from './mention-one-model.js'; // the one mention's title and the self check's proof line (Today round 3)
21
21
  import { wireSwipe } from './cozy-phone-swipe.js';
22
22
  import { noteUse } from './use-log.js'; // your-move (A468): each press on a Your move row is one ym-act line in the local use log (its health number)
23
+ import * as QB from './quiet-batch.js'; // quiet-rows: Today's batch, the popup (Approve, Skip, Change it first; nothing sent without a press)
23
24
  import * as CC from './change-cues.js'; // idea A313: a short cue on the row that is done, moved or dropped, before the log draws again // the phone: rows and the proposal swipe (phone design, Ph2_today)
24
25
 
25
26
  const ASK_SEND = new Set(['session']);
@@ -34,7 +35,7 @@ export function mountToday(ctx) {
34
35
 
35
36
  async function read() {
36
37
  const r = await ctx.pmGet('/api/today-log?day=' + day()).catch(() => null);
37
- if (r && r.ok) X.log = { entries: r.entries || [], marks: r.marks || {} };
38
+ if (r && r.ok) X.log = { entries: r.entries || [], marks: r.marks || {}, fixed: r.fixed || {} };
38
39
  X.read = true;
39
40
  draw();
40
41
  readReports();
@@ -49,6 +50,7 @@ export function mountToday(ctx) {
49
50
  const lines = [];
50
51
  got.forEach((r, i) => { if (r && r.ok && Array.isArray(r.lines)) for (const l of r.lines) lines.push({ ...l, ws: r.ws || L[i] }); });
51
52
  console.info('[open-questions-today] products=' + L.length + ' lines=' + lines.length);
53
+ if (!X.qRead) { X.qRead = true; draw(); } // quiet-rows: the day's line rows are fixed only once the questions are in
52
54
  if (JSON.stringify(lines) === JSON.stringify(X.questions || [])) return;
53
55
  X.questions = lines;
54
56
  draw();
@@ -83,7 +85,7 @@ export function mountToday(ctx) {
83
85
  const R = ctx.review();
84
86
  const lab = (S.lab || []).flatMap((l) => (l.items || []).map((f) => ({ ...f, ws: l.ws, board: l.board })));
85
87
  const L = TM.logModel({ rank: ctx.rank(), move, items: tdItems(), drafts, review: R && R.open && !R.done ? { title: 'Your weekly review' } : null,
86
- own: X.log.entries, marks: X.log.marks, lab, questions: X.questions || [], titleOf: ctx.titleOf, productOf, now,
88
+ own: X.log.entries, marks: X.log.marks, lab, questions: X.questions || [], titleOf: ctx.titleOf, productOf, now, fixed: X.log.fixed || {},
87
89
  // your-move (A468): an initiative's ship date is its board end date; a line with no default on work that ships soon blocks it
88
90
  shipOf: (id) => { const r = byId.get('i:' + id); return (r && r.board && r.board.end) || ''; } });
89
91
  if (L.move.length !== X.ymN) { X.ymN = L.move.length; console.info('[your-move] rows=' + L.move.length + ' shown=' + L.first.length + (L.move[0] ? ' first-tier=' + L.move[0].tier : '')); }
@@ -102,6 +104,7 @@ export function mountToday(ctx) {
102
104
  if (!ctx.S.ready) { if (!el.firstChild) el.innerHTML = '<p class="td-none">Reading your day.</p>'; return; }
103
105
  const { L, A, O } = models();
104
106
  X.model = L; X.agenda = A; X.overview = O;
107
+ if (L.toFix && X.read && X.qRead) fixDay(L.toFix, L.today);
105
108
  autoClosed();
106
109
  // the rail's number on every place: the lines for today (Your move and what waits today), the number the Overview says; kept for the
107
110
  // other places with its day (pm/cozy-nav.js reads it there)
@@ -196,9 +199,21 @@ export function mountToday(ctx) {
196
199
  const next = list[i < 0 ? 0 : i + d]; if (!next) return false;
197
200
  open(next); return true;
198
201
  }
202
+ /* quiet-rows: the day ledger. The first read of a day that has line rows writes each product's (at most 3) once; a new ship-date blocker
203
+ * that takes the lowest row's place writes them again. POST /api/today-log/fix; until it lands the page shows the same rows. */
204
+ function fixDay(toFix, today) {
205
+ X.fixSent = X.fixSent || new Set();
206
+ for (const [ws, keys] of Object.entries(toFix)) {
207
+ const k = today + '|' + ws + '|' + keys.join(','); if (X.fixSent.has(k)) continue;
208
+ X.fixSent.add(k);
209
+ X.log.fixed = { ...(X.log.fixed || {}), [ws]: keys };
210
+ ctx.pmPost('/api/today-log/fix', { day: today, ws, keys }).then((r) => { if (r && r.ok) console.info('[quiet-rows] day fixed rows=' + keys.length); }).catch(() => {});
211
+ }
212
+ }
199
213
  function open(r) {
200
214
  if (!r) return;
201
215
  const ref = r.ref || {};
216
+ if (r.src === 'batch') { pop(r); QB.openBatch(r.batch, { pmPost: ctx.pmPost, toast: ctx.toast, toastUndo: ctx.toastUndo, reload: ctx.reload, isPhone: ctx.isPhone, noteUse, onSwipe: (root, act) => wireSwipe(root, { act }) }); return; }
202
217
  if (r.members) { if (X.sopen.has(r.key)) X.sopen.delete(r.key); else X.sopen.add(r.key); draw(); return; } // the same step for N initiatives: list them
203
218
  X.last = r.key; // ↑ ↓ (j k) step from here (round 3 point 6)
204
219
  if (r.src === 'ask') {