create-pmos 0.727.0 → 0.729.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 (36) hide show
  1. package/package.json +39 -39
  2. package/payload/KIT-VERSION +1 -1
  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/workspace/changelog.json +38 -0
  7. package/workspace/guide/cli.md +14 -0
  8. package/workspace/guide/jira.md +18 -0
  9. package/workspace/guide/layout.md +1 -1
  10. package/workspace/lib/change-cues.js +34 -0
  11. package/workspace/lib/jira-cli.js +101 -3
  12. package/workspace/lib/jira-criteria.js +214 -0
  13. package/workspace/lib/jira-status.js +10 -5
  14. package/workspace/lib/jira-tiers.js +266 -0
  15. package/workspace/lib/open-questions.js +163 -0
  16. package/workspace/lib/pmos-verbs.js +3 -0
  17. package/workspace/lib/questions-cli.js +97 -0
  18. package/workspace/lib/refresh-probe.js +5 -0
  19. package/workspace/lib/refresh-run.js +2 -0
  20. package/workspace/lib/route-modules.js +1 -0
  21. package/workspace/lib/routes-jira-epics.js +62 -4
  22. package/workspace/lib/routes-open-questions.js +29 -0
  23. package/workspace/package-lock.json +2 -2
  24. package/workspace/package.json +1 -1
  25. package/workspace/public/pm/change-cues.css +15 -0
  26. package/workspace/public/pm/change-cues.js +52 -0
  27. package/workspace/public/pm/cozy-pop-work.js +46 -3
  28. package/workspace/public/pm/cozy-today-app.js +11 -8
  29. package/workspace/public/pm/home-app.js +4 -2
  30. package/workspace/public/today.html +1 -0
  31. package/workspace/skills/jira-criteria.skill +35 -0
  32. package/workspace/skills/jira-sync.skill +7 -2
  33. package/workspace/test-lists/change-cues.json +9 -0
  34. package/workspace/test-lists/jira-criteria-write.json +9 -0
  35. package/workspace/test-lists/jira-tiered-refresh.json +9 -0
  36. package/workspace/test-lists/open-questions.json +9 -0
@@ -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 };
@@ -350,7 +350,11 @@ function findTicket(root, key) {
350
350
  * Write the snapshot from a saved search result. Only the tickets this initiative pushed are kept; any other issue in
351
351
  * the result is counted and ignored. A pushed ticket missing from the result keeps its last reading, marked stale.
352
352
  */
353
- function sync(root, initiative, raw, { query, dryRun = false, now } = {}) {
353
+ /* PATCH (jira-tiered-refresh): a change search returns only the tickets Jira changed since the last check, for every initiative at
354
+ * once. `patch: true` merges them into the snapshot by key; a ticket the search did not return keeps its reading, is not marked stale
355
+ * and is not listed missing. In epic mode an issue with no parent is kept only when the snapshot already holds it (the search spans
356
+ * other initiatives' tickets too). A patch that keeps no issue of this initiative writes nothing (patched: false). */
357
+ function sync(root, initiative, raw, { query, dryRun = false, now, patch = false } = {}) {
354
358
  if (!jiraTickets.recordFm(root, initiative)) return { ok: false, error: `no initiative ${initiative} in this repository` };
355
359
  const n = normalize(raw);
356
360
  if (n.error) return { ok: false, error: n.error };
@@ -363,7 +367,7 @@ function sync(root, initiative, raw, { query, dryRun = false, now } = {}) {
363
367
  // with no parent field is kept, since the search was scoped to the epics; one under another parent is ignored.
364
368
  // In every mode the tickets the tasks name are kept too.
365
369
  const keep = pushed.size ? (i) => pushed.has(i.key) || tasks.has(i.key)
366
- : epics.length ? (i) => tasks.has(i.key) || epics.includes(i.key) || !i.parent || epics.includes(i.parent)
370
+ : epics.length ? (i) => tasks.has(i.key) || epics.includes(i.key) || epics.includes(i.parent) || (patch ? !!(prev && prev.tickets.has(i.key)) : !i.parent)
367
371
  : (i) => tasks.has(i.key);
368
372
  const got = new Map(n.issues.filter(keep).map((i) => [i.key, i]));
369
373
  const ignored = n.issues.length - got.size;
@@ -375,6 +379,7 @@ function sync(root, initiative, raw, { query, dryRun = false, now } = {}) {
375
379
  const r = got.get(key);
376
380
  const was = prev ? prev.tickets.get(key) : null;
377
381
  if (!r) {
382
+ if (patch) { if (was) readings.push(was); continue; }
378
383
  missing.push(key);
379
384
  if (was) readings.push({ ...was, stale: true });
380
385
  continue;
@@ -387,12 +392,12 @@ function sync(root, initiative, raw, { query, dryRun = false, now } = {}) {
387
392
  if (!!was.flagged !== !!r.flagged) changes.push({ key, what: r.flagged ? 'blocked' : 'unblocked', reason: r.reason || null });
388
393
  }
389
394
  const fetchedAt = nowIso(now);
390
- const result = { ok: true, initiative, read: got.size, ignored, skipped: n.skipped, missing, changes, snapshot: snapshotRel(root, initiative), dryRun: !!dryRun };
391
- if (dryRun) return result;
395
+ const result = { ok: true, initiative, read: got.size, ignored, skipped: n.skipped, missing, changes, snapshot: snapshotRel(root, initiative), dryRun: !!dryRun, ...(patch ? { patched: got.size > 0 } : {}) };
396
+ if (dryRun || (patch && !got.size)) return result;
392
397
  const file = snapshotPath(root, initiative);
393
398
  fs.mkdirSync(path.dirname(file), { recursive: true });
394
399
  const tmp = `${file}.${process.pid}.tmp`;
395
- fs.writeFileSync(tmp, renderSnapshot({ initiative, fetchedAt, query: query || (prev && prev.query) || null, readings, ids }));
400
+ fs.writeFileSync(tmp, renderSnapshot({ initiative, fetchedAt, query: (patch ? null : query) || (prev && prev.query) || null, readings, ids }));
396
401
  fs.renameSync(tmp, file);
397
402
  // the status moves this read saw, kept for the daily digest (daily-digest-from-tracker): the snapshot keeps only the latest state
398
403
  const TD = require('./tracker-digest.js');
@@ -0,0 +1,266 @@
1
+ 'use strict';
2
+ /* jira-tiers.js — refresh Jira by tier, reading only what changed (initiative jira-tiered-refresh).
3
+ *
4
+ * tierOf(reading, { pinned, sprintStates }) → 0 live · 1 next · 2 backlog · 3 done
5
+ * plan(root, { now }) → the searches this refresh runs (`pmos jira query --changed`), and records when it asked
6
+ * applyChanged(root, raw, { now, dryRun }) → patch the change search's issues into each initiative (`pmos jira sync --changed`)
7
+ * noteFull(root, initiative, sync result, { now }) a full read of one initiative (`pmos jira sync <ini>`): its checked time moves
8
+ * sprintDue(root, { now }) → { due, why }: is the whole-sprint read needed in this refresh?
9
+ * sprintRead(root) the whole-sprint read was saved: it is not needed again until a live ticket changes
10
+ * pin(root, initiative, on) the PM keeps an initiative live: all its tickets are Tier 0
11
+ * runStats(dir, since) → { mode, tiers, checked, fetched } of the run that asked at or after `since`, or null
12
+ *
13
+ * THE RULE. Every refresh asks Jira one cheap question about EVERY tracked ticket, of every tier: which of them changed since the last
14
+ * check (`key in (…) AND updated >= -<N>m`). A backlog ticket pulled into the sprint, a done ticket reopened, a new ticket under a linked
15
+ * epic: each comes back on the next refresh. Only the tickets Jira returns are fetched and patched in. The tier decides the follow-up
16
+ * work, not whether a change is seen: a change to a Tier 0 ticket marks the whole-sprint read and the sprint brief as needed; a Tier 1,
17
+ * 2 or 3 change is patched and nothing more.
18
+ *
19
+ * THE WEEKLY RECONCILE. Only a full read sees a ticket deleted in Jira or a link that changed. An initiative whose last full read is
20
+ * before this week's Monday (local time), or that has no snapshot yet, is read in full, as before.
21
+ *
22
+ * THE TIER IS NEVER STORED. It is derived from the stored reading on each run, so a ticket moves tier as soon as its reading does.
23
+ *
24
+ * FILE. <state>/tracker/jira/_tiers.json, local runtime state:
25
+ * { checked: { <ini>: iso }, full: { <ini>: iso }, pins: [ini], sprint_dirty: bool, sprint_read_at: iso,
26
+ * run: { asked_at, mode, change: [ini], full_due: [ini], checked, fetched, tiers: [n] } }
27
+ */
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+
31
+ const FILE = '_tiers.json';
32
+ const CHUNK = 100;
33
+ const SPARE_MIN = 5; // minutes added to each "updated since" window, as the refresh probe does
34
+ const LIVE_STATUS = /block|impediment|on hold/i;
35
+
36
+ const S = () => require('./jira-status.js');
37
+ const T = () => require('./jira-tickets.js');
38
+ const fileOf = (root) => path.join(T().jiraDir(root), FILE);
39
+ const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
40
+ const ms = (s) => { const t = Date.parse(s || ''); return Number.isFinite(t) ? t : 0; };
41
+
42
+ function readFile(f) {
43
+ try { const v = JSON.parse(fs.readFileSync(f, 'utf8')); return v && typeof v === 'object' && !Array.isArray(v) ? v : {}; } catch { return {}; }
44
+ }
45
+ function read(root) {
46
+ const v = readFile(fileOf(root));
47
+ return { checked: { ...(v.checked || {}) }, full: { ...(v.full || {}) }, pins: Array.isArray(v.pins) ? v.pins.filter((x) => typeof x === 'string') : [],
48
+ sprint_dirty: v.sprint_dirty === true, sprint_read_at: typeof v.sprint_read_at === 'string' ? v.sprint_read_at : null, run: v.run && typeof v.run === 'object' ? v.run : null };
49
+ }
50
+ function write(root, st) {
51
+ const f = fileOf(root);
52
+ fs.mkdirSync(path.dirname(f), { recursive: true });
53
+ const tmp = `${f}.${process.pid}.tmp`;
54
+ fs.writeFileSync(tmp, JSON.stringify(st) + '\n');
55
+ fs.renameSync(tmp, f);
56
+ }
57
+
58
+ // ── the tier ─────────────────────────────────────────────────────────────────────────────────────────
59
+ const sprintKey = (s) => (s && (s.id || s.name) ? String(s.id || s.name) : null);
60
+ /** The sprint states the last whole-sprint read saw (a future sprint that started is active there, while the ticket's own reading,
61
+ * not updated in Jira by the start, still says future). */
62
+ function sprintStatesOf(root) {
63
+ const out = new Map();
64
+ let snap = null; try { snap = S().readSprints(root); } catch { snap = null; }
65
+ if (!snap) return out;
66
+ for (const t of snap.tickets.values()) { const k = sprintKey(t.sprint); if (k && t.sprint.state) out.set(k, t.sprint.state); }
67
+ return out;
68
+ }
69
+ function tierOf(r, { pinned = false, sprintStates } = {}) {
70
+ if (!r) return 2;
71
+ if (pinned) return 0;
72
+ const done = r.category === 'done';
73
+ const sp = r.sprint || null;
74
+ const state = sp ? ((sprintStates && sprintStates.get(sprintKey(sp))) || sp.state || null) : null;
75
+ if (done) return 3;
76
+ if (state === 'active' || r.category === 'doing' || r.category === 'indeterminate' || r.flagged === true || LIVE_STATUS.test(String(r.status || ''))) return 0;
77
+ if (state === 'future') return 1;
78
+ return 2;
79
+ }
80
+
81
+ // ── which initiatives this refresh reads in full ───────────────────────────────────────────────────
82
+ /** The start of this week's Monday, local time, in ms. */
83
+ function mondayOf(now) {
84
+ const d = new Date(now);
85
+ d.setHours(0, 0, 0, 0);
86
+ d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
87
+ return d.getTime();
88
+ }
89
+ function fullWhy(st, q, snap, now) {
90
+ if (!snap) return 'no snapshot yet';
91
+ const f = ms(st.full[q.initiative]);
92
+ if (!f) return 'no full read recorded yet';
93
+ if (f < mondayOf(now)) return 'the weekly full read is due';
94
+ if (!ms(st.checked[q.initiative])) return 'no check recorded yet';
95
+ return null;
96
+ }
97
+ const chunks = (xs, n) => { const out = []; for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n)); return out; };
98
+
99
+ /**
100
+ * The searches of this refresh. Initiatives due a full read get their own full search; every other tracked ticket, of every tier, is in
101
+ * the change searches. Records when it asked, so the checks that follow stamp that time (a change made while the run reads is seen on
102
+ * the next refresh, not lost).
103
+ */
104
+ function plan(root, { now = Date.now(), record = true } = {}) {
105
+ const st = read(root);
106
+ const linked = S().linkedInitiatives(root).filter((x) => x.linked);
107
+ const full = []; const change = []; const keys = new Set(); const epics = new Set(); let since = 0;
108
+ for (const q of linked) {
109
+ const snap = S().readSnapshot(root, q.initiative);
110
+ const why = fullWhy(st, q, snap, now);
111
+ if (why) { full.push({ initiative: q.initiative, why, query: q.query }); continue; }
112
+ change.push(q.initiative);
113
+ for (const k of q.keys || []) keys.add(k);
114
+ for (const k of snap.tickets.keys()) keys.add(k);
115
+ for (const e of q.epics || []) epics.add(e);
116
+ const c = ms(st.checked[q.initiative]);
117
+ if (!since || c < since) since = c;
118
+ }
119
+ const minutes = change.length ? Math.max(1, Math.ceil((now - since) / 60000)) + SPARE_MIN : null;
120
+ const win = minutes ? ` AND updated >= -${minutes}m` : '';
121
+ const all = [...keys].sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
122
+ const searches = change.length ? [
123
+ ...chunks(all, CHUNK).map((ks) => `key in (${ks.join(', ')})${win} ORDER BY key`),
124
+ ...chunks([...epics].sort(), CHUNK).map((es) => `parent in (${es.join(', ')})${win} ORDER BY key`),
125
+ ] : [];
126
+ const out = { ok: true, mode: full.length && !change.length ? 'full' : 'changed', since: since ? iso(since) : null, minutes, checked: all.length,
127
+ change, searches, full, linked: linked.length };
128
+ if (record) {
129
+ st.run = { asked_at: iso(now), mode: full.length ? 'full' : 'changed', change, full_due: full.map((x) => x.initiative), checked: all.length, fetched: 0, tiers: [] };
130
+ write(root, st);
131
+ }
132
+ return out;
133
+ }
134
+
135
+ /** The time this run asked (plan), or now when no plan was made. */
136
+ const askedAt = (st, now) => (st.run && st.run.asked_at ? st.run.asked_at : iso(now));
137
+ const addRun = (st, { fetched = 0, checked = 0, tiers = [] }) => {
138
+ if (!st.run) st.run = { asked_at: null, mode: 'full', change: [], full_due: [], checked: 0, fetched: 0, tiers: [] };
139
+ st.run.fetched = (Number(st.run.fetched) || 0) + fetched;
140
+ st.run.checked = (Number(st.run.checked) || 0) + checked;
141
+ st.run.tiers = [...new Set([...(st.run.tiers || []), ...tiers])].sort();
142
+ };
143
+
144
+ /** What one sync changed, as follow-up: the tiers of the tickets it read, and whether the whole-sprint read is needed. */
145
+ function followUp(root, st, before, readings, initiative) {
146
+ const pinned = st.pins.includes(initiative);
147
+ const sprintStates = sprintStatesOf(root);
148
+ const tiers = []; let dirty = false;
149
+ for (const r of readings) {
150
+ const now = tierOf(r, { pinned, sprintStates });
151
+ const was = before ? before.get(r.key) : null;
152
+ tiers.push(now);
153
+ if (now === 0 || (was && tierOf(was, { pinned, sprintStates }) === 0)) dirty = true;
154
+ if (was && S().sprintLabel(was.sprint) !== S().sprintLabel(r.sprint)) dirty = true;
155
+ }
156
+ return { tiers, dirty };
157
+ }
158
+
159
+ /** A full read of one initiative was saved: its full and checked times move to the time this run asked. */
160
+ function noteFull(root, initiative, res, { now = Date.now(), before = null } = {}) {
161
+ if (!res || !res.ok || res.dryRun) return;
162
+ const st = read(root);
163
+ const at = askedAt(st, now);
164
+ st.full[initiative] = at; st.checked[initiative] = at;
165
+ const snap = S().readSnapshot(root, initiative);
166
+ const f = followUp(root, st, before, snap ? [...snap.tickets.values()] : [], initiative);
167
+ // a full read can see anything move: the sprint read follows it
168
+ st.sprint_dirty = true;
169
+ addRun(st, { fetched: res.read || 0, checked: snap ? snap.tickets.size : 0, tiers: f.tiers });
170
+ write(root, st);
171
+ }
172
+
173
+ /**
174
+ * Patch the change search's issues into each initiative they belong to. A ticket not returned keeps its reading. Every initiative of the
175
+ * change group gets the time this run asked as its checked time, also when nothing came back.
176
+ */
177
+ function applyChanged(root, raw, { now = Date.now(), dryRun = false } = {}) {
178
+ const n = S().normalize(raw);
179
+ if (n.error) return { ok: false, error: n.error };
180
+ const st = read(root);
181
+ const group = st.run && Array.isArray(st.run.change) && st.run.change.length ? st.run.change
182
+ : S().linkedInitiatives(root).filter((x) => x.linked).map((x) => x.initiative);
183
+ const at = askedAt(st, now);
184
+ const per = []; const kept = new Set(); let tiers = []; let dirty = false;
185
+ for (const ini of group) {
186
+ const prev = S().readSnapshot(root, ini);
187
+ const r = S().sync(root, ini, raw, { patch: true, dryRun, now });
188
+ if (!r.ok) { per.push({ initiative: ini, error: r.error }); continue; }
189
+ if (!r.read) continue;
190
+ const mine = n.issues.filter((i) => (prev && prev.tickets.has(i.key)) || r.changes.some((c) => c.key === i.key));
191
+ const got = S().readSnapshot(root, ini);
192
+ const readings = dryRun ? mine : mine.map((i) => (got && got.tickets.get(i.key)) || i);
193
+ readings.forEach((i) => kept.add(i.key));
194
+ const f = followUp(root, st, prev ? prev.tickets : null, readings, ini);
195
+ tiers = tiers.concat(f.tiers); dirty = dirty || f.dirty;
196
+ per.push({ initiative: ini, read: r.read, changes: r.changes });
197
+ }
198
+ const result = { ok: true, fetched: n.issues.length, kept: kept.size, ignored: n.issues.length - kept.size, skipped: n.skipped, initiatives: per,
199
+ tiers: [...new Set(tiers)].sort(), sprintNeeded: dirty, dryRun: !!dryRun };
200
+ if (dryRun) return result;
201
+ for (const ini of group) st.checked[ini] = at;
202
+ if (dirty) st.sprint_dirty = true;
203
+ addRun(st, { fetched: n.issues.length, tiers });
204
+ write(root, st);
205
+ return { ...result, checkedAt: at };
206
+ }
207
+
208
+ /** Is the whole-sprint read needed in this refresh? Without a tier record the answer is always yes (the old flow). */
209
+ function sprintDue(root, { now = Date.now() } = {}) {
210
+ const st = read(root);
211
+ if (!st.run || !st.run.asked_at) return { due: true, why: 'no tiered check recorded yet' };
212
+ if (st.sprint_dirty) return { due: true, why: 'a live ticket changed since the last sprint read' };
213
+ let snap = null; try { snap = S().readSprints(root); } catch { snap = null; }
214
+ if (!snap) return { due: true, why: 'no whole-sprint read yet' };
215
+ const today = iso(now).slice(0, 10);
216
+ for (const t of snap.tickets.values()) {
217
+ const sp = t.sprint || {};
218
+ if (sp.state === 'active' && sp.end && String(sp.end).slice(0, 10) < today) return { due: true, why: `${sp.name} ended, so it may have closed` };
219
+ if (sp.state === 'future' && sp.start && String(sp.start).slice(0, 10) <= today) return { due: true, why: `${sp.name} was due to start` };
220
+ }
221
+ return { due: false, why: 'no live ticket changed since the last sprint read' };
222
+ }
223
+ function sprintRead(root, { now = Date.now() } = {}) {
224
+ const st = read(root);
225
+ st.sprint_dirty = false; st.sprint_read_at = iso(now);
226
+ write(root, st);
227
+ }
228
+
229
+ function pin(root, initiative, on = true) {
230
+ if (!T().recordFm(root, initiative)) return { ok: false, error: `no initiative ${initiative} in this repository` };
231
+ const st = read(root);
232
+ const had = st.pins.includes(initiative);
233
+ st.pins = on ? [...new Set([...st.pins, initiative])].sort() : st.pins.filter((x) => x !== initiative);
234
+ write(root, st);
235
+ return { ok: true, initiative, pinned: !!on, changed: had !== !!on };
236
+ }
237
+
238
+ /** The tier counts of every stored reading, for `pmos jira query --changed` and tests. */
239
+ function counts(root) {
240
+ const st = read(root);
241
+ const sprintStates = sprintStatesOf(root);
242
+ const c = [0, 0, 0, 0];
243
+ for (const q of S().linkedInitiatives(root).filter((x) => x.linked)) {
244
+ const snap = S().readSnapshot(root, q.initiative);
245
+ if (!snap) continue;
246
+ for (const r of snap.tickets.values()) c[tierOf(r, { pinned: st.pins.includes(q.initiative), sprintStates })]++;
247
+ }
248
+ return c;
249
+ }
250
+
251
+ /** The measured run for the refresh log: from the Jira folder, when the run asked at or after `since` (ms). */
252
+ function runStats(jiraDir, since) {
253
+ if (!jiraDir) return null;
254
+ const v = readFile(path.join(jiraDir, FILE));
255
+ const r = v.run;
256
+ if (!r || !r.asked_at || ms(r.asked_at) < since) return null;
257
+ return { mode: r.mode === 'full' ? 'full' : 'changed', tiers: Array.isArray(r.tiers) ? r.tiers : [], checked: Number(r.checked) || 0, fetched: Number(r.fetched) || 0 };
258
+ }
259
+ /** For the refresh probe: the initiatives the last plan said are due a full read, or null when no tiered plan was made. */
260
+ function fullDue(jiraDir) {
261
+ if (!jiraDir) return null;
262
+ const v = readFile(path.join(jiraDir, FILE));
263
+ return v.run && Array.isArray(v.run.full_due) ? v.run.full_due : null;
264
+ }
265
+
266
+ module.exports = { FILE, CHUNK, tierOf, mondayOf, plan, applyChanged, noteFull, sprintDue, sprintRead, pin, counts, runStats, fullDue, read, fileOf };