create-pmos 0.728.0 → 0.730.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.
@@ -0,0 +1,214 @@
1
+ 'use strict';
2
+ /* jira-criteria.js — the done test's checks written onto the Jira tickets an initiative tracks, as acceptance criteria (initiative
3
+ * jira-criteria-write; bet A384, proofs/A384-ac: 69% of 236 recent tickets on 3 products state no acceptance criteria).
4
+ * THE ONE WRITER and THE ONE FOLD of <state>/tracker/jira/criteria.jsonl.
5
+ *
6
+ * PMOS already puts the checks on the tickets it drafts (lib/ticket-acceptance.js, ticket-acceptance-from-done-test). Most tickets an
7
+ * initiative tracks were made in Jira by people. Here PMOS proposes, for each open ticket the initiative tracks, the checks that fit it
8
+ * as a block "From the done test" (Given / When / Then). On the PM's yes each ticket becomes an ASK. The workspace server makes no
9
+ * request to Jira (D53, D88):
10
+ * · a ticket assigned to the PM is DIRECT: an agent session with the PM's own Atlassian connection (skill jira-criteria) puts the
11
+ * block at the end of its description and answers with `pmos jira criteria-done`. Direct Jira writes only on tickets assigned to
12
+ * the PM (Wawan 2026-11-22).
13
+ * · every other ticket goes to the day's DRAFT for its owner (`pmos jira criteria-asks --draft`), for the PM to read and send.
14
+ *
15
+ * THE LEDGER. One line per change, append-only:
16
+ * ask { v, kind: 'ask', id, key, ini, labels, block, hash, who, direct, at, by }
17
+ * written { v, kind: 'written', id, at, by } the agent put the block in Jira
18
+ * refused { v, kind: 'refused', id, why, at, by } Jira refused, or could not be reached
19
+ * withdrawn { v, kind: 'withdrawn', id, at, by } the PM's Undo, before an answer
20
+ *
21
+ * ticketsOf(root, ini) → [{ key, summary, who, done }] the tickets the initiative tracks (tasks that name a key, its reading)
22
+ * proposalsFor(checks, tickets, o) PURE → { proposals: [{ key, summary, who, direct, labels, block, hash }], unmatched }
23
+ * propose(root, ini, { me }) → { ok, doneTest, checks, proposals, unmatched } minus the tickets already asked with that block
24
+ * askCriteria(root, { ini, keys, me }, by) · answerCriteriaAsk(root, id, r, by) · withdrawCriteriaAsks(root, ids, by)
25
+ * readCriteriaAsks(root) · pendingCriteriaAsks(F, { direct }) · criteriaDraftText(F) · healthOf(F, now)
26
+ *
27
+ * BOUNDARY. No network. The block is always computed here from the done test: a block sent by the page is never written.
28
+ */
29
+ const fs = require('fs');
30
+ const path = require('path');
31
+ const crypto = require('crypto');
32
+ const TA = require('./ticket-acceptance.js');
33
+ const jiraTickets = require('./jira-tickets.js');
34
+
35
+ const FILE = 'criteria.jsonl';
36
+ const KEY_RE = /^[A-Z][A-Z0-9_]{0,30}-\d{1,9}$/;
37
+ const ID_RE = /^ac-[0-9a-f]{10}$/;
38
+ const LOG = '[jira-criteria]';
39
+ const DAY = 86400000;
40
+ const oneLine = (s, n) => { const t = String(s == null ? '' : s).replace(/[\r\n\t]+/g, ' ').replace(/\s{2,}/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
41
+ const hashOf = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 12);
42
+ const log = (...a) => console.log(LOG, ...a);
43
+
44
+ function criteriaFile(root) { return path.join(jiraTickets.jiraDir(root), FILE); }
45
+ function lines(root) {
46
+ let txt = '';
47
+ try { txt = fs.readFileSync(criteriaFile(root), 'utf8'); } catch { return []; }
48
+ const out = [];
49
+ for (const l of txt.split('\n')) { if (!l.trim()) continue; try { out.push(JSON.parse(l)); } catch { /* a torn line is skipped */ } }
50
+ return out;
51
+ }
52
+ function append(root, ls) {
53
+ fs.mkdirSync(path.dirname(criteriaFile(root)), { recursive: true });
54
+ fs.appendFileSync(criteriaFile(root), ls.map((l) => JSON.stringify(l)).join('\n') + '\n');
55
+ }
56
+
57
+ /** PURE: the latest ask of each ticket. An answer counts only for the ask it names, and only while that ask is still asked. */
58
+ function foldCriteriaAsks(ls) {
59
+ const by = new Map(), ids = new Map();
60
+ for (const l of ls || []) {
61
+ if (!l || typeof l !== 'object') continue;
62
+ if (l.kind === 'ask' && ID_RE.test(String(l.id || '')) && KEY_RE.test(String(l.key || '')) && typeof l.block === 'string' && l.block) {
63
+ const a = { id: l.id, key: l.key, ini: String(l.ini || ''), labels: Array.isArray(l.labels) ? l.labels.map(String) : [], block: l.block, hash: String(l.hash || hashOf(l.block)),
64
+ who: oneLine(l.who, 80), direct: l.direct === true, state: 'asked', why: '', at: l.at || '', askedAt: l.at || '' };
65
+ by.set(l.key, a); ids.set(l.id, a);
66
+ } else if (['written', 'refused', 'withdrawn'].includes(l.kind) && ids.has(l.id)) {
67
+ const a = ids.get(l.id);
68
+ if (by.get(a.key) !== a || a.state !== 'asked') continue;
69
+ a.state = l.kind; a.at = l.at || a.at;
70
+ if (l.kind === 'refused') a.why = oneLine(l.why, 200) || 'Jira did not say why';
71
+ }
72
+ }
73
+ return by;
74
+ }
75
+ function readCriteriaAsks(root) { return foldCriteriaAsks(lines(root)); }
76
+
77
+ /** The PM's own name against a Jira assignee: the same rule as the epic fix ("Wawan Setiawan" and "Wawan"). */
78
+ const isPmName = (who, me) => require('./jira-epics.js').isPmName(who, me);
79
+
80
+ /** The done test the initiative's record names, from the repository (or pmos/ in a kit repository). → { path, text } | null */
81
+ function doneTestOf(root, ini) {
82
+ const fm = jiraTickets.recordFm(root, ini);
83
+ const p = fm && typeof fm.done_test_path === 'string' ? fm.done_test_path.trim() : '';
84
+ if (!p) return null;
85
+ const bases = [root];
86
+ try { const m = require('./plan-items.js').ledgerRoot(root); if (m && m !== root) bases.push(m); } catch { /* the worktree only */ }
87
+ for (const base of bases) {
88
+ for (const rel of [p, path.join('pmos', p)]) {
89
+ const abs = path.resolve(base, rel);
90
+ if (!abs.startsWith(path.resolve(base) + path.sep)) continue;
91
+ try { return { path: p, text: fs.readFileSync(abs, 'utf8'), title: oneLine(fm.title || ini, 120) }; } catch { /* next */ }
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+
97
+ const DONE_WORDS = /\b(done|closed|resolved|released|complete|shipped|deployed|won'?t|invalid|cancel|duplicate|rejected|obsolete)\b/i;
98
+ /** The Jira tickets an initiative tracks: the keys its tasks name (not archived), and the tickets of its own Jira reading. Each with
99
+ * its summary and assignee from the newest reading, and done when Jira (or, with no reading, the task) says it is closed. */
100
+ function ticketsOf(root, ini) {
101
+ const TJ = require('./task-jira.js'), JS = require('./jira-status.js');
102
+ const by = new Map();
103
+ for (const t of TJ.keyedTasks(TJ.readLines(root)).values()) {
104
+ if (t.initiative !== ini || t.state === 'Archived') continue;
105
+ by.set(t.key, { key: t.key, summary: oneLine(t.title.replace(/^\s*\[?[A-Z][A-Z0-9_]*-\d+\]?\s*[·:\-–—]?\s*/, ''), 250), who: '', done: t.state === 'Done' || t.state === "Won't do" });
106
+ }
107
+ const snap = JS.readSnapshot(root, ini);
108
+ const reading = (k) => (snap && snap.tickets.get(k)) || JS.findTicket(root, k);
109
+ if (snap) for (const k of snap.tickets.keys()) if (!by.has(k)) by.set(k, { key: k, summary: '', who: '', done: false });
110
+ for (const t of by.values()) {
111
+ const r = reading(t.key);
112
+ if (!r) continue;
113
+ t.summary = oneLine(r.summary, 250) || t.summary;
114
+ t.who = oneLine(r.assignee, 80);
115
+ t.done = r.category === 'done' || DONE_WORDS.test(String(r.status || ''));
116
+ }
117
+ return [...by.values()].sort((a, b) => a.key.localeCompare(b.key, 'en', { numeric: true }));
118
+ }
119
+
120
+ /** PURE: the checks that fit each open ticket, as its block. checks: TA.checksOf; tickets: ticketsOf. o: { path, me } */
121
+ function proposalsFor(checks, tickets, o = {}) {
122
+ const open = (tickets || []).filter((t) => t && KEY_RE.test(String(t.key || '')) && !t.done);
123
+ if (!checks || !checks.length || !open.length) return { proposals: [], unmatched: (checks || []).map((c) => c.label) };
124
+ const a = TA.assign(checks, open.map((t) => ({ id: t.key, text: t.summary })));
125
+ const byLabel = new Map(checks.map((c) => [c.label, c]));
126
+ const proposals = [];
127
+ for (const t of open) {
128
+ const labels = a.byTicket.get(t.key) || [];
129
+ if (!labels.length) continue;
130
+ const block = TA.blockOf(labels.map((l) => byLabel.get(l)), { path: o.path, subject: t.summary || t.key });
131
+ proposals.push({ key: t.key, summary: t.summary, who: t.who, direct: isPmName(t.who, o.me), labels, block, hash: hashOf(block) });
132
+ }
133
+ return { proposals, unmatched: a.unmatched };
134
+ }
135
+
136
+ /** What PMOS proposes now for an initiative: the proposals, minus a ticket already asked or written with the same block. */
137
+ function propose(root, ini, { me } = {}) {
138
+ if (!jiraTickets.recordFm(root, ini)) return { ok: false, status: 404, error: `no initiative ${ini} in this repository` };
139
+ const dt = doneTestOf(root, ini);
140
+ const checks = dt ? TA.checksOf(dt.text) : [];
141
+ if (!dt || !checks.length) return { ok: true, initiative: ini, doneTest: dt ? dt.path : null, checks: 0, proposals: [], unmatched: [], note: dt ? 'the done test has no checks' : 'the initiative has no done test' };
142
+ const tickets = ticketsOf(root, ini);
143
+ const r = proposalsFor(checks, tickets, { path: dt.path, me });
144
+ const F = readCriteriaAsks(root);
145
+ const fresh = r.proposals.filter((p) => { const a = F.get(p.key); return !a || !(a.state === 'asked' || (a.state === 'written' && a.hash === p.hash)); });
146
+ return { ok: true, initiative: ini, doneTest: dt.path, checks: checks.length, tickets: tickets.filter((t) => !t.done).length, proposals: fresh, unmatched: r.unmatched };
147
+ }
148
+
149
+ /** The PM's yes for some of an initiative's proposals. o: { ini, keys, me }. The blocks are computed here, never taken from the caller.
150
+ * → { ok, direct: [ask], draft: [ask], ids, skipped: [key] } */
151
+ function askCriteria(root, o, by, now = Date.now()) {
152
+ const ini = String((o && o.ini) || '');
153
+ if (!/^[a-z0-9][a-z0-9-]{0,80}$/.test(ini)) return { ok: false, status: 400, error: 'name the initiative, for example checkout-redesign' };
154
+ const keys = Array.isArray(o.keys) ? [...new Set(o.keys.map((k) => String(k || '').toUpperCase()))] : null;
155
+ if (keys && (!keys.length || keys.length > 100 || keys.some((k) => !KEY_RE.test(k)))) return { ok: false, status: 400, error: 'keys is a list of 1 to 100 Jira keys, for example IDPF-2746' };
156
+ const p = propose(root, ini, { me: o.me });
157
+ if (!p.ok) return p;
158
+ if (!p.checks) return { ok: false, status: 409, error: `${ini}: ${p.note}` };
159
+ const pick = keys ? p.proposals.filter((x) => keys.includes(x.key)) : p.proposals;
160
+ const skipped = keys ? keys.filter((k) => !pick.some((x) => x.key === k)) : [];
161
+ if (!pick.length) return { ok: false, status: 409, error: 'no ticket to write: each one has no check that fits, is done, or is asked already', skipped };
162
+ const at = new Date(now).toISOString();
163
+ const out = pick.map((x) => ({ v: 1, kind: 'ask', id: 'ac-' + crypto.randomBytes(5).toString('hex'), key: x.key, ini, labels: x.labels, block: x.block, hash: x.hash, who: x.who, direct: x.direct, at, by: by || 'pm' }));
164
+ append(root, out);
165
+ const F = readCriteriaAsks(root);
166
+ const A = out.map((l) => F.get(l.key));
167
+ log('ask', ini, `direct=${A.filter((a) => a.direct).length}`, `draft=${A.filter((a) => !a.direct).length}`, `skipped=${skipped.length}`);
168
+ return { ok: true, direct: A.filter((a) => a.direct), draft: A.filter((a) => !a.direct), ids: out.map((l) => l.id), skipped };
169
+ }
170
+ /** The agent's answer for one direct ask: r { written: true } or { why }. */
171
+ function answerCriteriaAsk(root, id, r, by, now = Date.now()) {
172
+ if (!ID_RE.test(String(id || ''))) return { ok: false, status: 400, error: 'name a criteria ask id, for example ac-0a1b2c3d4e' };
173
+ const a = [...readCriteriaAsks(root).values()].find((x) => x.id === id);
174
+ if (!a) return { ok: false, status: 404, error: `${id} is not the latest criteria ask of any ticket` };
175
+ if (a.state !== 'asked') return { ok: false, status: 409, error: `${a.key} already has an answer (${a.state})` };
176
+ const refused = r && r.why != null;
177
+ const at = new Date(now).toISOString();
178
+ append(root, [refused ? { v: 1, kind: 'refused', id, why: oneLine(r.why, 200), at, by: by || 'agent' } : { v: 1, kind: 'written', id, at, by: by || 'agent' }]);
179
+ log(refused ? 'refused' : 'written', a.key, refused ? oneLine(r.why, 80) : '');
180
+ return { ok: true, ask: readCriteriaAsks(root).get(a.key) };
181
+ }
182
+ /** The PM's Undo: the asks not answered yet are withdrawn. → { ok, withdrawn: [key], kept: [key] (already in Jira) } */
183
+ function withdrawCriteriaAsks(root, ids, by, now = Date.now()) {
184
+ const F = readCriteriaAsks(root), want = new Set((ids || []).filter((x) => ID_RE.test(String(x))));
185
+ const A = [...F.values()].filter((a) => want.has(a.id));
186
+ const go = A.filter((a) => a.state === 'asked');
187
+ if (go.length) { append(root, go.map((a) => ({ v: 1, kind: 'withdrawn', id: a.id, at: new Date(now).toISOString(), by: by || 'pm' }))); log('withdrawn', go.length); }
188
+ return { ok: true, withdrawn: go.map((a) => a.key), kept: A.filter((a) => a.state === 'written').map((a) => a.key) };
189
+ }
190
+ /** The asks not answered yet, oldest first. o.direct: true only the direct ones, false only the draft ones. */
191
+ const pendingCriteriaAsks = (F, o = {}) => [...F.values()].filter((a) => a.state === 'asked' && (o.direct == null || a.direct === o.direct)).sort((a, b) => String(a.askedAt).localeCompare(String(b.askedAt)));
192
+ /** The day's draft, by owner: plain text the PM can read and send. Nothing is sent by PMOS. */
193
+ function criteriaDraftText(F) {
194
+ const P = pendingCriteriaAsks(F, { direct: false }), by = new Map();
195
+ for (const a of P) { const k = a.who || 'No assignee'; if (!by.has(k)) by.set(k, []); by.get(k).push(a); }
196
+ const out = [];
197
+ for (const [who, A] of by) {
198
+ out.push(`To ${who}:`);
199
+ out.push(`Please add these acceptance criteria to ${A.length === 1 ? 'this ticket' : 'these tickets'}. They come from the done test we agreed, so the work is checked the same way it is built:`);
200
+ for (const a of A) out.push('', `${a.key}:`, a.block);
201
+ out.push('');
202
+ }
203
+ return out.join('\n').trim();
204
+ }
205
+ /** The health number: of the asks answered in the last 14 days, the percent written (100 when none is answered). */
206
+ function healthOf(F, now = Date.now()) {
207
+ const since = now - 14 * DAY;
208
+ const A = [...F.values()].filter((a) => (a.state === 'written' || a.state === 'refused') && Date.parse(a.at || '') >= since);
209
+ const w = A.filter((a) => a.state === 'written').length;
210
+ return { written: w, refused: A.length - w, answered: A.length, pct: A.length ? Math.round((100 * w) / A.length) : 100 };
211
+ }
212
+
213
+ module.exports = { FILE, KEY_RE, ID_RE, LOG, criteriaFile, foldCriteriaAsks, readCriteriaAsks, isPmName, doneTestOf, ticketsOf, proposalsFor, propose,
214
+ askCriteria, answerCriteriaAsk, withdrawCriteriaAsks, pendingCriteriaAsks, criteriaDraftText, healthOf };
@@ -8,7 +8,7 @@
8
8
  * Stage project product sdlc
9
9
  * Triage, Discover hidden owned owned
10
10
  * Plan, Prioritize owned owned owned
11
- * Build watched (Jira) watched (Jira) owned (the factory opens pull requests)
11
+ * Build watched (milestone dates) watched (Jira) owned (the factory opens pull requests)
12
12
  * Deliver, Monitor, Evaluate owned owned owned
13
13
  * Gate Plan before start PRD and done test before build Done test and kill before build
14
14
  *
@@ -19,8 +19,12 @@
19
19
  * docHidden(kind, docKey) → bool
20
20
  * prePick(name, lane, role) → { kind, cue } lib/work-kind.js fromName, with the PM's role as the default when the name gives no cue
21
21
  * count(root) → n initiatives whose kind hides at least one stage (the health number)
22
+ * describe(kind) → [lines] the scope as a person reads it: the kind, owned, watched (and where), hidden, the gate
23
+ * writes() → [{ what, page, command }] each kind write the page offers, with the `pmos` command that does it from a chat
24
+ * (initiative kind-scope-chat-writes: anything the chat can be asked to change has a write path)
22
25
  *
23
- * node lib/kind-scope.js count [root] prints that number on its last line */
26
+ * node lib/kind-scope.js count [root] prints that number on its last line
27
+ * node lib/kind-scope.js writes prints how many kind writes have a pmos command, on its last line */
24
28
  const fs = require('fs');
25
29
  const path = require('path');
26
30
  const WK = require('./work-kind.js');
@@ -32,7 +36,7 @@ const TABLE = Object.freeze({
32
36
  product: Object.freeze({ ...all('owned'), build: 'watched' }),
33
37
  sdlc: Object.freeze(all('owned')),
34
38
  });
35
- const WATCH = Object.freeze({ project: { build: 'Jira' }, product: { build: 'Jira' }, sdlc: {} });
39
+ const WATCH = Object.freeze({ project: { build: 'milestone dates' }, product: { build: 'Jira' }, sdlc: {} });
36
40
  const GATE = Object.freeze({ project: 'Plan before start', product: 'PRD and done test before build', sdlc: 'Done test and kill before build' });
37
41
  const PRODUCT_DOCS = Object.freeze(new Set(['problem', 'research', 'prd', 'rubric', 'design']));
38
42
  const LOG = '[kind-scope]';
@@ -50,6 +54,24 @@ function prePick(name, lane, role) {
50
54
  return { kind: role, cue: '' };
51
55
  }
52
56
 
57
+ const STAGE_LABEL = Object.freeze({ triage: 'Triage', discover: 'Discover', plan: 'Plan', prioritize: 'Prioritize', build: 'Build', deliver: 'Deliver', monitor: 'Monitor', evaluate: 'Evaluate' });
58
+ function describe(kind) {
59
+ const s = scopeOf(kind), of = (v) => STAGES.filter((k) => s.stages[k] === v).map((k) => STAGE_LABEL[k]);
60
+ const lines = [`Kind: ${s.label}`, `Owned: ${of('owned').join(', ') || 'none'}`];
61
+ for (const k of STAGES) if (s.stages[k] === 'watched') lines.push(`${STAGE_LABEL[k]}: watched ${s.watch[k] === 'milestone dates' ? 'by' : 'in'} ${s.watch[k] || 'the tracker'}`);
62
+ lines.push(`Hidden: ${of('hidden').join(', ') || 'none'}${s.hidden.length ? ' (still in Move to a stage)' : ''}`);
63
+ if (s.kind === 'project') lines.push('Product documents (problem, research, PRD, rubric, design) sit in a closed fold');
64
+ lines.push(`Gate: ${s.gate}`);
65
+ return lines;
66
+ }
67
+
68
+ /** The kind writes the workspace page offers, each with its pmos command. A page write with no command is one the chat cannot make. */
69
+ const WRITES = Object.freeze([
70
+ Object.freeze({ what: "an initiative's kind", page: 'Viewer › kind switch (POST /api/initiatives/kind)', command: 'pmos initiative kind <id> product|project|sdlc' }),
71
+ Object.freeze({ what: 'the kind new work starts as', page: 'Settings › General › New work starts as (work.role)', command: 'pmos initiative role product|project|sdlc' }),
72
+ ]);
73
+ const writes = () => WRITES.map((w) => ({ ...w }));
74
+
53
75
  const kindLine = (text) => { const m = /^---\n([\s\S]*?)\n---/.exec(text); const l = m && /^kind:\s*(.+)$/m.exec(m[1]); return l ? WK.kindOf(l[1]) : 'product'; };
54
76
  function count(root) {
55
77
  let n = 0;
@@ -63,11 +85,17 @@ function count(root) {
63
85
 
64
86
  if (require.main === module) {
65
87
  const [verb, root] = process.argv.slice(2);
66
- if (verb !== 'count') { console.error('usage: node lib/kind-scope.js count [root]'); process.exit(2); }
88
+ if (verb === 'writes') {
89
+ const w = writes().filter((x) => x.command);
90
+ for (const x of w) console.log(`[kind-scope] ${x.what}: ${x.command}`);
91
+ console.log(String(w.length));
92
+ process.exit(0);
93
+ }
94
+ if (verb !== 'count') { console.error('usage: node lib/kind-scope.js count|writes [root]'); process.exit(2); }
67
95
  const r = path.resolve(root || process.cwd());
68
96
  const n = count(r);
69
97
  console.log(LOG + ' initiatives whose kind hides a stage in ' + r);
70
98
  console.log(String(n));
71
99
  }
72
100
 
73
- module.exports = { STAGES, TABLE, GATE, PRODUCT_DOCS, LOG, scopeOf, docHidden, prePick, count };
101
+ module.exports = { STAGES, TABLE, GATE, PRODUCT_DOCS, LOG, scopeOf, docHidden, prePick, count, describe, writes, kindOfText: kindLine };
@@ -7,27 +7,85 @@
7
7
  *
8
8
  * A ticket assigned to the PM is direct: a jira-epic session with the PM's own Atlassian connection sets its epic and answers with
9
9
  * `pmos jira epic-done`. Every other ticket waits in the day's draft for its owner, which the PM reads first. This route makes no request to
10
- * Jira (D53). Every POST passes pm-guard requirePagePress: the page only. */
10
+ * Jira (D53). Every POST passes pm-guard requirePagePress: the page only.
11
+ *
12
+ * The done test's acceptance criteria on the Jira tickets an initiative tracks (initiative jira-criteria-write, A384; lib/jira-criteria.js
13
+ * is the store), the same shape:
14
+ * GET /api/jira-criteria?ws&ini → { ok, proposals, unmatched, doneTest, asks, draft } the ✦'s proposals and what waits
15
+ * POST /api/jira-criteria/ask { ws, ini, keys } → { ok, direct: [key], draft: [{ key, who }], ids, skipped, session? }
16
+ * POST /api/jira-criteria/undo { ws, ids } → { ok, withdrawn, kept }
17
+ * The blocks are computed by the server from the done test; the page sends keys only. A ticket assigned to the PM is direct: one
18
+ * jira-criteria session writes it with the PM's own Atlassian connection. */
11
19
  const fs = require('fs');
12
20
  const path = require('path');
13
21
  const guard = require('./pm-guard.js');
14
22
  const JE = require('./jira-epics.js');
23
+ const JC = require('./jira-criteria.js');
15
24
 
16
25
  const pmNameOf = () => { try { return require('./routes-board-publish.js').sharedBy() || process.env.PMOS_PM_NAME || ''; } catch { return process.env.PMOS_PM_NAME || ''; } };
17
26
  const SKILL = path.join(__dirname, '..', 'skills', 'jira-epic.skill');
27
+ const CRITERIA_SKILL = path.join(__dirname, '..', 'skills', 'jira-criteria.skill');
18
28
  /** The skill's body: the prompt the session starts with. */
19
- function promptOf() {
29
+ function promptOf(file = SKILL) {
20
30
  let t = '';
21
- try { t = fs.readFileSync(SKILL, 'utf8'); } catch { return null; }
31
+ try { t = fs.readFileSync(file, 'utf8'); } catch { return null; }
22
32
  const m = /^---\n[\s\S]*?\n---\n([\s\S]*)$/.exec(t);
23
33
  return (m ? m[1] : t).trim() || null;
24
34
  }
25
35
  const running = new Map(); // ws id → session id
36
+ const runningCriteria = new Map(); // ws id → the jira-criteria session id
37
+
38
+ /** The acceptance-criteria routes (jira-criteria-write). */
39
+ async function handleCriteria(req, res, url, ctx) {
40
+ const p = url.pathname;
41
+ if (p === '/api/jira-criteria' && req.method === 'GET') {
42
+ const w = ctx.getWs(url.searchParams.get('ws'));
43
+ if (!w) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
44
+ const ini = url.searchParams.get('ini') || '';
45
+ const F = JC.readCriteriaAsks(w.root);
46
+ const base = { ok: true, asks: JC.pendingCriteriaAsks(F).filter((a) => !ini || a.ini === ini), draft: JC.criteriaDraftText(F) };
47
+ if (!ini) { ctx.json(res, { ...base, proposals: [] }); return true; }
48
+ const r = JC.propose(w.root, ini, { me: pmNameOf() });
49
+ if (!r.ok) { ctx.json(res, r, r.status || 400); return true; }
50
+ ctx.json(res, { ...base, doneTest: r.doneTest, checks: r.checks, unmatched: r.unmatched,
51
+ proposals: r.proposals.map((x) => ({ key: x.key, summary: x.summary, who: x.who, direct: x.direct, labels: x.labels, block: x.block })) });
52
+ return true;
53
+ }
54
+ if (req.method !== 'POST' || (p !== '/api/jira-criteria/ask' && p !== '/api/jira-criteria/undo')) return false;
55
+ const got = await ctx.readJson(req);
56
+ if (!got.ok) { ctx.json(res, { ok: false, error: 'invalid JSON body' }, 400); return true; }
57
+ const body = got.body || {};
58
+ const g = guard.requirePagePress(req, body);
59
+ if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
60
+ const w = ctx.getWs(typeof body.ws === 'string' && body.ws ? body.ws : null);
61
+ if (!w || (body.ws && w.id !== body.ws)) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
62
+ const by = (g.actor && g.actor.by) || 'pm';
63
+ if (p === '/api/jira-criteria/undo') { ctx.json(res, JC.withdrawCriteriaAsks(w.root, Array.isArray(body.ids) ? body.ids : [], by)); return true; }
64
+ // keys only: the blocks are computed here from the done test, never taken from the page
65
+ const r = JC.askCriteria(w.root, { ini: body.ini, keys: Array.isArray(body.keys) ? body.keys : null, me: pmNameOf() }, by);
66
+ if (!r.ok) { ctx.json(res, r, r.status || 400); return true; }
67
+ const out = { ok: true, direct: r.direct.map((a) => a.key), draft: r.draft.map((a) => ({ key: a.key, who: a.who })), ids: r.ids, skipped: r.skipped };
68
+ if (r.direct.length && typeof ctx.spawnSession === 'function') {
69
+ const prompt = promptOf(CRITERIA_SKILL), was = runningCriteria.get(w.id), live = was && typeof ctx.sessionList === 'function' && (ctx.sessionList() || []).some((s) => s && s.id === was && s.state !== 'exited');
70
+ const fail = (why) => { for (const a of r.direct) JC.answerCriteriaAsk(w.root, a.id, { why }, 'pmos'); };
71
+ if (prompt && !live) {
72
+ try {
73
+ const s = ctx.spawnSession({ name: 'Write criteria in Jira', agent: 'claude', ws: w.id, origin: 'jira:criteria', initialInput: prompt + `\n\nThis run: the asks \`pmos jira criteria-asks --direct\` lists (the first: ${r.direct[0].key}).\r` });
74
+ if (s && s.state !== 'exited') { runningCriteria.set(w.id, s.id); out.session = s.id; }
75
+ else fail((s && s.note) || 'the agent could not start');
76
+ } catch { fail('the agent could not start'); }
77
+ } else if (live) out.session = was;
78
+ else if (!prompt) fail('the jira-criteria skill is not installed');
79
+ }
80
+ ctx.json(res, out);
81
+ return true;
82
+ }
26
83
 
27
84
  module.exports = {
28
- prefixes: ['/api/jira-epics'],
85
+ prefixes: ['/api/jira-epics', '/api/jira-criteria'],
29
86
  handle: async (req, res, url, ctx) => {
30
87
  const p = url.pathname;
88
+ if (p === '/api/jira-criteria' || p.startsWith('/api/jira-criteria/')) return handleCriteria(req, res, url, ctx);
31
89
  if (p === '/api/jira-epics' && req.method === 'GET') {
32
90
  const w = ctx.getWs(url.searchParams.get('ws'));
33
91
  if (!w) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.728.0",
3
+ "version": "0.730.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.728.0",
9
+ "version": "0.730.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.728.0",
3
+ "version": "0.730.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",
@@ -0,0 +1,15 @@
1
+ /* change-cues.css — the short cue on a row that is done, moved or dropped (pm/change-cues.js, idea A313). Komorebi tokens only. */
2
+ .pm-cue-done, .pm-cue-moved, .pm-cue-gone { pointer-events: none; }
3
+ .pm-cue-done { animation: pmCueDone var(--duration-leaf) var(--ease-out) both; }
4
+ .pm-cue-moved { animation: pmCueMoved var(--duration-leaf) var(--ease-out) both; }
5
+ .pm-cue-gone { animation: pmCueGone var(--duration-leaf) var(--ease-out) both; }
6
+ @keyframes pmCueDone { 0% { background: transparent; } 35% { background: var(--leaf-tint); transform: none; opacity: 1; } 100% { background: var(--leaf-tint); transform: translateX(var(--space-24)); opacity: 0; } }
7
+ @keyframes pmCueMoved { 0% { background: transparent; } 30% { background: var(--blue-tint); transform: none; opacity: 1; } 100% { background: var(--blue-tint); transform: translateX(var(--space-24)); opacity: 0; } }
8
+ @keyframes pmCueGone { from { opacity: 1; } to { opacity: 0; } }
9
+ /* reduced motion: still. The row is tinted for the same time and nothing moves or fades. */
10
+ @media (prefers-reduced-motion: reduce) {
11
+ .pm-cue-done, .pm-cue-moved, .pm-cue-gone { animation: none; transform: none; }
12
+ .pm-cue-done { background: var(--leaf-tint); }
13
+ .pm-cue-moved { background: var(--blue-tint); }
14
+ .pm-cue-gone { background: var(--well); }
15
+ }
@@ -0,0 +1,52 @@
1
+ /* pm/change-cues.js — a short cue when an item moves or is done (idea A313, initiative change-cues, job #1616).
2
+ *
3
+ * When the user marks a row done, moves it to another day or drops it, the page saves the change and draws the list again. Without a cue
4
+ * the row just vanishes. This plays about half a second on the row first, so the eye sees which row went and how:
5
+ * done the row tints green and slides out (class pm-cue-done)
6
+ * moved the row slides out to the side (class pm-cue-moved)
7
+ * gone the row fades (class pm-cue-gone)
8
+ * The timing is the Komorebi motion tokens (--duration-leaf, --ease-out) in change-cues.css. With reduced motion asked for, the cue is
9
+ * still: the row is tinted for the same time and nothing moves (the CSS sets the still form; the script only waits less).
10
+ *
11
+ * kindOf(act) PURE: a page's action word → 'done' | 'moved' | 'gone' | ''
12
+ * classOf(kind) PURE: the class a kind adds, or ''
13
+ * reducedMotion(win) true when the window asks for reduced motion
14
+ * cue(el, kind, opt) adds the class and resolves when the cue ends (animationend, or a bounded wait); notes cue-<kind> in the local
15
+ * use log and writes one [change-cues] console line (the health log). A missing element or unknown kind resolves at once.
16
+ *
17
+ * Callers play the cue after the change is saved and before the list draws again; a failed save plays none. */
18
+ import { noteUse } from './use-log.js';
19
+
20
+ const KINDS = { done: 'done', tomorrow: 'moved', later: 'moved', move: 'moved', moved: 'moved', drop: 'gone', remove: 'gone', gone: 'gone' };
21
+ export const CUE_MS = 600; // the length of --duration-leaf; the wait if no animation event comes
22
+ export const STILL_MS = 450; // reduced motion: how long the still tint holds before the list draws again
23
+ const MARGIN_MS = 150;
24
+
25
+ export const kindOf = (act) => (Object.prototype.hasOwnProperty.call(KINDS, String(act || '')) ? KINDS[act] : '');
26
+ export const classOf = (kind) => (kind === 'done' || kind === 'moved' || kind === 'gone' ? 'pm-cue-' + kind : '');
27
+
28
+ export function reducedMotion(win) {
29
+ try { const w = win || (typeof window !== 'undefined' ? window : null); return !!(w && w.matchMedia && w.matchMedia('(prefers-reduced-motion: reduce)').matches); }
30
+ catch { return false; }
31
+ }
32
+
33
+ /** Play the cue on one element. opt: { win, note(control), log(line) } (tests pass fakes; the page uses window, noteUse, console.log). */
34
+ export function cue(el, kind, opt = {}) {
35
+ const cls = classOf(kind);
36
+ if (!el || !el.classList || !cls) return Promise.resolve(false);
37
+ const still = reducedMotion(opt.win);
38
+ const note = opt.note || noteUse;
39
+ const log = opt.log || ((s) => { try { console.log(s); } catch { /* no console */ } });
40
+ try { note('cue-' + kind); } catch { /* the use log is best effort */ }
41
+ log('[change-cues] ' + kind + (still ? ' still' : ''));
42
+ el.classList.add(cls);
43
+ return new Promise((resolve) => {
44
+ let over = false;
45
+ const end = () => { if (over) return; over = true; if (el.removeEventListener) el.removeEventListener('animationend', end); clearTimeout(t); resolve(true); };
46
+ const t = setTimeout(end, still ? STILL_MS : CUE_MS + MARGIN_MS);
47
+ if (!still && el.addEventListener) el.addEventListener('animationend', end);
48
+ });
49
+ }
50
+
51
+ /** The row an action button sits in: the closest list row, or the element itself. */
52
+ export const rowOf = (b) => (b && b.closest ? b.closest('.pm-li, [role="listitem"], li') || null : null);
@@ -92,7 +92,31 @@ function readItems(id, ws, redraw) {
92
92
  .then((x) => { ITEMS.set(id, x && x.ok && Array.isArray(x.items) ? x.items : false); if (x && x.ok && (x.items || []).length) redraw(); })
93
93
  .catch(() => ITEMS.set(id, false));
94
94
  }
95
- export const resetItems = () => ITEMS.clear();
95
+ export const resetItems = () => { ITEMS.clear(); CRIT.clear(); };
96
+ /* the done test's acceptance criteria for the initiative's Jira tickets (initiative jira-criteria-write, A384): GET /api/jira-criteria once
97
+ * per initiative; the ✦ shows when PMOS proposes at least one ticket (zero is silence) */
98
+ const CRIT = new Map(); // initiative id → { proposals, unmatched } | null while reading | false when there is nothing or no route
99
+ function readCrit(id, ws, redraw) {
100
+ if (!id || RO || CRIT.has(id)) return;
101
+ CRIT.set(id, null);
102
+ pmGet('/api/jira-criteria?ini=' + encodeURIComponent(id) + (ws ? '&ws=' + encodeURIComponent(ws) : ''))
103
+ .then((x) => { const ok = x && x.ok && Array.isArray(x.proposals) && x.proposals.length; CRIT.set(id, ok ? { proposals: x.proposals, unmatched: x.unmatched || [] } : false); if (ok) redraw(); })
104
+ .catch(() => CRIT.set(id, false));
105
+ }
106
+ /** The ✦ of the done test's criteria, above the list: each ticket, whose it is, and the checks it gets. */
107
+ function critSugHtml(cr) {
108
+ if (!cr || !cr.proposals || !cr.proposals.length) return '';
109
+ const L = cr.proposals, n = L.length, mine = L.filter((p) => p.direct).length;
110
+ const say = `Add the done test's checks to ${n === 1 ? L[0].key : n + ' Jira tickets'}`;
111
+ const row = (p) => `<li><b>${esc(p.key)}</b> ${esc(p.summary || '')} <span class="hi-small">${esc((p.direct ? 'yours, written in Jira' : 'draft for ' + (p.who || 'its owner')) + ' · check' + (p.labels.length === 1 ? ' ' : 's ') + p.labels.join(', '))}</span></li>`;
112
+ const will = [mine ? `Write them at the end of the description of ${mine === 1 ? 'your ticket' : 'your ' + mine + ' tickets'} in Jira, and change nothing else` : '',
113
+ n - mine ? `Put the other ${n - mine === 1 ? 'ticket' : n - mine + ' tickets'} in today's draft for ${n - mine === 1 ? 'its owner' : 'their owners'}, for you to send` : ''].filter(Boolean);
114
+ return `<div class="pm-sug x" role="group" aria-label="PMOS suggests"><div class="ttl">${SVG(P.spark || P.dia, 14)}<b class="say">${esc(say)}</b></div>`
115
+ + `<dl><dt>Why</dt><dd>${esc('The people who build these tickets do not see the done test. Each check goes on the ticket it fits, as Given / When / Then.')}</dd>`
116
+ + `<dt>PMOS will</dt><dd><ul>${will.map((w) => `<li>${esc(w)}</li>`).join('')}</ul></dd><dt>Tickets</dt><dd><ul>${L.map(row).join('')}</ul></dd></dl>`
117
+ + `<div class="ans"><button type="button" class="pm-btn primary" data-pw-crit-ok aria-label="Yes, do it" title="Yes, do it">${SVG(P.check, 14)}</button>`
118
+ + `<button type="button" class="pm-btn outline" data-pw-crit-drop aria-label="No" title="No">${SVG(P.x, 14)}</button></div></div>`;
119
+ }
96
120
  /* the goal's name, not its id (board 25: "De-risk Okta dependency", not KR-C4): GET /api/boards/anchors once per product */
97
121
  const GOALS = new Map(); // ws|board → [{ value, kind, label }] | null while reading | false
98
122
  let goalsRedraw = null;
@@ -350,7 +374,9 @@ function dsHtml(r, v, o, W, S, C, mode) {
350
374
  ? breakdownHtml(W, C, mode, false, S).replace('<h3>Work breakdown</h3>', head('gantt') + (S.sel.size ? SEL.barHtml(S.sel.size, { epic: epicSel }) : '')).replace('class="pw-sec"', 'class="pw-sec pm-block pwd-blk pwd-wbs"')
351
375
  : `<section class="pm-block pwd-blk pwd-wbs" aria-label="Work breakdown">${S.sel.size ? '' : head('list')}${PD.listHtml(stF, W, { looseN: W.looseN, epics, fix, ask, sel: S.sel, nested: st.some((x) => x.kids), drag: canDrag(), group, epicSel })}</section>`;
352
376
  const mg = mergeOf(W.artefacts), merge = mg ? `<div class="pw-sugs pw-amg" role="list" aria-label="PMOS suggests">${sugLine({ id: mg.id, say: mg.say, merge: mg })}</div>` : '';
353
- return `<div class="pw pwd">${'<div class="pwd-main">'}${PD.standsHtml(W, r)}${PD.stagesHtml(st, W)}${wbs}</div>`
377
+ // the done test's acceptance criteria on the initiative's Jira tickets (jira-criteria-write): its ✦ above the breakdown, unless the PM said no
378
+ const crit = S.sel.size || dropped().has('crit:' + id) ? '' : critSugHtml(CRIT.get(id));
379
+ return `<div class="pw pwd">${'<div class="pwd-main">'}${PD.standsHtml(W, r)}${PD.stagesHtml(st, W)}${crit}${wbs}</div>`
354
380
  + `<aside class="pwd-side">${PD.caseHtml(W, { oid: id, dropped: dropped() })}${PD.artsHtml(W.artefacts, { merge })}</aside></div>`;
355
381
  }
356
382
 
@@ -580,7 +606,7 @@ export function wire(body, h0, x0) {
580
606
  // the Viewer reuses its body for the next item: the presses read the item shown now from the body, so one set of listeners serves all
581
607
  body.__pwh = ED.writes(h0); body.__pwx = x0;
582
608
  { const o = x0 && x0.o ? x0.o() || {} : {}; ASK_AT = o.id ? { id: String(o.id), ws: o.ws || '' } : null; }
583
- { const c = cur(); if (c) { readItems(c.id, (x0.o() || {}).ws, () => redraw()); if (c.S.top) body.scrollTop = c.S.top; }
609
+ { const c = cur(); if (c) { readItems(c.id, (x0.o() || {}).ws, () => redraw()); readCrit(c.id, (x0.o() || {}).ws, () => redraw()); if (c.S.top) body.scrollTop = c.S.top; }
584
610
  const q = OPEN_ON_DRAW;
585
611
  if (c && q && q.id === String(c.id) && Date.now() - q.at < 15000) { OPEN_ON_DRAW = null; setTimeout(() => { const c2 = cur(); if (c2) openSmall(q.uid, c2, body.__pwh, body.__pwx, body); }, 0); } }
586
612
  if (body.__pw) return;
@@ -653,6 +679,8 @@ export function wire(body, h0, x0) {
653
679
  if ('pwTickNo' in d) { const u = S.tickAsk; S.tickAsk = ''; redraw(); if (u && h.status) await h.status(u, 'Done'); return; }
654
680
  if (d.pwSub) { const u = d.pwSub, open = b.getAttribute('aria-expanded') === 'true'; S.subOpen.delete(u); S.subShut.delete(u); (open ? S.subShut : S.subOpen).add(u); redraw(); return; }
655
681
  if ('pwEpicFix' in d) { b.disabled = true; await epicFix(c, h, x); return; }
682
+ if ('pwCritOk' in d) { b.disabled = true; await critFix(c, h, x); return; }
683
+ if ('pwCritDrop' in d) { const dd = dropped(); dd.add('crit:' + c.id); store.set(DROP, [...dd].slice(-200)); redraw(); return; }
656
684
  if ('pwEpicDrop' in d) { const dd = dropped(); dd.add('epic:' + c.id); store.set(DROP, [...dd].slice(-200)); redraw(); return; }
657
685
  if (d.wsOp) { await bulkPress(b, d.wsOp, c, h, x); return; }
658
686
  // the follow-ups (work-subtasks-followups): the Source filter, the ✦ grouping (✓ makes the parents, ✕ hides it)
@@ -1132,6 +1160,21 @@ async function epicFix(c, h, x) {
1132
1160
  say(words, async () => { const u = await pmPost('/api/jira-epics/undo', { ws: at.ws, ids: r.ids }).catch(() => null); dd.delete('epic:' + c.id); store.set(DROP, [...dd].slice(-200)); say(u && u.kept && u.kept.length ? 'Put back, except ' + u.kept.join(', ') + ': Jira already has it.' : 'Put back.'); if (h.redraw) h.redraw(); });
1133
1161
  if (h.redraw) h.redraw();
1134
1162
  }
1163
+ /** The done test's criteria ✦ (jira-criteria-write): the tickets it lists get them. The page sends the keys only; the server writes the
1164
+ * block from the done test. Tickets assigned to the PM are written in Jira by a session with the PM's own connection; the rest go to the
1165
+ * day's draft for their owners. Undo withdraws what Jira has not done yet (POST /api/jira-criteria/undo). */
1166
+ async function critFix(c, h, x) {
1167
+ const at = atOf(h, x), cr = CRIT.get(c.id);
1168
+ if (!cr || !cr.proposals.length) return;
1169
+ const r = await pmPost('/api/jira-criteria/ask', { ws: at.ws, ini: at.ini || c.id, keys: cr.proposals.map((p) => p.key) }).catch(() => null);
1170
+ const say = (m, u) => (u ? undoToast(m, u) : h.toast ? h.toast(m) : undoToast(m));
1171
+ if (!r || r.ok === false) { say((r && r.error) || 'The criteria were not asked.'); if (h.redraw) h.redraw(); return; }
1172
+ CRIT.set(c.id, false);
1173
+ const words = [r.direct.length ? (r.direct.length === 1 ? r.direct[0] + ' gets' : r.direct.length + ' tickets get') + ' the criteria in Jira now.' : '',
1174
+ r.draft.length ? (r.draft.length === 1 ? r.draft[0].key + ' is' : r.draft.length + ' tickets are') + ' in today\'s Jira draft for ' + [...new Set(r.draft.map((q) => q.who || 'their owner'))].join(', ') + '.' : ''].filter(Boolean).join(' ');
1175
+ say(words, async () => { const u = await pmPost('/api/jira-criteria/undo', { ws: at.ws, ids: r.ids }).catch(() => null); CRIT.delete(c.id); say(u && u.kept && u.kept.length ? 'Taken back, except ' + u.kept.join(', ') + ': Jira already has it.' : 'Taken back.'); if (h.redraw) h.redraw(); });
1176
+ if (h.redraw) h.redraw();
1177
+ }
1135
1178
  /* Who (WorkStatesDS 1): You, the people who own this initiative's tasks, and "PMOS does it". A name writes the owner (Undo puts the old one
1136
1179
  * back, POST /api/boards/tasks/edit with `from`); PMOS does it gives the task to PMOS (POST /api/backlog/give; Undo is /api/backlog/stop). */
1137
1180
  function whoMenu(btn, uid, c, h, x) {