create-pmos 0.444.0 → 0.446.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 (83) hide show
  1. package/package.json +25 -25
  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/README.md +1 -1
  8. package/workspace/adler-moments-test.js +8 -0
  9. package/workspace/adler-seasons-art-test.js +3 -0
  10. package/workspace/board-columns-test.js +168 -0
  11. package/workspace/board-programs-test.js +1 -1
  12. package/workspace/briefing-premium-board-test.js +83 -6
  13. package/workspace/briefing-premium-insights-test.js +43 -0
  14. package/workspace/calm-timeline-test.js +3 -1
  15. package/workspace/changelog.json +24 -0
  16. package/workspace/guide/jira.md +13 -1
  17. package/workspace/guide/ready-made-dashboards.md +2 -2
  18. package/workspace/lib/board-fold.js +33 -5
  19. package/workspace/lib/console-state.js +5 -1
  20. package/workspace/lib/factory-join.js +46 -14
  21. package/workspace/lib/freshness.js +14 -1
  22. package/workspace/lib/initiative-rows.js +38 -4
  23. package/workspace/lib/issues.js +8 -1
  24. package/workspace/lib/jira-cli.js +18 -2
  25. package/workspace/lib/jira-moves.js +119 -0
  26. package/workspace/lib/jira-tickets.js +23 -4
  27. package/workspace/lib/notes.js +4 -2
  28. package/workspace/lib/offloop.js +75 -29
  29. package/workspace/lib/page-build.js +97 -0
  30. package/workspace/lib/plan-items.js +24 -3
  31. package/workspace/lib/plan-tree.js +62 -9
  32. package/workspace/lib/ready-reports.js +22 -8
  33. package/workspace/lib/refresh.js +14 -2
  34. package/workspace/lib/routes-board-premium.js +9 -1
  35. package/workspace/lib/routes-boards.js +74 -15
  36. package/workspace/lib/routes-brief-page.js +3 -1
  37. package/workspace/lib/routes-calendar-import.js +13 -1
  38. package/workspace/lib/routes-ready-reports.js +28 -5
  39. package/workspace/lib/task-links.js +12 -1
  40. package/workspace/lib/workflows-store.js +14 -3
  41. package/workspace/milestone-pins-test.js +1 -1
  42. package/workspace/package-lock.json +2 -2
  43. package/workspace/package.json +1 -1
  44. package/workspace/panels-test.js +150 -6
  45. package/workspace/program-panel-test.js +6 -6
  46. package/workspace/public/pm/bd-cols.js +149 -0
  47. package/workspace/public/pm/bd-pane.js +41 -0
  48. package/workspace/public/pm/bd-span.js +29 -11
  49. package/workspace/public/pm/cozy-board.css +45 -0
  50. package/workspace/public/pm/cozy-insights.css +8 -0
  51. package/workspace/public/pm/cozy-live-pill.css +1 -0
  52. package/workspace/public/pm/cozy-live-pill.js +10 -1
  53. package/workspace/public/pm/cozy-panels.css +24 -3
  54. package/workspace/public/pm/cozy-panels.js +275 -108
  55. package/workspace/public/pm/cozy-viewer.js +3 -1
  56. package/workspace/public/pm/dash-view.js +5 -2
  57. package/workspace/public/pm/home-app.js +8 -8
  58. package/workspace/public/pm/ini-edit.js +5 -1
  59. package/workspace/public/pm/ini-tasks.js +134 -29
  60. package/workspace/public/pm/ini-view-model.js +4 -3
  61. package/workspace/public/pm/ini-view.css +74 -25
  62. package/workspace/public/pm/ini-view.js +4 -4
  63. package/workspace/public/pm/ini-wf-model.js +9 -0
  64. package/workspace/public/pm/ini-wf.js +14 -9
  65. package/workspace/public/pm/ins-pane.js +55 -0
  66. package/workspace/public/pm/jira-move.js +50 -0
  67. package/workspace/public/pm/live-model.js +3 -2
  68. package/workspace/public/pm/pn-narrow.js +76 -0
  69. package/workspace/public/pm/premium-board.js +77 -26
  70. package/workspace/public/pm/premium-insights.js +7 -1
  71. package/workspace/public/premium-board.html +2 -0
  72. package/workspace/ready-dash-ui-test.js +4 -4
  73. package/workspace/server.js +71 -20
  74. package/workspace/skills/jira-move.skill +35 -0
  75. package/workspace/stage-card-tasks-test.js +1 -0
  76. package/workspace/task-links-test.js +1 -0
  77. package/workspace/task-plans-test.js +1 -1
  78. package/workspace/task-views-test.js +161 -12
  79. package/workspace/test-lists/board-columns.json +5 -0
  80. package/workspace/test-lists/jira-moves.json +11 -0
  81. package/workspace/test-lists/page-speed-fold.json +5 -0
  82. package/workspace/test-lists/page-speed-reads.json +5 -0
  83. package/workspace/timeline-holds-test.js +1 -1
@@ -12,7 +12,8 @@
12
12
  *
13
13
  * THE ANSWER IS THE SAME FUNCTION'S. The worker requires the same module and calls the same export with the same
14
14
  * arguments; nothing is cached here. A worker that cannot start, crashes or times out rejects, and `run` then answers in
15
- * this thread, so a route never fails because of the worker. One worker serves every call, one call at a time in order.
15
+ * this thread, so a route never fails because of the worker. One worker serves every call, one call at a time in order;
16
+ * a call the same as one still queued joins it (ONE FOLD FOR A BURST, below).
16
17
  * Only modules in workspace/lib and only names in ALLOWED can be called.
17
18
  */
18
19
  const path = require('path');
@@ -23,10 +24,18 @@ const TIMEOUT_MS = 60000;
23
24
 
24
25
  let worker = null;
25
26
  let seq = 0;
26
- const pending = new Map(); // id -> { resolve, reject, timer }
27
+ const queue = []; // calls not yet sent to the worker: { mod, fn, args, key, waiters: [{ resolve, reject }] }
28
+ let inFlight = null; // the one call the worker is folding: the same shape, plus { id, timer }
27
29
 
28
30
  function allowed(mod, fn) { return Object.prototype.hasOwnProperty.call(ALLOWED, mod) && ALLOWED[mod].includes(fn); }
29
31
 
32
+ /* ONE FOLD FOR A BURST. One Home open asks for each repository's Board fold from five routes at once (My work, Inbox, News
33
+ * for you, the briefing, pm-items). A call that is the same as one still QUEUED (same module, function and arguments;
34
+ * the caller's `now` aside) waits for that call's answer instead of folding again. Only a queued call is joined, never
35
+ * one the worker has started: a queued call reads the files when it starts, after every caller that joined it asked, so
36
+ * a write made before any of them asked is in the answer. The answer keeps the clock of the call that was queued first. */
37
+ const keyOf = (mod, fn, args) => mod + '#' + fn + '#' + JSON.stringify(args, (k, v) => (k === 'now' ? undefined : v));
38
+
30
39
  const WORKER_SRC = `
31
40
  const { parentPort } = require('worker_threads');
32
41
  const path = require('path');
@@ -39,42 +48,69 @@ parentPort.on('message', (m) => {
39
48
  }
40
49
  });`;
41
50
 
42
- function failAll(err) {
43
- for (const [id, p] of pending) { clearTimeout(p.timer); p.reject(err); pending.delete(id); }
51
+ function settle(job, err, out) {
52
+ for (const w of job.waiters) { if (err) w.reject(err); else w.resolve(out); }
53
+ }
54
+
55
+ /** The worker went away: its call fails (run() answers it in this thread); the queue goes on with a new worker. */
56
+ function lost(w, err) {
57
+ if (worker !== w) return;
58
+ worker = null;
59
+ const job = inFlight; inFlight = null;
60
+ if (job) { clearTimeout(job.timer); settle(job, err); }
61
+ pump();
44
62
  }
45
63
 
46
64
  function ensure() {
47
65
  if (worker) return worker;
48
66
  const { Worker } = require('worker_threads');
49
- worker = new Worker(WORKER_SRC, { eval: true });
50
- worker.unref();
51
- worker.on('message', (m) => {
52
- const p = pending.get(m.id);
53
- if (!p) return;
54
- pending.delete(m.id); clearTimeout(p.timer);
55
- if (m.ok) p.resolve(m.out); else p.reject(new Error(m.error));
67
+ const w = new Worker(WORKER_SRC, { eval: true });
68
+ worker = w;
69
+ w.unref();
70
+ w.on('message', (m) => {
71
+ const job = inFlight;
72
+ if (!job || m.id !== job.id) return;
73
+ inFlight = null; clearTimeout(job.timer);
74
+ if (m.ok) settle(job, null, m.out); else settle(job, new Error(m.error));
75
+ pump();
56
76
  });
57
- worker.on('error', (e) => { worker = null; failAll(e); });
58
- worker.on('exit', () => { worker = null; failAll(new Error('the worker ended')); });
59
- return worker;
77
+ w.on('error', (e) => lost(w, e));
78
+ w.on('exit', () => lost(w, new Error('the worker ended')));
79
+ return w;
80
+ }
81
+
82
+ /** Send the next queued call, when the worker is free. */
83
+ function pump() {
84
+ if (inFlight) return;
85
+ const job = queue.shift();
86
+ if (!job) { if (worker) worker.unref(); return; }
87
+ let w;
88
+ try { w = ensure(); } catch (e) { settle(job, e); pump(); return; }
89
+ job.id = ++seq;
90
+ inFlight = job;
91
+ job.timer = setTimeout(() => {
92
+ if (inFlight !== job) return;
93
+ inFlight = null; settle(job, new Error('offloop: timed out'));
94
+ // a fold that hangs takes the worker with it; the next call starts a new one
95
+ if (worker === w) worker = null;
96
+ try { w.terminate(); } catch { /* already gone */ }
97
+ pump();
98
+ }, TIMEOUT_MS);
99
+ if (job.timer.unref) job.timer.unref();
100
+ w.ref(); // keep the process up while a call is in flight
101
+ w.postMessage({ id: job.id, mod: job.mod, fn: job.fn, args: job.args });
60
102
  }
61
103
 
62
104
  function call(mod, fn, args = []) {
63
105
  if (!allowed(mod, fn)) return Promise.reject(new Error(`offloop: ${mod}#${fn} is not allowed`));
64
106
  return new Promise((resolve, reject) => {
65
- let w;
66
- try { w = ensure(); } catch (e) { reject(e); return; }
67
- const id = ++seq;
68
- const timer = setTimeout(() => {
69
- pending.delete(id); reject(new Error('offloop: timed out'));
70
- // a fold that hangs takes the worker with it; the next call starts a new one
71
- try { w.terminate(); } catch { /* already gone */ }
72
- }, TIMEOUT_MS);
73
- if (timer.unref) timer.unref();
74
- pending.set(id, { resolve, reject, timer });
75
- w.ref(); // keep the process up while a call is in flight
76
- w.postMessage({ id, mod, fn, args });
77
- }).finally(() => { if (worker && !pending.size) worker.unref(); });
107
+ let key;
108
+ try { key = keyOf(mod, fn, args); } catch (e) { reject(e); return; }
109
+ const queued = queue.find((j) => j.key === key);
110
+ if (queued) { queued.waiters.push({ resolve, reject }); return; }
111
+ queue.push({ mod, fn, args, key, waiters: [{ resolve, reject }] });
112
+ pump();
113
+ });
78
114
  }
79
115
 
80
116
  function fallback(mod, fn, args = []) {
@@ -89,6 +125,16 @@ async function run(mod, fn, args = []) {
89
125
  try { return await call(mod, fn, args); } catch { return fallback(mod, fn, args); }
90
126
  }
91
127
 
92
- function stop() { if (worker) { const w = worker; worker = null; failAll(new Error('stopped')); return w.terminate(); } return Promise.resolve(); }
128
+ function stop() {
129
+ const err = new Error('stopped');
130
+ for (const job of queue.splice(0)) settle(job, err);
131
+ const job = inFlight; inFlight = null;
132
+ if (job) { clearTimeout(job.timer); settle(job, err); }
133
+ if (worker) { const w = worker; worker = null; return w.terminate(); }
134
+ return Promise.resolve();
135
+ }
136
+
137
+ /** What waits, for a suite: whether a call is in the worker, how many calls are queued and how many callers wait on them. */
138
+ function waiting() { return { inFlight: !!inFlight, queued: queue.length, callers: queue.reduce((n, j) => n + j.waiters.length, 0) }; }
93
139
 
94
- module.exports = { call, run, fallback, stop, ALLOWED };
140
+ module.exports = { call, run, fallback, stop, waiting, ALLOWED };
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+ /* page-build.js — the build prefix a page loads its code from, and the modules a page can ask for at once (page-speed).
3
+ *
4
+ * The prefix names the CONTENT of public/pm/, not the launch: it is the app version plus a hash of every file's size, mtime,
5
+ * change time and inode (the same signature serveFile uses). So:
6
+ * - an update, a merge or an edit changes at least one signature, and the page gets a new prefix: every module has a new
7
+ * address, which no cache (the browser, or one between it and this server) has seen. An update always shows new code.
8
+ * - a restart with the same files keeps the prefix, so the browser keeps what it has.
9
+ * That makes a file under the CURRENT prefix safe to keep for good ("immutable"): keeps() says yes only when the file the
10
+ * server is about to send has the signature the prefix was computed from. A file under an older prefix, or one edited after
11
+ * the page was served, is sent with no-cache as before.
12
+ *
13
+ * preloads() lists the modules a page's entry imports statically, directly or through others. The page names them in
14
+ * <link rel="modulepreload">, so the browser asks for all of them at once instead of finding them one import level at a time
15
+ * (Home is five levels deep). A dynamic import() is left out: it loads on use. */
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const crypto = require('crypto');
19
+
20
+ const sigOf = (st) => `${st.size}:${st.mtimeMs}:${st.ctimeMs}:${st.ino}`;
21
+ // A static import or re-export of a module in the same folder: `import x from './a.js'`, `import './a.js'`,
22
+ // `export { b } from './b.js'`. `import(` and `import.meta` do not match.
23
+ const STATIC_RE = /(?:^|[;\s}])(?:import\s*(?:[\w*{}\s,$]+?\s*from\s*)?|export\s*(?:\*(?:\s*as\s+[\w$]+)?|\{[^}]*\})\s*from\s*)(['"])([^'"\n]+)\1/g;
24
+ const stripComments = (src) => src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
25
+
26
+ /** The module names `src` imports statically, as file names in the same folder ('./a.js' or '/pm/a.js' → 'a.js'). */
27
+ function staticImports(src) {
28
+ const out = [];
29
+ for (const m of stripComments(String(src)).matchAll(STATIC_RE)) {
30
+ const s = m[2];
31
+ const name = s.startsWith('./') ? s.slice(2) : s.startsWith('/pm/') ? s.slice(4) : null;
32
+ if (name && !name.includes('/') && /\.m?js$/.test(name)) out.push(name);
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** dir: the folder the page code is in (public/pm). version: the app version, the readable start of the prefix. */
38
+ function create({ dir, version }) {
39
+ const ver = String(version || 'dev').replace(/[^0-9A-Za-z.-]/g, '') || 'dev';
40
+ let snap = null;
41
+ let pending = null;
42
+
43
+ async function compute() {
44
+ const names = (await fs.promises.readdir(dir)).filter((n) => /\.(js|mjs|css|json)$/.test(n)).sort();
45
+ const sts = await Promise.all(names.map((n) => fs.promises.stat(path.join(dir, n)).catch(() => null)));
46
+ const sigs = new Map();
47
+ names.forEach((n, i) => { if (sts[i] && sts[i].isFile()) sigs.set(n, sigOf(sts[i])); });
48
+ const h = crypto.createHash('sha1');
49
+ for (const [n, s] of sigs) h.update(n + '\0' + s + '\n');
50
+ const id = ver + '-' + h.digest('hex').slice(0, 12);
51
+ if (!snap || snap.id !== id) snap = { id, sigs, graphs: new Map() };
52
+ return snap;
53
+ }
54
+ /** The prefix for a page served now. Page loads that arrive together share one directory read. */
55
+ function current() {
56
+ if (!pending) pending = compute().finally(() => { pending = null; });
57
+ return pending;
58
+ }
59
+ /** May the file `name`, about to be sent with signature `sig` under prefix `id`, be kept by the browser for good? */
60
+ function keeps(id, name, sig) {
61
+ return !!snap && snap.id === id && snap.sigs.get(name) === sig;
62
+ }
63
+ /** Every module `entry` imports statically (not `entry` itself), nearest first. Read once per prefix. */
64
+ async function preloads(s, entry) {
65
+ if (s.graphs.has(entry)) return s.graphs.get(entry);
66
+ const seen = new Set([entry]);
67
+ let wave = [entry];
68
+ while (wave.length) {
69
+ const srcs = await Promise.all(wave.map((n) => fs.promises.readFile(path.join(dir, n), 'utf8').catch(() => '')));
70
+ const next = [];
71
+ for (const src of srcs) for (const d of staticImports(src)) if (!seen.has(d) && s.sigs.has(d)) { seen.add(d); next.push(d); }
72
+ wave = next;
73
+ }
74
+ const list = [...seen].slice(1);
75
+ s.graphs.set(entry, list);
76
+ return list;
77
+ }
78
+ return { current, keeps, preloads };
79
+ }
80
+
81
+ /** The page with its /pm/ and /lib/ references under prefix `id`, an import map that sends an absolute import('/pm/…') to the
82
+ * same address (so it gets the module instance the page already holds, not a second one), and a modulepreload line per module
83
+ * in `preload`. */
84
+ function withBuild(html, id, preload = []) {
85
+ const head = '\n<script type="importmap">' + JSON.stringify({ imports: { '/pm/': '/b/' + id + '/pm/' } }) + '</script>' +
86
+ preload.map((n) => '\n<link rel="modulepreload" href="/b/' + id + '/pm/' + n + '" />').join('');
87
+ return html
88
+ .replace(/(["'])\/(pm|lib)\//g, (m, q, d) => q + '/b/' + id + '/' + d + '/')
89
+ .replace('<meta charset="utf-8" />', '<meta charset="utf-8" />' + head);
90
+ }
91
+ /** The module the page starts from: its first <script type="module" src="/pm/…">, as a file name, or null. */
92
+ function entryOf(html) {
93
+ const m = /<script type="module" src="\/pm\/([\w.-]+\.m?js)"/.exec(String(html));
94
+ return m ? m[1] : null;
95
+ }
96
+
97
+ module.exports = { create, withBuild, entryOf, staticImports, sigOf };
@@ -471,9 +471,30 @@ function finish(S, { now = Date.now(), dupes = 0 } = {}) {
471
471
  };
472
472
  }
473
473
 
474
- function readFold(root, { now } = {}) {
474
+ /* THE FOLD MEMO. Board, My work and the Jira gate fold the same ledger many times a second (once per initiative, once per
475
+ * route). A fold is reused while the ledger's stat (inode, size, mtime, ctime) is the one taken BEFORE it was read, and the
476
+ * UTC day is the same (the clock decides only `late`, a due date before today). A write changes the stat, so it shows on
477
+ * the very next read; a write during a read leaves the older stat at worst, which costs one more read and hides nothing.
478
+ * readFold hands each caller its own copy; readFoldShared hands the memo itself, for a reader that never changes it. */
479
+ const foldMemo = new Map(); // ledger file -> { key, day, fold }
480
+ function readFoldShared(root, { now } = {}) {
481
+ const t = Number.isFinite(now) ? now : Date.now();
482
+ const day = new Date(t).toISOString().slice(0, 10);
483
+ let file = null; let key = null;
484
+ try {
485
+ file = ledgerPath(root);
486
+ const st = fs.statSync(file);
487
+ if (st.isFile()) key = `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`;
488
+ } catch { key = null; }
489
+ const hit = file && foldMemo.get(file);
490
+ if (key && hit && hit.key === key && hit.day === day) return hit.fold;
475
491
  const { lines, flags } = readLines(root);
476
- return fold(lines, { now, flags });
492
+ const out = fold(lines, { now: t, flags });
493
+ if (key) { if (foldMemo.size > 200) foldMemo.clear(); foldMemo.set(file, { key, day, fold: out }); }
494
+ return out;
495
+ }
496
+ function readFold(root, opts = {}) {
497
+ return structuredClone(readFoldShared(root, opts));
477
498
  }
478
499
 
479
500
  const progressLabel = planTree.progressLabel;
@@ -917,6 +938,6 @@ function handoffPrompt(item, initiativeId, stageLabel) {
917
938
  module.exports = {
918
939
  LEDGER, EVENTS, STATES, PM_SLUG, ID_RE, INIT_RE, SESSION_RE,
919
940
  ledgerRoot, ledgerPath, newItemId, newEventId, initiativeOf,
920
- readLines, parseText, fold, readFold, progressOf, progressLabel, lineErr,
941
+ readLines, parseText, fold, readFold, readFoldShared, progressOf, progressLabel, lineErr,
921
942
  actorFromCli, appendFromUi, appendFromCli, needsFor, ledgerSigs, readLayout, handoffPrompt, parseEvidence,
922
943
  };
@@ -3,8 +3,10 @@
3
3
  *
4
4
  * pm-os-absorb Run 1 (PRD R4, R5, R6, R18, R19). Pure apart from reading the initiative record and the
5
5
  * repository's profile: the caller passes the folded ledger (lib/plan-items.js) and the ladder
6
- * (lib/console-state.js `ladder()`), and this module groups them. Nothing here writes, and nothing is cached
7
- * (D33): every answer is derived from what the caller read on this request.
6
+ * (lib/console-state.js `ladder()`), and this module groups them. Nothing here writes. The two file reads (the record's
7
+ * frontmatter, the repository's profile) are memoized on the file's stat (size, mtime, ctime, inode), the same
8
+ * evidence lib/board-fold.js sideSig takes for "the record changed": an edit shows on the next read, and an
9
+ * unchanged record is not read and parsed again on every request (Board and My work ask four times per record).
8
10
  *
9
11
  * WHY THE STAGES ARE NOT A LIST OF THEIR OWN. A stage header groups the steps `scripts/workflow-state.js`
10
12
  * derives for the initiative's lane and profile (R4). The step keys come from the engine (lane-defs
@@ -65,7 +67,8 @@ function engine() {
65
67
  * of a bare repository has a common directory that is not named `.git`. Following those would put the ledger
66
68
  * outside the repository (or inside a git directory), where git, CI and every other clone never see it.
67
69
  */
68
- function mainTree(root) {
70
+ function mainTree(root) { return passed('main', root, () => mainTreeRead(root)); }
71
+ function mainTreeRead(root) {
69
72
  const dotgit = path.join(root, '.git');
70
73
  let st;
71
74
  try { st = fs.statSync(dotgit); } catch { return root; }
@@ -83,6 +86,54 @@ function mainTree(root) {
83
86
  return main;
84
87
  }
85
88
 
89
+ // ── the stat memo ───────────────────────────────────────────────────────────────────────────────
90
+ const MEMO_MAX = 20000;
91
+ /** fs.statSync(file), or null when it cannot be taken; inside a read pass, taken once per file. */
92
+ function statOnce(file) {
93
+ return passed('stats', file, () => { try { return fs.statSync(file); } catch { return null; } });
94
+ }
95
+ const statKey = (file) => { const st = statOnce(file); return st ? `${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}` : null; };
96
+ function memoPut(map, k, v) { if (map.size >= MEMO_MAX) map.clear(); map.set(k, v); return v; }
97
+
98
+ /* A READ PASS. One Board or My work fold asks for the same record's profile and lane four times (the signature, the work
99
+ * lanes, the layout, the stages) and for the main tree and profile once per record. Inside inPass(fn) each is looked up
100
+ * once per pass, and the pass ends with fn: the next request starts from the files again. Synchronous, so no other
101
+ * request runs inside a pass. */
102
+ let pass = null;
103
+ function inPass(fn) {
104
+ if (pass) return fn();
105
+ pass = { pl: new Map(), lanes: new Map(), main: new Map(), dirs: new Map(), stats: new Map() };
106
+ try { return fn(); } finally { pass = null; }
107
+ }
108
+ const passed = (bucket, k, make) => {
109
+ if (!pass) return make();
110
+ const m = pass[bucket];
111
+ if (m.has(k)) return m.get(k);
112
+ const v = make(); m.set(k, v); return v;
113
+ };
114
+
115
+ const fmMemo = new Map(); // file -> { key, fm }
116
+ /** The leading frontmatter of a record file ({} when it has none), read again only when the file's stat changes.
117
+ * Callers must not mutate the answer. Throws when the file cannot be read, as readFileSync does. */
118
+ function recordFrontmatter(file) {
119
+ const key = statKey(file);
120
+ const hit = fmMemo.get(file);
121
+ if (key && hit && hit.key === key) return hit.fm;
122
+ const fm = engine().parseLeadingFrontmatter(fs.readFileSync(file, 'utf8')) || {};
123
+ if (key) memoPut(fmMemo, file, { key, fm });
124
+ return fm;
125
+ }
126
+
127
+ const lanesMemo = new Map(); // root -> { key, lanes }
128
+ /** engine.lanesFor(root), read again only when the root's .pmos-profile changes (appears, goes, or is edited). */
129
+ function lanesOf(root) { return passed('lanes', root, () => lanesRead(root)); }
130
+ function lanesRead(root) {
131
+ const key = statKey(path.join(path.resolve(root || process.cwd()), '.pmos-profile')) || 'none';
132
+ const hit = lanesMemo.get(root);
133
+ if (hit && hit.key === key) return hit.lanes;
134
+ return memoPut(lanesMemo, root, { key, lanes: engine().lanesFor(root) }).lanes;
135
+ }
136
+
86
137
  /** The initiative record, looked up in this tree first and then in the main tree. null when neither has it. */
87
138
  function recordPath(root, initiative) {
88
139
  if (typeof initiative !== 'string' || !INIT_RE.test(initiative)) return null;
@@ -93,19 +144,21 @@ function recordPath(root, initiative) {
93
144
  const main = mainTree(root);
94
145
  if (main !== root) roots.push(main);
95
146
  for (const r of roots) {
96
- const file = path.join(eng.layout(r).initiatives, `${initiative}.md`);
97
- try { if (fs.statSync(file).isFile()) return file; } catch { /* try the next tree */ }
147
+ const file = path.join(passed('dirs', r, () => eng.layout(r).initiatives), `${initiative}.md`);
148
+ const st = statOnce(file);
149
+ if (st && st.isFile()) return file; // else try the next tree
98
150
  }
99
151
  return null;
100
152
  }
101
153
 
102
154
  /** The repository's profile, the initiative's lane (as workflow-state.js resolves it) and the lane definitions. */
103
- function profileAndLane(root, initiative) {
155
+ function profileAndLane(root, initiative) { return passed('pl', root + '\u0000' + initiative, () => profileAndLaneRead(root, initiative)); }
156
+ function profileAndLaneRead(root, initiative) {
104
157
  const eng = engine();
105
- const { profile, defs } = eng.lanesFor(root);
158
+ const { profile, defs } = lanesOf(root);
106
159
  const file = recordPath(root, initiative);
107
160
  let fm = {};
108
- if (file) { try { fm = eng.parseLeadingFrontmatter(fs.readFileSync(file, 'utf8')) || {}; } catch { fm = {}; } }
161
+ if (file) { try { fm = recordFrontmatter(file); } catch { fm = {}; } }
109
162
  const declared = eng.declaredLane(profile, fm);
110
163
  // An unknown or missing lane is the profile's strictest, exactly as workflow-state.js computes `effLane`.
111
164
  const fallback = profile === 'pm-artifacts' ? 'prd' : 'feature';
@@ -415,5 +468,5 @@ function layout({ root, initiative, fold, ladder, now }) {
415
468
 
416
469
  module.exports = {
417
470
  STAGE_GROUPS, STEP_NOUN, OWED_ACTOR, OPEN, DONE_WINDOW_MS, INIT_RE, NOT_MERGED_LABEL, withFactory,
418
- mainTree, recordPath, profileAndLane, viewGroup, stagesFor, stageIdsFor, resolveStage, owedFor, frontierOf, currentStage, nounFor, byLabel, progressLabel, layout, historyText,
471
+ inPass, statOnce, mainTree, recordPath, recordFrontmatter, profileAndLane, viewGroup, stagesFor, stageIdsFor, resolveStage, owedFor, frontierOf, currentStage, nounFor, byLabel, progressLabel, layout, historyText,
419
472
  };
@@ -51,7 +51,7 @@ const IR = require('./intel-report.js');
51
51
  const BP = require('./board-premium.js');
52
52
 
53
53
  const LEDGER = 'ready-reports.jsonl';
54
- const EVENTS = Object.freeze(['switch', 'picks', 'trust', 'trust-no', 'hold', 'overlap', 'promise', 'moment', 'quiet', 'heads-up']);
54
+ const EVENTS = Object.freeze(['switch', 'picks', 'trust', 'trust-no', 'hold', 'overlap', 'promise', 'moment', 'quiet', 'heads-up', 'auto-sent']);
55
55
  const LEVELS = Object.freeze(['program', 'product', 'initiative']);
56
56
  const KINDS = Object.freeze(['weekly', 'checkpoint', 'did-it-work']);
57
57
  const HOLD_ACTS = Object.freeze(['send-note', 'wait', 'skip']);
@@ -60,6 +60,7 @@ const KEY_RE = /^(product|(program|initiative):([A-Za-z0-9._-]{1,80}|\*))\|(week
60
60
  const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
61
61
  const DAY = 864e5;
62
62
  const STALE_MS = 2 * DAY; // a source not read for two days holds a report (PbG2)
63
+ const AUTO_MS = 10 * 60e3; // a calm weekly goes by itself 10 minutes after its time; until then the PM can hold it (batch 17 item 6)
63
64
  const TRUST_N = 4; // issues sent unchanged before "Send by itself" is offered (PbG6)
64
65
  const REFRESH_HOUR = 14, EVENING_HOUR = 18; // a late report: refreshed after 14:00, skipped by evening (PbG8)
65
66
  const WINDOW_DAYS = 28; // Did it work? drafts 4 weeks after launch
@@ -142,16 +143,17 @@ function checkLine(l) {
142
143
  case 'promise':
143
144
  if (!SCOPE_RE.test(String(l.scope || '')) || !['keep', 'drop'].includes(l.act) || !DATE_RE.test(String(l.date || ''))) return { ok: false, error: 'a promise is { scope, act: keep | drop, date: YYYY-MM-DD }' };
144
145
  return { ok: true, line: { ev: 'promise', scope: l.scope, act: l.act, date: l.date } };
145
- case 'moment': case 'quiet': case 'heads-up':
146
+ case 'moment': case 'quiet': case 'heads-up': case 'auto-sent':
146
147
  if (!key() || !DATE_RE.test(String(l.slot || ''))) return { ok: false, error: 'a draft line is { key, slot: YYYY-MM-DD }' };
147
148
  return { ok: true, line: { ev: l.ev, key: l.key, slot: l.slot, ...(typeof l.why === 'string' ? { why: clip(l.why, 120) } : {}), ...(typeof l.id === 'string' ? { id: clip(l.id, 120) } : {}), ...(typeof l.path === 'string' ? { path: clip(l.path, 300) } : {}) } };
148
149
  default: return { ok: false, error: 'unknown event' };
149
150
  }
150
151
  }
151
152
  /** → { switches: Map key→on, picks: { at, keys } | null, trust: Map key→on, trustNo: Set, holds: Map 'key|slot'→act, overlap: bool|null,
152
- * promises: Map scope→{ act, date }, moments: Map 'key|why'→slot, quiet: Map key→[slot], headsUps: Map id→{ key, slot, path } } */
153
+ * promises: Map scope→{ act, date }, moments: Map 'key|why'→slot, quiet: Map key→[slot], headsUps: Map id→{ key, slot, path },
154
+ * autoSent: Set 'key|slot' (a calm weekly the schedule issued by itself) } */
153
155
  function fold(lines) {
154
- const st = { switches: new Map(), picks: null, trust: new Map(), trustNo: new Set(), holds: new Map(), overlap: null, promises: new Map(), moments: new Map(), quiet: new Map(), headsUps: new Map() };
156
+ const st = { switches: new Map(), picks: null, trust: new Map(), trustNo: new Set(), holds: new Map(), overlap: null, promises: new Map(), moments: new Map(), quiet: new Map(), headsUps: new Map(), autoSent: new Set() };
155
157
  for (const l of lines || []) {
156
158
  if (!isObj(l) || !checkLine(l).ok) continue;
157
159
  switch (l.ev) {
@@ -165,6 +167,7 @@ function fold(lines) {
165
167
  case 'moment': st.moments.set(l.key + '|' + (l.why || l.slot), l.slot); break;
166
168
  case 'quiet': { const a = st.quiet.get(l.key) || []; a.push(l.slot); st.quiet.set(l.key, a); break; }
167
169
  case 'heads-up': st.headsUps.set(l.id || l.key + '|' + l.slot, { key: l.key, slot: l.slot, path: l.path || null, why: l.why || '' }); break;
170
+ case 'auto-sent': st.autoSent.add(l.key + '|' + l.slot); break;
168
171
  default: break;
169
172
  }
170
173
  }
@@ -413,6 +416,8 @@ function stateOfReport(o) {
413
416
  if (o.hold === 'skip') return { state: 'skipped', sub: 'You skipped it. The next issue covers both weeks' };
414
417
  if (o.stale && o.hold !== 'send-note') return { state: 'held', sub: o.hold === 'wait' ? 'Waits for ' + o.stale.source + ". It goes out once it reads again, if nothing changed" : 'Send it now with "' + o.stale.source + ' as of ' + whenTxt(o.stale.since, now) + '" written on it, or wait' };
415
418
  const due = dueAt(D.slot, time);
419
+ // a calm week (Wawan 2026-10-28, "Calm weeks send themselves"): it goes by itself 10 minutes after its time, and Skip holds it until then
420
+ if (o.auto && !o.hold && due !== null && now < due + AUTO_MS) return { state: 'drafted', calm: true, sub: 'Calm week · goes by itself ' + (localIso(now) === D.slot ? 'at ' : (sch && sch.day ? DAY1[sch.day] + ' ' : '')) + hhmm(due + AUTO_MS) + (s && s.audience ? ' to ' + clip(s.audience, 40) : '') };
416
421
  if (due === null || now < due) return { state: 'drafted', sub: 'Drafted · goes ' + (sch && sch.day ? DAY1[sch.day] + ' ' : '') + time + (s && s.audience ? ' to ' + clip(s.audience, 40) : '') };
417
422
  const d = new Date(now), sameDay = localIso(now) === D.slot;
418
423
  if (!sameDay || d.getHours() >= EVENING_HOUR) return { state: 'skipped', sub: 'Not sent by evening, so it is skipped. The next issue covers both weeks' };
@@ -440,7 +445,7 @@ function rowsFor(o) {
440
445
  const S = stateOfReport({ kind, level: o.level, on: on && (!setup || setup.status !== 'paused'), setup, doc, now: o.now, stale: o.stale, hold: doc ? o.st.holds.get(key + '|' + doc.slot) : null, paused: o.paused, closed: o.closed && kind !== 'did-it-work' ? true : o.closed && !doc, quiet, auto: !!(doc && doc.auto) });
441
446
  out.push({ id: setup ? setup.id : setupIdOf(o.scope, kind), key, kind, name: kindName(o.level, kind), state: S.state, sub: S.sub, on,
442
447
  ...(doc ? { path: doc.path, cadence: setup.id, slot: doc.slot, sha: doc.sha || null } : {}), ...(setup && setup.schedule && setup.schedule.day ? { day: setup.schedule.day } : {}),
443
- ...(S.refresh ? { refresh: true } : {}), trust: o.st.trust.get(key) === true });
448
+ ...(S.refresh ? { refresh: true } : {}), ...(S.calm ? { calm: true } : {}), trust: kind === 'weekly' && autoOn(o.st, key) });
444
449
  }
445
450
  for (const h of o.headsUps || []) out.unshift({ id: h.id, key: keyOf(o.scope, 'heads-up'), kind: 'heads-up', name: 'Heads-up', state: h.issued ? 'sent' : 'drafted', title: h.title, sub: h.sub, audience: h.audience || 'sponsors', channel: h.channel || 'mail', path: h.path, cadence: h.cadence, slot: h.slot, sha: h.sha || null, on: true });
446
451
  // the block shows what is live first; a row that is off is folded by the UI under "N more"
@@ -489,7 +494,7 @@ function libraryOf(o) {
489
494
  const setup = (o.setups || []).find((x) => x && x.ready && x.ready.scope === s.scope && x.ready.kind === kind) || null;
490
495
  const sub = kind === 'weekly' ? (on ? [setup && setup.schedule ? DAYS3[setup.schedule.day] || 'Weekly' : s.hand && s.hand.schedule && s.hand.schedule.day ? DAYS3[s.hand.schedule.day] : 'Mondays', setup && setup.audience ? clip(setup.audience, 40) : s.hand ? clip(s.hand.audience || '', 40) : '', p.why].filter(Boolean).join(' · ') : 'Off · drafts only in a week with news')
491
496
  : on ? (s.level === 'product' && kind === 'checkpoint' && s.quarterEnd ? 'Drafts ' + short(s.quarterEnd) + ' from the quarter score' : MOMENT_SUB[s.level][kind]) : 'Off';
492
- return { scope: s.scope, kind, name: kind === 'weekly' && s.hand && s.hand.name ? clip(s.hand.name, 60) : kindName(s.level, kind), sub, pick: kind === 'weekly' && p.pick, on, trust: st.trust.get(keyOf(s.scope, kind)) === true };
497
+ return { scope: s.scope, kind, name: kind === 'weekly' && s.hand && s.hand.name ? clip(s.hand.name, 60) : kindName(s.level, kind), sub, pick: kind === 'weekly' && p.pick, on, trust: kind === 'weekly' && autoOn(st, keyOf(s.scope, kind)) };
493
498
  };
494
499
  const groups = [];
495
500
  for (const s of scopes.filter((x) => x.level !== 'initiative')) groups.push({ scope: s.scope, level: s.level, name: s.name, rows: KINDS.map((k) => row(s, k)) });
@@ -540,11 +545,20 @@ function readersOf(audience) {
540
545
  /** "Send by itself" (PbG6). history: the issued documents of the report, oldest first, each { sha, draftSha }. Offered after 4 sent exactly as
541
546
  * drafted, unless it is on already or the PM said no to it. → { offer: bool, on: bool } */
542
547
  function trustOf(history, st, key) {
543
- const on = st.trust.get(key) === true;
548
+ const on = autoOn(st, key);
544
549
  if (on || st.trustNo.has(key)) return { offer: false, on };
545
550
  const last = (history || []).filter((h) => h && h.sha).slice(-TRUST_N);
546
551
  return { offer: last.length === TRUST_N && last.every((h) => h.draftSha && h.draftSha === h.sha), on };
547
552
  }
553
+ /** Calm weeks send themselves unless the PM turned "Send by itself" off for that report (Wawan 2026-10-28; it was off by default before). */
554
+ const autoOn = (st, key) => st.trust.get(key) !== false && !st.trustNo.has(key);
555
+ /** Is the newest drafted weekly ready to go by itself now: a calm draft, not issued, not held, its source fresh, past its time + 10 minutes,
556
+ * and the same day before evening. doc: { slot, issued, auto }; o: { time, now, hold, stale } */
557
+ function autoDue(doc, o) {
558
+ if (!doc || doc.issued || !doc.auto || o.hold || o.stale) return false;
559
+ const due = dueAt(doc.slot, o.time || '09:00'), now = fin(o.now) ? o.now : Date.now();
560
+ return due !== null && now >= due + AUTO_MS && localIso(now) === doc.slot && new Date(now).getHours() < EVENING_HOUR;
561
+ }
548
562
  /** A calm week: no scorecard row off plan, no miss comment, no decision asked, no "looks green" refusal. Any of those holds it for the PM. */
549
563
  function autoOk(markdown) {
550
564
  const t = String(markdown || '');
@@ -612,5 +626,5 @@ module.exports = {
612
626
  LEDGER, EVENTS, LEVELS, KINDS, HOLD_ACTS, SCOPE_RE, KEY_RE, STALE_MS, TRUST_N,
613
627
  parseScope, keyOf, kindName, setupIdOf, ledgerFile, readLines, append, checkLine, fold, stateOf, switchOf,
614
628
  forecastOf, dotOf, usualDays, promiseOf, goalsOf, stageOf, looksGreen, headsUpOf, handledOf, dashboardOf,
615
- picksOf, stateOfReport, rowsFor, withDesk, anchorGoalsOf, libraryOf, overlapOf, readersOf, trustOf, autoOk, sponsorsCut, momentsOf, quarterEndOf, movedOf,
629
+ picksOf, stateOfReport, rowsFor, withDesk, anchorGoalsOf, libraryOf, overlapOf, readersOf, trustOf, autoOn, autoDue, AUTO_MS, autoOk, sponsorsCut, momentsOf, quarterEndOf, movedOf,
616
630
  };
@@ -452,7 +452,17 @@ function readLog(dir) {
452
452
  return lines;
453
453
  }
454
454
  /** Fold the log into runs: { runs: [run], lastRun(id), runs(id, n) }. A run is { run, source, ws, trigger, start_at, end_at, result, took_ms, got, error, note, inputs, copy }. */
455
+ // One fold per read of the log (page-speed): readLog answers the same array until the file changes, and Sources, the freshness rows and
456
+ // every schedule asked foldLog again on each request, about a quarter second each on a busy log. The fold is kept beside that array.
457
+ // A caller must not change the runs it gets.
458
+ const folded = new WeakMap(); // lines -> fold
455
459
  function foldLog(lines) {
460
+ if (Array.isArray(lines) && folded.has(lines)) return folded.get(lines);
461
+ const out = foldLines(lines);
462
+ if (Array.isArray(lines)) folded.set(lines, out);
463
+ return out;
464
+ }
465
+ function foldLines(lines) {
456
466
  const byRun = new Map(); const order = [];
457
467
  for (const l of lines) {
458
468
  if (l.ev === 'skip') { const r = { run: l.run || 'skip-' + l.at, source: l.source, ws: l.ws || null, trigger: l.trigger || 'schedule', start_at: l.at, end_at: l.at, result: 'skipped', note: l.note || null, error: null }; byRun.set(r.run, r); order.push(r.run); continue; }
@@ -463,10 +473,12 @@ function foldLog(lines) {
463
473
  }
464
474
  const runs = order.map((id) => byRun.get(id));
465
475
  const real = (r) => r.result !== 'skipped';
476
+ const bySource = new Map(); // source -> its runs, in log order
477
+ for (const r of runs) { let a = bySource.get(r.source); if (!a) bySource.set(r.source, (a = [])); a.push(r); }
466
478
  return {
467
479
  all: runs,
468
- lastRun: (id) => { for (let i = runs.length - 1; i >= 0; i--) if (runs[i].source === id && real(runs[i])) return runs[i]; return null; },
469
- runs: (id, n) => runs.filter((r) => r.source === id).slice(-n).reverse(),
480
+ lastRun: (id) => { const a = bySource.get(id) || []; for (let i = a.length - 1; i >= 0; i--) if (real(a[i])) return a[i]; return null; },
481
+ runs: (id, n) => (bySource.get(id) || []).slice(-n).reverse(),
470
482
  };
471
483
  }
472
484
  /** Keep a copy of what a done run read. `paths` are files or folders. → the copy folder relative to the state dir, or null */
@@ -17,6 +17,7 @@ const path = require('path');
17
17
  const fs = require('fs');
18
18
  const Metrics = require('./board-metrics-premium.js');
19
19
  const TaskPlans = require('./task-plans.js');
20
+ const JiraMoves = require('./jira-moves.js');
20
21
  const TaskLinks = require('./task-links.js');
21
22
  const Suggest = require('./split-merge-suggest.js');
22
23
  const { ENGINE_PATHS } = require('./console-state.js');
@@ -55,8 +56,10 @@ module.exports = {
55
56
  if (url.pathname !== '/api/board-premium') return false;
56
57
  if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
57
58
  const fail = (error) => { ctx.json(res, { ok: false, state: 'error', error: String(error).slice(0, 240) }, 500); return true; };
59
+ // one read pass for the ten routes below: each workspace's board fold and rows are derived once for all of them (lib/routes-boards.js inPass)
60
+ ctx = Object.assign({}, ctx, { boardsPass: new Map() });
58
61
  try {
59
- const list = await via(boards, '/api/boards', req, ctx);
62
+ const list = await via(boards, '/api/boards?names=1', req, ctx); // the list and the names only: the picked board's rows are read below
60
63
  if (!list.body || list.body.ok === false) return fail((list.body && list.body.error) || 'the boards could not be listed');
61
64
  const all = list.body.boards || [];
62
65
  const wantWs = url.searchParams.get('ws'), wantId = url.searchParams.get('board');
@@ -103,6 +106,11 @@ module.exports = {
103
106
  const w = ctx.getWs ? ctx.getWs(pick.ws) : null, dir = w && ctx.stateDirFor ? ctx.stateDirFor(w) : null;
104
107
  if (dir) { const F = TaskPlans.read(dir); for (const L of [model.rows, ...(model.stages || []).map((x) => x.rows), model.cancelled, model.archived]) TaskPlans.decorate(L, F); }
105
108
  } catch { missing.push('saved plans'); }
109
+ // a Jira ticket's status moved in PMOS (lib/jira-moves.js): the ticket shows where the PM moved it while the agent asks Jira, then Jira's answer
110
+ try {
111
+ const w = ctx.getWs ? ctx.getWs(pick.ws) : null;
112
+ if (w) { const F = JiraMoves.read(w.root); for (const L of [model.rows, ...(model.stages || []).map((x) => x.rows), model.cancelled, model.archived]) JiraMoves.decorate(L, F); }
113
+ } catch { missing.push('Jira moves'); }
106
114
  // links between tasks (batch 11 item 15): each row's links, Claude's proposals, the quiet moves and what waits on the PM (task-links.jsonl)
107
115
  try {
108
116
  const w = ctx.getWs ? ctx.getWs(pick.ws) : null, dir = w && ctx.stateDirFor ? ctx.stateDirFor(w) : null;